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::borrow::Cow;
8 : use std::collections::HashMap;
9 :
10 : use std::io;
11 : use std::io::Write;
12 : use std::num::NonZeroU64;
13 : use std::path::PathBuf;
14 : use std::process::Command;
15 : use std::time::Duration;
16 :
17 : use anyhow::{bail, Context};
18 : use camino::Utf8PathBuf;
19 : use futures::SinkExt;
20 : use pageserver_api::models::{
21 : self, LocationConfig, ShardParameters, 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::{
29 : id::{TenantId, TimelineId},
30 : lsn::Lsn,
31 : };
32 :
33 : use crate::attachment_service::{AttachmentService, NodeRegisterRequest};
34 : use crate::local_env::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 0 : #[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 : /// Merge overrides provided by the user on the command line with our default overides derived from neon_local configuration.
79 : ///
80 : /// These all end up on the command line of the `pageserver` binary.
81 0 : fn neon_local_overrides(&self, cli_overrides: &[&str]) -> Vec<String> {
82 0 : let id = format!("id={}", self.conf.id);
83 0 : // FIXME: the paths should be shell-escaped to handle paths with spaces, quotas etc.
84 0 : let pg_distrib_dir_param = format!(
85 0 : "pg_distrib_dir='{}'",
86 0 : self.env.pg_distrib_dir_raw().display()
87 0 : );
88 0 :
89 0 : let http_auth_type_param = format!("http_auth_type='{}'", self.conf.http_auth_type);
90 0 : let listen_http_addr_param = format!("listen_http_addr='{}'", self.conf.listen_http_addr);
91 0 :
92 0 : let pg_auth_type_param = format!("pg_auth_type='{}'", self.conf.pg_auth_type);
93 0 : let listen_pg_addr_param = format!("listen_pg_addr='{}'", self.conf.listen_pg_addr);
94 0 :
95 0 : let broker_endpoint_param = format!("broker_endpoint='{}'", self.env.broker.client_url());
96 0 :
97 0 : let mut overrides = vec![
98 0 : id,
99 0 : pg_distrib_dir_param,
100 0 : http_auth_type_param,
101 0 : pg_auth_type_param,
102 0 : listen_http_addr_param,
103 0 : listen_pg_addr_param,
104 0 : broker_endpoint_param,
105 0 : ];
106 :
107 0 : if let Some(control_plane_api) = &self.env.control_plane_api {
108 0 : overrides.push(format!(
109 0 : "control_plane_api='{}'",
110 0 : control_plane_api.as_str()
111 0 : ));
112 :
113 : // Attachment service uses the same auth as pageserver: if JWT is enabled
114 : // for us, we will also need it to talk to them.
115 0 : if matches!(self.conf.http_auth_type, AuthType::NeonJWT) {
116 0 : let jwt_token = self
117 0 : .env
118 0 : .generate_auth_token(&Claims::new(None, Scope::PageServerApi))
119 0 : .unwrap();
120 0 : overrides.push(format!("control_plane_api_token='{}'", jwt_token));
121 0 : }
122 0 : }
123 :
124 0 : if !cli_overrides
125 0 : .iter()
126 0 : .any(|c| c.starts_with("remote_storage"))
127 0 : {
128 0 : overrides.push(format!(
129 0 : "remote_storage={{local_path='../{PAGESERVER_REMOTE_STORAGE_DIR}'}}"
130 0 : ));
131 0 : }
132 :
133 0 : if self.conf.http_auth_type != AuthType::Trust || self.conf.pg_auth_type != AuthType::Trust
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 : // Apply the user-provided overrides
141 0 : overrides.extend(cli_overrides.iter().map(|&c| c.to_owned()));
142 0 :
143 0 : overrides
144 0 : }
145 :
146 : /// Initializes a pageserver node by creating its config with the overrides provided.
147 0 : pub fn initialize(&self, config_overrides: &[&str]) -> anyhow::Result<()> {
148 0 : // First, run `pageserver --init` and wait for it to write a config into FS and exit.
149 0 : self.pageserver_init(config_overrides)
150 0 : .with_context(|| format!("Failed to run init for pageserver node {}", self.conf.id))
151 0 : }
152 :
153 0 : pub fn repo_path(&self) -> PathBuf {
154 0 : self.env.pageserver_data_dir(self.conf.id)
155 0 : }
156 :
157 : /// The pid file is created by the pageserver process, with its pid stored inside.
158 : /// Other pageservers cannot lock the same file and overwrite it for as long as the current
159 : /// pageserver runs. (Unless someone removes the file manually; never do that!)
160 0 : fn pid_file(&self) -> Utf8PathBuf {
161 0 : Utf8PathBuf::from_path_buf(self.repo_path().join("pageserver.pid"))
162 0 : .expect("non-Unicode path")
163 0 : }
164 :
165 0 : pub async fn start(&self, config_overrides: &[&str], register: bool) -> anyhow::Result<()> {
166 0 : self.start_node(config_overrides, false, register).await
167 0 : }
168 :
169 0 : fn pageserver_init(&self, config_overrides: &[&str]) -> anyhow::Result<()> {
170 0 : let datadir = self.repo_path();
171 0 : let node_id = self.conf.id;
172 0 : println!(
173 0 : "Initializing pageserver node {} at '{}' in {:?}",
174 0 : node_id,
175 0 : self.pg_connection_config.raw_address(),
176 0 : datadir
177 0 : );
178 0 : io::stdout().flush()?;
179 :
180 0 : if !datadir.exists() {
181 0 : std::fs::create_dir(&datadir)?;
182 0 : }
183 :
184 0 : let datadir_path_str = datadir.to_str().with_context(|| {
185 0 : format!("Cannot start pageserver node {node_id} in path that has no string representation: {datadir:?}")
186 0 : })?;
187 0 : let mut args = self.pageserver_basic_args(config_overrides, datadir_path_str);
188 0 : args.push(Cow::Borrowed("--init"));
189 :
190 0 : let init_output = Command::new(self.env.pageserver_bin())
191 0 : .args(args.iter().map(Cow::as_ref))
192 0 : .envs(self.pageserver_env_variables()?)
193 0 : .output()
194 0 : .with_context(|| format!("Failed to run pageserver init for node {node_id}"))?;
195 :
196 0 : anyhow::ensure!(
197 0 : init_output.status.success(),
198 0 : "Pageserver init for node {} did not finish successfully, stdout: {}, stderr: {}",
199 0 : node_id,
200 0 : String::from_utf8_lossy(&init_output.stdout),
201 0 : String::from_utf8_lossy(&init_output.stderr),
202 : );
203 :
204 0 : Ok(())
205 0 : }
206 :
207 0 : async fn start_node(
208 0 : &self,
209 0 : config_overrides: &[&str],
210 0 : update_config: bool,
211 0 : register: bool,
212 0 : ) -> anyhow::Result<()> {
213 0 : // Register the node with the storage controller before starting pageserver: pageserver must be registered to
214 0 : // successfully call /re-attach and finish starting up.
215 0 : if register {
216 0 : let attachment_service = AttachmentService::from_env(&self.env);
217 0 : let (pg_host, pg_port) =
218 0 : parse_host_port(&self.conf.listen_pg_addr).expect("Unable to parse listen_pg_addr");
219 0 : let (http_host, http_port) = parse_host_port(&self.conf.listen_http_addr)
220 0 : .expect("Unable to parse listen_http_addr");
221 0 : attachment_service
222 0 : .node_register(NodeRegisterRequest {
223 0 : node_id: self.conf.id,
224 0 : listen_pg_addr: pg_host.to_string(),
225 0 : listen_pg_port: pg_port.unwrap_or(5432),
226 0 : listen_http_addr: http_host.to_string(),
227 0 : listen_http_port: http_port.unwrap_or(80),
228 0 : })
229 0 : .await?;
230 0 : }
231 :
232 : // TODO: using a thread here because start_process() is not async but we need to call check_status()
233 0 : let datadir = self.repo_path();
234 0 : print!(
235 0 : "Starting pageserver node {} at '{}' in {:?}",
236 0 : self.conf.id,
237 0 : self.pg_connection_config.raw_address(),
238 0 : datadir
239 0 : );
240 0 : io::stdout().flush().context("flush stdout")?;
241 :
242 0 : let datadir_path_str = datadir.to_str().with_context(|| {
243 0 : format!(
244 0 : "Cannot start pageserver node {} in path that has no string representation: {:?}",
245 0 : self.conf.id, datadir,
246 0 : )
247 0 : })?;
248 0 : let mut args = self.pageserver_basic_args(config_overrides, datadir_path_str);
249 0 : if update_config {
250 0 : args.push(Cow::Borrowed("--update-config"));
251 0 : }
252 : background_process::start_process(
253 0 : "pageserver",
254 0 : &datadir,
255 0 : &self.env.pageserver_bin(),
256 0 : args.iter().map(Cow::as_ref),
257 0 : self.pageserver_env_variables()?,
258 0 : background_process::InitialPidFile::Expect(self.pid_file()),
259 0 : || async {
260 0 : let st = self.check_status().await;
261 0 : match st {
262 0 : Ok(()) => Ok(true),
263 0 : Err(mgmt_api::Error::ReceiveBody(_)) => Ok(false),
264 0 : Err(e) => Err(anyhow::anyhow!("Failed to check node status: {e}")),
265 : }
266 0 : },
267 : )
268 0 : .await?;
269 :
270 0 : Ok(())
271 0 : }
272 :
273 0 : fn pageserver_basic_args<'a>(
274 0 : &self,
275 0 : config_overrides: &'a [&'a str],
276 0 : datadir_path_str: &'a str,
277 0 : ) -> Vec<Cow<'a, str>> {
278 0 : let mut args = vec![Cow::Borrowed("-D"), Cow::Borrowed(datadir_path_str)];
279 0 :
280 0 : let overrides = self.neon_local_overrides(config_overrides);
281 0 : for config_override in overrides {
282 0 : args.push(Cow::Borrowed("-c"));
283 0 : args.push(Cow::Owned(config_override));
284 0 : }
285 :
286 0 : args
287 0 : }
288 :
289 0 : fn pageserver_env_variables(&self) -> anyhow::Result<Vec<(String, String)>> {
290 0 : // FIXME: why is this tied to pageserver's auth type? Whether or not the safekeeper
291 0 : // needs a token, and how to generate that token, seems independent to whether
292 0 : // the pageserver requires a token in incoming requests.
293 0 : Ok(if self.conf.http_auth_type != AuthType::Trust {
294 : // Generate a token to connect from the pageserver to a safekeeper
295 0 : let token = self
296 0 : .env
297 0 : .generate_auth_token(&Claims::new(None, Scope::SafekeeperData))?;
298 0 : vec![("NEON_AUTH_TOKEN".to_owned(), token)]
299 : } else {
300 0 : Vec::new()
301 : })
302 0 : }
303 :
304 : ///
305 : /// Stop the server.
306 : ///
307 : /// If 'immediate' is true, we use SIGQUIT, killing the process immediately.
308 : /// Otherwise we use SIGTERM, triggering a clean shutdown
309 : ///
310 : /// If the server is not running, returns success
311 : ///
312 0 : pub fn stop(&self, immediate: bool) -> anyhow::Result<()> {
313 0 : background_process::stop_process(immediate, "pageserver", &self.pid_file())
314 0 : }
315 :
316 0 : pub async fn page_server_psql_client(
317 0 : &self,
318 0 : ) -> anyhow::Result<(
319 0 : tokio_postgres::Client,
320 0 : tokio_postgres::Connection<tokio_postgres::Socket, tokio_postgres::tls::NoTlsStream>,
321 0 : )> {
322 0 : let mut config = self.pg_connection_config.clone();
323 0 : if self.conf.pg_auth_type == AuthType::NeonJWT {
324 0 : let token = self
325 0 : .env
326 0 : .generate_auth_token(&Claims::new(None, Scope::PageServerApi))?;
327 0 : config = config.set_password(Some(token));
328 0 : }
329 0 : Ok(config.connect_no_tls().await?)
330 0 : }
331 :
332 0 : pub async fn check_status(&self) -> mgmt_api::Result<()> {
333 0 : self.http_client.status().await
334 0 : }
335 :
336 0 : pub async fn tenant_list(&self) -> mgmt_api::Result<Vec<TenantInfo>> {
337 0 : self.http_client.list_tenants().await
338 0 : }
339 0 : pub fn parse_config(mut settings: HashMap<&str, &str>) -> anyhow::Result<models::TenantConfig> {
340 0 : let result = models::TenantConfig {
341 0 : checkpoint_distance: settings
342 0 : .remove("checkpoint_distance")
343 0 : .map(|x| x.parse::<u64>())
344 0 : .transpose()?,
345 0 : checkpoint_timeout: settings.remove("checkpoint_timeout").map(|x| x.to_string()),
346 0 : compaction_target_size: settings
347 0 : .remove("compaction_target_size")
348 0 : .map(|x| x.parse::<u64>())
349 0 : .transpose()?,
350 0 : compaction_period: settings.remove("compaction_period").map(|x| x.to_string()),
351 0 : compaction_threshold: settings
352 0 : .remove("compaction_threshold")
353 0 : .map(|x| x.parse::<usize>())
354 0 : .transpose()?,
355 0 : gc_horizon: settings
356 0 : .remove("gc_horizon")
357 0 : .map(|x| x.parse::<u64>())
358 0 : .transpose()?,
359 0 : gc_period: settings.remove("gc_period").map(|x| x.to_string()),
360 0 : image_creation_threshold: settings
361 0 : .remove("image_creation_threshold")
362 0 : .map(|x| x.parse::<usize>())
363 0 : .transpose()?,
364 0 : pitr_interval: settings.remove("pitr_interval").map(|x| x.to_string()),
365 0 : walreceiver_connect_timeout: settings
366 0 : .remove("walreceiver_connect_timeout")
367 0 : .map(|x| x.to_string()),
368 0 : lagging_wal_timeout: settings
369 0 : .remove("lagging_wal_timeout")
370 0 : .map(|x| x.to_string()),
371 0 : max_lsn_wal_lag: settings
372 0 : .remove("max_lsn_wal_lag")
373 0 : .map(|x| x.parse::<NonZeroU64>())
374 0 : .transpose()
375 0 : .context("Failed to parse 'max_lsn_wal_lag' as non zero integer")?,
376 0 : trace_read_requests: settings
377 0 : .remove("trace_read_requests")
378 0 : .map(|x| x.parse::<bool>())
379 0 : .transpose()
380 0 : .context("Failed to parse 'trace_read_requests' as bool")?,
381 0 : eviction_policy: settings
382 0 : .remove("eviction_policy")
383 0 : .map(serde_json::from_str)
384 0 : .transpose()
385 0 : .context("Failed to parse 'eviction_policy' json")?,
386 0 : min_resident_size_override: settings
387 0 : .remove("min_resident_size_override")
388 0 : .map(|x| x.parse::<u64>())
389 0 : .transpose()
390 0 : .context("Failed to parse 'min_resident_size_override' as integer")?,
391 0 : evictions_low_residence_duration_metric_threshold: settings
392 0 : .remove("evictions_low_residence_duration_metric_threshold")
393 0 : .map(|x| x.to_string()),
394 0 : gc_feedback: settings
395 0 : .remove("gc_feedback")
396 0 : .map(|x| x.parse::<bool>())
397 0 : .transpose()
398 0 : .context("Failed to parse 'gc_feedback' as bool")?,
399 0 : heatmap_period: settings.remove("heatmap_period").map(|x| x.to_string()),
400 0 : lazy_slru_download: settings
401 0 : .remove("lazy_slru_download")
402 0 : .map(|x| x.parse::<bool>())
403 0 : .transpose()
404 0 : .context("Failed to parse 'lazy_slru_download' as bool")?,
405 0 : timeline_get_throttle: settings
406 0 : .remove("timeline_get_throttle")
407 0 : .map(serde_json::from_str)
408 0 : .transpose()
409 0 : .context("parse `timeline_get_throttle` from json")?,
410 : };
411 0 : if !settings.is_empty() {
412 0 : bail!("Unrecognized tenant settings: {settings:?}")
413 : } else {
414 0 : Ok(result)
415 : }
416 0 : }
417 :
418 0 : pub async fn tenant_create(
419 0 : &self,
420 0 : new_tenant_id: TenantId,
421 0 : generation: Option<u32>,
422 0 : settings: HashMap<&str, &str>,
423 0 : ) -> anyhow::Result<TenantId> {
424 0 : let config = Self::parse_config(settings.clone())?;
425 :
426 0 : let request = models::TenantCreateRequest {
427 0 : new_tenant_id: TenantShardId::unsharded(new_tenant_id),
428 0 : generation,
429 0 : config,
430 0 : shard_parameters: ShardParameters::default(),
431 0 : };
432 0 : if !settings.is_empty() {
433 0 : bail!("Unrecognized tenant settings: {settings:?}")
434 0 : }
435 0 : Ok(self.http_client.tenant_create(&request).await?)
436 0 : }
437 :
438 0 : pub async fn tenant_config(
439 0 : &self,
440 0 : tenant_id: TenantId,
441 0 : mut settings: HashMap<&str, &str>,
442 0 : ) -> anyhow::Result<()> {
443 0 : let config = {
444 : // Braces to make the diff easier to read
445 : models::TenantConfig {
446 0 : checkpoint_distance: settings
447 0 : .remove("checkpoint_distance")
448 0 : .map(|x| x.parse::<u64>())
449 0 : .transpose()
450 0 : .context("Failed to parse 'checkpoint_distance' as an integer")?,
451 0 : checkpoint_timeout: settings.remove("checkpoint_timeout").map(|x| x.to_string()),
452 0 : compaction_target_size: settings
453 0 : .remove("compaction_target_size")
454 0 : .map(|x| x.parse::<u64>())
455 0 : .transpose()
456 0 : .context("Failed to parse 'compaction_target_size' as an integer")?,
457 0 : compaction_period: settings.remove("compaction_period").map(|x| x.to_string()),
458 0 : compaction_threshold: settings
459 0 : .remove("compaction_threshold")
460 0 : .map(|x| x.parse::<usize>())
461 0 : .transpose()
462 0 : .context("Failed to parse 'compaction_threshold' as an integer")?,
463 0 : gc_horizon: settings
464 0 : .remove("gc_horizon")
465 0 : .map(|x| x.parse::<u64>())
466 0 : .transpose()
467 0 : .context("Failed to parse 'gc_horizon' as an integer")?,
468 0 : gc_period: settings.remove("gc_period").map(|x| x.to_string()),
469 0 : image_creation_threshold: settings
470 0 : .remove("image_creation_threshold")
471 0 : .map(|x| x.parse::<usize>())
472 0 : .transpose()
473 0 : .context("Failed to parse 'image_creation_threshold' as non zero integer")?,
474 0 : pitr_interval: settings.remove("pitr_interval").map(|x| x.to_string()),
475 0 : walreceiver_connect_timeout: settings
476 0 : .remove("walreceiver_connect_timeout")
477 0 : .map(|x| x.to_string()),
478 0 : lagging_wal_timeout: settings
479 0 : .remove("lagging_wal_timeout")
480 0 : .map(|x| x.to_string()),
481 0 : max_lsn_wal_lag: settings
482 0 : .remove("max_lsn_wal_lag")
483 0 : .map(|x| x.parse::<NonZeroU64>())
484 0 : .transpose()
485 0 : .context("Failed to parse 'max_lsn_wal_lag' as non zero integer")?,
486 0 : trace_read_requests: settings
487 0 : .remove("trace_read_requests")
488 0 : .map(|x| x.parse::<bool>())
489 0 : .transpose()
490 0 : .context("Failed to parse 'trace_read_requests' as bool")?,
491 0 : eviction_policy: settings
492 0 : .remove("eviction_policy")
493 0 : .map(serde_json::from_str)
494 0 : .transpose()
495 0 : .context("Failed to parse 'eviction_policy' json")?,
496 0 : min_resident_size_override: settings
497 0 : .remove("min_resident_size_override")
498 0 : .map(|x| x.parse::<u64>())
499 0 : .transpose()
500 0 : .context("Failed to parse 'min_resident_size_override' as an integer")?,
501 0 : evictions_low_residence_duration_metric_threshold: settings
502 0 : .remove("evictions_low_residence_duration_metric_threshold")
503 0 : .map(|x| x.to_string()),
504 0 : gc_feedback: settings
505 0 : .remove("gc_feedback")
506 0 : .map(|x| x.parse::<bool>())
507 0 : .transpose()
508 0 : .context("Failed to parse 'gc_feedback' as bool")?,
509 0 : heatmap_period: settings.remove("heatmap_period").map(|x| x.to_string()),
510 0 : lazy_slru_download: settings
511 0 : .remove("lazy_slru_download")
512 0 : .map(|x| x.parse::<bool>())
513 0 : .transpose()
514 0 : .context("Failed to parse 'lazy_slru_download' as bool")?,
515 0 : timeline_get_throttle: settings
516 0 : .remove("timeline_get_throttle")
517 0 : .map(serde_json::from_str)
518 0 : .transpose()
519 0 : .context("parse `timeline_get_throttle` from json")?,
520 : }
521 : };
522 :
523 0 : if !settings.is_empty() {
524 0 : bail!("Unrecognized tenant settings: {settings:?}")
525 0 : }
526 0 :
527 0 : self.http_client
528 0 : .tenant_config(&models::TenantConfigRequest { tenant_id, config })
529 0 : .await?;
530 :
531 0 : Ok(())
532 0 : }
533 :
534 0 : pub async fn location_config(
535 0 : &self,
536 0 : tenant_shard_id: TenantShardId,
537 0 : config: LocationConfig,
538 0 : flush_ms: Option<Duration>,
539 0 : ) -> anyhow::Result<()> {
540 0 : Ok(self
541 0 : .http_client
542 0 : .location_config(tenant_shard_id, config, flush_ms)
543 0 : .await?)
544 0 : }
545 :
546 0 : pub async fn timeline_list(
547 0 : &self,
548 0 : tenant_shard_id: &TenantShardId,
549 0 : ) -> anyhow::Result<Vec<TimelineInfo>> {
550 0 : Ok(self.http_client.list_timelines(*tenant_shard_id).await?)
551 0 : }
552 :
553 0 : pub async fn tenant_secondary_download(&self, tenant_id: &TenantShardId) -> anyhow::Result<()> {
554 0 : Ok(self
555 0 : .http_client
556 0 : .tenant_secondary_download(*tenant_id)
557 0 : .await?)
558 0 : }
559 :
560 0 : pub async fn timeline_create(
561 0 : &self,
562 0 : tenant_shard_id: TenantShardId,
563 0 : new_timeline_id: TimelineId,
564 0 : ancestor_start_lsn: Option<Lsn>,
565 0 : ancestor_timeline_id: Option<TimelineId>,
566 0 : pg_version: Option<u32>,
567 0 : existing_initdb_timeline_id: Option<TimelineId>,
568 0 : ) -> anyhow::Result<TimelineInfo> {
569 0 : let req = models::TimelineCreateRequest {
570 0 : new_timeline_id,
571 0 : ancestor_start_lsn,
572 0 : ancestor_timeline_id,
573 0 : pg_version,
574 0 : existing_initdb_timeline_id,
575 0 : };
576 0 : Ok(self
577 0 : .http_client
578 0 : .timeline_create(tenant_shard_id, &req)
579 0 : .await?)
580 0 : }
581 :
582 : /// Import a basebackup prepared using either:
583 : /// a) `pg_basebackup -F tar`, or
584 : /// b) The `fullbackup` pageserver endpoint
585 : ///
586 : /// # Arguments
587 : /// * `tenant_id` - tenant to import into. Created if not exists
588 : /// * `timeline_id` - id to assign to imported timeline
589 : /// * `base` - (start lsn of basebackup, path to `base.tar` file)
590 : /// * `pg_wal` - if there's any wal to import: (end lsn, path to `pg_wal.tar`)
591 0 : pub async fn timeline_import(
592 0 : &self,
593 0 : tenant_id: TenantId,
594 0 : timeline_id: TimelineId,
595 0 : base: (Lsn, PathBuf),
596 0 : pg_wal: Option<(Lsn, PathBuf)>,
597 0 : pg_version: u32,
598 0 : ) -> anyhow::Result<()> {
599 0 : let (client, conn) = self.page_server_psql_client().await?;
600 : // The connection object performs the actual communication with the database,
601 : // so spawn it off to run on its own.
602 0 : tokio::spawn(async move {
603 0 : if let Err(e) = conn.await {
604 0 : eprintln!("connection error: {}", e);
605 0 : }
606 0 : });
607 0 : tokio::pin!(client);
608 0 :
609 0 : // Init base reader
610 0 : let (start_lsn, base_tarfile_path) = base;
611 0 : let base_tarfile = tokio::fs::File::open(base_tarfile_path).await?;
612 0 : let base_tarfile = tokio_util::io::ReaderStream::new(base_tarfile);
613 :
614 : // Init wal reader if necessary
615 0 : let (end_lsn, wal_reader) = if let Some((end_lsn, wal_tarfile_path)) = pg_wal {
616 0 : let wal_tarfile = tokio::fs::File::open(wal_tarfile_path).await?;
617 0 : let wal_reader = tokio_util::io::ReaderStream::new(wal_tarfile);
618 0 : (end_lsn, Some(wal_reader))
619 : } else {
620 0 : (start_lsn, None)
621 : };
622 :
623 0 : let copy_in = |reader, cmd| {
624 0 : let client = &client;
625 0 : async move {
626 0 : let writer = client.copy_in(&cmd).await?;
627 0 : let writer = std::pin::pin!(writer);
628 0 : let mut writer = writer.sink_map_err(|e| {
629 0 : std::io::Error::new(std::io::ErrorKind::Other, format!("{e}"))
630 0 : });
631 0 : let mut reader = std::pin::pin!(reader);
632 0 : writer.send_all(&mut reader).await?;
633 0 : writer.into_inner().finish().await?;
634 0 : anyhow::Ok(())
635 0 : }
636 0 : };
637 :
638 : // Import base
639 0 : copy_in(
640 0 : base_tarfile,
641 0 : format!(
642 0 : "import basebackup {tenant_id} {timeline_id} {start_lsn} {end_lsn} {pg_version}"
643 0 : ),
644 0 : )
645 0 : .await?;
646 : // Import wal if necessary
647 0 : if let Some(wal_reader) = wal_reader {
648 0 : copy_in(
649 0 : wal_reader,
650 0 : format!("import wal {tenant_id} {timeline_id} {start_lsn} {end_lsn}"),
651 0 : )
652 0 : .await?;
653 0 : }
654 :
655 0 : Ok(())
656 0 : }
657 :
658 0 : pub async fn tenant_synthetic_size(
659 0 : &self,
660 0 : tenant_shard_id: TenantShardId,
661 0 : ) -> anyhow::Result<TenantHistorySize> {
662 0 : Ok(self
663 0 : .http_client
664 0 : .tenant_synthetic_size(tenant_shard_id)
665 0 : .await?)
666 0 : }
667 : }
|