Line data Source code
1 : #![recursion_limit = "300"]
2 :
3 : //! Main entry point for the Page Server executable.
4 :
5 : use std::env;
6 : use std::env::{VarError, var};
7 : use std::io::Read;
8 : use std::str::FromStr;
9 : use std::sync::Arc;
10 : use std::time::Duration;
11 :
12 : use anyhow::{Context, anyhow};
13 : use camino::Utf8Path;
14 : use clap::{Arg, ArgAction, Command};
15 : use http_utils::tls_certs::ReloadingCertificateResolver;
16 : use metrics::launch_timestamp::{LaunchTimestamp, set_launch_timestamp_metric};
17 : use metrics::set_build_info_metric;
18 : use nix::sys::socket::{setsockopt, sockopt};
19 : use pageserver::config::{PageServerConf, PageserverIdentity, ignored_fields};
20 : use pageserver::controller_upcall_client::StorageControllerUpcallClient;
21 : use pageserver::deletion_queue::DeletionQueue;
22 : use pageserver::disk_usage_eviction_task::{self, launch_disk_usage_global_eviction_task};
23 : use pageserver::metrics::{STARTUP_DURATION, STARTUP_IS_LOADING};
24 : use pageserver::task_mgr::{
25 : BACKGROUND_RUNTIME, COMPUTE_REQUEST_RUNTIME, MGMT_REQUEST_RUNTIME, WALRECEIVER_RUNTIME,
26 : };
27 : use pageserver::tenant::{TenantSharedResources, mgr, secondary};
28 : use pageserver::{
29 : CancellableTask, ConsumptionMetricsTasks, HttpEndpointListener, HttpsEndpointListener, http,
30 : page_cache, page_service, task_mgr, virtual_file,
31 : };
32 : use postgres_backend::AuthType;
33 : use remote_storage::GenericRemoteStorage;
34 : use tokio::time::Instant;
35 : use tokio_util::sync::CancellationToken;
36 : use tracing::*;
37 : use tracing_utils::OtelGuard;
38 : use utils::auth::{JwtAuth, SwappableJwtAuth};
39 : use utils::crashsafe::syncfs;
40 : use utils::logging::TracingErrorLayerEnablement;
41 : use utils::sentry_init::init_sentry;
42 : use utils::{failpoint_support, logging, project_build_tag, project_git_version, tcp_listener};
43 :
44 : project_git_version!(GIT_VERSION);
45 : project_build_tag!(BUILD_TAG);
46 :
47 : #[global_allocator]
48 : static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
49 :
50 : /// Configure jemalloc to profile heap allocations by sampling stack traces every 2 MB (1 << 21).
51 : /// This adds roughly 3% overhead for allocations on average, which is acceptable considering
52 : /// performance-sensitive code will avoid allocations as far as possible anyway.
53 : #[allow(non_upper_case_globals)]
54 : #[unsafe(export_name = "malloc_conf")]
55 : pub static malloc_conf: &[u8] = b"prof:true,prof_active:true,lg_prof_sample:21\0";
56 :
57 : const PID_FILE_NAME: &str = "pageserver.pid";
58 :
59 : const FEATURES: &[&str] = &[
60 : #[cfg(feature = "testing")]
61 : "testing",
62 : ];
63 :
64 12 : fn version() -> String {
65 12 : format!(
66 12 : "{GIT_VERSION} failpoints: {}, features: {:?}",
67 12 : fail::has_failpoints(),
68 12 : FEATURES,
69 12 : )
70 12 : }
71 :
72 0 : fn main() -> anyhow::Result<()> {
73 0 : let launch_ts = Box::leak(Box::new(LaunchTimestamp::generate()));
74 0 :
75 0 : let arg_matches = cli().get_matches();
76 0 :
77 0 : if arg_matches.get_flag("enabled-features") {
78 0 : println!("{{\"features\": {FEATURES:?} }}");
79 0 : return Ok(());
80 0 : }
81 0 :
82 0 : // Initialize up failpoints support
83 0 : let scenario = failpoint_support::init();
84 0 :
85 0 : let workdir = arg_matches
86 0 : .get_one::<String>("workdir")
87 0 : .map(Utf8Path::new)
88 0 : .unwrap_or_else(|| Utf8Path::new(".neon"));
89 0 : let workdir = workdir
90 0 : .canonicalize_utf8()
91 0 : .with_context(|| format!("Error opening workdir '{workdir}'"))?;
92 :
93 0 : let cfg_file_path = workdir.join("pageserver.toml");
94 0 : let identity_file_path = workdir.join("identity.toml");
95 0 :
96 0 : // Set CWD to workdir for non-daemon modes
97 0 : env::set_current_dir(&workdir)
98 0 : .with_context(|| format!("Failed to set application's current dir to '{workdir}'"))?;
99 :
100 0 : let (conf, ignored) = initialize_config(&identity_file_path, &cfg_file_path, &workdir)?;
101 :
102 : // Initialize logging.
103 : //
104 : // It must be initialized before the custom panic hook is installed below.
105 : //
106 : // Regarding tracing_error enablement: at this time, we only use the
107 : // tracing_error crate to debug_assert that log spans contain tenant and timeline ids.
108 : // See `debug_assert_current_span_has_tenant_and_timeline_id` in the timeline module
109 0 : let tracing_error_layer_enablement = if cfg!(debug_assertions) {
110 0 : TracingErrorLayerEnablement::EnableWithRustLogFilter
111 : } else {
112 0 : TracingErrorLayerEnablement::Disabled
113 : };
114 :
115 0 : logging::init(
116 0 : conf.log_format,
117 0 : tracing_error_layer_enablement,
118 0 : logging::Output::Stdout,
119 0 : )?;
120 :
121 0 : let otel_enablement = match &conf.tracing {
122 0 : Some(cfg) => tracing_utils::OtelEnablement::Enabled {
123 0 : service_name: "pageserver".to_string(),
124 0 : export_config: (&cfg.export_config).into(),
125 0 : runtime: *COMPUTE_REQUEST_RUNTIME,
126 0 : },
127 0 : None => tracing_utils::OtelEnablement::Disabled,
128 : };
129 :
130 0 : let otel_guard = tracing_utils::init_performance_tracing(otel_enablement);
131 0 :
132 0 : if otel_guard.is_some() {
133 0 : info!(?conf.tracing, "starting with OTEL tracing enabled");
134 0 : }
135 :
136 : // mind the order required here: 1. logging, 2. panic_hook, 3. sentry.
137 : // disarming this hook on pageserver, because we never tear down tracing.
138 0 : logging::replace_panic_hook_with_tracing_panic_hook().forget();
139 0 :
140 0 : // initialize sentry if SENTRY_DSN is provided
141 0 : let _sentry_guard = init_sentry(
142 0 : Some(GIT_VERSION.into()),
143 0 : &[("node_id", &conf.id.to_string())],
144 0 : );
145 0 :
146 0 : // Warn about ignored config items; see pageserver_api::config::ConfigToml
147 0 : // doc comment for rationale why we prefer this over serde(deny_unknown_fields).
148 0 : {
149 0 : let ignored_fields::Paths { paths } = &ignored;
150 0 : for path in paths {
151 0 : warn!(?path, "ignoring unknown configuration item");
152 : }
153 : }
154 :
155 : // Log configuration items for feature-flag-like config
156 : // (maybe we should automate this with a visitor?).
157 0 : info!(?conf.virtual_file_io_engine, "starting with virtual_file IO engine");
158 0 : info!(?conf.virtual_file_io_mode, "starting with virtual_file IO mode");
159 0 : info!(?conf.wal_receiver_protocol, "starting with WAL receiver protocol");
160 0 : info!(?conf.validate_wal_contiguity, "starting with WAL contiguity validation");
161 0 : info!(?conf.page_service_pipelining, "starting with page service pipelining config");
162 0 : info!(?conf.get_vectored_concurrent_io, "starting with get_vectored IO concurrency config");
163 :
164 : // The tenants directory contains all the pageserver local disk state.
165 : // Create if not exists and make sure all the contents are durable before proceeding.
166 : // Ensuring durability eliminates a whole bug class where we come up after an unclean shutdown.
167 : // After unclea shutdown, we don't know if all the filesystem content we can read via syscalls is actually durable or not.
168 : // Examples for that: OOM kill, systemd killing us during shutdown, self abort due to unrecoverable IO error.
169 0 : let tenants_path = conf.tenants_path();
170 0 : {
171 0 : let open = || {
172 0 : nix::dir::Dir::open(
173 0 : tenants_path.as_std_path(),
174 0 : nix::fcntl::OFlag::O_DIRECTORY | nix::fcntl::OFlag::O_RDONLY,
175 0 : nix::sys::stat::Mode::empty(),
176 0 : )
177 0 : };
178 0 : let dirfd = match open() {
179 0 : Ok(dirfd) => dirfd,
180 0 : Err(e) => match e {
181 : nix::errno::Errno::ENOENT => {
182 0 : utils::crashsafe::create_dir_all(&tenants_path).with_context(|| {
183 0 : format!("Failed to create tenants root dir at '{tenants_path}'")
184 0 : })?;
185 0 : open().context("open tenants dir after creating it")?
186 : }
187 0 : e => anyhow::bail!(e),
188 : },
189 : };
190 :
191 0 : if conf.no_sync {
192 0 : info!("Skipping syncfs on startup");
193 : } else {
194 0 : let started = Instant::now();
195 0 : syncfs(dirfd)?;
196 0 : let elapsed = started.elapsed();
197 0 : info!(
198 0 : elapsed_ms = elapsed.as_millis(),
199 0 : "made tenant directory contents durable"
200 : );
201 : }
202 : }
203 :
204 : // Basic initialization of things that don't change after startup
205 0 : tracing::info!("Initializing virtual_file...");
206 : virtual_file::init(
207 0 : conf.max_file_descriptors,
208 0 : conf.virtual_file_io_engine,
209 0 : conf.virtual_file_io_mode,
210 0 : if conf.no_sync {
211 0 : virtual_file::SyncMode::UnsafeNoSync
212 : } else {
213 0 : virtual_file::SyncMode::Sync
214 : },
215 : );
216 0 : tracing::info!("Initializing page_cache...");
217 0 : page_cache::init(conf.page_cache_size);
218 0 :
219 0 : start_pageserver(launch_ts, conf, ignored, otel_guard).context("Failed to start pageserver")?;
220 :
221 0 : scenario.teardown();
222 0 : Ok(())
223 0 : }
224 :
225 0 : fn initialize_config(
226 0 : identity_file_path: &Utf8Path,
227 0 : cfg_file_path: &Utf8Path,
228 0 : workdir: &Utf8Path,
229 0 : ) -> anyhow::Result<(&'static PageServerConf, ignored_fields::Paths)> {
230 : // The deployment orchestrator writes out an indentity file containing the node id
231 : // for all pageservers. This file is the source of truth for the node id. In order
232 : // to allow for rolling back pageserver releases, the node id is also included in
233 : // the pageserver config that the deployment orchestrator writes to disk for the pageserver.
234 : // A rolled back version of the pageserver will get the node id from the pageserver.toml
235 : // config file.
236 0 : let identity = match std::fs::File::open(identity_file_path) {
237 0 : Ok(mut f) => {
238 0 : let md = f.metadata().context("stat config file")?;
239 0 : if !md.is_file() {
240 0 : anyhow::bail!(
241 0 : "Pageserver found identity file but it is a dir entry: {identity_file_path}. Aborting start up ..."
242 0 : );
243 0 : }
244 0 :
245 0 : let mut s = String::new();
246 0 : f.read_to_string(&mut s).context("read identity file")?;
247 0 : toml_edit::de::from_str::<PageserverIdentity>(&s)?
248 : }
249 0 : Err(e) => {
250 0 : anyhow::bail!(
251 0 : "Pageserver could not read identity file: {identity_file_path}: {e}. Aborting start up ..."
252 0 : );
253 : }
254 : };
255 :
256 0 : let config_file_contents =
257 0 : std::fs::read_to_string(cfg_file_path).context("read config file from filesystem")?;
258 :
259 : // Deserialize the config file contents into a ConfigToml.
260 0 : let config_toml: pageserver_api::config::ConfigToml = {
261 0 : let deserializer = toml_edit::de::Deserializer::from_str(&config_file_contents)
262 0 : .context("build toml deserializer")?;
263 0 : let mut path_to_error_track = serde_path_to_error::Track::new();
264 0 : let deserializer =
265 0 : serde_path_to_error::Deserializer::new(deserializer, &mut path_to_error_track);
266 0 : serde::Deserialize::deserialize(deserializer).context("deserialize config toml")?
267 : };
268 :
269 : // Find unknown fields by re-serializing the parsed ConfigToml and comparing it to the on-disk file.
270 : // Any fields that are only in the on-disk version are unknown.
271 : // (The assumption here is that the ConfigToml doesn't to skip_serializing_if.)
272 : // (Make sure to read the ConfigToml doc comment on why we only want to warn about, but not fail startup, on unknown fields).
273 0 : let ignored = {
274 0 : let ondisk_toml = config_file_contents
275 0 : .parse::<toml_edit::DocumentMut>()
276 0 : .context("parse original config as toml document")?;
277 0 : let parsed_toml = toml_edit::ser::to_document(&config_toml)
278 0 : .context("re-serialize config to toml document")?;
279 0 : pageserver::config::ignored_fields::find(ondisk_toml, parsed_toml)
280 : };
281 :
282 : // Construct the runtime god object (it's called PageServerConf but actually is just global shared state).
283 0 : let conf = PageServerConf::parse_and_validate(identity.id, config_toml, workdir)
284 0 : .context("runtime-validation of config toml")?;
285 0 : let conf = Box::leak(Box::new(conf));
286 0 :
287 0 : Ok((conf, ignored))
288 0 : }
289 :
290 : struct WaitForPhaseResult<F: std::future::Future + Unpin> {
291 : timeout_remaining: Duration,
292 : skipped: Option<F>,
293 : }
294 :
295 : /// During startup, we apply a timeout to our waits for readiness, to avoid
296 : /// stalling the whole service if one Tenant experiences some problem. Each
297 : /// phase may consume some of the timeout: this function returns the updated
298 : /// timeout for use in the next call.
299 0 : async fn wait_for_phase<F>(phase: &str, mut fut: F, timeout: Duration) -> WaitForPhaseResult<F>
300 0 : where
301 0 : F: std::future::Future + Unpin,
302 0 : {
303 0 : let initial_t = Instant::now();
304 0 : let skipped = match tokio::time::timeout(timeout, &mut fut).await {
305 0 : Ok(_) => None,
306 : Err(_) => {
307 0 : tracing::info!(
308 0 : timeout_millis = timeout.as_millis(),
309 0 : %phase,
310 0 : "Startup phase timed out, proceeding anyway"
311 : );
312 0 : Some(fut)
313 : }
314 : };
315 :
316 0 : WaitForPhaseResult {
317 0 : timeout_remaining: timeout
318 0 : .checked_sub(Instant::now().duration_since(initial_t))
319 0 : .unwrap_or(Duration::ZERO),
320 0 : skipped,
321 0 : }
322 0 : }
323 :
324 0 : fn startup_checkpoint(started_at: Instant, phase: &str, human_phase: &str) {
325 0 : let elapsed = started_at.elapsed();
326 0 : let secs = elapsed.as_secs_f64();
327 0 : STARTUP_DURATION.with_label_values(&[phase]).set(secs);
328 0 :
329 0 : info!(
330 0 : elapsed_ms = elapsed.as_millis(),
331 0 : "{human_phase} ({secs:.3}s since start)"
332 : )
333 0 : }
334 :
335 0 : fn start_pageserver(
336 0 : launch_ts: &'static LaunchTimestamp,
337 0 : conf: &'static PageServerConf,
338 0 : ignored: ignored_fields::Paths,
339 0 : otel_guard: Option<OtelGuard>,
340 0 : ) -> anyhow::Result<()> {
341 0 : // Monotonic time for later calculating startup duration
342 0 : let started_startup_at = Instant::now();
343 0 :
344 0 : // Print version and launch timestamp to the log,
345 0 : // and expose them as prometheus metrics.
346 0 : // A changed version string indicates changed software.
347 0 : // A changed launch timestamp indicates a pageserver restart.
348 0 : info!(
349 0 : "version: {} launch_timestamp: {} build_tag: {}",
350 0 : version(),
351 0 : launch_ts.to_string(),
352 : BUILD_TAG,
353 : );
354 0 : set_build_info_metric(GIT_VERSION, BUILD_TAG);
355 0 : set_launch_timestamp_metric(launch_ts);
356 0 : #[cfg(target_os = "linux")]
357 0 : metrics::register_internal(Box::new(metrics::more_process_metrics::Collector::new())).unwrap();
358 0 : metrics::register_internal(Box::new(
359 0 : pageserver::metrics::tokio_epoll_uring::Collector::new(),
360 0 : ))
361 0 : .unwrap();
362 0 : pageserver::preinitialize_metrics(conf, ignored);
363 0 :
364 0 : // If any failpoints were set from FAILPOINTS environment variable,
365 0 : // print them to the log for debugging purposes
366 0 : let failpoints = fail::list();
367 0 : if !failpoints.is_empty() {
368 0 : info!(
369 0 : "started with failpoints: {}",
370 0 : failpoints
371 0 : .iter()
372 0 : .map(|(name, actions)| format!("{name}={actions}"))
373 0 : .collect::<Vec<String>>()
374 0 : .join(";")
375 : )
376 0 : }
377 :
378 : // Create and lock PID file. This ensures that there cannot be more than one
379 : // pageserver process running at the same time.
380 0 : let lock_file_path = conf.workdir.join(PID_FILE_NAME);
381 0 : info!("Claiming pid file at {lock_file_path:?}...");
382 0 : let lock_file =
383 0 : utils::pid_file::claim_for_current_process(&lock_file_path).context("claim pid file")?;
384 0 : info!("Claimed pid file at {lock_file_path:?}");
385 :
386 : // Ensure that the lock file is held even if the main thread of the process panics.
387 : // We need to release the lock file only when the process exits.
388 0 : std::mem::forget(lock_file);
389 0 :
390 0 : // Bind the HTTP and libpq ports early, so that if they are in use by some other
391 0 : // process, we error out early.
392 0 : let http_addr = &conf.listen_http_addr;
393 0 : info!("Starting pageserver http handler on {http_addr}");
394 0 : let http_listener = tcp_listener::bind(http_addr)?;
395 :
396 0 : let https_listener = match conf.listen_https_addr.as_ref() {
397 0 : Some(https_addr) => {
398 0 : info!("Starting pageserver https handler on {https_addr}");
399 0 : Some(tcp_listener::bind(https_addr)?)
400 : }
401 0 : None => None,
402 : };
403 :
404 0 : let pg_addr = &conf.listen_pg_addr;
405 0 : info!("Starting pageserver pg protocol handler on {pg_addr}");
406 0 : let pageserver_listener = tcp_listener::bind(pg_addr)?;
407 :
408 : // Enable SO_KEEPALIVE on the socket, to detect dead connections faster.
409 : // These are configured via net.ipv4.tcp_keepalive_* sysctls.
410 : //
411 : // TODO: also set this on the walreceiver socket, but tokio-postgres doesn't
412 : // support enabling keepalives while using the default OS sysctls.
413 0 : setsockopt(&pageserver_listener, sockopt::KeepAlive, &true)?;
414 :
415 : // Launch broker client
416 : // The storage_broker::connect call needs to happen inside a tokio runtime thread.
417 0 : let broker_client = WALRECEIVER_RUNTIME
418 0 : .block_on(async {
419 0 : let tls_config = storage_broker::ClientTlsConfig::new().ca_certificates(
420 0 : conf.ssl_ca_certs
421 0 : .iter()
422 0 : .map(pem::encode)
423 0 : .map(storage_broker::Certificate::from_pem),
424 0 : );
425 0 : // Note: we do not attempt connecting here (but validate endpoints sanity).
426 0 : storage_broker::connect(
427 0 : conf.broker_endpoint.clone(),
428 0 : conf.broker_keepalive_interval,
429 0 : tls_config,
430 0 : )
431 0 : })
432 0 : .with_context(|| {
433 0 : format!(
434 0 : "create broker client for uri={:?} keepalive_interval={:?}",
435 0 : &conf.broker_endpoint, conf.broker_keepalive_interval,
436 0 : )
437 0 : })?;
438 :
439 : // Initialize authentication for incoming connections
440 : let http_auth;
441 : let pg_auth;
442 0 : if conf.http_auth_type == AuthType::NeonJWT || conf.pg_auth_type == AuthType::NeonJWT {
443 : // unwrap is ok because check is performed when creating config, so path is set and exists
444 0 : let key_path = conf.auth_validation_public_key_path.as_ref().unwrap();
445 0 : info!("Loading public key(s) for verifying JWT tokens from {key_path:?}");
446 :
447 0 : let jwt_auth = JwtAuth::from_key_path(key_path)?;
448 0 : let auth: Arc<SwappableJwtAuth> = Arc::new(SwappableJwtAuth::new(jwt_auth));
449 :
450 0 : http_auth = match &conf.http_auth_type {
451 0 : AuthType::Trust => None,
452 0 : AuthType::NeonJWT => Some(auth.clone()),
453 : };
454 0 : pg_auth = match &conf.pg_auth_type {
455 0 : AuthType::Trust => None,
456 0 : AuthType::NeonJWT => Some(auth),
457 : };
458 0 : } else {
459 0 : http_auth = None;
460 0 : pg_auth = None;
461 0 : }
462 0 : info!("Using auth for http API: {:#?}", conf.http_auth_type);
463 0 : info!("Using auth for pg connections: {:#?}", conf.pg_auth_type);
464 :
465 0 : let tls_server_config = if conf.listen_https_addr.is_some() || conf.enable_tls_page_service_api
466 : {
467 0 : let resolver = BACKGROUND_RUNTIME.block_on(ReloadingCertificateResolver::new(
468 0 : "main",
469 0 : &conf.ssl_key_file,
470 0 : &conf.ssl_cert_file,
471 0 : conf.ssl_cert_reload_period,
472 0 : ))?;
473 :
474 0 : let server_config = rustls::ServerConfig::builder()
475 0 : .with_no_client_auth()
476 0 : .with_cert_resolver(resolver);
477 0 :
478 0 : Some(Arc::new(server_config))
479 : } else {
480 0 : None
481 : };
482 :
483 0 : match var("NEON_AUTH_TOKEN") {
484 0 : Ok(v) => {
485 0 : info!("Loaded JWT token for authentication with Safekeeper");
486 0 : pageserver::config::SAFEKEEPER_AUTH_TOKEN
487 0 : .set(Arc::new(v))
488 0 : .map_err(|_| anyhow!("Could not initialize SAFEKEEPER_AUTH_TOKEN"))?;
489 : }
490 : Err(VarError::NotPresent) => {
491 0 : info!("No JWT token for authentication with Safekeeper detected");
492 : }
493 0 : Err(e) => return Err(e).with_context(
494 0 : || "Failed to either load to detect non-present NEON_AUTH_TOKEN environment variable",
495 0 : ),
496 : };
497 :
498 : // Top-level cancellation token for the process
499 0 : let shutdown_pageserver = tokio_util::sync::CancellationToken::new();
500 :
501 : // Set up remote storage client
502 0 : let remote_storage = BACKGROUND_RUNTIME.block_on(create_remote_storage_client(conf))?;
503 :
504 : // Set up deletion queue
505 0 : let (deletion_queue, deletion_workers) = DeletionQueue::new(
506 0 : remote_storage.clone(),
507 0 : StorageControllerUpcallClient::new(conf, &shutdown_pageserver)?,
508 0 : conf,
509 0 : );
510 0 : deletion_workers.spawn_with(BACKGROUND_RUNTIME.handle());
511 0 :
512 0 : // Up to this point no significant I/O has been done: this should have been fast. Record
513 0 : // duration prior to starting I/O intensive phase of startup.
514 0 : startup_checkpoint(started_startup_at, "initial", "Starting loading tenants");
515 0 : STARTUP_IS_LOADING.set(1);
516 0 :
517 0 : // Startup staging or optimizing:
518 0 : //
519 0 : // We want to minimize downtime for `page_service` connections, and trying not to overload
520 0 : // BACKGROUND_RUNTIME by doing initial compactions and initial logical sizes at the same time.
521 0 : //
522 0 : // init_done_rx will notify when all initial load operations have completed.
523 0 : //
524 0 : // background_jobs_can_start (same name used to hold off background jobs from starting at
525 0 : // consumer side) will be dropped once we can start the background jobs. Currently it is behind
526 0 : // completing all initial logical size calculations (init_logical_size_done_rx) and a timeout
527 0 : // (background_task_maximum_delay).
528 0 : let (init_remote_done_tx, init_remote_done_rx) = utils::completion::channel();
529 0 : let (init_done_tx, init_done_rx) = utils::completion::channel();
530 0 :
531 0 : let (background_jobs_can_start, background_jobs_barrier) = utils::completion::channel();
532 0 :
533 0 : let order = pageserver::InitializationOrder {
534 0 : initial_tenant_load_remote: Some(init_done_tx),
535 0 : initial_tenant_load: Some(init_remote_done_tx),
536 0 : background_jobs_can_start: background_jobs_barrier.clone(),
537 0 : };
538 0 :
539 0 : info!(config=?conf.l0_flush, "using l0_flush config");
540 0 : let l0_flush_global_state =
541 0 : pageserver::l0_flush::L0FlushGlobalState::new(conf.l0_flush.clone());
542 0 :
543 0 : // Scan the local 'tenants/' directory and start loading the tenants
544 0 : let deletion_queue_client = deletion_queue.new_client();
545 0 : let background_purges = mgr::BackgroundPurges::default();
546 0 : let tenant_manager = BACKGROUND_RUNTIME.block_on(mgr::init_tenant_mgr(
547 0 : conf,
548 0 : background_purges.clone(),
549 0 : TenantSharedResources {
550 0 : broker_client: broker_client.clone(),
551 0 : remote_storage: remote_storage.clone(),
552 0 : deletion_queue_client,
553 0 : l0_flush_global_state,
554 0 : },
555 0 : order,
556 0 : shutdown_pageserver.clone(),
557 0 : ))?;
558 0 : let tenant_manager = Arc::new(tenant_manager);
559 0 :
560 0 : BACKGROUND_RUNTIME.spawn({
561 0 : let shutdown_pageserver = shutdown_pageserver.clone();
562 0 : let drive_init = async move {
563 0 : // NOTE: unlike many futures in pageserver, this one is cancellation-safe
564 0 : let guard = scopeguard::guard_on_success((), |_| {
565 0 : tracing::info!("Cancelled before initial load completed")
566 0 : });
567 0 :
568 0 : let timeout = conf.background_task_maximum_delay;
569 0 :
570 0 : let init_remote_done = std::pin::pin!(async {
571 0 : init_remote_done_rx.wait().await;
572 0 : startup_checkpoint(
573 0 : started_startup_at,
574 0 : "initial_tenant_load_remote",
575 0 : "Remote part of initial load completed",
576 0 : );
577 0 : });
578 :
579 : let WaitForPhaseResult {
580 0 : timeout_remaining: timeout,
581 0 : skipped: init_remote_skipped,
582 0 : } = wait_for_phase("initial_tenant_load_remote", init_remote_done, timeout).await;
583 :
584 0 : let init_load_done = std::pin::pin!(async {
585 0 : init_done_rx.wait().await;
586 0 : startup_checkpoint(
587 0 : started_startup_at,
588 0 : "initial_tenant_load",
589 0 : "Initial load completed",
590 0 : );
591 0 : STARTUP_IS_LOADING.set(0);
592 0 : });
593 :
594 : let WaitForPhaseResult {
595 0 : timeout_remaining: _timeout,
596 0 : skipped: init_load_skipped,
597 0 : } = wait_for_phase("initial_tenant_load", init_load_done, timeout).await;
598 :
599 : // initial logical sizes can now start, as they were waiting on init_done_rx.
600 :
601 0 : scopeguard::ScopeGuard::into_inner(guard);
602 0 :
603 0 : // allow background jobs to start: we either completed prior stages, or they reached timeout
604 0 : // and were skipped. It is important that we do not let them block background jobs indefinitely,
605 0 : // because things like consumption metrics for billing are blocked by this barrier.
606 0 : drop(background_jobs_can_start);
607 0 : startup_checkpoint(
608 0 : started_startup_at,
609 0 : "background_jobs_can_start",
610 0 : "Starting background jobs",
611 0 : );
612 0 :
613 0 : // We are done. If we skipped any phases due to timeout, run them to completion here so that
614 0 : // they will eventually update their startup_checkpoint, and so that we do not declare the
615 0 : // 'complete' stage until all the other stages are really done.
616 0 : let guard = scopeguard::guard_on_success((), |_| {
617 0 : tracing::info!("Cancelled before waiting for skipped phases done")
618 0 : });
619 0 : if let Some(f) = init_remote_skipped {
620 0 : f.await;
621 0 : }
622 0 : if let Some(f) = init_load_skipped {
623 0 : f.await;
624 0 : }
625 0 : scopeguard::ScopeGuard::into_inner(guard);
626 0 :
627 0 : startup_checkpoint(started_startup_at, "complete", "Startup complete");
628 0 : };
629 0 :
630 0 : async move {
631 0 : let mut drive_init = std::pin::pin!(drive_init);
632 0 : // just race these tasks
633 0 : tokio::select! {
634 0 : _ = shutdown_pageserver.cancelled() => {},
635 0 : _ = &mut drive_init => {},
636 : }
637 0 : }
638 0 : });
639 0 :
640 0 : let (secondary_controller, secondary_controller_tasks) = secondary::spawn_tasks(
641 0 : tenant_manager.clone(),
642 0 : remote_storage.clone(),
643 0 : background_jobs_barrier.clone(),
644 0 : shutdown_pageserver.clone(),
645 0 : );
646 0 :
647 0 : // shared state between the disk-usage backed eviction background task and the http endpoint
648 0 : // that allows triggering disk-usage based eviction manually. note that the http endpoint
649 0 : // is still accessible even if background task is not configured as long as remote storage has
650 0 : // been configured.
651 0 : let disk_usage_eviction_state: Arc<disk_usage_eviction_task::State> = Arc::default();
652 0 :
653 0 : let disk_usage_eviction_task = launch_disk_usage_global_eviction_task(
654 0 : conf,
655 0 : remote_storage.clone(),
656 0 : disk_usage_eviction_state.clone(),
657 0 : tenant_manager.clone(),
658 0 : background_jobs_barrier.clone(),
659 0 : );
660 :
661 : // Start up the service to handle HTTP mgmt API request. We created the
662 : // listener earlier already.
663 0 : let (http_endpoint_listener, https_endpoint_listener) = {
664 0 : let _rt_guard = MGMT_REQUEST_RUNTIME.enter(); // for hyper
665 :
666 0 : let router_state = Arc::new(
667 0 : http::routes::State::new(
668 0 : conf,
669 0 : tenant_manager.clone(),
670 0 : http_auth.clone(),
671 0 : remote_storage.clone(),
672 0 : broker_client.clone(),
673 0 : disk_usage_eviction_state,
674 0 : deletion_queue.new_client(),
675 0 : secondary_controller,
676 0 : )
677 0 : .context("Failed to initialize router state")?,
678 : );
679 :
680 0 : let router = http::make_router(router_state, launch_ts, http_auth.clone())?
681 0 : .build()
682 0 : .map_err(|err| anyhow!(err))?;
683 :
684 0 : let service =
685 0 : Arc::new(http_utils::RequestServiceBuilder::new(router).map_err(|err| anyhow!(err))?);
686 :
687 0 : let http_task = {
688 0 : let server =
689 0 : http_utils::server::Server::new(Arc::clone(&service), http_listener, None)?;
690 0 : let cancel = CancellationToken::new();
691 0 :
692 0 : let task = MGMT_REQUEST_RUNTIME.spawn(task_mgr::exit_on_panic_or_error(
693 0 : "http endpoint listener",
694 0 : server.serve(cancel.clone()),
695 0 : ));
696 0 : HttpEndpointListener(CancellableTask { task, cancel })
697 : };
698 :
699 0 : let https_task = match https_listener {
700 0 : Some(https_listener) => {
701 0 : let tls_server_config = tls_server_config
702 0 : .clone()
703 0 : .expect("tls_server_config is set earlier if https is enabled");
704 0 :
705 0 : let tls_acceptor = tokio_rustls::TlsAcceptor::from(tls_server_config);
706 :
707 0 : let server =
708 0 : http_utils::server::Server::new(service, https_listener, Some(tls_acceptor))?;
709 0 : let cancel = CancellationToken::new();
710 0 :
711 0 : let task = MGMT_REQUEST_RUNTIME.spawn(task_mgr::exit_on_panic_or_error(
712 0 : "https endpoint listener",
713 0 : server.serve(cancel.clone()),
714 0 : ));
715 0 : Some(HttpsEndpointListener(CancellableTask { task, cancel }))
716 : }
717 0 : None => None,
718 : };
719 :
720 0 : (http_task, https_task)
721 0 : };
722 0 :
723 0 : let consumption_metrics_tasks = {
724 0 : let cancel = shutdown_pageserver.child_token();
725 0 : let task = crate::BACKGROUND_RUNTIME.spawn({
726 0 : let tenant_manager = tenant_manager.clone();
727 0 : let cancel = cancel.clone();
728 0 : async move {
729 0 : // first wait until background jobs are cleared to launch.
730 0 : //
731 0 : // this is because we only process active tenants and timelines, and the
732 0 : // Timeline::get_current_logical_size will spawn the logical size calculation,
733 0 : // which will not be rate-limited.
734 0 : tokio::select! {
735 0 : _ = cancel.cancelled() => { return; },
736 0 : _ = background_jobs_barrier.wait() => {}
737 0 : };
738 0 :
739 0 : pageserver::consumption_metrics::run(conf, tenant_manager, cancel).await;
740 0 : }
741 0 : });
742 0 : ConsumptionMetricsTasks(CancellableTask { task, cancel })
743 0 : };
744 0 :
745 0 : // Spawn a task to listen for libpq connections. It will spawn further tasks
746 0 : // for each connection. We created the listener earlier already.
747 0 : let perf_trace_dispatch = otel_guard.as_ref().map(|g| g.dispatch.clone());
748 0 : let page_service = page_service::spawn(
749 0 : conf,
750 0 : tenant_manager.clone(),
751 0 : pg_auth,
752 0 : perf_trace_dispatch,
753 0 : {
754 0 : let _entered = COMPUTE_REQUEST_RUNTIME.enter(); // TcpListener::from_std requires it
755 0 : pageserver_listener
756 0 : .set_nonblocking(true)
757 0 : .context("set listener to nonblocking")?;
758 0 : tokio::net::TcpListener::from_std(pageserver_listener)
759 0 : .context("create tokio listener")?
760 : },
761 0 : if conf.enable_tls_page_service_api {
762 0 : tls_server_config
763 : } else {
764 0 : None
765 : },
766 : );
767 :
768 : // All started up! Now just sit and wait for shutdown signal.
769 0 : BACKGROUND_RUNTIME.block_on(async move {
770 0 : let signal_token = CancellationToken::new();
771 0 : let signal_cancel = signal_token.child_token();
772 0 :
773 0 : tokio::spawn(utils::signals::signal_handler(signal_token));
774 0 :
775 0 : // Wait for cancellation signal and shut down the pageserver.
776 0 : //
777 0 : // This cancels the `shutdown_pageserver` cancellation tree. Right now that tree doesn't
778 0 : // reach very far, and `task_mgr` is used instead. The plan is to change that over time.
779 0 : signal_cancel.cancelled().await;
780 :
781 0 : shutdown_pageserver.cancel();
782 0 : pageserver::shutdown_pageserver(
783 0 : http_endpoint_listener,
784 0 : https_endpoint_listener,
785 0 : page_service,
786 0 : consumption_metrics_tasks,
787 0 : disk_usage_eviction_task,
788 0 : &tenant_manager,
789 0 : background_purges,
790 0 : deletion_queue.clone(),
791 0 : secondary_controller_tasks,
792 0 : 0,
793 0 : )
794 0 : .await;
795 0 : unreachable!();
796 0 : })
797 0 : }
798 :
799 0 : async fn create_remote_storage_client(
800 0 : conf: &'static PageServerConf,
801 0 : ) -> anyhow::Result<GenericRemoteStorage> {
802 0 : let config = if let Some(config) = &conf.remote_storage_config {
803 0 : config
804 : } else {
805 0 : anyhow::bail!("no remote storage configured, this is a deprecated configuration");
806 : };
807 :
808 : // Create the client
809 0 : let mut remote_storage = GenericRemoteStorage::from_config(config).await?;
810 :
811 : // If `test_remote_failures` is non-zero, wrap the client with a
812 : // wrapper that simulates failures.
813 0 : if conf.test_remote_failures > 0 {
814 0 : if !cfg!(feature = "testing") {
815 0 : anyhow::bail!(
816 0 : "test_remote_failures option is not available because pageserver was compiled without the 'testing' feature"
817 0 : );
818 0 : }
819 0 : info!(
820 0 : "Simulating remote failures for first {} attempts of each op",
821 : conf.test_remote_failures
822 : );
823 0 : remote_storage =
824 0 : GenericRemoteStorage::unreliable_wrapper(remote_storage, conf.test_remote_failures);
825 0 : }
826 :
827 0 : Ok(remote_storage)
828 0 : }
829 :
830 12 : fn cli() -> Command {
831 12 : Command::new("Neon page server")
832 12 : .about("Materializes WAL stream to pages and serves them to the postgres")
833 12 : .version(version())
834 12 : .arg(
835 12 : Arg::new("workdir")
836 12 : .short('D')
837 12 : .long("workdir")
838 12 : .help("Working directory for the pageserver"),
839 12 : )
840 12 : .arg(
841 12 : Arg::new("enabled-features")
842 12 : .long("enabled-features")
843 12 : .action(ArgAction::SetTrue)
844 12 : .help("Show enabled compile time features"),
845 12 : )
846 12 : }
847 :
848 : #[test]
849 12 : fn verify_cli() {
850 12 : cli().debug_assert();
851 12 : }
|