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

Generated by: LCOV version 2.1-beta