LCOV - code coverage report
Current view: top level - control_plane/src - pageserver.rs (source / functions) Coverage Total Hit
Test: 1e20c4f2b28aa592527961bb32170ebbd2c9172f.info Lines: 0.0 % 484 0
Test Date: 2025-07-16 12:29:03 Functions: 0.0 % 57 0

            Line data    Source code
       1              : //! Code to manage pageservers
       2              : //!
       3              : //! In the local test environment, the data for each pageserver is stored in
       4              : //!
       5              : //! ```text
       6              : //!   .neon/pageserver_<pageserver_id>
       7              : //! ```
       8              : //!
       9              : use std::collections::HashMap;
      10              : use std::io;
      11              : use std::io::Write;
      12              : use std::num::NonZeroU64;
      13              : use std::path::PathBuf;
      14              : use std::str::FromStr;
      15              : use std::time::Duration;
      16              : 
      17              : use anyhow::{Context, bail};
      18              : use camino::Utf8PathBuf;
      19              : use pageserver_api::config::{DEFAULT_GRPC_LISTEN_PORT, DEFAULT_HTTP_LISTEN_PORT};
      20              : use pageserver_api::models::{self, TenantInfo, TimelineInfo};
      21              : use pageserver_api::shard::TenantShardId;
      22              : use pageserver_client::mgmt_api;
      23              : use postgres_backend::AuthType;
      24              : use postgres_connection::{PgConnectionConfig, parse_host_port};
      25              : use safekeeper_api::PgMajorVersion;
      26              : use utils::auth::{Claims, Scope};
      27              : use utils::id::{NodeId, TenantId, TimelineId};
      28              : use utils::lsn::Lsn;
      29              : 
      30              : use crate::background_process;
      31              : use crate::local_env::{LocalEnv, NeonLocalInitPageserverConf, PageServerConf};
      32              : 
      33              : /// Directory within .neon which will be used by default for LocalFs remote storage.
      34              : pub const PAGESERVER_REMOTE_STORAGE_DIR: &str = "local_fs_remote_storage/pageserver";
      35              : 
      36              : //
      37              : // Control routines for pageserver.
      38              : //
      39              : // Used in CLI and tests.
      40              : //
      41              : #[derive(Debug)]
      42              : pub struct PageServerNode {
      43              :     pub pg_connection_config: PgConnectionConfig,
      44              :     pub conf: PageServerConf,
      45              :     pub env: LocalEnv,
      46              :     pub http_client: mgmt_api::Client,
      47              : }
      48              : 
      49              : impl PageServerNode {
      50            0 :     pub fn from_env(env: &LocalEnv, conf: &PageServerConf) -> PageServerNode {
      51            0 :         let (host, port) =
      52            0 :             parse_host_port(&conf.listen_pg_addr).expect("Unable to parse listen_pg_addr");
      53            0 :         let port = port.unwrap_or(5432);
      54              : 
      55            0 :         let endpoint = if env.storage_controller.use_https_pageserver_api {
      56            0 :             format!(
      57            0 :                 "https://{}",
      58            0 :                 conf.listen_https_addr.as_ref().expect(
      59            0 :                     "listen https address should be specified if use_https_pageserver_api is on"
      60              :                 )
      61              :             )
      62              :         } else {
      63            0 :             format!("http://{}", conf.listen_http_addr)
      64              :         };
      65              : 
      66              :         Self {
      67            0 :             pg_connection_config: PgConnectionConfig::new_host_port(host, port),
      68            0 :             conf: conf.clone(),
      69            0 :             env: env.clone(),
      70            0 :             http_client: mgmt_api::Client::new(
      71            0 :                 env.create_http_client(),
      72            0 :                 endpoint,
      73              :                 {
      74            0 :                     match conf.http_auth_type {
      75            0 :                         AuthType::Trust => None,
      76            0 :                         AuthType::NeonJWT => Some(
      77            0 :                             env.generate_auth_token(&Claims::new(None, Scope::PageServerApi))
      78            0 :                                 .unwrap(),
      79            0 :                         ),
      80              :                     }
      81              :                 }
      82            0 :                 .as_deref(),
      83              :             ),
      84              :         }
      85            0 :     }
      86              : 
      87            0 :     fn pageserver_make_identity_toml(&self, node_id: NodeId) -> toml_edit::DocumentMut {
      88            0 :         toml_edit::DocumentMut::from_str(&format!("id={node_id}")).unwrap()
      89            0 :     }
      90              : 
      91            0 :     fn pageserver_init_make_toml(
      92            0 :         &self,
      93            0 :         conf: NeonLocalInitPageserverConf,
      94            0 :     ) -> anyhow::Result<toml_edit::DocumentMut> {
      95            0 :         assert_eq!(
      96            0 :             &PageServerConf::from(&conf),
      97            0 :             &self.conf,
      98            0 :             "during neon_local init, we derive the runtime state of ps conf (self.conf) from the --config flag fully"
      99              :         );
     100              : 
     101              :         // TODO(christian): instead of what we do here, create a pageserver_api::config::ConfigToml (PR #7656)
     102              : 
     103              :         // FIXME: the paths should be shell-escaped to handle paths with spaces, quotas etc.
     104            0 :         let pg_distrib_dir_param = format!(
     105            0 :             "pg_distrib_dir='{}'",
     106            0 :             self.env.pg_distrib_dir_raw().display()
     107              :         );
     108              : 
     109            0 :         let broker_endpoint_param = format!("broker_endpoint='{}'", self.env.broker.client_url());
     110              : 
     111            0 :         let mut overrides = vec![pg_distrib_dir_param, broker_endpoint_param];
     112              : 
     113            0 :         overrides.push(format!(
     114            0 :             "control_plane_api='{}'",
     115            0 :             self.env.control_plane_api.as_str()
     116              :         ));
     117              : 
     118              :         // Storage controller uses the same auth as pageserver: if JWT is enabled
     119              :         // for us, we will also need it to talk to them.
     120            0 :         if matches!(conf.http_auth_type, AuthType::NeonJWT) {
     121            0 :             let jwt_token = self
     122            0 :                 .env
     123            0 :                 .generate_auth_token(&Claims::new(None, Scope::GenerationsApi))
     124            0 :                 .unwrap();
     125            0 :             overrides.push(format!("control_plane_api_token='{jwt_token}'"));
     126            0 :         }
     127              : 
     128            0 :         if !conf.other.contains_key("remote_storage") {
     129            0 :             overrides.push(format!(
     130            0 :                 "remote_storage={{local_path='../{PAGESERVER_REMOTE_STORAGE_DIR}'}}"
     131            0 :             ));
     132            0 :         }
     133              : 
     134            0 :         if [conf.http_auth_type, conf.pg_auth_type, conf.grpc_auth_type]
     135            0 :             .contains(&AuthType::NeonJWT)
     136            0 :         {
     137            0 :             // Keys are generated in the toplevel repo dir, pageservers' workdirs
     138            0 :             // are one level below that, so refer to keys with ../
     139            0 :             overrides.push("auth_validation_public_key_path='../auth_public_key.pem'".to_owned());
     140            0 :         }
     141              : 
     142            0 :         if let Some(ssl_ca_file) = self.env.ssl_ca_cert_path() {
     143            0 :             overrides.push(format!("ssl_ca_file='{}'", ssl_ca_file.to_str().unwrap()));
     144            0 :         }
     145              : 
     146              :         // Apply the user-provided overrides
     147            0 :         overrides.push({
     148            0 :             let mut doc =
     149            0 :                 toml_edit::ser::to_document(&conf).expect("we deserialized this from toml earlier");
     150              :             // `id` is written out to `identity.toml` instead of `pageserver.toml`
     151            0 :             doc.remove("id").expect("it's part of the struct");
     152            0 :             doc.to_string()
     153              :         });
     154              : 
     155              :         // Turn `overrides` into a toml document.
     156              :         // TODO: above code is legacy code, it should be refactored to use toml_edit directly.
     157            0 :         let mut config_toml = toml_edit::DocumentMut::new();
     158            0 :         for fragment_str in overrides {
     159            0 :             let fragment = toml_edit::DocumentMut::from_str(&fragment_str)
     160            0 :                 .expect("all fragments in `overrides` are valid toml documents, this function controls that");
     161            0 :             for (key, item) in fragment.iter() {
     162            0 :                 config_toml.insert(key, item.clone());
     163            0 :             }
     164              :         }
     165            0 :         Ok(config_toml)
     166            0 :     }
     167              : 
     168              :     /// Initializes a pageserver node by creating its config with the overrides provided.
     169            0 :     pub fn initialize(&self, conf: NeonLocalInitPageserverConf) -> anyhow::Result<()> {
     170            0 :         self.pageserver_init(conf)
     171            0 :             .with_context(|| format!("Failed to run init for pageserver node {}", self.conf.id))
     172            0 :     }
     173              : 
     174            0 :     pub fn repo_path(&self) -> PathBuf {
     175            0 :         self.env.pageserver_data_dir(self.conf.id)
     176            0 :     }
     177              : 
     178              :     /// The pid file is created by the pageserver process, with its pid stored inside.
     179              :     /// Other pageservers cannot lock the same file and overwrite it for as long as the current
     180              :     /// pageserver runs. (Unless someone removes the file manually; never do that!)
     181            0 :     fn pid_file(&self) -> Utf8PathBuf {
     182            0 :         Utf8PathBuf::from_path_buf(self.repo_path().join("pageserver.pid"))
     183            0 :             .expect("non-Unicode path")
     184            0 :     }
     185              : 
     186            0 :     pub async fn start(&self, retry_timeout: &Duration) -> anyhow::Result<()> {
     187            0 :         self.start_node(retry_timeout).await
     188            0 :     }
     189              : 
     190            0 :     fn pageserver_init(&self, conf: NeonLocalInitPageserverConf) -> anyhow::Result<()> {
     191            0 :         let datadir = self.repo_path();
     192            0 :         let node_id = self.conf.id;
     193            0 :         println!(
     194            0 :             "Initializing pageserver node {} at '{}' in {:?}",
     195              :             node_id,
     196            0 :             self.pg_connection_config.raw_address(),
     197              :             datadir
     198              :         );
     199            0 :         io::stdout().flush()?;
     200              : 
     201              :         // If the config file we got as a CLI argument includes the `availability_zone`
     202              :         // config, then use that to populate the `metadata.json` file for the pageserver.
     203              :         // In production the deployment orchestrator does this for us.
     204            0 :         let az_id = conf
     205            0 :             .other
     206            0 :             .get("availability_zone")
     207            0 :             .map(|toml| {
     208            0 :                 let az_str = toml.to_string();
     209              :                 // Trim the (") chars from the toml representation
     210            0 :                 if az_str.starts_with('"') && az_str.ends_with('"') {
     211            0 :                     az_str[1..az_str.len() - 1].to_string()
     212              :                 } else {
     213            0 :                     az_str
     214              :                 }
     215            0 :             })
     216            0 :             .unwrap_or("local".to_string());
     217              : 
     218            0 :         let config = self
     219            0 :             .pageserver_init_make_toml(conf)
     220            0 :             .context("make pageserver toml")?;
     221            0 :         let config_file_path = datadir.join("pageserver.toml");
     222            0 :         let mut config_file = std::fs::OpenOptions::new()
     223            0 :             .create_new(true)
     224            0 :             .write(true)
     225            0 :             .open(&config_file_path)
     226            0 :             .with_context(|| format!("open pageserver toml for write: {config_file_path:?}"))?;
     227            0 :         config_file
     228            0 :             .write_all(config.to_string().as_bytes())
     229            0 :             .context("write pageserver toml")?;
     230            0 :         drop(config_file);
     231              : 
     232            0 :         let identity_file_path = datadir.join("identity.toml");
     233            0 :         let mut identity_file = std::fs::OpenOptions::new()
     234            0 :             .create_new(true)
     235            0 :             .write(true)
     236            0 :             .open(identity_file_path)
     237            0 :             .with_context(|| format!("open identity toml for write: {config_file_path:?}"))?;
     238            0 :         let identity_toml = self.pageserver_make_identity_toml(node_id);
     239            0 :         identity_file
     240            0 :             .write_all(identity_toml.to_string().as_bytes())
     241            0 :             .context("write identity toml")?;
     242            0 :         drop(identity_toml);
     243              : 
     244            0 :         if self.env.generate_local_ssl_certs {
     245            0 :             self.env.generate_ssl_cert(
     246            0 :                 datadir.join("server.crt").as_path(),
     247            0 :                 datadir.join("server.key").as_path(),
     248            0 :             )?;
     249            0 :         }
     250              : 
     251              :         // TODO: invoke a TBD config-check command to validate that pageserver will start with the written config
     252              : 
     253              :         // Write metadata file, used by pageserver on startup to register itself with
     254              :         // the storage controller
     255            0 :         let metadata_path = datadir.join("metadata.json");
     256              : 
     257            0 :         let http_host = "localhost".to_string();
     258            0 :         let (_, http_port) =
     259            0 :             parse_host_port(&self.conf.listen_http_addr).expect("Unable to parse listen_http_addr");
     260            0 :         let http_port = http_port.unwrap_or(DEFAULT_HTTP_LISTEN_PORT);
     261              : 
     262            0 :         let https_port = match self.conf.listen_https_addr.as_ref() {
     263            0 :             Some(https_addr) => {
     264            0 :                 let (_https_host, https_port) =
     265            0 :                     parse_host_port(https_addr).expect("Unable to parse listen_https_addr");
     266            0 :                 Some(https_port.unwrap_or(9899))
     267              :             }
     268            0 :             None => None,
     269              :         };
     270              : 
     271            0 :         let (mut grpc_host, mut grpc_port) = (None, None);
     272            0 :         if let Some(grpc_addr) = &self.conf.listen_grpc_addr {
     273            0 :             let (_, port) = parse_host_port(grpc_addr).expect("Unable to parse listen_grpc_addr");
     274            0 :             grpc_host = Some("localhost".to_string());
     275            0 :             grpc_port = Some(port.unwrap_or(DEFAULT_GRPC_LISTEN_PORT));
     276            0 :         }
     277              : 
     278              :         // Intentionally hand-craft JSON: this acts as an implicit format compat test
     279              :         // in case the pageserver-side structure is edited, and reflects the real life
     280              :         // situation: the metadata is written by some other script.
     281            0 :         std::fs::write(
     282            0 :             metadata_path,
     283            0 :             serde_json::to_vec(&pageserver_api::config::NodeMetadata {
     284            0 :                 postgres_host: "localhost".to_string(),
     285            0 :                 postgres_port: self.pg_connection_config.port(),
     286            0 :                 grpc_host,
     287            0 :                 grpc_port,
     288            0 :                 http_host,
     289            0 :                 http_port,
     290            0 :                 https_port,
     291            0 :                 other: HashMap::from([(
     292            0 :                     "availability_zone_id".to_string(),
     293            0 :                     serde_json::json!(az_id),
     294            0 :                 )]),
     295            0 :             })
     296            0 :             .unwrap(),
     297              :         )
     298            0 :         .expect("Failed to write metadata file");
     299              : 
     300            0 :         Ok(())
     301            0 :     }
     302              : 
     303            0 :     async fn start_node(&self, retry_timeout: &Duration) -> anyhow::Result<()> {
     304              :         // TODO: using a thread here because start_process() is not async but we need to call check_status()
     305            0 :         let datadir = self.repo_path();
     306            0 :         println!(
     307            0 :             "Starting pageserver node {} at '{}' in {:?}, retrying for {:?}",
     308              :             self.conf.id,
     309            0 :             self.pg_connection_config.raw_address(),
     310              :             datadir,
     311              :             retry_timeout
     312              :         );
     313            0 :         io::stdout().flush().context("flush stdout")?;
     314              : 
     315            0 :         let datadir_path_str = datadir.to_str().with_context(|| {
     316            0 :             format!(
     317            0 :                 "Cannot start pageserver node {} in path that has no string representation: {:?}",
     318              :                 self.conf.id, datadir,
     319              :             )
     320            0 :         })?;
     321            0 :         let args = vec!["-D", datadir_path_str];
     322              : 
     323            0 :         background_process::start_process(
     324            0 :             "pageserver",
     325            0 :             &datadir,
     326            0 :             &self.env.pageserver_bin(),
     327            0 :             args,
     328            0 :             self.pageserver_env_variables()?,
     329            0 :             background_process::InitialPidFile::Expect(self.pid_file()),
     330            0 :             retry_timeout,
     331            0 :             || async {
     332            0 :                 let st = self.check_status().await;
     333            0 :                 match st {
     334            0 :                     Ok(()) => Ok(true),
     335            0 :                     Err(mgmt_api::Error::ReceiveBody(_)) => Ok(false),
     336            0 :                     Err(e) => Err(anyhow::anyhow!("Failed to check node status: {e}")),
     337              :                 }
     338            0 :             },
     339              :         )
     340            0 :         .await?;
     341              : 
     342            0 :         Ok(())
     343            0 :     }
     344              : 
     345            0 :     fn pageserver_env_variables(&self) -> anyhow::Result<Vec<(String, String)>> {
     346              :         // FIXME: why is this tied to pageserver's auth type? Whether or not the safekeeper
     347              :         // needs a token, and how to generate that token, seems independent to whether
     348              :         // the pageserver requires a token in incoming requests.
     349            0 :         Ok(if self.conf.http_auth_type != AuthType::Trust {
     350              :             // Generate a token to connect from the pageserver to a safekeeper
     351            0 :             let token = self
     352            0 :                 .env
     353            0 :                 .generate_auth_token(&Claims::new(None, Scope::SafekeeperData))?;
     354            0 :             vec![("NEON_AUTH_TOKEN".to_owned(), token)]
     355              :         } else {
     356            0 :             Vec::new()
     357              :         })
     358            0 :     }
     359              : 
     360              :     ///
     361              :     /// Stop the server.
     362              :     ///
     363              :     /// If 'immediate' is true, we use SIGQUIT, killing the process immediately.
     364              :     /// Otherwise we use SIGTERM, triggering a clean shutdown
     365              :     ///
     366              :     /// If the server is not running, returns success
     367              :     ///
     368            0 :     pub fn stop(&self, immediate: bool) -> anyhow::Result<()> {
     369            0 :         background_process::stop_process(immediate, "pageserver", &self.pid_file())
     370            0 :     }
     371              : 
     372            0 :     pub async fn check_status(&self) -> mgmt_api::Result<()> {
     373            0 :         self.http_client.status().await
     374            0 :     }
     375              : 
     376            0 :     pub async fn tenant_list(&self) -> mgmt_api::Result<Vec<TenantInfo>> {
     377            0 :         self.http_client.list_tenants().await
     378            0 :     }
     379            0 :     pub fn parse_config(mut settings: HashMap<&str, &str>) -> anyhow::Result<models::TenantConfig> {
     380            0 :         let result = models::TenantConfig {
     381            0 :             checkpoint_distance: settings
     382            0 :                 .remove("checkpoint_distance")
     383            0 :                 .map(|x| x.parse::<u64>())
     384            0 :                 .transpose()
     385            0 :                 .context("Failed to parse 'checkpoint_distance' as an integer")?,
     386            0 :             checkpoint_timeout: settings
     387            0 :                 .remove("checkpoint_timeout")
     388            0 :                 .map(humantime::parse_duration)
     389            0 :                 .transpose()
     390            0 :                 .context("Failed to parse 'checkpoint_timeout' as duration")?,
     391            0 :             compaction_target_size: settings
     392            0 :                 .remove("compaction_target_size")
     393            0 :                 .map(|x| x.parse::<u64>())
     394            0 :                 .transpose()
     395            0 :                 .context("Failed to parse 'compaction_target_size' as an integer")?,
     396            0 :             compaction_period: settings
     397            0 :                 .remove("compaction_period")
     398            0 :                 .map(humantime::parse_duration)
     399            0 :                 .transpose()
     400            0 :                 .context("Failed to parse 'compaction_period' as duration")?,
     401            0 :             compaction_threshold: settings
     402            0 :                 .remove("compaction_threshold")
     403            0 :                 .map(|x| x.parse::<usize>())
     404            0 :                 .transpose()
     405            0 :                 .context("Failed to parse 'compaction_threshold' as an integer")?,
     406            0 :             compaction_upper_limit: settings
     407            0 :                 .remove("compaction_upper_limit")
     408            0 :                 .map(|x| x.parse::<usize>())
     409            0 :                 .transpose()
     410            0 :                 .context("Failed to parse 'compaction_upper_limit' as an integer")?,
     411            0 :             compaction_algorithm: settings
     412            0 :                 .remove("compaction_algorithm")
     413            0 :                 .map(serde_json::from_str)
     414            0 :                 .transpose()
     415            0 :                 .context("Failed to parse 'compaction_algorithm' json")?,
     416            0 :             compaction_shard_ancestor: settings
     417            0 :                 .remove("compaction_shard_ancestor")
     418            0 :                 .map(|x| x.parse::<bool>())
     419            0 :                 .transpose()
     420            0 :                 .context("Failed to parse 'compaction_shard_ancestor' as a bool")?,
     421            0 :             compaction_l0_first: settings
     422            0 :                 .remove("compaction_l0_first")
     423            0 :                 .map(|x| x.parse::<bool>())
     424            0 :                 .transpose()
     425            0 :                 .context("Failed to parse 'compaction_l0_first' as a bool")?,
     426            0 :             compaction_l0_semaphore: settings
     427            0 :                 .remove("compaction_l0_semaphore")
     428            0 :                 .map(|x| x.parse::<bool>())
     429            0 :                 .transpose()
     430            0 :                 .context("Failed to parse 'compaction_l0_semaphore' as a bool")?,
     431            0 :             l0_flush_delay_threshold: settings
     432            0 :                 .remove("l0_flush_delay_threshold")
     433            0 :                 .map(|x| x.parse::<usize>())
     434            0 :                 .transpose()
     435            0 :                 .context("Failed to parse 'l0_flush_delay_threshold' as an integer")?,
     436            0 :             l0_flush_stall_threshold: settings
     437            0 :                 .remove("l0_flush_stall_threshold")
     438            0 :                 .map(|x| x.parse::<usize>())
     439            0 :                 .transpose()
     440            0 :                 .context("Failed to parse 'l0_flush_stall_threshold' as an integer")?,
     441            0 :             gc_horizon: settings
     442            0 :                 .remove("gc_horizon")
     443            0 :                 .map(|x| x.parse::<u64>())
     444            0 :                 .transpose()
     445            0 :                 .context("Failed to parse 'gc_horizon' as an integer")?,
     446            0 :             gc_period: settings.remove("gc_period")
     447            0 :                 .map(humantime::parse_duration)
     448            0 :                 .transpose()
     449            0 :                 .context("Failed to parse 'gc_period' as duration")?,
     450            0 :             image_creation_threshold: settings
     451            0 :                 .remove("image_creation_threshold")
     452            0 :                 .map(|x| x.parse::<usize>())
     453            0 :                 .transpose()
     454            0 :                 .context("Failed to parse 'image_creation_threshold' as non zero integer")?,
     455              :             // HADRON
     456            0 :             image_layer_force_creation_period: settings
     457            0 :                 .remove("image_layer_force_creation_period")
     458            0 :                 .map(humantime::parse_duration)
     459            0 :                 .transpose()
     460            0 :                 .context("Failed to parse 'image_layer_force_creation_period' as duration")?,
     461            0 :             image_layer_creation_check_threshold: settings
     462            0 :                 .remove("image_layer_creation_check_threshold")
     463            0 :                 .map(|x| x.parse::<u8>())
     464            0 :                 .transpose()
     465            0 :                 .context("Failed to parse 'image_creation_check_threshold' as integer")?,
     466            0 :             image_creation_preempt_threshold: settings
     467            0 :                 .remove("image_creation_preempt_threshold")
     468            0 :                 .map(|x| x.parse::<usize>())
     469            0 :                 .transpose()
     470            0 :                 .context("Failed to parse 'image_creation_preempt_threshold' as integer")?,
     471            0 :             pitr_interval: settings.remove("pitr_interval")
     472            0 :                 .map(humantime::parse_duration)
     473            0 :                 .transpose()
     474            0 :                 .context("Failed to parse 'pitr_interval' as duration")?,
     475            0 :             walreceiver_connect_timeout: settings
     476            0 :                 .remove("walreceiver_connect_timeout")
     477            0 :                 .map(humantime::parse_duration)
     478            0 :                 .transpose()
     479            0 :                 .context("Failed to parse 'walreceiver_connect_timeout' as duration")?,
     480            0 :             lagging_wal_timeout: settings
     481            0 :                 .remove("lagging_wal_timeout")
     482            0 :                 .map(humantime::parse_duration)
     483            0 :                 .transpose()
     484            0 :                 .context("Failed to parse 'lagging_wal_timeout' as duration")?,
     485            0 :             max_lsn_wal_lag: settings
     486            0 :                 .remove("max_lsn_wal_lag")
     487            0 :                 .map(|x| x.parse::<NonZeroU64>())
     488            0 :                 .transpose()
     489            0 :                 .context("Failed to parse 'max_lsn_wal_lag' as non zero integer")?,
     490            0 :             eviction_policy: settings
     491            0 :                 .remove("eviction_policy")
     492            0 :                 .map(serde_json::from_str)
     493            0 :                 .transpose()
     494            0 :                 .context("Failed to parse 'eviction_policy' json")?,
     495            0 :             min_resident_size_override: settings
     496            0 :                 .remove("min_resident_size_override")
     497            0 :                 .map(|x| x.parse::<u64>())
     498            0 :                 .transpose()
     499            0 :                 .context("Failed to parse 'min_resident_size_override' as integer")?,
     500            0 :             evictions_low_residence_duration_metric_threshold: settings
     501            0 :                 .remove("evictions_low_residence_duration_metric_threshold")
     502            0 :                 .map(humantime::parse_duration)
     503            0 :                 .transpose()
     504            0 :                 .context("Failed to parse 'evictions_low_residence_duration_metric_threshold' as duration")?,
     505            0 :             heatmap_period: settings
     506            0 :                 .remove("heatmap_period")
     507            0 :                 .map(humantime::parse_duration)
     508            0 :                 .transpose()
     509            0 :                 .context("Failed to parse 'heatmap_period' as duration")?,
     510            0 :             lazy_slru_download: settings
     511            0 :                 .remove("lazy_slru_download")
     512            0 :                 .map(|x| x.parse::<bool>())
     513            0 :                 .transpose()
     514            0 :                 .context("Failed to parse 'lazy_slru_download' as bool")?,
     515            0 :             timeline_get_throttle: settings
     516            0 :                 .remove("timeline_get_throttle")
     517            0 :                 .map(serde_json::from_str)
     518            0 :                 .transpose()
     519            0 :                 .context("parse `timeline_get_throttle` from json")?,
     520            0 :             lsn_lease_length: settings.remove("lsn_lease_length")
     521            0 :                 .map(humantime::parse_duration)
     522            0 :                 .transpose()
     523            0 :                 .context("Failed to parse 'lsn_lease_length' as duration")?,
     524            0 :             lsn_lease_length_for_ts: settings
     525            0 :                 .remove("lsn_lease_length_for_ts")
     526            0 :                 .map(humantime::parse_duration)
     527            0 :                 .transpose()
     528            0 :                 .context("Failed to parse 'lsn_lease_length_for_ts' as duration")?,
     529            0 :             timeline_offloading: settings
     530            0 :                 .remove("timeline_offloading")
     531            0 :                 .map(|x| x.parse::<bool>())
     532            0 :                 .transpose()
     533            0 :                 .context("Failed to parse 'timeline_offloading' as bool")?,
     534            0 :             rel_size_v2_enabled: settings
     535            0 :                 .remove("rel_size_v2_enabled")
     536            0 :                 .map(|x| x.parse::<bool>())
     537            0 :                 .transpose()
     538            0 :                 .context("Failed to parse 'rel_size_v2_enabled' as bool")?,
     539            0 :             gc_compaction_enabled: settings
     540            0 :                 .remove("gc_compaction_enabled")
     541            0 :                 .map(|x| x.parse::<bool>())
     542            0 :                 .transpose()
     543            0 :                 .context("Failed to parse 'gc_compaction_enabled' as bool")?,
     544            0 :             gc_compaction_verification: settings
     545            0 :                 .remove("gc_compaction_verification")
     546            0 :                 .map(|x| x.parse::<bool>())
     547            0 :                 .transpose()
     548            0 :                 .context("Failed to parse 'gc_compaction_verification' as bool")?,
     549            0 :             gc_compaction_initial_threshold_kb: settings
     550            0 :                 .remove("gc_compaction_initial_threshold_kb")
     551            0 :                 .map(|x| x.parse::<u64>())
     552            0 :                 .transpose()
     553            0 :                 .context("Failed to parse 'gc_compaction_initial_threshold_kb' as integer")?,
     554            0 :             gc_compaction_ratio_percent: settings
     555            0 :                 .remove("gc_compaction_ratio_percent")
     556            0 :                 .map(|x| x.parse::<u64>())
     557            0 :                 .transpose()
     558            0 :                 .context("Failed to parse 'gc_compaction_ratio_percent' as integer")?,
     559            0 :             sampling_ratio: settings
     560            0 :                 .remove("sampling_ratio")
     561            0 :                 .map(serde_json::from_str)
     562            0 :                 .transpose()
     563            0 :                 .context("Falied to parse 'sampling_ratio'")?,
     564            0 :             relsize_snapshot_cache_capacity: settings
     565            0 :                 .remove("relsize snapshot cache capacity")
     566            0 :                 .map(|x| x.parse::<usize>())
     567            0 :                 .transpose()
     568            0 :                 .context("Falied to parse 'relsize_snapshot_cache_capacity' as integer")?,
     569            0 :             basebackup_cache_enabled: settings
     570            0 :                 .remove("basebackup_cache_enabled")
     571            0 :                 .map(|x| x.parse::<bool>())
     572            0 :                 .transpose()
     573            0 :                 .context("Failed to parse 'basebackup_cache_enabled' as bool")?,
     574              :         };
     575            0 :         if !settings.is_empty() {
     576            0 :             bail!("Unrecognized tenant settings: {settings:?}")
     577              :         } else {
     578            0 :             Ok(result)
     579              :         }
     580            0 :     }
     581              : 
     582            0 :     pub async fn tenant_config(
     583            0 :         &self,
     584            0 :         tenant_id: TenantId,
     585            0 :         settings: HashMap<&str, &str>,
     586            0 :     ) -> anyhow::Result<()> {
     587            0 :         let config = Self::parse_config(settings)?;
     588            0 :         self.http_client
     589            0 :             .set_tenant_config(&models::TenantConfigRequest { tenant_id, config })
     590            0 :             .await?;
     591              : 
     592            0 :         Ok(())
     593            0 :     }
     594              : 
     595            0 :     pub async fn timeline_list(
     596            0 :         &self,
     597            0 :         tenant_shard_id: &TenantShardId,
     598            0 :     ) -> anyhow::Result<Vec<TimelineInfo>> {
     599            0 :         Ok(self.http_client.list_timelines(*tenant_shard_id).await?)
     600            0 :     }
     601              : 
     602              :     /// Import a basebackup prepared using either:
     603              :     /// a) `pg_basebackup -F tar`, or
     604              :     /// b) The `fullbackup` pageserver endpoint
     605              :     ///
     606              :     /// # Arguments
     607              :     /// * `tenant_id` - tenant to import into. Created if not exists
     608              :     /// * `timeline_id` - id to assign to imported timeline
     609              :     /// * `base` - (start lsn of basebackup, path to `base.tar` file)
     610              :     /// * `pg_wal` - if there's any wal to import: (end lsn, path to `pg_wal.tar`)
     611            0 :     pub async fn timeline_import(
     612            0 :         &self,
     613            0 :         tenant_id: TenantId,
     614            0 :         timeline_id: TimelineId,
     615            0 :         base: (Lsn, PathBuf),
     616            0 :         pg_wal: Option<(Lsn, PathBuf)>,
     617            0 :         pg_version: PgMajorVersion,
     618            0 :     ) -> anyhow::Result<()> {
     619              :         // Init base reader
     620            0 :         let (start_lsn, base_tarfile_path) = base;
     621            0 :         let base_tarfile = tokio::fs::File::open(base_tarfile_path).await?;
     622            0 :         let base_tarfile =
     623            0 :             mgmt_api::ReqwestBody::wrap_stream(tokio_util::io::ReaderStream::new(base_tarfile));
     624              : 
     625              :         // Init wal reader if necessary
     626            0 :         let (end_lsn, wal_reader) = if let Some((end_lsn, wal_tarfile_path)) = pg_wal {
     627            0 :             let wal_tarfile = tokio::fs::File::open(wal_tarfile_path).await?;
     628            0 :             let wal_reader =
     629            0 :                 mgmt_api::ReqwestBody::wrap_stream(tokio_util::io::ReaderStream::new(wal_tarfile));
     630            0 :             (end_lsn, Some(wal_reader))
     631              :         } else {
     632            0 :             (start_lsn, None)
     633              :         };
     634              : 
     635              :         // Import base
     636            0 :         self.http_client
     637            0 :             .import_basebackup(
     638            0 :                 tenant_id,
     639            0 :                 timeline_id,
     640            0 :                 start_lsn,
     641            0 :                 end_lsn,
     642            0 :                 pg_version,
     643            0 :                 base_tarfile,
     644            0 :             )
     645            0 :             .await?;
     646              : 
     647              :         // Import wal if necessary
     648            0 :         if let Some(wal_reader) = wal_reader {
     649            0 :             self.http_client
     650            0 :                 .import_wal(tenant_id, timeline_id, start_lsn, end_lsn, wal_reader)
     651            0 :                 .await?;
     652            0 :         }
     653              : 
     654            0 :         Ok(())
     655            0 :     }
     656            0 :     pub async fn timeline_info(
     657            0 :         &self,
     658            0 :         tenant_shard_id: TenantShardId,
     659            0 :         timeline_id: TimelineId,
     660            0 :         force_await_logical_size: mgmt_api::ForceAwaitLogicalSize,
     661            0 :     ) -> anyhow::Result<TimelineInfo> {
     662            0 :         let timeline_info = self
     663            0 :             .http_client
     664            0 :             .timeline_info(tenant_shard_id, timeline_id, force_await_logical_size)
     665            0 :             .await?;
     666            0 :         Ok(timeline_info)
     667            0 :     }
     668              : }
        

Generated by: LCOV version 2.1-beta