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

Generated by: LCOV version 2.1-beta