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