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

Generated by: LCOV version 2.1-beta