LCOV - code coverage report
Current view: top level - compute_tools/src/bin - compute_ctl.rs (source / functions) Coverage Total Hit
Test: 98683a8629f0f7f0031d02e04512998d589d76ea.info Lines: 4.1 % 122 5
Test Date: 2025-04-11 16:58:57 Functions: 8.8 % 34 3

            Line data    Source code
       1              : //!
       2              : //! Postgres wrapper (`compute_ctl`) is intended to be run as a Docker entrypoint or as a `systemd`
       3              : //! `ExecStart` option. It will handle all the `Neon` specifics during compute node
       4              : //! initialization:
       5              : //! - `compute_ctl` accepts cluster (compute node) specification as a JSON file.
       6              : //! - Every start is a fresh start, so the data directory is removed and
       7              : //!   initialized again on each run.
       8              : //! - If remote_extension_config is provided, it will be used to fetch extensions list
       9              : //!   and download `shared_preload_libraries` from the remote storage.
      10              : //! - Next it will put configuration files into the `PGDATA` directory.
      11              : //! - Sync safekeepers and get commit LSN.
      12              : //! - Get `basebackup` from pageserver using the returned on the previous step LSN.
      13              : //! - Try to start `postgres` and wait until it is ready to accept connections.
      14              : //! - Check and alter/drop/create roles and databases.
      15              : //! - Hang waiting on the `postmaster` process to exit.
      16              : //!
      17              : //! Also `compute_ctl` spawns two separate service threads:
      18              : //! - `compute-monitor` checks the last Postgres activity timestamp and saves it
      19              : //!   into the shared `ComputeNode`;
      20              : //! - `http-endpoint` runs a Hyper HTTP API server, which serves readiness and the
      21              : //!   last activity requests.
      22              : //!
      23              : //! If `AUTOSCALING` environment variable is set, `compute_ctl` will start the
      24              : //! `vm-monitor` located in [`neon/libs/vm_monitor`]. For VM compute nodes,
      25              : //! `vm-monitor` communicates with the VM autoscaling system. It coordinates
      26              : //! downscaling and requests immediate upscaling under resource pressure.
      27              : //!
      28              : //! Usage example:
      29              : //! ```sh
      30              : //! compute_ctl -D /var/db/postgres/compute \
      31              : //!             -C 'postgresql://cloud_admin@localhost/postgres' \
      32              : //!             -S /var/db/postgres/specs/current.json \
      33              : //!             -b /usr/local/bin/postgres \
      34              : //!             -r http://pg-ext-s3-gateway \
      35              : //! ```
      36              : use std::ffi::OsString;
      37              : use std::fs::File;
      38              : use std::path::Path;
      39              : use std::process::exit;
      40              : use std::sync::mpsc;
      41              : use std::thread;
      42              : use std::time::Duration;
      43              : 
      44              : use anyhow::{Context, Result};
      45              : use clap::Parser;
      46              : use compute_api::responses::ComputeCtlConfig;
      47              : use compute_api::spec::ComputeSpec;
      48              : use compute_tools::compute::{
      49              :     BUILD_TAG, ComputeNode, ComputeNodeParams, forward_termination_signal,
      50              : };
      51              : use compute_tools::extension_server::get_pg_version_string;
      52              : use compute_tools::logger::*;
      53              : use compute_tools::params::*;
      54              : use compute_tools::spec::*;
      55              : use rlimit::{Resource, setrlimit};
      56              : use signal_hook::consts::{SIGINT, SIGQUIT, SIGTERM};
      57              : use signal_hook::iterator::Signals;
      58              : use tracing::{error, info};
      59              : use url::Url;
      60              : use utils::failpoint_support;
      61              : 
      62              : // Compatibility hack: if the control plane specified any remote-ext-config
      63              : // use the default value for extension storage proxy gateway.
      64              : // Remove this once the control plane is updated to pass the gateway URL
      65            0 : fn parse_remote_ext_config(arg: &str) -> Result<String> {
      66            0 :     if arg.starts_with("http") {
      67            0 :         Ok(arg.trim_end_matches('/').to_string())
      68              :     } else {
      69            0 :         Ok("http://pg-ext-s3-gateway".to_string())
      70              :     }
      71            0 : }
      72              : 
      73              : #[derive(Parser)]
      74              : #[command(rename_all = "kebab-case")]
      75              : struct Cli {
      76              :     #[arg(short = 'b', long, default_value = "postgres", env = "POSTGRES_PATH")]
      77            0 :     pub pgbin: String,
      78              : 
      79              :     #[arg(short = 'r', long, value_parser = parse_remote_ext_config)]
      80              :     pub remote_ext_config: Option<String>,
      81              : 
      82              :     /// The port to bind the external listening HTTP server to. Clients running
      83              :     /// outside the compute will talk to the compute through this port. Keep
      84              :     /// the previous name for this argument around for a smoother release
      85              :     /// with the control plane.
      86            1 :     #[arg(long, default_value_t = 3080)]
      87            0 :     pub external_http_port: u16,
      88              : 
      89              :     /// The port to bind the internal listening HTTP server to. Clients include
      90              :     /// the neon extension (for installing remote extensions) and local_proxy.
      91            1 :     #[arg(long, default_value_t = 3081)]
      92            0 :     pub internal_http_port: u16,
      93              : 
      94              :     #[arg(short = 'D', long, value_name = "DATADIR")]
      95            0 :     pub pgdata: String,
      96              : 
      97              :     #[arg(short = 'C', long, value_name = "DATABASE_URL")]
      98            0 :     pub connstr: String,
      99              : 
     100              :     #[cfg(target_os = "linux")]
     101              :     #[arg(long, default_value = "neon-postgres")]
     102            0 :     pub cgroup: String,
     103              : 
     104              :     #[cfg(target_os = "linux")]
     105              :     #[arg(
     106              :         long,
     107              :         default_value = "host=localhost port=5432 dbname=postgres user=cloud_admin sslmode=disable application_name=vm-monitor"
     108              :     )]
     109            0 :     pub filecache_connstr: String,
     110              : 
     111              :     #[cfg(target_os = "linux")]
     112              :     #[arg(long, default_value = "0.0.0.0:10301")]
     113            0 :     pub vm_monitor_addr: String,
     114              : 
     115              :     #[arg(long, action = clap::ArgAction::SetTrue)]
     116            0 :     pub resize_swap_on_bind: bool,
     117              : 
     118              :     #[arg(long)]
     119              :     pub set_disk_quota_for_fs: Option<String>,
     120              : 
     121              :     #[arg(short = 'S', long, group = "spec-path")]
     122              :     pub spec_path: Option<OsString>,
     123              : 
     124              :     #[arg(short = 'i', long, group = "compute-id")]
     125            0 :     pub compute_id: String,
     126              : 
     127              :     #[arg(
     128              :         short = 'p',
     129              :         long,
     130              :         conflicts_with = "spec-path",
     131              :         value_name = "CONTROL_PLANE_API_BASE_URL"
     132              :     )]
     133              :     pub control_plane_uri: Option<String>,
     134              : }
     135              : 
     136            0 : fn main() -> Result<()> {
     137            0 :     let cli = Cli::parse();
     138            0 : 
     139            0 :     let scenario = failpoint_support::init();
     140              : 
     141              :     // For historical reasons, the main thread that processes the spec and launches postgres
     142              :     // is synchronous, but we always have this tokio runtime available and we "enter" it so
     143              :     // that you can use tokio::spawn() and tokio::runtime::Handle::current().block_on(...)
     144              :     // from all parts of compute_ctl.
     145            0 :     let runtime = tokio::runtime::Builder::new_multi_thread()
     146            0 :         .enable_all()
     147            0 :         .build()?;
     148            0 :     let _rt_guard = runtime.enter();
     149            0 : 
     150            0 :     runtime.block_on(init())?;
     151              : 
     152              :     // enable core dumping for all child processes
     153            0 :     setrlimit(Resource::CORE, rlimit::INFINITY, rlimit::INFINITY)?;
     154              : 
     155            0 :     let connstr = Url::parse(&cli.connstr).context("cannot parse connstr as a URL")?;
     156              : 
     157            0 :     let cli_spec = try_spec_from_cli(&cli)?;
     158              : 
     159            0 :     let compute_node = ComputeNode::new(
     160            0 :         ComputeNodeParams {
     161            0 :             compute_id: cli.compute_id,
     162            0 :             connstr,
     163            0 :             pgdata: cli.pgdata.clone(),
     164            0 :             pgbin: cli.pgbin.clone(),
     165            0 :             pgversion: get_pg_version_string(&cli.pgbin),
     166            0 :             external_http_port: cli.external_http_port,
     167            0 :             internal_http_port: cli.internal_http_port,
     168            0 :             ext_remote_storage: cli.remote_ext_config.clone(),
     169            0 :             resize_swap_on_bind: cli.resize_swap_on_bind,
     170            0 :             set_disk_quota_for_fs: cli.set_disk_quota_for_fs,
     171            0 :             #[cfg(target_os = "linux")]
     172            0 :             filecache_connstr: cli.filecache_connstr,
     173            0 :             #[cfg(target_os = "linux")]
     174            0 :             cgroup: cli.cgroup,
     175            0 :             #[cfg(target_os = "linux")]
     176            0 :             vm_monitor_addr: cli.vm_monitor_addr,
     177            0 :         },
     178            0 :         cli_spec.spec,
     179            0 :         cli_spec.compute_ctl_config,
     180            0 :     )?;
     181              : 
     182            0 :     let exit_code = compute_node.run()?;
     183              : 
     184            0 :     scenario.teardown();
     185            0 : 
     186            0 :     deinit_and_exit(exit_code);
     187            0 : }
     188              : 
     189            0 : async fn init() -> Result<()> {
     190            0 :     init_tracing_and_logging(DEFAULT_LOG_LEVEL).await?;
     191              : 
     192            0 :     let mut signals = Signals::new([SIGINT, SIGTERM, SIGQUIT])?;
     193            0 :     thread::spawn(move || {
     194            0 :         for sig in signals.forever() {
     195            0 :             handle_exit_signal(sig);
     196            0 :         }
     197            0 :     });
     198            0 : 
     199            0 :     info!("compute build_tag: {}", &BUILD_TAG.to_string());
     200              : 
     201            0 :     Ok(())
     202            0 : }
     203              : 
     204            0 : fn try_spec_from_cli(cli: &Cli) -> Result<CliSpecParams> {
     205              :     // First, read spec from the path if provided
     206            0 :     if let Some(ref spec_path) = cli.spec_path {
     207            0 :         let file = File::open(Path::new(spec_path))?;
     208              :         return Ok(CliSpecParams {
     209            0 :             spec: Some(serde_json::from_reader(file)?),
     210            0 :             compute_ctl_config: ComputeCtlConfig::default(),
     211              :         });
     212            0 :     }
     213            0 : 
     214            0 :     if cli.control_plane_uri.is_none() {
     215            0 :         panic!("must specify --control-plane-uri");
     216            0 :     };
     217            0 : 
     218            0 :     // If the spec wasn't provided in the CLI arguments, then retrieve it from
     219            0 :     // the control plane
     220            0 :     match get_spec_from_control_plane(cli.control_plane_uri.as_ref().unwrap(), &cli.compute_id) {
     221            0 :         Ok(resp) => Ok(CliSpecParams {
     222            0 :             spec: resp.0,
     223            0 :             compute_ctl_config: resp.1,
     224            0 :         }),
     225            0 :         Err(e) => {
     226            0 :             error!(
     227            0 :                 "cannot get response from control plane: {}\n\
     228            0 :                 neither spec nor confirmation that compute is in the Empty state was received",
     229              :                 e
     230              :             );
     231            0 :             Err(e)
     232              :         }
     233              :     }
     234            0 : }
     235              : 
     236              : struct CliSpecParams {
     237              :     /// If a spec was provided via CLI or file, the [`ComputeSpec`]
     238              :     spec: Option<ComputeSpec>,
     239              :     #[allow(dead_code)]
     240              :     compute_ctl_config: ComputeCtlConfig,
     241              : }
     242              : 
     243            0 : fn deinit_and_exit(exit_code: Option<i32>) -> ! {
     244            0 :     // Shutdown trace pipeline gracefully, so that it has a chance to send any
     245            0 :     // pending traces before we exit. Shutting down OTEL tracing provider may
     246            0 :     // hang for quite some time, see, for example:
     247            0 :     // - https://github.com/open-telemetry/opentelemetry-rust/issues/868
     248            0 :     // - and our problems with staging https://github.com/neondatabase/cloud/issues/3707#issuecomment-1493983636
     249            0 :     //
     250            0 :     // Yet, we want computes to shut down fast enough, as we may need a new one
     251            0 :     // for the same timeline ASAP. So wait no longer than 2s for the shutdown to
     252            0 :     // complete, then just error out and exit the main thread.
     253            0 :     info!("shutting down tracing");
     254            0 :     let (sender, receiver) = mpsc::channel();
     255            0 :     let _ = thread::spawn(move || {
     256            0 :         tracing_utils::shutdown_tracing();
     257            0 :         sender.send(()).ok()
     258            0 :     });
     259            0 :     let shutdown_res = receiver.recv_timeout(Duration::from_millis(2000));
     260            0 :     if shutdown_res.is_err() {
     261            0 :         error!("timed out while shutting down tracing, exiting anyway");
     262            0 :     }
     263              : 
     264            0 :     info!("shutting down");
     265            0 :     exit(exit_code.unwrap_or(1))
     266              : }
     267              : 
     268              : /// When compute_ctl is killed, send also termination signal to sync-safekeepers
     269              : /// to prevent leakage. TODO: it is better to convert compute_ctl to async and
     270              : /// wait for termination which would be easy then.
     271            0 : fn handle_exit_signal(sig: i32) {
     272            0 :     info!("received {sig} termination signal");
     273            0 :     forward_termination_signal();
     274            0 :     exit(1);
     275              : }
     276              : 
     277              : #[cfg(test)]
     278              : mod test {
     279              :     use clap::CommandFactory;
     280              : 
     281              :     use super::Cli;
     282              : 
     283              :     #[test]
     284            1 :     fn verify_cli() {
     285            1 :         Cli::command().debug_assert()
     286            1 :     }
     287              : }
        

Generated by: LCOV version 2.1-beta