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

Generated by: LCOV version 2.1-beta