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