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