LCOV - code coverage report
Current view: top level - pageserver/src/bin - pageserver.rs (source / functions) Coverage Total Hit
Test: 465a86b0c1fda0069b3e0f6c1c126e6b635a1f72.info Lines: 7.8 % 553 43
Test Date: 2024-06-25 15:47:26 Functions: 8.3 % 36 3

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

Generated by: LCOV version 2.1-beta