LCOV - code coverage report
Current view: top level - pageserver/src/bin - pageserver.rs (source / functions) Coverage Total Hit
Test: 2e3a7638747e564a4f6d1af1cc0c3b3438fbb740.info Lines: 5.2 % 516 27
Test Date: 2024-11-20 01:36:58 Functions: 8.8 % 34 3

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

Generated by: LCOV version 2.1-beta