LCOV - code coverage report
Current view: top level - compute_tools/src/bin - compute_ctl.rs (source / functions) Coverage Total Hit
Test: 6aa1d3391fe07ff9b962ba08ababc18abe4bbab3.info Lines: 1.0 % 403 4
Test Date: 2025-01-31 18:59:31 Functions: 5.6 % 36 2

            Line data    Source code
       1              : //!
       2              : //! Postgres wrapper (`compute_ctl`) is intended to be run as a Docker entrypoint or as a `systemd`
       3              : //! `ExecStart` option. It will handle all the `Neon` specifics during compute node
       4              : //! initialization:
       5              : //! - `compute_ctl` accepts cluster (compute node) specification as a JSON file.
       6              : //! - Every start is a fresh start, so the data directory is removed and
       7              : //!   initialized again on each run.
       8              : //! - If remote_extension_config is provided, it will be used to fetch extensions list
       9              : //!   and download `shared_preload_libraries` from the remote storage.
      10              : //! - Next it will put configuration files into the `PGDATA` directory.
      11              : //! - Sync safekeepers and get commit LSN.
      12              : //! - Get `basebackup` from pageserver using the returned on the previous step LSN.
      13              : //! - Try to start `postgres` and wait until it is ready to accept connections.
      14              : //! - Check and alter/drop/create roles and databases.
      15              : //! - Hang waiting on the `postmaster` process to exit.
      16              : //!
      17              : //! Also `compute_ctl` spawns two separate service threads:
      18              : //! - `compute-monitor` checks the last Postgres activity timestamp and saves it
      19              : //!   into the shared `ComputeNode`;
      20              : //! - `http-endpoint` runs a Hyper HTTP API server, which serves readiness and the
      21              : //!   last activity requests.
      22              : //!
      23              : //! If `AUTOSCALING` environment variable is set, `compute_ctl` will start the
      24              : //! `vm-monitor` located in [`neon/libs/vm_monitor`]. For VM compute nodes,
      25              : //! `vm-monitor` communicates with the VM autoscaling system. It coordinates
      26              : //! downscaling and requests immediate upscaling under resource pressure.
      27              : //!
      28              : //! Usage example:
      29              : //! ```sh
      30              : //! compute_ctl -D /var/db/postgres/compute \
      31              : //!             -C 'postgresql://cloud_admin@localhost/postgres' \
      32              : //!             -S /var/db/postgres/specs/current.json \
      33              : //!             -b /usr/local/bin/postgres \
      34              : //!             -r http://pg-ext-s3-gateway \
      35              : //! ```
      36              : use std::collections::HashMap;
      37              : use std::ffi::OsString;
      38              : use std::fs::File;
      39              : use std::path::Path;
      40              : use std::process::exit;
      41              : use std::str::FromStr;
      42              : use std::sync::atomic::Ordering;
      43              : use std::sync::{mpsc, Arc, Condvar, Mutex, RwLock};
      44              : use std::{thread, time::Duration};
      45              : 
      46              : use anyhow::{Context, Result};
      47              : use chrono::Utc;
      48              : use clap::Parser;
      49              : use compute_tools::disk_quota::set_disk_quota;
      50              : use compute_tools::lsn_lease::launch_lsn_lease_bg_task_for_static;
      51              : use signal_hook::consts::{SIGQUIT, SIGTERM};
      52              : use signal_hook::{consts::SIGINT, iterator::Signals};
      53              : use tracing::{error, info, warn};
      54              : use url::Url;
      55              : 
      56              : use compute_api::responses::ComputeStatus;
      57              : use compute_api::spec::ComputeSpec;
      58              : 
      59              : use compute_tools::compute::{
      60              :     forward_termination_signal, ComputeNode, ComputeState, ParsedSpec, PG_PID,
      61              : };
      62              : use compute_tools::configurator::launch_configurator;
      63              : use compute_tools::extension_server::get_pg_version_string;
      64              : use compute_tools::http::launch_http_server;
      65              : use compute_tools::logger::*;
      66              : use compute_tools::monitor::launch_monitor;
      67              : use compute_tools::params::*;
      68              : use compute_tools::spec::*;
      69              : use compute_tools::swap::resize_swap;
      70              : use rlimit::{setrlimit, Resource};
      71              : use utils::failpoint_support;
      72              : 
      73              : // this is an arbitrary build tag. Fine as a default / for testing purposes
      74              : // in-case of not-set environment var
      75              : const BUILD_TAG_DEFAULT: &str = "latest";
      76              : 
      77              : // Compatibility hack: if the control plane specified any remote-ext-config
      78              : // use the default value for extension storage proxy gateway.
      79              : // Remove this once the control plane is updated to pass the gateway URL
      80            0 : fn parse_remote_ext_config(arg: &str) -> Result<String> {
      81            0 :     if arg.starts_with("http") {
      82            0 :         Ok(arg.trim_end_matches('/').to_string())
      83              :     } else {
      84            0 :         Ok("http://pg-ext-s3-gateway".to_string())
      85              :     }
      86            0 : }
      87              : 
      88              : #[derive(Parser)]
      89              : #[command(rename_all = "kebab-case")]
      90              : struct Cli {
      91              :     #[arg(short = 'b', long, default_value = "postgres", env = "POSTGRES_PATH")]
      92            0 :     pub pgbin: String,
      93              : 
      94              :     #[arg(short = 'r', long, value_parser = parse_remote_ext_config)]
      95              :     pub remote_ext_config: Option<String>,
      96              : 
      97            1 :     #[arg(long, default_value_t = 3080)]
      98            0 :     pub http_port: u16,
      99              : 
     100              :     #[arg(short = 'D', long, value_name = "DATADIR")]
     101            0 :     pub pgdata: String,
     102              : 
     103              :     #[arg(short = 'C', long, value_name = "DATABASE_URL")]
     104            0 :     pub connstr: String,
     105              : 
     106              :     #[cfg(target_os = "linux")]
     107              :     #[arg(long, default_value = "neon-postgres")]
     108            0 :     pub cgroup: String,
     109              : 
     110              :     #[cfg(target_os = "linux")]
     111              :     #[arg(
     112              :         long,
     113              :         default_value = "host=localhost port=5432 dbname=postgres user=cloud_admin sslmode=disable application_name=vm-monitor"
     114              :     )]
     115            0 :     pub filecache_connstr: String,
     116              : 
     117              :     #[cfg(target_os = "linux")]
     118              :     #[arg(long, default_value = "0.0.0.0:10301")]
     119            0 :     pub vm_monitor_addr: String,
     120              : 
     121              :     #[arg(long, action = clap::ArgAction::SetTrue)]
     122            0 :     pub resize_swap_on_bind: bool,
     123              : 
     124              :     #[arg(long)]
     125              :     pub set_disk_quota_for_fs: Option<String>,
     126              : 
     127              :     #[arg(short = 's', long = "spec", group = "spec")]
     128              :     pub spec_json: Option<String>,
     129              : 
     130              :     #[arg(short = 'S', long, group = "spec-path")]
     131              :     pub spec_path: Option<OsString>,
     132              : 
     133              :     #[arg(short = 'i', long, group = "compute-id", conflicts_with_all = ["spec", "spec-path"])]
     134              :     pub compute_id: Option<String>,
     135              : 
     136              :     #[arg(short = 'p', long, conflicts_with_all = ["spec", "spec-path"], requires = "compute-id", value_name = "CONTROL_PLANE_API_BASE_URL")]
     137              :     pub control_plane_uri: Option<String>,
     138              : }
     139              : 
     140            0 : fn main() -> Result<()> {
     141            0 :     let cli = Cli::parse();
     142              : 
     143            0 :     let build_tag = init()?;
     144              : 
     145            0 :     let scenario = failpoint_support::init();
     146            0 : 
     147            0 :     // enable core dumping for all child processes
     148            0 :     setrlimit(Resource::CORE, rlimit::INFINITY, rlimit::INFINITY)?;
     149              : 
     150            0 :     let (pg_handle, start_pg_result) = {
     151              :         // Enter startup tracing context
     152            0 :         let _startup_context_guard = startup_context_from_env();
     153              : 
     154            0 :         let cli_spec = try_spec_from_cli(&cli)?;
     155              : 
     156            0 :         let compute = wait_spec(build_tag, &cli, cli_spec)?;
     157              : 
     158            0 :         start_postgres(&cli, compute)?
     159              : 
     160              :         // Startup is finished, exit the startup tracing span
     161              :     };
     162              : 
     163              :     // PostgreSQL is now running, if startup was successful. Wait until it exits.
     164            0 :     let wait_pg_result = wait_postgres(pg_handle)?;
     165              : 
     166            0 :     let delay_exit = cleanup_after_postgres_exit(start_pg_result)?;
     167              : 
     168            0 :     maybe_delay_exit(delay_exit);
     169            0 : 
     170            0 :     scenario.teardown();
     171            0 : 
     172            0 :     deinit_and_exit(wait_pg_result);
     173            0 : }
     174              : 
     175            0 : fn init() -> Result<String> {
     176            0 :     init_tracing_and_logging(DEFAULT_LOG_LEVEL)?;
     177              : 
     178            0 :     let mut signals = Signals::new([SIGINT, SIGTERM, SIGQUIT])?;
     179            0 :     thread::spawn(move || {
     180            0 :         for sig in signals.forever() {
     181            0 :             handle_exit_signal(sig);
     182            0 :         }
     183            0 :     });
     184            0 : 
     185            0 :     let build_tag = option_env!("BUILD_TAG")
     186            0 :         .unwrap_or(BUILD_TAG_DEFAULT)
     187            0 :         .to_string();
     188            0 :     info!("build_tag: {build_tag}");
     189              : 
     190            0 :     Ok(build_tag)
     191            0 : }
     192              : 
     193            0 : fn startup_context_from_env() -> Option<opentelemetry::ContextGuard> {
     194            0 :     // Extract OpenTelemetry context for the startup actions from the
     195            0 :     // TRACEPARENT and TRACESTATE env variables, and attach it to the current
     196            0 :     // tracing context.
     197            0 :     //
     198            0 :     // This is used to propagate the context for the 'start_compute' operation
     199            0 :     // from the neon control plane. This allows linking together the wider
     200            0 :     // 'start_compute' operation that creates the compute container, with the
     201            0 :     // startup actions here within the container.
     202            0 :     //
     203            0 :     // There is no standard for passing context in env variables, but a lot of
     204            0 :     // tools use TRACEPARENT/TRACESTATE, so we use that convention too. See
     205            0 :     // https://github.com/open-telemetry/opentelemetry-specification/issues/740
     206            0 :     //
     207            0 :     // Switch to the startup context here, and exit it once the startup has
     208            0 :     // completed and Postgres is up and running.
     209            0 :     //
     210            0 :     // If this pod is pre-created without binding it to any particular endpoint
     211            0 :     // yet, this isn't the right place to enter the startup context. In that
     212            0 :     // case, the control plane should pass the tracing context as part of the
     213            0 :     // /configure API call.
     214            0 :     //
     215            0 :     // NOTE: This is supposed to only cover the *startup* actions. Once
     216            0 :     // postgres is configured and up-and-running, we exit this span. Any other
     217            0 :     // actions that are performed on incoming HTTP requests, for example, are
     218            0 :     // performed in separate spans.
     219            0 :     //
     220            0 :     // XXX: If the pod is restarted, we perform the startup actions in the same
     221            0 :     // context as the original startup actions, which probably doesn't make
     222            0 :     // sense.
     223            0 :     let mut startup_tracing_carrier: HashMap<String, String> = HashMap::new();
     224            0 :     if let Ok(val) = std::env::var("TRACEPARENT") {
     225            0 :         startup_tracing_carrier.insert("traceparent".to_string(), val);
     226            0 :     }
     227            0 :     if let Ok(val) = std::env::var("TRACESTATE") {
     228            0 :         startup_tracing_carrier.insert("tracestate".to_string(), val);
     229            0 :     }
     230            0 :     if !startup_tracing_carrier.is_empty() {
     231              :         use opentelemetry::propagation::TextMapPropagator;
     232              :         use opentelemetry_sdk::propagation::TraceContextPropagator;
     233            0 :         let guard = TraceContextPropagator::new()
     234            0 :             .extract(&startup_tracing_carrier)
     235            0 :             .attach();
     236            0 :         info!("startup tracing context attached");
     237            0 :         Some(guard)
     238              :     } else {
     239            0 :         None
     240              :     }
     241            0 : }
     242              : 
     243            0 : fn try_spec_from_cli(cli: &Cli) -> Result<CliSpecParams> {
     244              :     // First, try to get cluster spec from the cli argument
     245            0 :     if let Some(ref spec_json) = cli.spec_json {
     246            0 :         info!("got spec from cli argument {}", spec_json);
     247              :         return Ok(CliSpecParams {
     248            0 :             spec: Some(serde_json::from_str(spec_json)?),
     249              :             live_config_allowed: false,
     250              :         });
     251            0 :     }
     252              : 
     253              :     // Second, try to read it from the file if path is provided
     254            0 :     if let Some(ref spec_path) = cli.spec_path {
     255            0 :         let file = File::open(Path::new(spec_path))?;
     256              :         return Ok(CliSpecParams {
     257            0 :             spec: Some(serde_json::from_reader(file)?),
     258              :             live_config_allowed: true,
     259              :         });
     260            0 :     }
     261            0 : 
     262            0 :     if cli.compute_id.is_none() {
     263            0 :         panic!(
     264            0 :             "compute spec should be provided by one of the following ways: \
     265            0 :                 --spec OR --spec-path OR --control-plane-uri and --compute-id"
     266            0 :         );
     267            0 :     };
     268            0 :     if cli.control_plane_uri.is_none() {
     269            0 :         panic!("must specify both --control-plane-uri and --compute-id or none");
     270            0 :     };
     271            0 : 
     272            0 :     match get_spec_from_control_plane(
     273            0 :         cli.control_plane_uri.as_ref().unwrap(),
     274            0 :         cli.compute_id.as_ref().unwrap(),
     275            0 :     ) {
     276            0 :         Ok(spec) => Ok(CliSpecParams {
     277            0 :             spec,
     278            0 :             live_config_allowed: true,
     279            0 :         }),
     280            0 :         Err(e) => {
     281            0 :             error!(
     282            0 :                 "cannot get response from control plane: {}\n\
     283            0 :                 neither spec nor confirmation that compute is in the Empty state was received",
     284              :                 e
     285              :             );
     286            0 :             Err(e)
     287              :         }
     288              :     }
     289            0 : }
     290              : 
     291              : struct CliSpecParams {
     292              :     /// If a spec was provided via CLI or file, the [`ComputeSpec`]
     293              :     spec: Option<ComputeSpec>,
     294              :     live_config_allowed: bool,
     295              : }
     296              : 
     297            0 : fn wait_spec(
     298            0 :     build_tag: String,
     299            0 :     cli: &Cli,
     300            0 :     CliSpecParams {
     301            0 :         spec,
     302            0 :         live_config_allowed,
     303            0 :     }: CliSpecParams,
     304            0 : ) -> Result<Arc<ComputeNode>> {
     305            0 :     let mut new_state = ComputeState::new();
     306              :     let spec_set;
     307              : 
     308            0 :     if let Some(spec) = spec {
     309            0 :         let pspec = ParsedSpec::try_from(spec).map_err(|msg| anyhow::anyhow!(msg))?;
     310            0 :         info!("new pspec.spec: {:?}", pspec.spec);
     311            0 :         new_state.pspec = Some(pspec);
     312            0 :         spec_set = true;
     313            0 :     } else {
     314            0 :         spec_set = false;
     315            0 :     }
     316            0 :     let connstr = Url::parse(&cli.connstr).context("cannot parse connstr as a URL")?;
     317            0 :     let conn_conf = postgres::config::Config::from_str(connstr.as_str())
     318            0 :         .context("cannot build postgres config from connstr")?;
     319            0 :     let tokio_conn_conf = tokio_postgres::config::Config::from_str(connstr.as_str())
     320            0 :         .context("cannot build tokio postgres config from connstr")?;
     321            0 :     let compute_node = ComputeNode {
     322            0 :         connstr,
     323            0 :         conn_conf,
     324            0 :         tokio_conn_conf,
     325            0 :         pgdata: cli.pgdata.clone(),
     326            0 :         pgbin: cli.pgbin.clone(),
     327            0 :         pgversion: get_pg_version_string(&cli.pgbin),
     328            0 :         http_port: cli.http_port,
     329            0 :         live_config_allowed,
     330            0 :         state: Mutex::new(new_state),
     331            0 :         state_changed: Condvar::new(),
     332            0 :         ext_remote_storage: cli.remote_ext_config.clone(),
     333            0 :         ext_download_progress: RwLock::new(HashMap::new()),
     334            0 :         build_tag,
     335            0 :     };
     336            0 :     let compute = Arc::new(compute_node);
     337            0 : 
     338            0 :     // If this is a pooled VM, prewarm before starting HTTP server and becoming
     339            0 :     // available for binding. Prewarming helps Postgres start quicker later,
     340            0 :     // because QEMU will already have its memory allocated from the host, and
     341            0 :     // the necessary binaries will already be cached.
     342            0 :     if !spec_set {
     343            0 :         compute.prewarm_postgres()?;
     344            0 :     }
     345              : 
     346              :     // Launch http service first, so that we can serve control-plane requests
     347              :     // while configuration is still in progress.
     348            0 :     let _http_handle =
     349            0 :         launch_http_server(cli.http_port, &compute).expect("cannot launch http endpoint thread");
     350            0 : 
     351            0 :     if !spec_set {
     352              :         // No spec provided, hang waiting for it.
     353            0 :         info!("no compute spec provided, waiting");
     354              : 
     355            0 :         let mut state = compute.state.lock().unwrap();
     356            0 :         while state.status != ComputeStatus::ConfigurationPending {
     357            0 :             state = compute.state_changed.wait(state).unwrap();
     358            0 : 
     359            0 :             if state.status == ComputeStatus::ConfigurationPending {
     360            0 :                 info!("got spec, continue configuration");
     361              :                 // Spec is already set by the http server handler.
     362            0 :                 break;
     363            0 :             }
     364              :         }
     365              : 
     366              :         // Record for how long we slept waiting for the spec.
     367            0 :         let now = Utc::now();
     368            0 :         state.metrics.wait_for_spec_ms = now
     369            0 :             .signed_duration_since(state.start_time)
     370            0 :             .to_std()
     371            0 :             .unwrap()
     372            0 :             .as_millis() as u64;
     373            0 : 
     374            0 :         // Reset start time, so that the total startup time that is calculated later will
     375            0 :         // not include the time that we waited for the spec.
     376            0 :         state.start_time = now;
     377            0 :     }
     378              : 
     379            0 :     launch_lsn_lease_bg_task_for_static(&compute);
     380            0 : 
     381            0 :     Ok(compute)
     382            0 : }
     383              : 
     384            0 : fn start_postgres(
     385            0 :     cli: &Cli,
     386            0 :     compute: Arc<ComputeNode>,
     387            0 : ) -> Result<(Option<PostgresHandle>, StartPostgresResult)> {
     388            0 :     // We got all we need, update the state.
     389            0 :     let mut state = compute.state.lock().unwrap();
     390            0 :     state.set_status(ComputeStatus::Init, &compute.state_changed);
     391            0 : 
     392            0 :     info!(
     393            0 :         "running compute with features: {:?}",
     394            0 :         state.pspec.as_ref().unwrap().spec.features
     395              :     );
     396              :     // before we release the mutex, fetch some parameters for later.
     397              :     let &ComputeSpec {
     398            0 :         swap_size_bytes,
     399            0 :         disk_quota_bytes,
     400            0 :         #[cfg(target_os = "linux")]
     401            0 :         disable_lfc_resizing,
     402            0 :         ..
     403            0 :     } = &state.pspec.as_ref().unwrap().spec;
     404            0 :     drop(state);
     405            0 : 
     406            0 :     // Launch remaining service threads
     407            0 :     let _monitor_handle = launch_monitor(&compute);
     408            0 :     let _configurator_handle = launch_configurator(&compute);
     409            0 : 
     410            0 :     let mut prestartup_failed = false;
     411            0 :     let mut delay_exit = false;
     412              : 
     413              :     // Resize swap to the desired size if the compute spec says so
     414            0 :     if let (Some(size_bytes), true) = (swap_size_bytes, cli.resize_swap_on_bind) {
     415              :         // To avoid 'swapoff' hitting postgres startup, we need to run resize-swap to completion
     416              :         // *before* starting postgres.
     417              :         //
     418              :         // In theory, we could do this asynchronously if SkipSwapon was enabled for VMs, but this
     419              :         // carries a risk of introducing hard-to-debug issues - e.g. if postgres sometimes gets
     420              :         // OOM-killed during startup because swap wasn't available yet.
     421            0 :         match resize_swap(size_bytes) {
     422              :             Ok(()) => {
     423            0 :                 let size_mib = size_bytes as f32 / (1 << 20) as f32; // just for more coherent display.
     424            0 :                 info!(%size_bytes, %size_mib, "resized swap");
     425              :             }
     426            0 :             Err(err) => {
     427            0 :                 let err = err.context("failed to resize swap");
     428            0 :                 error!("{err:#}");
     429              : 
     430              :                 // Mark compute startup as failed; don't try to start postgres, and report this
     431              :                 // error to the control plane when it next asks.
     432            0 :                 prestartup_failed = true;
     433            0 :                 compute.set_failed_status(err);
     434            0 :                 delay_exit = true;
     435              :             }
     436              :         }
     437            0 :     }
     438              : 
     439              :     // Set disk quota if the compute spec says so
     440            0 :     if let (Some(disk_quota_bytes), Some(disk_quota_fs_mountpoint)) =
     441            0 :         (disk_quota_bytes, cli.set_disk_quota_for_fs.as_ref())
     442              :     {
     443            0 :         match set_disk_quota(disk_quota_bytes, disk_quota_fs_mountpoint) {
     444              :             Ok(()) => {
     445            0 :                 let size_mib = disk_quota_bytes as f32 / (1 << 20) as f32; // just for more coherent display.
     446            0 :                 info!(%disk_quota_bytes, %size_mib, "set disk quota");
     447              :             }
     448            0 :             Err(err) => {
     449            0 :                 let err = err.context("failed to set disk quota");
     450            0 :                 error!("{err:#}");
     451              : 
     452              :                 // Mark compute startup as failed; don't try to start postgres, and report this
     453              :                 // error to the control plane when it next asks.
     454            0 :                 prestartup_failed = true;
     455            0 :                 compute.set_failed_status(err);
     456            0 :                 delay_exit = true;
     457              :             }
     458              :         }
     459            0 :     }
     460              : 
     461              :     // Start Postgres
     462            0 :     let mut pg = None;
     463            0 :     if !prestartup_failed {
     464            0 :         pg = match compute.start_compute() {
     465            0 :             Ok(pg) => {
     466            0 :                 info!(postmaster_pid = %pg.0.id(), "Postgres was started");
     467            0 :                 Some(pg)
     468              :             }
     469            0 :             Err(err) => {
     470            0 :                 error!("could not start the compute node: {:#}", err);
     471            0 :                 compute.set_failed_status(err);
     472            0 :                 delay_exit = true;
     473            0 :                 None
     474              :             }
     475              :         };
     476              :     } else {
     477            0 :         warn!("skipping postgres startup because pre-startup step failed");
     478              :     }
     479              : 
     480              :     // Start the vm-monitor if directed to. The vm-monitor only runs on linux
     481              :     // because it requires cgroups.
     482              :     cfg_if::cfg_if! {
     483              :         if #[cfg(target_os = "linux")] {
     484              :             use std::env;
     485              :             use tokio_util::sync::CancellationToken;
     486              : 
     487              :             // Note: it seems like you can make a runtime in an inner scope and
     488              :             // if you start a task in it it won't be dropped. However, make it
     489              :             // in the outermost scope just to be safe.
     490            0 :             let rt = if env::var_os("AUTOSCALING").is_some() {
     491            0 :                 Some(
     492            0 :                     tokio::runtime::Builder::new_multi_thread()
     493            0 :                         .worker_threads(4)
     494            0 :                         .enable_all()
     495            0 :                         .build()
     496            0 :                         .expect("failed to create tokio runtime for monitor")
     497            0 :                 )
     498              :             } else {
     499            0 :                 None
     500              :             };
     501              : 
     502              :             // This token is used internally by the monitor to clean up all threads
     503            0 :             let token = CancellationToken::new();
     504              : 
     505              :             // don't pass postgres connection string to vm-monitor if we don't want it to resize LFC
     506            0 :             let pgconnstr = if disable_lfc_resizing.unwrap_or(false) {
     507            0 :                 None
     508              :             } else {
     509            0 :                 Some(cli.filecache_connstr.clone())
     510              :             };
     511              : 
     512            0 :             let vm_monitor = rt.as_ref().map(|rt| {
     513            0 :                 rt.spawn(vm_monitor::start(
     514            0 :                     Box::leak(Box::new(vm_monitor::Args {
     515            0 :                         cgroup: Some(cli.cgroup.clone()),
     516            0 :                         pgconnstr,
     517            0 :                         addr: cli.vm_monitor_addr.clone(),
     518            0 :                     })),
     519            0 :                     token.clone(),
     520            0 :                 ))
     521            0 :             });
     522            0 :         }
     523            0 :     }
     524            0 : 
     525            0 :     Ok((
     526            0 :         pg,
     527            0 :         StartPostgresResult {
     528            0 :             delay_exit,
     529            0 :             compute,
     530            0 :             #[cfg(target_os = "linux")]
     531            0 :             rt,
     532            0 :             #[cfg(target_os = "linux")]
     533            0 :             token,
     534            0 :             #[cfg(target_os = "linux")]
     535            0 :             vm_monitor,
     536            0 :         },
     537            0 :     ))
     538            0 : }
     539              : 
     540              : type PostgresHandle = (std::process::Child, std::thread::JoinHandle<()>);
     541              : 
     542              : struct StartPostgresResult {
     543              :     delay_exit: bool,
     544              :     // passed through from WaitSpecResult
     545              :     compute: Arc<ComputeNode>,
     546              : 
     547              :     #[cfg(target_os = "linux")]
     548              :     rt: Option<tokio::runtime::Runtime>,
     549              :     #[cfg(target_os = "linux")]
     550              :     token: tokio_util::sync::CancellationToken,
     551              :     #[cfg(target_os = "linux")]
     552              :     vm_monitor: Option<tokio::task::JoinHandle<Result<()>>>,
     553              : }
     554              : 
     555            0 : fn wait_postgres(pg: Option<PostgresHandle>) -> Result<WaitPostgresResult> {
     556            0 :     // Wait for the child Postgres process forever. In this state Ctrl+C will
     557            0 :     // propagate to Postgres and it will be shut down as well.
     558            0 :     let mut exit_code = None;
     559            0 :     if let Some((mut pg, logs_handle)) = pg {
     560            0 :         info!(postmaster_pid = %pg.id(), "Waiting for Postgres to exit");
     561              : 
     562            0 :         let ecode = pg
     563            0 :             .wait()
     564            0 :             .expect("failed to start waiting on Postgres process");
     565            0 :         PG_PID.store(0, Ordering::SeqCst);
     566            0 : 
     567            0 :         // Process has exited, so we can join the logs thread.
     568            0 :         let _ = logs_handle
     569            0 :             .join()
     570            0 :             .map_err(|e| tracing::error!("log thread panicked: {:?}", e));
     571            0 : 
     572            0 :         info!("Postgres exited with code {}, shutting down", ecode);
     573            0 :         exit_code = ecode.code()
     574            0 :     }
     575              : 
     576            0 :     Ok(WaitPostgresResult { exit_code })
     577            0 : }
     578              : 
     579              : struct WaitPostgresResult {
     580              :     exit_code: Option<i32>,
     581              : }
     582              : 
     583            0 : fn cleanup_after_postgres_exit(
     584            0 :     StartPostgresResult {
     585            0 :         mut delay_exit,
     586            0 :         compute,
     587            0 :         #[cfg(target_os = "linux")]
     588            0 :         vm_monitor,
     589            0 :         #[cfg(target_os = "linux")]
     590            0 :         token,
     591            0 :         #[cfg(target_os = "linux")]
     592            0 :         rt,
     593            0 :     }: StartPostgresResult,
     594            0 : ) -> Result<bool> {
     595              :     // Terminate the vm_monitor so it releases the file watcher on
     596              :     // /sys/fs/cgroup/neon-postgres.
     597              :     // Note: the vm-monitor only runs on linux because it requires cgroups.
     598              :     cfg_if::cfg_if! {
     599              :         if #[cfg(target_os = "linux")] {
     600            0 :             if let Some(handle) = vm_monitor {
     601            0 :                 // Kills all threads spawned by the monitor
     602            0 :                 token.cancel();
     603            0 :                 // Kills the actual task running the monitor
     604            0 :                 handle.abort();
     605            0 : 
     606            0 :                 // If handle is some, rt must have been used to produce it, and
     607            0 :                 // hence is also some
     608            0 :                 rt.unwrap().shutdown_timeout(Duration::from_secs(2));
     609            0 :             }
     610              :         }
     611              :     }
     612              : 
     613              :     // Maybe sync safekeepers again, to speed up next startup
     614            0 :     let compute_state = compute.state.lock().unwrap().clone();
     615            0 :     let pspec = compute_state.pspec.as_ref().expect("spec must be set");
     616            0 :     if matches!(pspec.spec.mode, compute_api::spec::ComputeMode::Primary) {
     617            0 :         info!("syncing safekeepers on shutdown");
     618            0 :         let storage_auth_token = pspec.storage_auth_token.clone();
     619            0 :         let lsn = compute.sync_safekeepers(storage_auth_token)?;
     620            0 :         info!("synced safekeepers at lsn {lsn}");
     621            0 :     }
     622              : 
     623            0 :     let mut state = compute.state.lock().unwrap();
     624            0 :     if state.status == ComputeStatus::TerminationPending {
     625            0 :         state.status = ComputeStatus::Terminated;
     626            0 :         compute.state_changed.notify_all();
     627            0 :         // we were asked to terminate gracefully, don't exit to avoid restart
     628            0 :         delay_exit = true
     629            0 :     }
     630            0 :     drop(state);
     631              : 
     632            0 :     if let Err(err) = compute.check_for_core_dumps() {
     633            0 :         error!("error while checking for core dumps: {err:?}");
     634            0 :     }
     635              : 
     636            0 :     Ok(delay_exit)
     637            0 : }
     638              : 
     639            0 : fn maybe_delay_exit(delay_exit: bool) {
     640            0 :     // If launch failed, keep serving HTTP requests for a while, so the cloud
     641            0 :     // control plane can get the actual error.
     642            0 :     if delay_exit {
     643            0 :         info!("giving control plane 30s to collect the error before shutdown");
     644            0 :         thread::sleep(Duration::from_secs(30));
     645            0 :     }
     646            0 : }
     647              : 
     648            0 : fn deinit_and_exit(WaitPostgresResult { exit_code }: WaitPostgresResult) -> ! {
     649            0 :     // Shutdown trace pipeline gracefully, so that it has a chance to send any
     650            0 :     // pending traces before we exit. Shutting down OTEL tracing provider may
     651            0 :     // hang for quite some time, see, for example:
     652            0 :     // - https://github.com/open-telemetry/opentelemetry-rust/issues/868
     653            0 :     // - and our problems with staging https://github.com/neondatabase/cloud/issues/3707#issuecomment-1493983636
     654            0 :     //
     655            0 :     // Yet, we want computes to shut down fast enough, as we may need a new one
     656            0 :     // for the same timeline ASAP. So wait no longer than 2s for the shutdown to
     657            0 :     // complete, then just error out and exit the main thread.
     658            0 :     info!("shutting down tracing");
     659            0 :     let (sender, receiver) = mpsc::channel();
     660            0 :     let _ = thread::spawn(move || {
     661            0 :         tracing_utils::shutdown_tracing();
     662            0 :         sender.send(()).ok()
     663            0 :     });
     664            0 :     let shutdown_res = receiver.recv_timeout(Duration::from_millis(2000));
     665            0 :     if shutdown_res.is_err() {
     666            0 :         error!("timed out while shutting down tracing, exiting anyway");
     667            0 :     }
     668              : 
     669            0 :     info!("shutting down");
     670            0 :     exit(exit_code.unwrap_or(1))
     671              : }
     672              : 
     673              : /// When compute_ctl is killed, send also termination signal to sync-safekeepers
     674              : /// to prevent leakage. TODO: it is better to convert compute_ctl to async and
     675              : /// wait for termination which would be easy then.
     676            0 : fn handle_exit_signal(sig: i32) {
     677            0 :     info!("received {sig} termination signal");
     678            0 :     forward_termination_signal();
     679            0 :     exit(1);
     680              : }
     681              : 
     682              : #[cfg(test)]
     683              : mod test {
     684              :     use clap::CommandFactory;
     685              : 
     686              :     use super::Cli;
     687              : 
     688              :     #[test]
     689            1 :     fn verify_cli() {
     690            1 :         Cli::command().debug_assert()
     691            1 :     }
     692              : }
        

Generated by: LCOV version 2.1-beta