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

Generated by: LCOV version 2.1-beta