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

Generated by: LCOV version 2.1-beta