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

Generated by: LCOV version 2.1-beta