LCOV - code coverage report
Current view: top level - compute_tools/src/bin - compute_ctl.rs (source / functions) Coverage Total Hit
Test: 45c9170b95180e9ecfad9a53e031030abf2a178c.info Lines: 1.3 % 391 5
Test Date: 2025-02-21 15:51:08 Functions: 7.1 % 42 3

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

Generated by: LCOV version 2.1-beta