LCOV - code coverage report
Current view: top level - pageserver/src/bin - pageserver.rs (source / functions) Coverage Total Hit
Test: 91bf6c8f32e5e69adde6241313e732fdd6d6e277.info Lines: 5.0 % 538 27
Test Date: 2025-03-04 12:19:20 Functions: 8.6 % 35 3

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

Generated by: LCOV version 2.1-beta