LCOV - code coverage report
Current view: top level - control_plane/src - endpoint.rs (source / functions) Coverage Total Hit
Test: 65975feb441523e1ae5866ecbec0610188cb8ce3.info Lines: 0.0 % 643 0
Test Date: 2025-02-12 20:31:43 Functions: 0.0 % 46 0

            Line data    Source code
       1              : //! Code to manage compute endpoints
       2              : //!
       3              : //! In the local test environment, the data for each endpoint is stored in
       4              : //!
       5              : //! ```text
       6              : //!   .neon/endpoints/<endpoint id>
       7              : //! ```
       8              : //!
       9              : //! Some basic information about the endpoint, like the tenant and timeline IDs,
      10              : //! are stored in the `endpoint.json` file. The `endpoint.json` file is created
      11              : //! when the endpoint is created, and doesn't change afterwards.
      12              : //!
      13              : //! The endpoint is managed by the `compute_ctl` binary. When an endpoint is
      14              : //! started, we launch `compute_ctl` It synchronizes the safekeepers, downloads
      15              : //! the basebackup from the pageserver to initialize the data directory, and
      16              : //! finally launches the PostgreSQL process. It watches the PostgreSQL process
      17              : //! until it exits.
      18              : //!
      19              : //! When an endpoint is created, a `postgresql.conf` file is also created in
      20              : //! the endpoint's directory. The file can be modified before starting PostgreSQL.
      21              : //! However, the `postgresql.conf` file in the endpoint directory is not used directly
      22              : //! by PostgreSQL. It is passed to `compute_ctl`, and `compute_ctl` writes another
      23              : //! copy of it in the data directory.
      24              : //!
      25              : //! Directory contents:
      26              : //!
      27              : //! ```text
      28              : //! .neon/endpoints/main/
      29              : //!     compute.log               - log output of `compute_ctl` and `postgres`
      30              : //!     endpoint.json             - serialized `EndpointConf` struct
      31              : //!     postgresql.conf           - postgresql settings
      32              : //!     spec.json                 - passed to `compute_ctl`
      33              : //!     pgdata/
      34              : //!         postgresql.conf       - copy of postgresql.conf created by `compute_ctl`
      35              : //!         zenith.signal
      36              : //!         <other PostgreSQL files>
      37              : //! ```
      38              : //!
      39              : use std::collections::BTreeMap;
      40              : use std::net::IpAddr;
      41              : use std::net::Ipv4Addr;
      42              : use std::net::SocketAddr;
      43              : use std::net::TcpStream;
      44              : use std::path::PathBuf;
      45              : use std::process::Command;
      46              : use std::str::FromStr;
      47              : use std::sync::Arc;
      48              : use std::time::Duration;
      49              : 
      50              : use anyhow::{anyhow, bail, Context, Result};
      51              : use compute_api::spec::Database;
      52              : use compute_api::spec::PgIdent;
      53              : use compute_api::spec::RemoteExtSpec;
      54              : use compute_api::spec::Role;
      55              : use nix::sys::signal::kill;
      56              : use nix::sys::signal::Signal;
      57              : use pageserver_api::shard::ShardStripeSize;
      58              : use reqwest::header::CONTENT_TYPE;
      59              : use serde::{Deserialize, Serialize};
      60              : use url::Host;
      61              : use utils::id::{NodeId, TenantId, TimelineId};
      62              : 
      63              : use crate::local_env::LocalEnv;
      64              : use crate::postgresql_conf::PostgresConf;
      65              : use crate::storage_controller::StorageController;
      66              : 
      67              : use compute_api::responses::{ComputeStatus, ComputeStatusResponse};
      68              : use compute_api::spec::{Cluster, ComputeFeature, ComputeMode, ComputeSpec};
      69              : 
      70              : // contents of a endpoint.json file
      71            0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
      72              : pub struct EndpointConf {
      73              :     endpoint_id: String,
      74              :     tenant_id: TenantId,
      75              :     timeline_id: TimelineId,
      76              :     mode: ComputeMode,
      77              :     pg_port: u16,
      78              :     external_http_port: u16,
      79              :     internal_http_port: u16,
      80              :     pg_version: u32,
      81              :     skip_pg_catalog_updates: bool,
      82              :     drop_subscriptions_before_start: bool,
      83              :     features: Vec<ComputeFeature>,
      84              : }
      85              : 
      86              : //
      87              : // ComputeControlPlane
      88              : //
      89              : pub struct ComputeControlPlane {
      90              :     base_port: u16,
      91              : 
      92              :     // endpoint ID is the key
      93              :     pub endpoints: BTreeMap<String, Arc<Endpoint>>,
      94              : 
      95              :     env: LocalEnv,
      96              : }
      97              : 
      98              : impl ComputeControlPlane {
      99              :     // Load current endpoints from the endpoints/ subdirectories
     100            0 :     pub fn load(env: LocalEnv) -> Result<ComputeControlPlane> {
     101            0 :         let mut endpoints = BTreeMap::default();
     102            0 :         for endpoint_dir in std::fs::read_dir(env.endpoints_path())
     103            0 :             .with_context(|| format!("failed to list {}", env.endpoints_path().display()))?
     104              :         {
     105            0 :             let ep_res = Endpoint::from_dir_entry(endpoint_dir?, &env);
     106            0 :             let ep = match ep_res {
     107            0 :                 Ok(ep) => ep,
     108            0 :                 Err(e) => match e.downcast::<std::io::Error>() {
     109            0 :                     Ok(e) => {
     110            0 :                         // A parallel task could delete an endpoint while we have just scanned the directory
     111            0 :                         if e.kind() == std::io::ErrorKind::NotFound {
     112            0 :                             continue;
     113              :                         } else {
     114            0 :                             Err(e)?
     115              :                         }
     116              :                     }
     117            0 :                     Err(e) => Err(e)?,
     118              :                 },
     119              :             };
     120            0 :             endpoints.insert(ep.endpoint_id.clone(), Arc::new(ep));
     121              :         }
     122              : 
     123            0 :         Ok(ComputeControlPlane {
     124            0 :             base_port: 55431,
     125            0 :             endpoints,
     126            0 :             env,
     127            0 :         })
     128            0 :     }
     129              : 
     130            0 :     fn get_port(&mut self) -> u16 {
     131            0 :         1 + self
     132            0 :             .endpoints
     133            0 :             .values()
     134            0 :             .map(|ep| std::cmp::max(ep.pg_address.port(), ep.external_http_address.port()))
     135            0 :             .max()
     136            0 :             .unwrap_or(self.base_port)
     137            0 :     }
     138              : 
     139              :     #[allow(clippy::too_many_arguments)]
     140            0 :     pub fn new_endpoint(
     141            0 :         &mut self,
     142            0 :         endpoint_id: &str,
     143            0 :         tenant_id: TenantId,
     144            0 :         timeline_id: TimelineId,
     145            0 :         pg_port: Option<u16>,
     146            0 :         external_http_port: Option<u16>,
     147            0 :         internal_http_port: Option<u16>,
     148            0 :         pg_version: u32,
     149            0 :         mode: ComputeMode,
     150            0 :         skip_pg_catalog_updates: bool,
     151            0 :         drop_subscriptions_before_start: bool,
     152            0 :     ) -> Result<Arc<Endpoint>> {
     153            0 :         let pg_port = pg_port.unwrap_or_else(|| self.get_port());
     154            0 :         let external_http_port = external_http_port.unwrap_or_else(|| self.get_port() + 1);
     155            0 :         let internal_http_port = internal_http_port.unwrap_or_else(|| external_http_port + 1);
     156            0 :         let ep = Arc::new(Endpoint {
     157            0 :             endpoint_id: endpoint_id.to_owned(),
     158            0 :             pg_address: SocketAddr::new(IpAddr::from(Ipv4Addr::LOCALHOST), pg_port),
     159            0 :             external_http_address: SocketAddr::new(
     160            0 :                 IpAddr::from(Ipv4Addr::UNSPECIFIED),
     161            0 :                 external_http_port,
     162            0 :             ),
     163            0 :             internal_http_address: SocketAddr::new(
     164            0 :                 IpAddr::from(Ipv4Addr::LOCALHOST),
     165            0 :                 internal_http_port,
     166            0 :             ),
     167            0 :             env: self.env.clone(),
     168            0 :             timeline_id,
     169            0 :             mode,
     170            0 :             tenant_id,
     171            0 :             pg_version,
     172            0 :             // We don't setup roles and databases in the spec locally, so we don't need to
     173            0 :             // do catalog updates. Catalog updates also include check availability
     174            0 :             // data creation. Yet, we have tests that check that size and db dump
     175            0 :             // before and after start are the same. So, skip catalog updates,
     176            0 :             // with this we basically test a case of waking up an idle compute, where
     177            0 :             // we also skip catalog updates in the cloud.
     178            0 :             skip_pg_catalog_updates,
     179            0 :             drop_subscriptions_before_start,
     180            0 :             features: vec![],
     181            0 :         });
     182            0 : 
     183            0 :         ep.create_endpoint_dir()?;
     184              :         std::fs::write(
     185            0 :             ep.endpoint_path().join("endpoint.json"),
     186            0 :             serde_json::to_string_pretty(&EndpointConf {
     187            0 :                 endpoint_id: endpoint_id.to_string(),
     188            0 :                 tenant_id,
     189            0 :                 timeline_id,
     190            0 :                 mode,
     191            0 :                 external_http_port,
     192            0 :                 internal_http_port,
     193            0 :                 pg_port,
     194            0 :                 pg_version,
     195            0 :                 skip_pg_catalog_updates,
     196            0 :                 drop_subscriptions_before_start,
     197            0 :                 features: vec![],
     198            0 :             })?,
     199            0 :         )?;
     200              :         std::fs::write(
     201            0 :             ep.endpoint_path().join("postgresql.conf"),
     202            0 :             ep.setup_pg_conf()?.to_string(),
     203            0 :         )?;
     204              : 
     205            0 :         self.endpoints
     206            0 :             .insert(ep.endpoint_id.clone(), Arc::clone(&ep));
     207            0 : 
     208            0 :         Ok(ep)
     209            0 :     }
     210              : 
     211            0 :     pub fn check_conflicting_endpoints(
     212            0 :         &self,
     213            0 :         mode: ComputeMode,
     214            0 :         tenant_id: TenantId,
     215            0 :         timeline_id: TimelineId,
     216            0 :     ) -> Result<()> {
     217            0 :         if matches!(mode, ComputeMode::Primary) {
     218              :             // this check is not complete, as you could have a concurrent attempt at
     219              :             // creating another primary, both reading the state before checking it here,
     220              :             // but it's better than nothing.
     221            0 :             let mut duplicates = self.endpoints.iter().filter(|(_k, v)| {
     222            0 :                 v.tenant_id == tenant_id
     223            0 :                     && v.timeline_id == timeline_id
     224            0 :                     && v.mode == mode
     225            0 :                     && v.status() != EndpointStatus::Stopped
     226            0 :             });
     227              : 
     228            0 :             if let Some((key, _)) = duplicates.next() {
     229            0 :                 bail!("attempting to create a duplicate primary endpoint on tenant {tenant_id}, timeline {timeline_id}: endpoint {key:?} exists already. please don't do this, it is not supported.");
     230            0 :             }
     231            0 :         }
     232            0 :         Ok(())
     233            0 :     }
     234              : }
     235              : 
     236              : ///////////////////////////////////////////////////////////////////////////////
     237              : 
     238              : #[derive(Debug)]
     239              : pub struct Endpoint {
     240              :     /// used as the directory name
     241              :     endpoint_id: String,
     242              :     pub tenant_id: TenantId,
     243              :     pub timeline_id: TimelineId,
     244              :     pub mode: ComputeMode,
     245              : 
     246              :     // port and address of the Postgres server and `compute_ctl`'s HTTP APIs
     247              :     pub pg_address: SocketAddr,
     248              :     pub external_http_address: SocketAddr,
     249              :     pub internal_http_address: SocketAddr,
     250              : 
     251              :     // postgres major version in the format: 14, 15, etc.
     252              :     pg_version: u32,
     253              : 
     254              :     // These are not part of the endpoint as such, but the environment
     255              :     // the endpoint runs in.
     256              :     pub env: LocalEnv,
     257              : 
     258              :     // Optimizations
     259              :     skip_pg_catalog_updates: bool,
     260              : 
     261              :     drop_subscriptions_before_start: bool,
     262              :     // Feature flags
     263              :     features: Vec<ComputeFeature>,
     264              : }
     265              : 
     266              : #[derive(PartialEq, Eq)]
     267              : pub enum EndpointStatus {
     268              :     Running,
     269              :     Stopped,
     270              :     Crashed,
     271              :     RunningNoPidfile,
     272              : }
     273              : 
     274              : impl std::fmt::Display for EndpointStatus {
     275            0 :     fn fmt(&self, writer: &mut std::fmt::Formatter) -> std::fmt::Result {
     276            0 :         let s = match self {
     277            0 :             Self::Running => "running",
     278            0 :             Self::Stopped => "stopped",
     279            0 :             Self::Crashed => "crashed",
     280            0 :             Self::RunningNoPidfile => "running, no pidfile",
     281              :         };
     282            0 :         write!(writer, "{}", s)
     283            0 :     }
     284              : }
     285              : 
     286              : impl Endpoint {
     287            0 :     fn from_dir_entry(entry: std::fs::DirEntry, env: &LocalEnv) -> Result<Endpoint> {
     288            0 :         if !entry.file_type()?.is_dir() {
     289            0 :             anyhow::bail!(
     290            0 :                 "Endpoint::from_dir_entry failed: '{}' is not a directory",
     291            0 :                 entry.path().display()
     292            0 :             );
     293            0 :         }
     294            0 : 
     295            0 :         // parse data directory name
     296            0 :         let fname = entry.file_name();
     297            0 :         let endpoint_id = fname.to_str().unwrap().to_string();
     298              : 
     299              :         // Read the endpoint.json file
     300            0 :         let conf: EndpointConf =
     301            0 :             serde_json::from_slice(&std::fs::read(entry.path().join("endpoint.json"))?)?;
     302              : 
     303            0 :         Ok(Endpoint {
     304            0 :             pg_address: SocketAddr::new(IpAddr::from(Ipv4Addr::LOCALHOST), conf.pg_port),
     305            0 :             external_http_address: SocketAddr::new(
     306            0 :                 IpAddr::from(Ipv4Addr::UNSPECIFIED),
     307            0 :                 conf.external_http_port,
     308            0 :             ),
     309            0 :             internal_http_address: SocketAddr::new(
     310            0 :                 IpAddr::from(Ipv4Addr::LOCALHOST),
     311            0 :                 conf.internal_http_port,
     312            0 :             ),
     313            0 :             endpoint_id,
     314            0 :             env: env.clone(),
     315            0 :             timeline_id: conf.timeline_id,
     316            0 :             mode: conf.mode,
     317            0 :             tenant_id: conf.tenant_id,
     318            0 :             pg_version: conf.pg_version,
     319            0 :             skip_pg_catalog_updates: conf.skip_pg_catalog_updates,
     320            0 :             drop_subscriptions_before_start: conf.drop_subscriptions_before_start,
     321            0 :             features: conf.features,
     322            0 :         })
     323            0 :     }
     324              : 
     325            0 :     fn create_endpoint_dir(&self) -> Result<()> {
     326            0 :         std::fs::create_dir_all(self.endpoint_path()).with_context(|| {
     327            0 :             format!(
     328            0 :                 "could not create endpoint directory {}",
     329            0 :                 self.endpoint_path().display()
     330            0 :             )
     331            0 :         })
     332            0 :     }
     333              : 
     334              :     // Generate postgresql.conf with default configuration
     335            0 :     fn setup_pg_conf(&self) -> Result<PostgresConf> {
     336            0 :         let mut conf = PostgresConf::new();
     337            0 :         conf.append("max_wal_senders", "10");
     338            0 :         conf.append("wal_log_hints", "off");
     339            0 :         conf.append("max_replication_slots", "10");
     340            0 :         conf.append("hot_standby", "on");
     341            0 :         // Set to 1MB to both exercise getPage requests/LFC, and still have enough room for
     342            0 :         // Postgres to operate. Everything smaller might be not enough for Postgres under load,
     343            0 :         // and can cause errors like 'no unpinned buffers available', see
     344            0 :         // <https://github.com/neondatabase/neon/issues/9956>
     345            0 :         conf.append("shared_buffers", "1MB");
     346            0 :         // Postgres defaults to effective_io_concurrency=1, which does not exercise the pageserver's
     347            0 :         // batching logic.  Set this to 2 so that we exercise the code a bit without letting
     348            0 :         // individual tests do a lot of concurrent work on underpowered test machines
     349            0 :         conf.append("effective_io_concurrency", "2");
     350            0 :         conf.append("fsync", "off");
     351            0 :         conf.append("max_connections", "100");
     352            0 :         conf.append("wal_level", "logical");
     353            0 :         // wal_sender_timeout is the maximum time to wait for WAL replication.
     354            0 :         // It also defines how often the walreciever will send a feedback message to the wal sender.
     355            0 :         conf.append("wal_sender_timeout", "5s");
     356            0 :         conf.append("listen_addresses", &self.pg_address.ip().to_string());
     357            0 :         conf.append("port", &self.pg_address.port().to_string());
     358            0 :         conf.append("wal_keep_size", "0");
     359            0 :         // walproposer panics when basebackup is invalid, it is pointless to restart in this case.
     360            0 :         conf.append("restart_after_crash", "off");
     361            0 : 
     362            0 :         // Load the 'neon' extension
     363            0 :         conf.append("shared_preload_libraries", "neon");
     364            0 : 
     365            0 :         conf.append_line("");
     366            0 :         // Replication-related configurations, such as WAL sending
     367            0 :         match &self.mode {
     368              :             ComputeMode::Primary => {
     369              :                 // Configure backpressure
     370              :                 // - Replication write lag depends on how fast the walreceiver can process incoming WAL.
     371              :                 //   This lag determines latency of get_page_at_lsn. Speed of applying WAL is about 10MB/sec,
     372              :                 //   so to avoid expiration of 1 minute timeout, this lag should not be larger than 600MB.
     373              :                 //   Actually latency should be much smaller (better if < 1sec). But we assume that recently
     374              :                 //   updates pages are not requested from pageserver.
     375              :                 // - Replication flush lag depends on speed of persisting data by checkpointer (creation of
     376              :                 //   delta/image layers) and advancing disk_consistent_lsn. Safekeepers are able to
     377              :                 //   remove/archive WAL only beyond disk_consistent_lsn. Too large a lag can cause long
     378              :                 //   recovery time (in case of pageserver crash) and disk space overflow at safekeepers.
     379              :                 // - Replication apply lag depends on speed of uploading changes to S3 by uploader thread.
     380              :                 //   To be able to restore database in case of pageserver node crash, safekeeper should not
     381              :                 //   remove WAL beyond this point. Too large lag can cause space exhaustion in safekeepers
     382              :                 //   (if they are not able to upload WAL to S3).
     383            0 :                 conf.append("max_replication_write_lag", "15MB");
     384            0 :                 conf.append("max_replication_flush_lag", "10GB");
     385            0 : 
     386            0 :                 if !self.env.safekeepers.is_empty() {
     387            0 :                     // Configure Postgres to connect to the safekeepers
     388            0 :                     conf.append("synchronous_standby_names", "walproposer");
     389            0 : 
     390            0 :                     let safekeepers = self
     391            0 :                         .env
     392            0 :                         .safekeepers
     393            0 :                         .iter()
     394            0 :                         .map(|sk| format!("localhost:{}", sk.get_compute_port()))
     395            0 :                         .collect::<Vec<String>>()
     396            0 :                         .join(",");
     397            0 :                     conf.append("neon.safekeepers", &safekeepers);
     398            0 :                 } else {
     399            0 :                     // We only use setup without safekeepers for tests,
     400            0 :                     // and don't care about data durability on pageserver,
     401            0 :                     // so set more relaxed synchronous_commit.
     402            0 :                     conf.append("synchronous_commit", "remote_write");
     403            0 : 
     404            0 :                     // Configure the node to stream WAL directly to the pageserver
     405            0 :                     // This isn't really a supported configuration, but can be useful for
     406            0 :                     // testing.
     407            0 :                     conf.append("synchronous_standby_names", "pageserver");
     408            0 :                 }
     409              :             }
     410            0 :             ComputeMode::Static(lsn) => {
     411            0 :                 conf.append("recovery_target_lsn", &lsn.to_string());
     412            0 :             }
     413              :             ComputeMode::Replica => {
     414            0 :                 assert!(!self.env.safekeepers.is_empty());
     415              : 
     416              :                 // TODO: use future host field from safekeeper spec
     417              :                 // Pass the list of safekeepers to the replica so that it can connect to any of them,
     418              :                 // whichever is available.
     419            0 :                 let sk_ports = self
     420            0 :                     .env
     421            0 :                     .safekeepers
     422            0 :                     .iter()
     423            0 :                     .map(|x| x.get_compute_port().to_string())
     424            0 :                     .collect::<Vec<_>>()
     425            0 :                     .join(",");
     426            0 :                 let sk_hosts = vec!["localhost"; self.env.safekeepers.len()].join(",");
     427            0 : 
     428            0 :                 let connstr = format!(
     429            0 :                     "host={} port={} options='-c timeline_id={} tenant_id={}' application_name=replica replication=true",
     430            0 :                     sk_hosts,
     431            0 :                     sk_ports,
     432            0 :                     &self.timeline_id.to_string(),
     433            0 :                     &self.tenant_id.to_string(),
     434            0 :                 );
     435            0 : 
     436            0 :                 let slot_name = format!("repl_{}_", self.timeline_id);
     437            0 :                 conf.append("primary_conninfo", connstr.as_str());
     438            0 :                 conf.append("primary_slot_name", slot_name.as_str());
     439            0 :                 conf.append("hot_standby", "on");
     440            0 :                 // prefetching of blocks referenced in WAL doesn't make sense for us
     441            0 :                 // Neon hot standby ignores pages that are not in the shared_buffers
     442            0 :                 if self.pg_version >= 15 {
     443            0 :                     conf.append("recovery_prefetch", "off");
     444            0 :                 }
     445              :             }
     446              :         }
     447              : 
     448            0 :         Ok(conf)
     449            0 :     }
     450              : 
     451            0 :     pub fn endpoint_path(&self) -> PathBuf {
     452            0 :         self.env.endpoints_path().join(&self.endpoint_id)
     453            0 :     }
     454              : 
     455            0 :     pub fn pgdata(&self) -> PathBuf {
     456            0 :         self.endpoint_path().join("pgdata")
     457            0 :     }
     458              : 
     459            0 :     pub fn status(&self) -> EndpointStatus {
     460            0 :         let timeout = Duration::from_millis(300);
     461            0 :         let has_pidfile = self.pgdata().join("postmaster.pid").exists();
     462            0 :         let can_connect = TcpStream::connect_timeout(&self.pg_address, timeout).is_ok();
     463            0 : 
     464            0 :         match (has_pidfile, can_connect) {
     465            0 :             (true, true) => EndpointStatus::Running,
     466            0 :             (false, false) => EndpointStatus::Stopped,
     467            0 :             (true, false) => EndpointStatus::Crashed,
     468            0 :             (false, true) => EndpointStatus::RunningNoPidfile,
     469              :         }
     470            0 :     }
     471              : 
     472            0 :     fn pg_ctl(&self, args: &[&str], auth_token: &Option<String>) -> Result<()> {
     473            0 :         let pg_ctl_path = self.env.pg_bin_dir(self.pg_version)?.join("pg_ctl");
     474            0 :         let mut cmd = Command::new(&pg_ctl_path);
     475            0 :         cmd.args(
     476            0 :             [
     477            0 :                 &[
     478            0 :                     "-D",
     479            0 :                     self.pgdata().to_str().unwrap(),
     480            0 :                     "-w", //wait till pg_ctl actually does what was asked
     481            0 :                 ],
     482            0 :                 args,
     483            0 :             ]
     484            0 :             .concat(),
     485            0 :         )
     486            0 :         .env_clear()
     487            0 :         .env(
     488            0 :             "LD_LIBRARY_PATH",
     489            0 :             self.env.pg_lib_dir(self.pg_version)?.to_str().unwrap(),
     490            0 :         )
     491            0 :         .env(
     492            0 :             "DYLD_LIBRARY_PATH",
     493            0 :             self.env.pg_lib_dir(self.pg_version)?.to_str().unwrap(),
     494              :         );
     495              : 
     496              :         // Pass authentication token used for the connections to pageserver and safekeepers
     497            0 :         if let Some(token) = auth_token {
     498            0 :             cmd.env("NEON_AUTH_TOKEN", token);
     499            0 :         }
     500              : 
     501            0 :         let pg_ctl = cmd
     502            0 :             .output()
     503            0 :             .context(format!("{} failed", pg_ctl_path.display()))?;
     504            0 :         if !pg_ctl.status.success() {
     505            0 :             anyhow::bail!(
     506            0 :                 "pg_ctl failed, exit code: {}, stdout: {}, stderr: {}",
     507            0 :                 pg_ctl.status,
     508            0 :                 String::from_utf8_lossy(&pg_ctl.stdout),
     509            0 :                 String::from_utf8_lossy(&pg_ctl.stderr),
     510            0 :             );
     511            0 :         }
     512            0 : 
     513            0 :         Ok(())
     514            0 :     }
     515              : 
     516            0 :     fn wait_for_compute_ctl_to_exit(&self, send_sigterm: bool) -> Result<()> {
     517            0 :         // TODO use background_process::stop_process instead: https://github.com/neondatabase/neon/pull/6482
     518            0 :         let pidfile_path = self.endpoint_path().join("compute_ctl.pid");
     519            0 :         let pid: u32 = std::fs::read_to_string(pidfile_path)?.parse()?;
     520            0 :         let pid = nix::unistd::Pid::from_raw(pid as i32);
     521            0 :         if send_sigterm {
     522            0 :             kill(pid, Signal::SIGTERM).ok();
     523            0 :         }
     524            0 :         crate::background_process::wait_until_stopped("compute_ctl", pid)?;
     525            0 :         Ok(())
     526            0 :     }
     527              : 
     528            0 :     fn read_postgresql_conf(&self) -> Result<String> {
     529            0 :         // Slurp the endpoints/<endpoint id>/postgresql.conf file into
     530            0 :         // memory. We will include it in the spec file that we pass to
     531            0 :         // `compute_ctl`, and `compute_ctl` will write it to the postgresql.conf
     532            0 :         // in the data directory.
     533            0 :         let postgresql_conf_path = self.endpoint_path().join("postgresql.conf");
     534            0 :         match std::fs::read(&postgresql_conf_path) {
     535            0 :             Ok(content) => Ok(String::from_utf8(content)?),
     536            0 :             Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok("".to_string()),
     537            0 :             Err(e) => Err(anyhow::Error::new(e).context(format!(
     538            0 :                 "failed to read config file in {}",
     539            0 :                 postgresql_conf_path.to_str().unwrap()
     540            0 :             ))),
     541              :         }
     542            0 :     }
     543              : 
     544            0 :     fn build_pageserver_connstr(pageservers: &[(Host, u16)]) -> String {
     545            0 :         pageservers
     546            0 :             .iter()
     547            0 :             .map(|(host, port)| format!("postgresql://no_user@{host}:{port}"))
     548            0 :             .collect::<Vec<_>>()
     549            0 :             .join(",")
     550            0 :     }
     551              : 
     552              :     /// Map safekeepers ids to the actual connection strings.
     553            0 :     fn build_safekeepers_connstrs(&self, sk_ids: Vec<NodeId>) -> Result<Vec<String>> {
     554            0 :         let mut safekeeper_connstrings = Vec::new();
     555            0 :         if self.mode == ComputeMode::Primary {
     556            0 :             for sk_id in sk_ids {
     557            0 :                 let sk = self
     558            0 :                     .env
     559            0 :                     .safekeepers
     560            0 :                     .iter()
     561            0 :                     .find(|node| node.id == sk_id)
     562            0 :                     .ok_or_else(|| anyhow!("safekeeper {sk_id} does not exist"))?;
     563            0 :                 safekeeper_connstrings.push(format!("127.0.0.1:{}", sk.get_compute_port()));
     564              :             }
     565            0 :         }
     566            0 :         Ok(safekeeper_connstrings)
     567            0 :     }
     568              : 
     569            0 :     pub async fn start(
     570            0 :         &self,
     571            0 :         auth_token: &Option<String>,
     572            0 :         safekeepers: Vec<NodeId>,
     573            0 :         pageservers: Vec<(Host, u16)>,
     574            0 :         remote_ext_config: Option<&String>,
     575            0 :         shard_stripe_size: usize,
     576            0 :         create_test_user: bool,
     577            0 :     ) -> Result<()> {
     578            0 :         if self.status() == EndpointStatus::Running {
     579            0 :             anyhow::bail!("The endpoint is already running");
     580            0 :         }
     581              : 
     582            0 :         let postgresql_conf = self.read_postgresql_conf()?;
     583              : 
     584              :         // We always start the compute node from scratch, so if the Postgres
     585              :         // data dir exists from a previous launch, remove it first.
     586            0 :         if self.pgdata().exists() {
     587            0 :             std::fs::remove_dir_all(self.pgdata())?;
     588            0 :         }
     589              : 
     590            0 :         let pageserver_connstring = Self::build_pageserver_connstr(&pageservers);
     591            0 :         assert!(!pageserver_connstring.is_empty());
     592              : 
     593            0 :         let safekeeper_connstrings = self.build_safekeepers_connstrs(safekeepers)?;
     594              : 
     595              :         // check for file remote_extensions_spec.json
     596              :         // if it is present, read it and pass to compute_ctl
     597            0 :         let remote_extensions_spec_path = self.endpoint_path().join("remote_extensions_spec.json");
     598            0 :         let remote_extensions_spec = std::fs::File::open(remote_extensions_spec_path);
     599              :         let remote_extensions: Option<RemoteExtSpec>;
     600              : 
     601            0 :         if let Ok(spec_file) = remote_extensions_spec {
     602            0 :             remote_extensions = serde_json::from_reader(spec_file).ok();
     603            0 :         } else {
     604            0 :             remote_extensions = None;
     605            0 :         };
     606              : 
     607              :         // Create spec file
     608            0 :         let spec = ComputeSpec {
     609            0 :             skip_pg_catalog_updates: self.skip_pg_catalog_updates,
     610            0 :             format_version: 1.0,
     611            0 :             operation_uuid: None,
     612            0 :             features: self.features.clone(),
     613            0 :             swap_size_bytes: None,
     614            0 :             disk_quota_bytes: None,
     615            0 :             disable_lfc_resizing: None,
     616            0 :             cluster: Cluster {
     617            0 :                 cluster_id: None, // project ID: not used
     618            0 :                 name: None,       // project name: not used
     619            0 :                 state: None,
     620            0 :                 roles: if create_test_user {
     621            0 :                     vec![Role {
     622            0 :                         name: PgIdent::from_str("test").unwrap(),
     623            0 :                         encrypted_password: None,
     624            0 :                         options: None,
     625            0 :                     }]
     626              :                 } else {
     627            0 :                     Vec::new()
     628              :                 },
     629            0 :                 databases: if create_test_user {
     630            0 :                     vec![Database {
     631            0 :                         name: PgIdent::from_str("neondb").unwrap(),
     632            0 :                         owner: PgIdent::from_str("test").unwrap(),
     633            0 :                         options: None,
     634            0 :                         restrict_conn: false,
     635            0 :                         invalid: false,
     636            0 :                     }]
     637              :                 } else {
     638            0 :                     Vec::new()
     639              :                 },
     640            0 :                 settings: None,
     641            0 :                 postgresql_conf: Some(postgresql_conf),
     642            0 :             },
     643            0 :             delta_operations: None,
     644            0 :             tenant_id: Some(self.tenant_id),
     645            0 :             timeline_id: Some(self.timeline_id),
     646            0 :             mode: self.mode,
     647            0 :             pageserver_connstring: Some(pageserver_connstring),
     648            0 :             safekeeper_connstrings,
     649            0 :             storage_auth_token: auth_token.clone(),
     650            0 :             remote_extensions,
     651            0 :             pgbouncer_settings: None,
     652            0 :             shard_stripe_size: Some(shard_stripe_size),
     653            0 :             local_proxy_config: None,
     654            0 :             reconfigure_concurrency: 1,
     655            0 :             drop_subscriptions_before_start: self.drop_subscriptions_before_start,
     656            0 :         };
     657            0 :         let spec_path = self.endpoint_path().join("spec.json");
     658            0 :         std::fs::write(spec_path, serde_json::to_string_pretty(&spec)?)?;
     659              : 
     660              :         // Open log file. We'll redirect the stdout and stderr of `compute_ctl` to it.
     661            0 :         let logfile = std::fs::OpenOptions::new()
     662            0 :             .create(true)
     663            0 :             .append(true)
     664            0 :             .open(self.endpoint_path().join("compute.log"))?;
     665              : 
     666              :         // Launch compute_ctl
     667            0 :         let conn_str = self.connstr("cloud_admin", "postgres");
     668            0 :         println!("Starting postgres node at '{}'", conn_str);
     669            0 :         if create_test_user {
     670            0 :             let conn_str = self.connstr("test", "neondb");
     671            0 :             println!("Also at '{}'", conn_str);
     672            0 :         }
     673            0 :         let mut cmd = Command::new(self.env.neon_distrib_dir.join("compute_ctl"));
     674            0 :         //cmd.args([
     675            0 :         //    "--external-http-port",
     676            0 :         //    &self.external_http_address.port().to_string(),
     677            0 :         //])
     678            0 :         //.args([
     679            0 :         //    "--internal-http-port",
     680            0 :         //    &self.internal_http_address.port().to_string(),
     681            0 :         //])
     682            0 :         cmd.args([
     683            0 :             "--http-port",
     684            0 :             &self.external_http_address.port().to_string(),
     685            0 :         ])
     686            0 :         .args(["--pgdata", self.pgdata().to_str().unwrap()])
     687            0 :         .args(["--connstr", &conn_str])
     688            0 :         .args([
     689            0 :             "--spec-path",
     690            0 :             self.endpoint_path().join("spec.json").to_str().unwrap(),
     691            0 :         ])
     692            0 :         .args([
     693            0 :             "--pgbin",
     694            0 :             self.env
     695            0 :                 .pg_bin_dir(self.pg_version)?
     696            0 :                 .join("postgres")
     697            0 :                 .to_str()
     698            0 :                 .unwrap(),
     699            0 :         ])
     700            0 :         // TODO: It would be nice if we generated compute IDs with the same
     701            0 :         // algorithm as the real control plane.
     702            0 :         //
     703            0 :         // TODO: Add this back when
     704            0 :         // https://github.com/neondatabase/neon/pull/10747 is merged.
     705            0 :         //
     706            0 :         //.args([
     707            0 :         //    "--compute-id",
     708            0 :         //    &format!(
     709            0 :         //        "compute-{}",
     710            0 :         //        SystemTime::now()
     711            0 :         //            .duration_since(UNIX_EPOCH)
     712            0 :         //            .unwrap()
     713            0 :         //            .as_secs()
     714            0 :         //    ),
     715            0 :         //])
     716            0 :         .stdin(std::process::Stdio::null())
     717            0 :         .stderr(logfile.try_clone()?)
     718            0 :         .stdout(logfile);
     719              : 
     720            0 :         if let Some(remote_ext_config) = remote_ext_config {
     721            0 :             cmd.args(["--remote-ext-config", remote_ext_config]);
     722            0 :         }
     723              : 
     724            0 :         let child = cmd.spawn()?;
     725              :         // set up a scopeguard to kill & wait for the child in case we panic or bail below
     726            0 :         let child = scopeguard::guard(child, |mut child| {
     727            0 :             println!("SIGKILL & wait the started process");
     728            0 :             (|| {
     729            0 :                 // TODO: use another signal that can be caught by the child so it can clean up any children it spawned
     730            0 :                 child.kill().context("SIGKILL child")?;
     731            0 :                 child.wait().context("wait() for child process")?;
     732            0 :                 anyhow::Ok(())
     733            0 :             })()
     734            0 :             .with_context(|| format!("scopeguard kill&wait child {child:?}"))
     735            0 :             .unwrap();
     736            0 :         });
     737            0 : 
     738            0 :         // Write down the pid so we can wait for it when we want to stop
     739            0 :         // TODO use background_process::start_process instead: https://github.com/neondatabase/neon/pull/6482
     740            0 :         let pid = child.id();
     741            0 :         let pidfile_path = self.endpoint_path().join("compute_ctl.pid");
     742            0 :         std::fs::write(pidfile_path, pid.to_string())?;
     743              : 
     744              :         // Wait for it to start
     745            0 :         let mut attempt = 0;
     746              :         const ATTEMPT_INTERVAL: Duration = Duration::from_millis(100);
     747              :         const MAX_ATTEMPTS: u32 = 10 * 90; // Wait up to 1.5 min
     748              :         loop {
     749            0 :             attempt += 1;
     750            0 :             match self.get_status().await {
     751            0 :                 Ok(state) => {
     752            0 :                     match state.status {
     753              :                         ComputeStatus::Init => {
     754            0 :                             if attempt == MAX_ATTEMPTS {
     755            0 :                                 bail!("compute startup timed out; still in Init state");
     756            0 :                             }
     757              :                             // keep retrying
     758              :                         }
     759              :                         ComputeStatus::Running => {
     760              :                             // All good!
     761            0 :                             break;
     762              :                         }
     763              :                         ComputeStatus::Failed => {
     764            0 :                             bail!(
     765            0 :                                 "compute startup failed: {}",
     766            0 :                                 state
     767            0 :                                     .error
     768            0 :                                     .as_deref()
     769            0 :                                     .unwrap_or("<no error from compute_ctl>")
     770            0 :                             );
     771              :                         }
     772              :                         ComputeStatus::Empty
     773              :                         | ComputeStatus::ConfigurationPending
     774              :                         | ComputeStatus::Configuration
     775              :                         | ComputeStatus::TerminationPending
     776              :                         | ComputeStatus::Terminated => {
     777            0 :                             bail!("unexpected compute status: {:?}", state.status)
     778              :                         }
     779              :                     }
     780              :                 }
     781            0 :                 Err(e) => {
     782            0 :                     if attempt == MAX_ATTEMPTS {
     783            0 :                         return Err(e).context("timed out waiting to connect to compute_ctl HTTP");
     784            0 :                     }
     785              :                 }
     786              :             }
     787            0 :             tokio::time::sleep(ATTEMPT_INTERVAL).await;
     788              :         }
     789              : 
     790              :         // disarm the scopeguard, let the child outlive this function (and neon_local invoction)
     791            0 :         drop(scopeguard::ScopeGuard::into_inner(child));
     792            0 : 
     793            0 :         Ok(())
     794            0 :     }
     795              : 
     796              :     // Call the /status HTTP API
     797            0 :     pub async fn get_status(&self) -> Result<ComputeStatusResponse> {
     798            0 :         let client = reqwest::Client::new();
     799              : 
     800            0 :         let response = client
     801            0 :             .request(
     802            0 :                 reqwest::Method::GET,
     803            0 :                 format!(
     804            0 :                     "http://{}:{}/status",
     805            0 :                     self.external_http_address.ip(),
     806            0 :                     self.external_http_address.port()
     807            0 :                 ),
     808            0 :             )
     809            0 :             .send()
     810            0 :             .await?;
     811              : 
     812              :         // Interpret the response
     813            0 :         let status = response.status();
     814            0 :         if !(status.is_client_error() || status.is_server_error()) {
     815            0 :             Ok(response.json().await?)
     816              :         } else {
     817              :             // reqwest does not export its error construction utility functions, so let's craft the message ourselves
     818            0 :             let url = response.url().to_owned();
     819            0 :             let msg = match response.text().await {
     820            0 :                 Ok(err_body) => format!("Error: {}", err_body),
     821            0 :                 Err(_) => format!("Http error ({}) at {}.", status.as_u16(), url),
     822              :             };
     823            0 :             Err(anyhow::anyhow!(msg))
     824              :         }
     825            0 :     }
     826              : 
     827            0 :     pub async fn reconfigure(
     828            0 :         &self,
     829            0 :         mut pageservers: Vec<(Host, u16)>,
     830            0 :         stripe_size: Option<ShardStripeSize>,
     831            0 :         safekeepers: Option<Vec<NodeId>>,
     832            0 :     ) -> Result<()> {
     833            0 :         let mut spec: ComputeSpec = {
     834            0 :             let spec_path = self.endpoint_path().join("spec.json");
     835            0 :             let file = std::fs::File::open(spec_path)?;
     836            0 :             serde_json::from_reader(file)?
     837              :         };
     838              : 
     839            0 :         let postgresql_conf = self.read_postgresql_conf()?;
     840            0 :         spec.cluster.postgresql_conf = Some(postgresql_conf);
     841            0 : 
     842            0 :         // If we weren't given explicit pageservers, query the storage controller
     843            0 :         if pageservers.is_empty() {
     844            0 :             let storage_controller = StorageController::from_env(&self.env);
     845            0 :             let locate_result = storage_controller.tenant_locate(self.tenant_id).await?;
     846            0 :             pageservers = locate_result
     847            0 :                 .shards
     848            0 :                 .into_iter()
     849            0 :                 .map(|shard| {
     850            0 :                     (
     851            0 :                         Host::parse(&shard.listen_pg_addr)
     852            0 :                             .expect("Storage controller reported bad hostname"),
     853            0 :                         shard.listen_pg_port,
     854            0 :                     )
     855            0 :                 })
     856            0 :                 .collect::<Vec<_>>();
     857            0 :         }
     858              : 
     859            0 :         let pageserver_connstr = Self::build_pageserver_connstr(&pageservers);
     860            0 :         assert!(!pageserver_connstr.is_empty());
     861            0 :         spec.pageserver_connstring = Some(pageserver_connstr);
     862            0 :         if stripe_size.is_some() {
     863            0 :             spec.shard_stripe_size = stripe_size.map(|s| s.0 as usize);
     864            0 :         }
     865              : 
     866              :         // If safekeepers are not specified, don't change them.
     867            0 :         if let Some(safekeepers) = safekeepers {
     868            0 :             let safekeeper_connstrings = self.build_safekeepers_connstrs(safekeepers)?;
     869            0 :             spec.safekeeper_connstrings = safekeeper_connstrings;
     870            0 :         }
     871              : 
     872            0 :         let client = reqwest::Client::builder()
     873            0 :             .timeout(Duration::from_secs(120))
     874            0 :             .build()
     875            0 :             .unwrap();
     876            0 :         let response = client
     877            0 :             .post(format!(
     878            0 :                 "http://{}:{}/configure",
     879            0 :                 self.external_http_address.ip(),
     880            0 :                 self.external_http_address.port()
     881            0 :             ))
     882            0 :             .header(CONTENT_TYPE.as_str(), "application/json")
     883            0 :             .body(format!(
     884            0 :                 "{{\"spec\":{}}}",
     885            0 :                 serde_json::to_string_pretty(&spec)?
     886              :             ))
     887            0 :             .send()
     888            0 :             .await?;
     889              : 
     890            0 :         let status = response.status();
     891            0 :         if !(status.is_client_error() || status.is_server_error()) {
     892            0 :             Ok(())
     893              :         } else {
     894            0 :             let url = response.url().to_owned();
     895            0 :             let msg = match response.text().await {
     896            0 :                 Ok(err_body) => format!("Error: {}", err_body),
     897            0 :                 Err(_) => format!("Http error ({}) at {}.", status.as_u16(), url),
     898              :             };
     899            0 :             Err(anyhow::anyhow!(msg))
     900              :         }
     901            0 :     }
     902              : 
     903            0 :     pub fn stop(&self, mode: &str, destroy: bool) -> Result<()> {
     904            0 :         self.pg_ctl(&["-m", mode, "stop"], &None)?;
     905              : 
     906              :         // Also wait for the compute_ctl process to die. It might have some
     907              :         // cleanup work to do after postgres stops, like syncing safekeepers,
     908              :         // etc.
     909              :         //
     910              :         // If destroying or stop mode is immediate, send it SIGTERM before
     911              :         // waiting. Sometimes we do *not* want this cleanup: tests intentionally
     912              :         // do stop when majority of safekeepers is down, so sync-safekeepers
     913              :         // would hang otherwise. This could be a separate flag though.
     914            0 :         let send_sigterm = destroy || mode == "immediate";
     915            0 :         self.wait_for_compute_ctl_to_exit(send_sigterm)?;
     916            0 :         if destroy {
     917            0 :             println!(
     918            0 :                 "Destroying postgres data directory '{}'",
     919            0 :                 self.pgdata().to_str().unwrap()
     920            0 :             );
     921            0 :             std::fs::remove_dir_all(self.endpoint_path())?;
     922            0 :         }
     923            0 :         Ok(())
     924            0 :     }
     925              : 
     926            0 :     pub fn connstr(&self, user: &str, db_name: &str) -> String {
     927            0 :         format!(
     928            0 :             "postgresql://{}@{}:{}/{}",
     929            0 :             user,
     930            0 :             self.pg_address.ip(),
     931            0 :             self.pg_address.port(),
     932            0 :             db_name
     933            0 :         )
     934            0 :     }
     935              : }
        

Generated by: LCOV version 2.1-beta