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

Generated by: LCOV version 2.1-beta