LCOV - code coverage report
Current view: top level - compute_tools/src/bin - compute_ctl.rs (source / functions) Coverage Total Hit
Test: 15f04989d2faf4ce76cecb56042184aca56ebae6.info Lines: 35.5 % 124 44
Test Date: 2025-07-14 11:50:36 Functions: 27.3 % 11 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              : //!             -c /var/db/postgres/configs/config.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::process::exit;
      39              : use std::sync::Arc;
      40              : use std::sync::atomic::AtomicU64;
      41              : use std::sync::mpsc;
      42              : use std::thread;
      43              : use std::time::Duration;
      44              : 
      45              : use anyhow::{Context, Result, bail};
      46              : use clap::Parser;
      47              : use compute_api::responses::ComputeConfig;
      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              : #[derive(Debug, Parser)]
      63              : #[command(rename_all = "kebab-case")]
      64              : struct Cli {
      65              :     #[arg(short = 'b', long, default_value = "postgres", env = "POSTGRES_PATH")]
      66              :     pub pgbin: String,
      67              : 
      68              :     /// The base URL for the remote extension storage proxy gateway.
      69              :     #[arg(short = 'r', long, value_parser = Self::parse_remote_ext_base_url)]
      70              :     pub remote_ext_base_url: Option<Url>,
      71              : 
      72              :     /// The port to bind the external listening HTTP server to. Clients running
      73              :     /// outside the compute will talk to the compute through this port. Keep
      74              :     /// the previous name for this argument around for a smoother release
      75              :     /// with the control plane.
      76              :     #[arg(long, default_value_t = 3080)]
      77              :     pub external_http_port: u16,
      78              : 
      79              :     /// The port to bind the internal listening HTTP server to. Clients include
      80              :     /// the neon extension (for installing remote extensions) and local_proxy.
      81              :     #[arg(long, default_value_t = 3081)]
      82              :     pub internal_http_port: u16,
      83              : 
      84              :     #[arg(short = 'D', long, value_name = "DATADIR")]
      85              :     pub pgdata: String,
      86              : 
      87              :     #[arg(short = 'C', long, value_name = "DATABASE_URL")]
      88              :     pub connstr: String,
      89              : 
      90              :     #[cfg(target_os = "linux")]
      91              :     #[arg(long, default_value = "neon-postgres")]
      92              :     pub cgroup: String,
      93              : 
      94              :     #[cfg(target_os = "linux")]
      95              :     #[arg(
      96              :         long,
      97              :         default_value = "host=localhost port=5432 dbname=postgres user=cloud_admin sslmode=disable application_name=vm-monitor"
      98              :     )]
      99              :     pub filecache_connstr: String,
     100              : 
     101              :     #[cfg(target_os = "linux")]
     102              :     #[arg(long, default_value = "0.0.0.0:10301")]
     103              :     pub vm_monitor_addr: String,
     104              : 
     105              :     #[arg(long, action = clap::ArgAction::SetTrue)]
     106              :     pub resize_swap_on_bind: bool,
     107              : 
     108              :     #[arg(long)]
     109              :     pub set_disk_quota_for_fs: Option<String>,
     110              : 
     111              :     #[arg(short = 'c', long)]
     112              :     pub config: Option<OsString>,
     113              : 
     114              :     #[arg(short = 'i', long, group = "compute-id")]
     115              :     pub compute_id: String,
     116              : 
     117              :     #[arg(
     118              :         short = 'p',
     119              :         long,
     120              :         conflicts_with = "config",
     121              :         value_name = "CONTROL_PLANE_API_BASE_URL",
     122              :         requires = "compute-id"
     123              :     )]
     124              :     pub control_plane_uri: Option<String>,
     125              : 
     126              :     /// Interval in seconds for collecting installed extensions statistics
     127              :     #[arg(long, default_value = "3600")]
     128              :     pub installed_extensions_collection_interval: u64,
     129              : 
     130              :     /// Run in development mode, skipping VM-specific operations like process termination
     131              :     #[arg(long, action = clap::ArgAction::SetTrue)]
     132              :     pub dev: bool,
     133              : }
     134              : 
     135              : impl Cli {
     136              :     /// Parse a URL from an argument. By default, this isn't necessary, but we
     137              :     /// want to do some sanity checking.
     138            3 :     fn parse_remote_ext_base_url(value: &str) -> Result<Url> {
     139              :         // Remove extra trailing slashes, and add one. We use Url::join() later
     140              :         // when downloading remote extensions. If the base URL is something like
     141              :         // http://example.com/pg-ext-s3-gateway, and join() is called with
     142              :         // something like "xyz", the resulting URL is http://example.com/xyz.
     143            3 :         let value = value.trim_end_matches('/').to_owned() + "/";
     144            3 :         let url = Url::parse(&value)?;
     145              : 
     146            3 :         if url.query_pairs().count() != 0 {
     147            1 :             bail!("parameters detected in remote extensions base URL")
     148            2 :         }
     149              : 
     150            2 :         Ok(url)
     151            3 :     }
     152              : }
     153              : 
     154            0 : fn main() -> Result<()> {
     155            0 :     let cli = Cli::parse();
     156              : 
     157            0 :     let scenario = failpoint_support::init();
     158              : 
     159              :     // For historical reasons, the main thread that processes the config and launches postgres
     160              :     // is synchronous, but we always have this tokio runtime available and we "enter" it so
     161              :     // that you can use tokio::spawn() and tokio::runtime::Handle::current().block_on(...)
     162              :     // from all parts of compute_ctl.
     163            0 :     let runtime = tokio::runtime::Builder::new_multi_thread()
     164            0 :         .enable_all()
     165            0 :         .build()?;
     166            0 :     let _rt_guard = runtime.enter();
     167              : 
     168            0 :     runtime.block_on(init(cli.dev))?;
     169              : 
     170              :     // enable core dumping for all child processes
     171            0 :     setrlimit(Resource::CORE, rlimit::INFINITY, rlimit::INFINITY)?;
     172              : 
     173            0 :     let connstr = Url::parse(&cli.connstr).context("cannot parse connstr as a URL")?;
     174              : 
     175            0 :     let config = get_config(&cli)?;
     176              : 
     177            0 :     let compute_node = ComputeNode::new(
     178            0 :         ComputeNodeParams {
     179            0 :             compute_id: cli.compute_id,
     180            0 :             connstr,
     181            0 :             pgdata: cli.pgdata.clone(),
     182            0 :             pgbin: cli.pgbin.clone(),
     183            0 :             pgversion: get_pg_version_string(&cli.pgbin),
     184            0 :             external_http_port: cli.external_http_port,
     185            0 :             internal_http_port: cli.internal_http_port,
     186            0 :             remote_ext_base_url: cli.remote_ext_base_url.clone(),
     187            0 :             resize_swap_on_bind: cli.resize_swap_on_bind,
     188            0 :             set_disk_quota_for_fs: cli.set_disk_quota_for_fs,
     189            0 :             #[cfg(target_os = "linux")]
     190            0 :             filecache_connstr: cli.filecache_connstr,
     191            0 :             #[cfg(target_os = "linux")]
     192            0 :             cgroup: cli.cgroup,
     193            0 :             #[cfg(target_os = "linux")]
     194            0 :             vm_monitor_addr: cli.vm_monitor_addr,
     195            0 :             installed_extensions_collection_interval: Arc::new(AtomicU64::new(
     196            0 :                 cli.installed_extensions_collection_interval,
     197            0 :             )),
     198            0 :         },
     199            0 :         config,
     200            0 :     )?;
     201              : 
     202            0 :     let exit_code = compute_node.run()?;
     203              : 
     204            0 :     scenario.teardown();
     205              : 
     206            0 :     deinit_and_exit(exit_code);
     207            0 : }
     208              : 
     209            0 : async fn init(dev_mode: bool) -> Result<()> {
     210            0 :     init_tracing_and_logging(DEFAULT_LOG_LEVEL).await?;
     211              : 
     212            0 :     let mut signals = Signals::new([SIGINT, SIGTERM, SIGQUIT])?;
     213            0 :     thread::spawn(move || {
     214            0 :         for sig in signals.forever() {
     215            0 :             handle_exit_signal(sig, dev_mode);
     216            0 :         }
     217            0 :     });
     218              : 
     219            0 :     info!("compute build_tag: {}", &BUILD_TAG.to_string());
     220              : 
     221            0 :     Ok(())
     222            0 : }
     223              : 
     224            0 : fn get_config(cli: &Cli) -> Result<ComputeConfig> {
     225              :     // First, read the config from the path if provided
     226            0 :     if let Some(ref config) = cli.config {
     227            0 :         let file = File::open(config)?;
     228            0 :         return Ok(serde_json::from_reader(&file)?);
     229            0 :     }
     230              : 
     231              :     // If the config wasn't provided in the CLI arguments, then retrieve it from
     232              :     // the control plane
     233            0 :     match get_config_from_control_plane(cli.control_plane_uri.as_ref().unwrap(), &cli.compute_id) {
     234            0 :         Ok(config) => Ok(config),
     235            0 :         Err(e) => {
     236            0 :             error!(
     237            0 :                 "cannot get response from control plane: {}\n\
     238            0 :                 neither spec nor confirmation that compute is in the Empty state was received",
     239              :                 e
     240              :             );
     241            0 :             Err(e)
     242              :         }
     243              :     }
     244            0 : }
     245              : 
     246            0 : fn deinit_and_exit(exit_code: Option<i32>) -> ! {
     247              :     // Shutdown trace pipeline gracefully, so that it has a chance to send any
     248              :     // pending traces before we exit. Shutting down OTEL tracing provider may
     249              :     // hang for quite some time, see, for example:
     250              :     // - https://github.com/open-telemetry/opentelemetry-rust/issues/868
     251              :     // - and our problems with staging https://github.com/neondatabase/cloud/issues/3707#issuecomment-1493983636
     252              :     //
     253              :     // Yet, we want computes to shut down fast enough, as we may need a new one
     254              :     // for the same timeline ASAP. So wait no longer than 2s for the shutdown to
     255              :     // complete, then just error out and exit the main thread.
     256            0 :     info!("shutting down tracing");
     257            0 :     let (sender, receiver) = mpsc::channel();
     258            0 :     let _ = thread::spawn(move || {
     259            0 :         tracing_utils::shutdown_tracing();
     260            0 :         sender.send(()).ok()
     261            0 :     });
     262            0 :     let shutdown_res = receiver.recv_timeout(Duration::from_millis(2000));
     263            0 :     if shutdown_res.is_err() {
     264            0 :         error!("timed out while shutting down tracing, exiting anyway");
     265            0 :     }
     266              : 
     267            0 :     info!("shutting down");
     268            0 :     exit(exit_code.unwrap_or(1))
     269              : }
     270              : 
     271              : /// When compute_ctl is killed, send also termination signal to sync-safekeepers
     272              : /// to prevent leakage. TODO: it is better to convert compute_ctl to async and
     273              : /// wait for termination which would be easy then.
     274            0 : fn handle_exit_signal(sig: i32, dev_mode: bool) {
     275            0 :     info!("received {sig} termination signal");
     276            0 :     forward_termination_signal(dev_mode);
     277            0 :     exit(1);
     278              : }
     279              : 
     280              : #[cfg(test)]
     281              : mod test {
     282              :     use clap::{CommandFactory, Parser};
     283              :     use url::Url;
     284              : 
     285              :     use super::Cli;
     286              : 
     287              :     #[test]
     288            1 :     fn verify_cli() {
     289            1 :         Cli::command().debug_assert()
     290            1 :     }
     291              : 
     292              :     #[test]
     293            1 :     fn verify_remote_ext_base_url() {
     294            1 :         let cli = Cli::parse_from([
     295            1 :             "compute_ctl",
     296            1 :             "--pgdata=test",
     297            1 :             "--connstr=test",
     298            1 :             "--compute-id=test",
     299            1 :             "--remote-ext-base-url",
     300            1 :             "https://example.com/subpath",
     301            1 :         ]);
     302            1 :         assert_eq!(
     303            1 :             cli.remote_ext_base_url.unwrap(),
     304            1 :             Url::parse("https://example.com/subpath/").unwrap()
     305              :         );
     306              : 
     307            1 :         let cli = Cli::parse_from([
     308            1 :             "compute_ctl",
     309            1 :             "--pgdata=test",
     310            1 :             "--connstr=test",
     311            1 :             "--compute-id=test",
     312            1 :             "--remote-ext-base-url",
     313            1 :             "https://example.com//",
     314            1 :         ]);
     315            1 :         assert_eq!(
     316            1 :             cli.remote_ext_base_url.unwrap(),
     317            1 :             Url::parse("https://example.com").unwrap()
     318              :         );
     319              : 
     320            1 :         Cli::try_parse_from([
     321            1 :             "compute_ctl",
     322            1 :             "--pgdata=test",
     323            1 :             "--connstr=test",
     324            1 :             "--compute-id=test",
     325            1 :             "--remote-ext-base-url",
     326            1 :             "https://example.com?hello=world",
     327            1 :         ])
     328            1 :         .expect_err("URL parameters are not allowed");
     329            1 :     }
     330              : }
        

Generated by: LCOV version 2.1-beta