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

Generated by: LCOV version 2.1-beta