LCOV - code coverage report
Current view: top level - control_plane/src - pageserver.rs (source / functions) Coverage Total Hit
Test: 42f947419473a288706e86ecdf7c2863d760d5d7.info Lines: 0.0 % 498 0
Test Date: 2024-08-02 21:34:27 Functions: 0.0 % 78 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::Document {
      79            0 :         toml_edit::Document::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::Document> {
      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::Document::new();
     141            0 :         for fragment_str in overrides {
     142            0 :             let fragment = toml_edit::Document::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            0 :         let config = self
     185            0 :             .pageserver_init_make_toml(conf)
     186            0 :             .context("make pageserver toml")?;
     187            0 :         let config_file_path = datadir.join("pageserver.toml");
     188            0 :         let mut config_file = std::fs::OpenOptions::new()
     189            0 :             .create_new(true)
     190            0 :             .write(true)
     191            0 :             .open(&config_file_path)
     192            0 :             .with_context(|| format!("open pageserver toml for write: {config_file_path:?}"))?;
     193            0 :         config_file
     194            0 :             .write_all(config.to_string().as_bytes())
     195            0 :             .context("write pageserver toml")?;
     196            0 :         drop(config_file);
     197            0 : 
     198            0 :         let identity_file_path = datadir.join("identity.toml");
     199            0 :         let mut identity_file = std::fs::OpenOptions::new()
     200            0 :             .create_new(true)
     201            0 :             .write(true)
     202            0 :             .open(identity_file_path)
     203            0 :             .with_context(|| format!("open identity toml for write: {config_file_path:?}"))?;
     204            0 :         let identity_toml = self.pageserver_make_identity_toml(node_id);
     205            0 :         identity_file
     206            0 :             .write_all(identity_toml.to_string().as_bytes())
     207            0 :             .context("write identity toml")?;
     208            0 :         drop(identity_toml);
     209            0 : 
     210            0 :         // TODO: invoke a TBD config-check command to validate that pageserver will start with the written config
     211            0 : 
     212            0 :         // Write metadata file, used by pageserver on startup to register itself with
     213            0 :         // the storage controller
     214            0 :         let metadata_path = datadir.join("metadata.json");
     215            0 : 
     216            0 :         let (_http_host, http_port) =
     217            0 :             parse_host_port(&self.conf.listen_http_addr).expect("Unable to parse listen_http_addr");
     218            0 :         let http_port = http_port.unwrap_or(9898);
     219            0 :         // Intentionally hand-craft JSON: this acts as an implicit format compat test
     220            0 :         // in case the pageserver-side structure is edited, and reflects the real life
     221            0 :         // situation: the metadata is written by some other script.
     222            0 :         std::fs::write(
     223            0 :             metadata_path,
     224            0 :             serde_json::to_vec(&pageserver_api::config::NodeMetadata {
     225            0 :                 postgres_host: "localhost".to_string(),
     226            0 :                 postgres_port: self.pg_connection_config.port(),
     227            0 :                 http_host: "localhost".to_string(),
     228            0 :                 http_port,
     229            0 :                 other: HashMap::new(),
     230            0 :             })
     231            0 :             .unwrap(),
     232            0 :         )
     233            0 :         .expect("Failed to write metadata file");
     234            0 : 
     235            0 :         Ok(())
     236            0 :     }
     237              : 
     238            0 :     async fn start_node(&self, retry_timeout: &Duration) -> anyhow::Result<()> {
     239            0 :         // TODO: using a thread here because start_process() is not async but we need to call check_status()
     240            0 :         let datadir = self.repo_path();
     241            0 :         print!(
     242            0 :             "Starting pageserver node {} at '{}' in {:?}, retrying for {:?}",
     243            0 :             self.conf.id,
     244            0 :             self.pg_connection_config.raw_address(),
     245            0 :             datadir,
     246            0 :             retry_timeout
     247            0 :         );
     248            0 :         io::stdout().flush().context("flush stdout")?;
     249              : 
     250            0 :         let datadir_path_str = datadir.to_str().with_context(|| {
     251            0 :             format!(
     252            0 :                 "Cannot start pageserver node {} in path that has no string representation: {:?}",
     253            0 :                 self.conf.id, datadir,
     254            0 :             )
     255            0 :         })?;
     256            0 :         let args = vec!["-D", datadir_path_str];
     257            0 :         background_process::start_process(
     258            0 :             "pageserver",
     259            0 :             &datadir,
     260            0 :             &self.env.pageserver_bin(),
     261            0 :             args,
     262            0 :             self.pageserver_env_variables()?,
     263            0 :             background_process::InitialPidFile::Expect(self.pid_file()),
     264            0 :             retry_timeout,
     265            0 :             || async {
     266            0 :                 let st = self.check_status().await;
     267            0 :                 match st {
     268            0 :                     Ok(()) => Ok(true),
     269            0 :                     Err(mgmt_api::Error::ReceiveBody(_)) => Ok(false),
     270            0 :                     Err(e) => Err(anyhow::anyhow!("Failed to check node status: {e}")),
     271            0 :                 }
     272            0 :             },
     273            0 :         )
     274            0 :         .await?;
     275              : 
     276            0 :         Ok(())
     277            0 :     }
     278              : 
     279            0 :     fn pageserver_env_variables(&self) -> anyhow::Result<Vec<(String, String)>> {
     280            0 :         // FIXME: why is this tied to pageserver's auth type? Whether or not the safekeeper
     281            0 :         // needs a token, and how to generate that token, seems independent to whether
     282            0 :         // the pageserver requires a token in incoming requests.
     283            0 :         Ok(if self.conf.http_auth_type != AuthType::Trust {
     284              :             // Generate a token to connect from the pageserver to a safekeeper
     285            0 :             let token = self
     286            0 :                 .env
     287            0 :                 .generate_auth_token(&Claims::new(None, Scope::SafekeeperData))?;
     288            0 :             vec![("NEON_AUTH_TOKEN".to_owned(), token)]
     289              :         } else {
     290            0 :             Vec::new()
     291              :         })
     292            0 :     }
     293              : 
     294              :     ///
     295              :     /// Stop the server.
     296              :     ///
     297              :     /// If 'immediate' is true, we use SIGQUIT, killing the process immediately.
     298              :     /// Otherwise we use SIGTERM, triggering a clean shutdown
     299              :     ///
     300              :     /// If the server is not running, returns success
     301              :     ///
     302            0 :     pub fn stop(&self, immediate: bool) -> anyhow::Result<()> {
     303            0 :         background_process::stop_process(immediate, "pageserver", &self.pid_file())
     304            0 :     }
     305              : 
     306            0 :     pub async fn page_server_psql_client(
     307            0 :         &self,
     308            0 :     ) -> anyhow::Result<(
     309            0 :         tokio_postgres::Client,
     310            0 :         tokio_postgres::Connection<tokio_postgres::Socket, tokio_postgres::tls::NoTlsStream>,
     311            0 :     )> {
     312            0 :         let mut config = self.pg_connection_config.clone();
     313            0 :         if self.conf.pg_auth_type == AuthType::NeonJWT {
     314            0 :             let token = self
     315            0 :                 .env
     316            0 :                 .generate_auth_token(&Claims::new(None, Scope::PageServerApi))?;
     317            0 :             config = config.set_password(Some(token));
     318            0 :         }
     319            0 :         Ok(config.connect_no_tls().await?)
     320            0 :     }
     321              : 
     322            0 :     pub async fn check_status(&self) -> mgmt_api::Result<()> {
     323            0 :         self.http_client.status().await
     324            0 :     }
     325              : 
     326            0 :     pub async fn tenant_list(&self) -> mgmt_api::Result<Vec<TenantInfo>> {
     327            0 :         self.http_client.list_tenants().await
     328            0 :     }
     329            0 :     pub fn parse_config(mut settings: HashMap<&str, &str>) -> anyhow::Result<models::TenantConfig> {
     330            0 :         let result = models::TenantConfig {
     331            0 :             checkpoint_distance: settings
     332            0 :                 .remove("checkpoint_distance")
     333            0 :                 .map(|x| x.parse::<u64>())
     334            0 :                 .transpose()?,
     335            0 :             checkpoint_timeout: settings.remove("checkpoint_timeout").map(|x| x.to_string()),
     336            0 :             compaction_target_size: settings
     337            0 :                 .remove("compaction_target_size")
     338            0 :                 .map(|x| x.parse::<u64>())
     339            0 :                 .transpose()?,
     340            0 :             compaction_period: settings.remove("compaction_period").map(|x| x.to_string()),
     341            0 :             compaction_threshold: settings
     342            0 :                 .remove("compaction_threshold")
     343            0 :                 .map(|x| x.parse::<usize>())
     344            0 :                 .transpose()?,
     345            0 :             compaction_algorithm: settings
     346            0 :                 .remove("compaction_algorithm")
     347            0 :                 .map(serde_json::from_str)
     348            0 :                 .transpose()
     349            0 :                 .context("Failed to parse 'compaction_algorithm' json")?,
     350            0 :             gc_horizon: settings
     351            0 :                 .remove("gc_horizon")
     352            0 :                 .map(|x| x.parse::<u64>())
     353            0 :                 .transpose()?,
     354            0 :             gc_period: settings.remove("gc_period").map(|x| x.to_string()),
     355            0 :             image_creation_threshold: settings
     356            0 :                 .remove("image_creation_threshold")
     357            0 :                 .map(|x| x.parse::<usize>())
     358            0 :                 .transpose()?,
     359            0 :             image_layer_creation_check_threshold: settings
     360            0 :                 .remove("image_layer_creation_check_threshold")
     361            0 :                 .map(|x| x.parse::<u8>())
     362            0 :                 .transpose()?,
     363            0 :             pitr_interval: settings.remove("pitr_interval").map(|x| x.to_string()),
     364            0 :             walreceiver_connect_timeout: settings
     365            0 :                 .remove("walreceiver_connect_timeout")
     366            0 :                 .map(|x| x.to_string()),
     367            0 :             lagging_wal_timeout: settings
     368            0 :                 .remove("lagging_wal_timeout")
     369            0 :                 .map(|x| x.to_string()),
     370            0 :             max_lsn_wal_lag: settings
     371            0 :                 .remove("max_lsn_wal_lag")
     372            0 :                 .map(|x| x.parse::<NonZeroU64>())
     373            0 :                 .transpose()
     374            0 :                 .context("Failed to parse 'max_lsn_wal_lag' as non zero integer")?,
     375            0 :             eviction_policy: settings
     376            0 :                 .remove("eviction_policy")
     377            0 :                 .map(serde_json::from_str)
     378            0 :                 .transpose()
     379            0 :                 .context("Failed to parse 'eviction_policy' json")?,
     380            0 :             min_resident_size_override: settings
     381            0 :                 .remove("min_resident_size_override")
     382            0 :                 .map(|x| x.parse::<u64>())
     383            0 :                 .transpose()
     384            0 :                 .context("Failed to parse 'min_resident_size_override' as integer")?,
     385            0 :             evictions_low_residence_duration_metric_threshold: settings
     386            0 :                 .remove("evictions_low_residence_duration_metric_threshold")
     387            0 :                 .map(|x| x.to_string()),
     388            0 :             heatmap_period: settings.remove("heatmap_period").map(|x| x.to_string()),
     389            0 :             lazy_slru_download: settings
     390            0 :                 .remove("lazy_slru_download")
     391            0 :                 .map(|x| x.parse::<bool>())
     392            0 :                 .transpose()
     393            0 :                 .context("Failed to parse 'lazy_slru_download' as bool")?,
     394            0 :             timeline_get_throttle: settings
     395            0 :                 .remove("timeline_get_throttle")
     396            0 :                 .map(serde_json::from_str)
     397            0 :                 .transpose()
     398            0 :                 .context("parse `timeline_get_throttle` from json")?,
     399            0 :             switch_aux_file_policy: settings
     400            0 :                 .remove("switch_aux_file_policy")
     401            0 :                 .map(|x| x.parse::<AuxFilePolicy>())
     402            0 :                 .transpose()
     403            0 :                 .context("Failed to parse 'switch_aux_file_policy'")?,
     404            0 :             lsn_lease_length: settings.remove("lsn_lease_length").map(|x| x.to_string()),
     405            0 :             lsn_lease_length_for_ts: settings
     406            0 :                 .remove("lsn_lease_length_for_ts")
     407            0 :                 .map(|x| x.to_string()),
     408            0 :         };
     409            0 :         if !settings.is_empty() {
     410            0 :             bail!("Unrecognized tenant settings: {settings:?}")
     411              :         } else {
     412            0 :             Ok(result)
     413              :         }
     414            0 :     }
     415              : 
     416            0 :     pub async fn tenant_config(
     417            0 :         &self,
     418            0 :         tenant_id: TenantId,
     419            0 :         mut settings: HashMap<&str, &str>,
     420            0 :     ) -> anyhow::Result<()> {
     421            0 :         let config = {
     422              :             // Braces to make the diff easier to read
     423              :             models::TenantConfig {
     424            0 :                 checkpoint_distance: settings
     425            0 :                     .remove("checkpoint_distance")
     426            0 :                     .map(|x| x.parse::<u64>())
     427            0 :                     .transpose()
     428            0 :                     .context("Failed to parse 'checkpoint_distance' as an integer")?,
     429            0 :                 checkpoint_timeout: settings.remove("checkpoint_timeout").map(|x| x.to_string()),
     430            0 :                 compaction_target_size: settings
     431            0 :                     .remove("compaction_target_size")
     432            0 :                     .map(|x| x.parse::<u64>())
     433            0 :                     .transpose()
     434            0 :                     .context("Failed to parse 'compaction_target_size' as an integer")?,
     435            0 :                 compaction_period: settings.remove("compaction_period").map(|x| x.to_string()),
     436            0 :                 compaction_threshold: settings
     437            0 :                     .remove("compaction_threshold")
     438            0 :                     .map(|x| x.parse::<usize>())
     439            0 :                     .transpose()
     440            0 :                     .context("Failed to parse 'compaction_threshold' as an integer")?,
     441            0 :                 compaction_algorithm: settings
     442            0 :                     .remove("compactin_algorithm")
     443            0 :                     .map(serde_json::from_str)
     444            0 :                     .transpose()
     445            0 :                     .context("Failed to parse 'compaction_algorithm' json")?,
     446            0 :                 gc_horizon: settings
     447            0 :                     .remove("gc_horizon")
     448            0 :                     .map(|x| x.parse::<u64>())
     449            0 :                     .transpose()
     450            0 :                     .context("Failed to parse 'gc_horizon' as an integer")?,
     451            0 :                 gc_period: settings.remove("gc_period").map(|x| x.to_string()),
     452            0 :                 image_creation_threshold: settings
     453            0 :                     .remove("image_creation_threshold")
     454            0 :                     .map(|x| x.parse::<usize>())
     455            0 :                     .transpose()
     456            0 :                     .context("Failed to parse 'image_creation_threshold' as non zero integer")?,
     457            0 :                 image_layer_creation_check_threshold: settings
     458            0 :                     .remove("image_layer_creation_check_threshold")
     459            0 :                     .map(|x| x.parse::<u8>())
     460            0 :                     .transpose()
     461            0 :                     .context("Failed to parse 'image_creation_check_threshold' as integer")?,
     462              : 
     463            0 :                 pitr_interval: settings.remove("pitr_interval").map(|x| x.to_string()),
     464            0 :                 walreceiver_connect_timeout: settings
     465            0 :                     .remove("walreceiver_connect_timeout")
     466            0 :                     .map(|x| x.to_string()),
     467            0 :                 lagging_wal_timeout: settings
     468            0 :                     .remove("lagging_wal_timeout")
     469            0 :                     .map(|x| x.to_string()),
     470            0 :                 max_lsn_wal_lag: settings
     471            0 :                     .remove("max_lsn_wal_lag")
     472            0 :                     .map(|x| x.parse::<NonZeroU64>())
     473            0 :                     .transpose()
     474            0 :                     .context("Failed to parse 'max_lsn_wal_lag' as non zero integer")?,
     475            0 :                 eviction_policy: settings
     476            0 :                     .remove("eviction_policy")
     477            0 :                     .map(serde_json::from_str)
     478            0 :                     .transpose()
     479            0 :                     .context("Failed to parse 'eviction_policy' json")?,
     480            0 :                 min_resident_size_override: settings
     481            0 :                     .remove("min_resident_size_override")
     482            0 :                     .map(|x| x.parse::<u64>())
     483            0 :                     .transpose()
     484            0 :                     .context("Failed to parse 'min_resident_size_override' as an integer")?,
     485            0 :                 evictions_low_residence_duration_metric_threshold: settings
     486            0 :                     .remove("evictions_low_residence_duration_metric_threshold")
     487            0 :                     .map(|x| x.to_string()),
     488            0 :                 heatmap_period: settings.remove("heatmap_period").map(|x| x.to_string()),
     489            0 :                 lazy_slru_download: settings
     490            0 :                     .remove("lazy_slru_download")
     491            0 :                     .map(|x| x.parse::<bool>())
     492            0 :                     .transpose()
     493            0 :                     .context("Failed to parse 'lazy_slru_download' as bool")?,
     494            0 :                 timeline_get_throttle: settings
     495            0 :                     .remove("timeline_get_throttle")
     496            0 :                     .map(serde_json::from_str)
     497            0 :                     .transpose()
     498            0 :                     .context("parse `timeline_get_throttle` from json")?,
     499            0 :                 switch_aux_file_policy: settings
     500            0 :                     .remove("switch_aux_file_policy")
     501            0 :                     .map(|x| x.parse::<AuxFilePolicy>())
     502            0 :                     .transpose()
     503            0 :                     .context("Failed to parse 'switch_aux_file_policy'")?,
     504            0 :                 lsn_lease_length: settings.remove("lsn_lease_length").map(|x| x.to_string()),
     505            0 :                 lsn_lease_length_for_ts: settings
     506            0 :                     .remove("lsn_lease_length_for_ts")
     507            0 :                     .map(|x| x.to_string()),
     508            0 :             }
     509            0 :         };
     510            0 : 
     511            0 :         if !settings.is_empty() {
     512            0 :             bail!("Unrecognized tenant settings: {settings:?}")
     513            0 :         }
     514            0 : 
     515            0 :         self.http_client
     516            0 :             .tenant_config(&models::TenantConfigRequest { tenant_id, config })
     517            0 :             .await?;
     518              : 
     519            0 :         Ok(())
     520            0 :     }
     521              : 
     522            0 :     pub async fn location_config(
     523            0 :         &self,
     524            0 :         tenant_shard_id: TenantShardId,
     525            0 :         config: LocationConfig,
     526            0 :         flush_ms: Option<Duration>,
     527            0 :         lazy: bool,
     528            0 :     ) -> anyhow::Result<()> {
     529            0 :         Ok(self
     530            0 :             .http_client
     531            0 :             .location_config(tenant_shard_id, config, flush_ms, lazy)
     532            0 :             .await?)
     533            0 :     }
     534              : 
     535            0 :     pub async fn timeline_list(
     536            0 :         &self,
     537            0 :         tenant_shard_id: &TenantShardId,
     538            0 :     ) -> anyhow::Result<Vec<TimelineInfo>> {
     539            0 :         Ok(self.http_client.list_timelines(*tenant_shard_id).await?)
     540            0 :     }
     541              : 
     542            0 :     pub async fn timeline_create(
     543            0 :         &self,
     544            0 :         tenant_shard_id: TenantShardId,
     545            0 :         new_timeline_id: TimelineId,
     546            0 :         ancestor_start_lsn: Option<Lsn>,
     547            0 :         ancestor_timeline_id: Option<TimelineId>,
     548            0 :         pg_version: Option<u32>,
     549            0 :         existing_initdb_timeline_id: Option<TimelineId>,
     550            0 :     ) -> anyhow::Result<TimelineInfo> {
     551            0 :         let req = models::TimelineCreateRequest {
     552            0 :             new_timeline_id,
     553            0 :             ancestor_start_lsn,
     554            0 :             ancestor_timeline_id,
     555            0 :             pg_version,
     556            0 :             existing_initdb_timeline_id,
     557            0 :         };
     558            0 :         Ok(self
     559            0 :             .http_client
     560            0 :             .timeline_create(tenant_shard_id, &req)
     561            0 :             .await?)
     562            0 :     }
     563              : 
     564              :     /// Import a basebackup prepared using either:
     565              :     /// a) `pg_basebackup -F tar`, or
     566              :     /// b) The `fullbackup` pageserver endpoint
     567              :     ///
     568              :     /// # Arguments
     569              :     /// * `tenant_id` - tenant to import into. Created if not exists
     570              :     /// * `timeline_id` - id to assign to imported timeline
     571              :     /// * `base` - (start lsn of basebackup, path to `base.tar` file)
     572              :     /// * `pg_wal` - if there's any wal to import: (end lsn, path to `pg_wal.tar`)
     573            0 :     pub async fn timeline_import(
     574            0 :         &self,
     575            0 :         tenant_id: TenantId,
     576            0 :         timeline_id: TimelineId,
     577            0 :         base: (Lsn, PathBuf),
     578            0 :         pg_wal: Option<(Lsn, PathBuf)>,
     579            0 :         pg_version: u32,
     580            0 :     ) -> anyhow::Result<()> {
     581            0 :         // Init base reader
     582            0 :         let (start_lsn, base_tarfile_path) = base;
     583            0 :         let base_tarfile = tokio::fs::File::open(base_tarfile_path).await?;
     584            0 :         let base_tarfile =
     585            0 :             mgmt_api::ReqwestBody::wrap_stream(tokio_util::io::ReaderStream::new(base_tarfile));
     586              : 
     587              :         // Init wal reader if necessary
     588            0 :         let (end_lsn, wal_reader) = if let Some((end_lsn, wal_tarfile_path)) = pg_wal {
     589            0 :             let wal_tarfile = tokio::fs::File::open(wal_tarfile_path).await?;
     590            0 :             let wal_reader =
     591            0 :                 mgmt_api::ReqwestBody::wrap_stream(tokio_util::io::ReaderStream::new(wal_tarfile));
     592            0 :             (end_lsn, Some(wal_reader))
     593              :         } else {
     594            0 :             (start_lsn, None)
     595              :         };
     596              : 
     597              :         // Import base
     598            0 :         self.http_client
     599            0 :             .import_basebackup(
     600            0 :                 tenant_id,
     601            0 :                 timeline_id,
     602            0 :                 start_lsn,
     603            0 :                 end_lsn,
     604            0 :                 pg_version,
     605            0 :                 base_tarfile,
     606            0 :             )
     607            0 :             .await?;
     608              : 
     609              :         // Import wal if necessary
     610            0 :         if let Some(wal_reader) = wal_reader {
     611            0 :             self.http_client
     612            0 :                 .import_wal(tenant_id, timeline_id, start_lsn, end_lsn, wal_reader)
     613            0 :                 .await?;
     614            0 :         }
     615              : 
     616            0 :         Ok(())
     617            0 :     }
     618              : 
     619            0 :     pub async fn tenant_synthetic_size(
     620            0 :         &self,
     621            0 :         tenant_shard_id: TenantShardId,
     622            0 :     ) -> anyhow::Result<TenantHistorySize> {
     623            0 :         Ok(self
     624            0 :             .http_client
     625            0 :             .tenant_synthetic_size(tenant_shard_id)
     626            0 :             .await?)
     627            0 :     }
     628              : }
        

Generated by: LCOV version 2.1-beta