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

Generated by: LCOV version 2.1-beta