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