LCOV - code coverage report
Current view: top level - pageserver/src/bin - pageserver.rs (source / functions) Coverage Total Hit
Test: 892dcde01f16175bbb7038896f6f080ec7094ee6.info Lines: 4.3 % 626 27
Test Date: 2025-05-22 14:16:19 Functions: 8.6 % 35 3

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

Generated by: LCOV version 2.1-beta