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

Generated by: LCOV version 2.1-beta