LCOV - code coverage report
Current view: top level - pageserver/src/bin - pageserver.rs (source / functions) Coverage Total Hit
Test: 32f4a56327bc9da697706839ed4836b2a00a408f.info Lines: 94.9 % 571 542
Test Date: 2024-02-07 07:37:29 Functions: 64.1 % 64 41

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

Generated by: LCOV version 2.1-beta