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

Generated by: LCOV version 2.1-beta