Line data Source code
1 : //!
2 : //! Generate a tarball with files needed to bootstrap ComputeNode.
3 : //!
4 : //! TODO: this module has nothing to do with PostgreSQL pg_basebackup.
5 : //! It could use a better name.
6 : //!
7 : //! Stateless Postgres compute node is launched by sending a tarball
8 : //! which contains non-relational data (multixacts, clog, filenodemaps, twophase files),
9 : //! generated pg_control and dummy segment of WAL.
10 : //! This module is responsible for creation of such tarball
11 : //! from data stored in object storage.
12 : //!
13 : use anyhow::{anyhow, Context};
14 : use bytes::{BufMut, Bytes, BytesMut};
15 : use fail::fail_point;
16 : use pageserver_api::key::Key;
17 : use postgres_ffi::pg_constants;
18 : use std::fmt::Write as FmtWrite;
19 : use std::time::{Instant, SystemTime};
20 : use tokio::io;
21 : use tokio::io::AsyncWrite;
22 : use tracing::*;
23 :
24 : use tokio_tar::{Builder, EntryType, Header};
25 :
26 : use crate::context::RequestContext;
27 : use crate::pgdatadir_mapping::Version;
28 : use crate::tenant::Timeline;
29 : use pageserver_api::reltag::{RelTag, SlruKind};
30 :
31 : use postgres_ffi::dispatch_pgversion;
32 : use postgres_ffi::pg_constants::{DEFAULTTABLESPACE_OID, GLOBALTABLESPACE_OID};
33 : use postgres_ffi::pg_constants::{PGDATA_SPECIAL_FILES, PG_HBA};
34 : use postgres_ffi::relfile_utils::{INIT_FORKNUM, MAIN_FORKNUM};
35 : use postgres_ffi::XLogFileName;
36 : use postgres_ffi::PG_TLI;
37 : use postgres_ffi::{BLCKSZ, RELSEG_SIZE, WAL_SEGMENT_SIZE};
38 : use utils::lsn::Lsn;
39 :
40 0 : #[derive(Debug, thiserror::Error)]
41 : pub enum BasebackupError {
42 : #[error("basebackup pageserver error {0:#}")]
43 : Server(#[from] anyhow::Error),
44 : #[error("basebackup client error {0:#}")]
45 : Client(#[source] io::Error),
46 : }
47 :
48 : /// Create basebackup with non-rel data in it.
49 : /// Only include relational data if 'full_backup' is true.
50 : ///
51 : /// Currently we use empty 'req_lsn' in two cases:
52 : /// * During the basebackup right after timeline creation
53 : /// * When working without safekeepers. In this situation it is important to match the lsn
54 : /// we are taking basebackup on with the lsn that is used in pageserver's walreceiver
55 : /// to start the replication.
56 0 : pub async fn send_basebackup_tarball<'a, W>(
57 0 : write: &'a mut W,
58 0 : timeline: &'a Timeline,
59 0 : req_lsn: Option<Lsn>,
60 0 : prev_lsn: Option<Lsn>,
61 0 : full_backup: bool,
62 0 : ctx: &'a RequestContext,
63 0 : ) -> Result<(), BasebackupError>
64 0 : where
65 0 : W: AsyncWrite + Send + Sync + Unpin,
66 0 : {
67 : // Compute postgres doesn't have any previous WAL files, but the first
68 : // record that it's going to write needs to include the LSN of the
69 : // previous record (xl_prev). We include prev_record_lsn in the
70 : // "zenith.signal" file, so that postgres can read it during startup.
71 : //
72 : // We don't keep full history of record boundaries in the page server,
73 : // however, only the predecessor of the latest record on each
74 : // timeline. So we can only provide prev_record_lsn when you take a
75 : // base backup at the end of the timeline, i.e. at last_record_lsn.
76 : // Even at the end of the timeline, we sometimes don't have a valid
77 : // prev_lsn value; that happens if the timeline was just branched from
78 : // an old LSN and it doesn't have any WAL of its own yet. We will set
79 : // prev_lsn to Lsn(0) if we cannot provide the correct value.
80 0 : let (backup_prev, backup_lsn) = if let Some(req_lsn) = req_lsn {
81 : // Backup was requested at a particular LSN. The caller should've
82 : // already checked that it's a valid LSN.
83 :
84 : // If the requested point is the end of the timeline, we can
85 : // provide prev_lsn. (get_last_record_rlsn() might return it as
86 : // zero, though, if no WAL has been generated on this timeline
87 : // yet.)
88 0 : let end_of_timeline = timeline.get_last_record_rlsn();
89 0 : if req_lsn == end_of_timeline.last {
90 0 : (end_of_timeline.prev, req_lsn)
91 : } else {
92 0 : (Lsn(0), req_lsn)
93 : }
94 : } else {
95 : // Backup was requested at end of the timeline.
96 0 : let end_of_timeline = timeline.get_last_record_rlsn();
97 0 : (end_of_timeline.prev, end_of_timeline.last)
98 : };
99 :
100 : // Consolidate the derived and the provided prev_lsn values
101 0 : let prev_lsn = if let Some(provided_prev_lsn) = prev_lsn {
102 0 : if backup_prev != Lsn(0) && backup_prev != provided_prev_lsn {
103 0 : return Err(BasebackupError::Server(anyhow!(
104 0 : "backup_prev {backup_prev} != provided_prev_lsn {provided_prev_lsn}"
105 0 : )));
106 0 : }
107 0 : provided_prev_lsn
108 : } else {
109 0 : backup_prev
110 : };
111 :
112 0 : info!(
113 0 : "taking basebackup lsn={}, prev_lsn={} (full_backup={})",
114 : backup_lsn, prev_lsn, full_backup
115 : );
116 :
117 0 : let basebackup = Basebackup {
118 0 : ar: Builder::new_non_terminated(write),
119 0 : timeline,
120 0 : lsn: backup_lsn,
121 0 : prev_record_lsn: prev_lsn,
122 0 : full_backup,
123 0 : ctx,
124 0 : };
125 0 : basebackup
126 0 : .send_tarball()
127 0 : .instrument(info_span!("send_tarball", backup_lsn=%backup_lsn))
128 0 : .await
129 0 : }
130 :
131 : /// This is short-living object only for the time of tarball creation,
132 : /// created mostly to avoid passing a lot of parameters between various functions
133 : /// used for constructing tarball.
134 : struct Basebackup<'a, W>
135 : where
136 : W: AsyncWrite + Send + Sync + Unpin,
137 : {
138 : ar: Builder<&'a mut W>,
139 : timeline: &'a Timeline,
140 : lsn: Lsn,
141 : prev_record_lsn: Lsn,
142 : full_backup: bool,
143 : ctx: &'a RequestContext,
144 : }
145 :
146 : /// A sink that accepts SLRU blocks ordered by key and forwards
147 : /// full segments to the archive.
148 : struct SlruSegmentsBuilder<'a, 'b, W>
149 : where
150 : W: AsyncWrite + Send + Sync + Unpin,
151 : {
152 : ar: &'a mut Builder<&'b mut W>,
153 : buf: Vec<u8>,
154 : current_segment: Option<(SlruKind, u32)>,
155 : total_blocks: usize,
156 : }
157 :
158 : impl<'a, 'b, W> SlruSegmentsBuilder<'a, 'b, W>
159 : where
160 : W: AsyncWrite + Send + Sync + Unpin,
161 : {
162 0 : fn new(ar: &'a mut Builder<&'b mut W>) -> Self {
163 0 : Self {
164 0 : ar,
165 0 : buf: Vec::new(),
166 0 : current_segment: None,
167 0 : total_blocks: 0,
168 0 : }
169 0 : }
170 :
171 0 : async fn add_block(&mut self, key: &Key, block: Bytes) -> Result<(), BasebackupError> {
172 0 : let (kind, segno, _) = key.to_slru_block()?;
173 :
174 0 : match kind {
175 : SlruKind::Clog => {
176 0 : if !(block.len() == BLCKSZ as usize || block.len() == BLCKSZ as usize + 8) {
177 0 : return Err(BasebackupError::Server(anyhow!(
178 0 : "invalid SlruKind::Clog record: block.len()={}",
179 0 : block.len()
180 0 : )));
181 0 : }
182 : }
183 : SlruKind::MultiXactMembers | SlruKind::MultiXactOffsets => {
184 0 : if block.len() != BLCKSZ as usize {
185 0 : return Err(BasebackupError::Server(anyhow!(
186 0 : "invalid {:?} record: block.len()={}",
187 0 : kind,
188 0 : block.len()
189 0 : )));
190 0 : }
191 : }
192 : }
193 :
194 0 : let segment = (kind, segno);
195 0 : match self.current_segment {
196 0 : None => {
197 0 : self.current_segment = Some(segment);
198 0 : self.buf
199 0 : .extend_from_slice(block.slice(..BLCKSZ as usize).as_ref());
200 0 : }
201 0 : Some(current_seg) if current_seg == segment => {
202 0 : self.buf
203 0 : .extend_from_slice(block.slice(..BLCKSZ as usize).as_ref());
204 0 : }
205 : Some(_) => {
206 0 : self.flush().await?;
207 :
208 0 : self.current_segment = Some(segment);
209 0 : self.buf
210 0 : .extend_from_slice(block.slice(..BLCKSZ as usize).as_ref());
211 : }
212 : }
213 :
214 0 : Ok(())
215 0 : }
216 :
217 0 : async fn flush(&mut self) -> Result<(), BasebackupError> {
218 0 : let nblocks = self.buf.len() / BLCKSZ as usize;
219 0 : let (kind, segno) = self.current_segment.take().unwrap();
220 0 : let segname = format!("{}/{:>04X}", kind.to_str(), segno);
221 0 : let header = new_tar_header(&segname, self.buf.len() as u64)?;
222 0 : self.ar
223 0 : .append(&header, self.buf.as_slice())
224 0 : .await
225 0 : .map_err(BasebackupError::Client)?;
226 :
227 0 : self.total_blocks += nblocks;
228 0 : debug!("Added to basebackup slru {} relsize {}", segname, nblocks);
229 :
230 0 : self.buf.clear();
231 0 :
232 0 : Ok(())
233 0 : }
234 :
235 0 : async fn finish(mut self) -> Result<(), BasebackupError> {
236 0 : let res = if self.current_segment.is_none() || self.buf.is_empty() {
237 0 : Ok(())
238 : } else {
239 0 : self.flush().await
240 : };
241 :
242 0 : info!("Collected {} SLRU blocks", self.total_blocks);
243 :
244 0 : res
245 0 : }
246 : }
247 :
248 : impl<'a, W> Basebackup<'a, W>
249 : where
250 : W: AsyncWrite + Send + Sync + Unpin,
251 : {
252 0 : async fn send_tarball(mut self) -> Result<(), BasebackupError> {
253 : // TODO include checksum
254 :
255 0 : let lazy_slru_download = self.timeline.get_lazy_slru_download() && !self.full_backup;
256 :
257 0 : let pgversion = self.timeline.pg_version;
258 0 : let subdirs = dispatch_pgversion!(pgversion, &pgv::bindings::PGDATA_SUBDIRS[..]);
259 :
260 : // Create pgdata subdirs structure
261 0 : for dir in subdirs.iter() {
262 0 : let header = new_tar_header_dir(dir)?;
263 0 : self.ar
264 0 : .append(&header, &mut io::empty())
265 0 : .await
266 0 : .context("could not add directory to basebackup tarball")?;
267 : }
268 :
269 : // Send config files.
270 0 : for filepath in PGDATA_SPECIAL_FILES.iter() {
271 0 : if *filepath == "pg_hba.conf" {
272 0 : let data = PG_HBA.as_bytes();
273 0 : let header = new_tar_header(filepath, data.len() as u64)?;
274 0 : self.ar
275 0 : .append(&header, data)
276 0 : .await
277 0 : .context("could not add config file to basebackup tarball")?;
278 : } else {
279 0 : let header = new_tar_header(filepath, 0)?;
280 0 : self.ar
281 0 : .append(&header, &mut io::empty())
282 0 : .await
283 0 : .context("could not add config file to basebackup tarball")?;
284 : }
285 : }
286 0 : if !lazy_slru_download {
287 : // Gather non-relational files from object storage pages.
288 0 : let slru_partitions = self
289 0 : .timeline
290 0 : .get_slru_keyspace(Version::Lsn(self.lsn), self.ctx)
291 0 : .await
292 0 : .map_err(|e| BasebackupError::Server(e.into()))?
293 0 : .partition(
294 0 : self.timeline.get_shard_identity(),
295 0 : Timeline::MAX_GET_VECTORED_KEYS * BLCKSZ as u64,
296 0 : );
297 0 :
298 0 : let mut slru_builder = SlruSegmentsBuilder::new(&mut self.ar);
299 :
300 0 : for part in slru_partitions.parts {
301 0 : let blocks = self
302 0 : .timeline
303 0 : .get_vectored(part, self.lsn, self.ctx)
304 0 : .await
305 0 : .map_err(|e| BasebackupError::Server(e.into()))?;
306 :
307 0 : for (key, block) in blocks {
308 0 : let block = block.map_err(|e| BasebackupError::Server(e.into()))?;
309 0 : slru_builder.add_block(&key, block).await?;
310 : }
311 : }
312 0 : slru_builder.finish().await?;
313 0 : }
314 :
315 0 : let mut min_restart_lsn: Lsn = Lsn::MAX;
316 : // Create tablespace directories
317 0 : for ((spcnode, dbnode), has_relmap_file) in self
318 0 : .timeline
319 0 : .list_dbdirs(self.lsn, self.ctx)
320 0 : .await
321 0 : .map_err(|e| BasebackupError::Server(e.into()))?
322 : {
323 0 : self.add_dbdir(spcnode, dbnode, has_relmap_file).await?;
324 :
325 : // If full backup is requested, include all relation files.
326 : // Otherwise only include init forks of unlogged relations.
327 0 : let rels = self
328 0 : .timeline
329 0 : .list_rels(spcnode, dbnode, Version::Lsn(self.lsn), self.ctx)
330 0 : .await
331 0 : .map_err(|e| BasebackupError::Server(e.into()))?;
332 0 : for &rel in rels.iter() {
333 : // Send init fork as main fork to provide well formed empty
334 : // contents of UNLOGGED relations. Postgres copies it in
335 : // `reinit.c` during recovery.
336 0 : if rel.forknum == INIT_FORKNUM {
337 : // I doubt we need _init fork itself, but having it at least
338 : // serves as a marker relation is unlogged.
339 0 : self.add_rel(rel, rel).await?;
340 0 : self.add_rel(rel, rel.with_forknum(MAIN_FORKNUM)).await?;
341 0 : continue;
342 0 : }
343 0 :
344 0 : if self.full_backup {
345 0 : if rel.forknum == MAIN_FORKNUM && rels.contains(&rel.with_forknum(INIT_FORKNUM))
346 : {
347 : // skip this, will include it when we reach the init fork
348 0 : continue;
349 0 : }
350 0 : self.add_rel(rel, rel).await?;
351 0 : }
352 : }
353 : }
354 :
355 0 : let start_time = Instant::now();
356 0 : let aux_files = self
357 0 : .timeline
358 0 : .list_aux_files(self.lsn, self.ctx)
359 0 : .await
360 0 : .map_err(|e| BasebackupError::Server(e.into()))?;
361 0 : let aux_scan_time = start_time.elapsed();
362 0 : let aux_estimated_size = aux_files
363 0 : .values()
364 0 : .map(|content| content.len())
365 0 : .sum::<usize>();
366 0 : info!(
367 0 : "Scanned {} aux files in {}ms, aux file content size = {}",
368 0 : aux_files.len(),
369 0 : aux_scan_time.as_millis(),
370 : aux_estimated_size
371 : );
372 :
373 0 : for (path, content) in aux_files {
374 0 : if path.starts_with("pg_replslot") {
375 0 : let offs = pg_constants::REPL_SLOT_ON_DISK_OFFSETOF_RESTART_LSN;
376 0 : let restart_lsn = Lsn(u64::from_le_bytes(
377 0 : content[offs..offs + 8].try_into().unwrap(),
378 0 : ));
379 0 : info!("Replication slot {} restart LSN={}", path, restart_lsn);
380 0 : min_restart_lsn = Lsn::min(min_restart_lsn, restart_lsn);
381 0 : } else if path == "pg_logical/replorigin_checkpoint" {
382 : // replorigin_checkoint is written only on compute shutdown, so it contains
383 : // deteriorated values. So we generate our own version of this file for the particular LSN
384 : // based on information about replorigins extracted from transaction commit records.
385 : // In future we will not generate AUX record for "pg_logical/replorigin_checkpoint" at all,
386 : // but now we should handle (skip) it for backward compatibility.
387 0 : continue;
388 0 : }
389 0 : let header = new_tar_header(&path, content.len() as u64)?;
390 0 : self.ar
391 0 : .append(&header, &*content)
392 0 : .await
393 0 : .context("could not add aux file to basebackup tarball")?;
394 : }
395 :
396 0 : if min_restart_lsn != Lsn::MAX {
397 0 : info!(
398 0 : "Min restart LSN for logical replication is {}",
399 : min_restart_lsn
400 : );
401 0 : let data = min_restart_lsn.0.to_le_bytes();
402 0 : let header = new_tar_header("restart.lsn", data.len() as u64)?;
403 0 : self.ar
404 0 : .append(&header, &data[..])
405 0 : .await
406 0 : .context("could not add restart.lsn file to basebackup tarball")?;
407 0 : }
408 0 : for xid in self
409 0 : .timeline
410 0 : .list_twophase_files(self.lsn, self.ctx)
411 0 : .await
412 0 : .map_err(|e| BasebackupError::Server(e.into()))?
413 : {
414 0 : self.add_twophase_file(xid).await?;
415 : }
416 0 : let repl_origins = self
417 0 : .timeline
418 0 : .get_replorigins(self.lsn, self.ctx)
419 0 : .await
420 0 : .map_err(|e| BasebackupError::Server(e.into()))?;
421 0 : let n_origins = repl_origins.len();
422 0 : if n_origins != 0 {
423 : //
424 : // Construct "pg_logical/replorigin_checkpoint" file based on information about replication origins
425 : // extracted from transaction commit record. We are using this file to pass information about replication
426 : // origins to compute to allow logical replication to restart from proper point.
427 : //
428 0 : let mut content = Vec::with_capacity(n_origins * 16 + 8);
429 0 : content.extend_from_slice(&pg_constants::REPLICATION_STATE_MAGIC.to_le_bytes());
430 0 : for (origin_id, origin_lsn) in repl_origins {
431 0 : content.extend_from_slice(&origin_id.to_le_bytes());
432 0 : content.extend_from_slice(&[0u8; 6]); // align to 8 bytes
433 0 : content.extend_from_slice(&origin_lsn.0.to_le_bytes());
434 0 : }
435 0 : let crc32 = crc32c::crc32c(&content);
436 0 : content.extend_from_slice(&crc32.to_le_bytes());
437 0 : let header = new_tar_header("pg_logical/replorigin_checkpoint", content.len() as u64)?;
438 0 : self.ar.append(&header, &*content).await.context(
439 0 : "could not add pg_logical/replorigin_checkpoint file to basebackup tarball",
440 0 : )?;
441 0 : }
442 :
443 0 : fail_point!("basebackup-before-control-file", |_| {
444 0 : Err(BasebackupError::Server(anyhow!(
445 0 : "failpoint basebackup-before-control-file"
446 0 : )))
447 0 : });
448 :
449 : // Generate pg_control and bootstrap WAL segment.
450 0 : self.add_pgcontrol_file().await?;
451 0 : self.ar.finish().await.map_err(BasebackupError::Client)?;
452 0 : debug!("all tarred up!");
453 0 : Ok(())
454 0 : }
455 :
456 : /// Add contents of relfilenode `src`, naming it as `dst`.
457 0 : async fn add_rel(&mut self, src: RelTag, dst: RelTag) -> Result<(), BasebackupError> {
458 0 : let nblocks = self
459 0 : .timeline
460 0 : .get_rel_size(src, Version::Lsn(self.lsn), self.ctx)
461 0 : .await
462 0 : .map_err(|e| BasebackupError::Server(e.into()))?;
463 :
464 : // If the relation is empty, create an empty file
465 0 : if nblocks == 0 {
466 0 : let file_name = dst.to_segfile_name(0);
467 0 : let header = new_tar_header(&file_name, 0)?;
468 0 : self.ar
469 0 : .append(&header, &mut io::empty())
470 0 : .await
471 0 : .map_err(BasebackupError::Client)?;
472 0 : return Ok(());
473 0 : }
474 0 :
475 0 : // Add a file for each chunk of blocks (aka segment)
476 0 : let mut startblk = 0;
477 0 : let mut seg = 0;
478 0 : while startblk < nblocks {
479 0 : let endblk = std::cmp::min(startblk + RELSEG_SIZE, nblocks);
480 0 :
481 0 : let mut segment_data: Vec<u8> = vec![];
482 0 : for blknum in startblk..endblk {
483 0 : let img = self
484 0 : .timeline
485 0 : .get_rel_page_at_lsn(src, blknum, Version::Lsn(self.lsn), self.ctx)
486 0 : .await
487 0 : .map_err(|e| BasebackupError::Server(e.into()))?;
488 0 : segment_data.extend_from_slice(&img[..]);
489 : }
490 :
491 0 : let file_name = dst.to_segfile_name(seg as u32);
492 0 : let header = new_tar_header(&file_name, segment_data.len() as u64)?;
493 0 : self.ar
494 0 : .append(&header, segment_data.as_slice())
495 0 : .await
496 0 : .map_err(BasebackupError::Client)?;
497 :
498 0 : seg += 1;
499 0 : startblk = endblk;
500 : }
501 :
502 0 : Ok(())
503 0 : }
504 :
505 : //
506 : // Include database/tablespace directories.
507 : //
508 : // Each directory contains a PG_VERSION file, and the default database
509 : // directories also contain pg_filenode.map files.
510 : //
511 0 : async fn add_dbdir(
512 0 : &mut self,
513 0 : spcnode: u32,
514 0 : dbnode: u32,
515 0 : has_relmap_file: bool,
516 0 : ) -> Result<(), BasebackupError> {
517 0 : let relmap_img = if has_relmap_file {
518 0 : let img = self
519 0 : .timeline
520 0 : .get_relmap_file(spcnode, dbnode, Version::Lsn(self.lsn), self.ctx)
521 0 : .await
522 0 : .map_err(|e| BasebackupError::Server(e.into()))?;
523 :
524 0 : if img.len()
525 0 : != dispatch_pgversion!(self.timeline.pg_version, pgv::bindings::SIZEOF_RELMAPFILE)
526 : {
527 0 : return Err(BasebackupError::Server(anyhow!(
528 0 : "img.len() != SIZE_OF_RELMAPFILE, img.len()={}",
529 0 : img.len(),
530 0 : )));
531 0 : }
532 0 :
533 0 : Some(img)
534 : } else {
535 0 : None
536 : };
537 :
538 0 : if spcnode == GLOBALTABLESPACE_OID {
539 0 : let pg_version_str = match self.timeline.pg_version {
540 0 : 14 | 15 => self.timeline.pg_version.to_string(),
541 0 : ver => format!("{ver}\x0A"),
542 : };
543 0 : let header = new_tar_header("PG_VERSION", pg_version_str.len() as u64)?;
544 0 : self.ar
545 0 : .append(&header, pg_version_str.as_bytes())
546 0 : .await
547 0 : .map_err(BasebackupError::Client)?;
548 :
549 0 : info!("timeline.pg_version {}", self.timeline.pg_version);
550 :
551 0 : if let Some(img) = relmap_img {
552 : // filenode map for global tablespace
553 0 : let header = new_tar_header("global/pg_filenode.map", img.len() as u64)?;
554 0 : self.ar
555 0 : .append(&header, &img[..])
556 0 : .await
557 0 : .map_err(BasebackupError::Client)?;
558 : } else {
559 0 : warn!("global/pg_filenode.map is missing");
560 : }
561 : } else {
562 : // User defined tablespaces are not supported. However, as
563 : // a special case, if a tablespace/db directory is
564 : // completely empty, we can leave it out altogether. This
565 : // makes taking a base backup after the 'tablespace'
566 : // regression test pass, because the test drops the
567 : // created tablespaces after the tests.
568 : //
569 : // FIXME: this wouldn't be necessary, if we handled
570 : // XLOG_TBLSPC_DROP records. But we probably should just
571 : // throw an error on CREATE TABLESPACE in the first place.
572 0 : if !has_relmap_file
573 0 : && self
574 0 : .timeline
575 0 : .list_rels(spcnode, dbnode, Version::Lsn(self.lsn), self.ctx)
576 0 : .await
577 0 : .map_err(|e| BasebackupError::Server(e.into()))?
578 0 : .is_empty()
579 : {
580 0 : return Ok(());
581 0 : }
582 0 : // User defined tablespaces are not supported
583 0 : if spcnode != DEFAULTTABLESPACE_OID {
584 0 : return Err(BasebackupError::Server(anyhow!(
585 0 : "spcnode != DEFAULTTABLESPACE_OID, spcnode={spcnode}"
586 0 : )));
587 0 : }
588 0 :
589 0 : // Append dir path for each database
590 0 : let path = format!("base/{}", dbnode);
591 0 : let header = new_tar_header_dir(&path)?;
592 0 : self.ar
593 0 : .append(&header, &mut io::empty())
594 0 : .await
595 0 : .map_err(BasebackupError::Client)?;
596 :
597 0 : if let Some(img) = relmap_img {
598 0 : let dst_path = format!("base/{}/PG_VERSION", dbnode);
599 :
600 0 : let pg_version_str = match self.timeline.pg_version {
601 0 : 14 | 15 => self.timeline.pg_version.to_string(),
602 0 : ver => format!("{ver}\x0A"),
603 : };
604 0 : let header = new_tar_header(&dst_path, pg_version_str.len() as u64)?;
605 0 : self.ar
606 0 : .append(&header, pg_version_str.as_bytes())
607 0 : .await
608 0 : .map_err(BasebackupError::Client)?;
609 :
610 0 : let relmap_path = format!("base/{}/pg_filenode.map", dbnode);
611 0 : let header = new_tar_header(&relmap_path, img.len() as u64)?;
612 0 : self.ar
613 0 : .append(&header, &img[..])
614 0 : .await
615 0 : .map_err(BasebackupError::Client)?;
616 0 : }
617 : };
618 0 : Ok(())
619 0 : }
620 :
621 : //
622 : // Extract twophase state files
623 : //
624 0 : async fn add_twophase_file(&mut self, xid: u64) -> Result<(), BasebackupError> {
625 0 : let img = self
626 0 : .timeline
627 0 : .get_twophase_file(xid, self.lsn, self.ctx)
628 0 : .await
629 0 : .map_err(|e| BasebackupError::Server(e.into()))?;
630 :
631 0 : let mut buf = BytesMut::new();
632 0 : buf.extend_from_slice(&img[..]);
633 0 : let crc = crc32c::crc32c(&img[..]);
634 0 : buf.put_u32_le(crc);
635 0 : let path = if self.timeline.pg_version < 17 {
636 0 : format!("pg_twophase/{:>08X}", xid)
637 : } else {
638 0 : format!("pg_twophase/{:>016X}", xid)
639 : };
640 0 : let header = new_tar_header(&path, buf.len() as u64)?;
641 0 : self.ar
642 0 : .append(&header, &buf[..])
643 0 : .await
644 0 : .map_err(BasebackupError::Client)?;
645 :
646 0 : Ok(())
647 0 : }
648 :
649 : //
650 : // Add generated pg_control file and bootstrap WAL segment.
651 : // Also send zenith.signal file with extra bootstrap data.
652 : //
653 0 : async fn add_pgcontrol_file(&mut self) -> Result<(), BasebackupError> {
654 0 : // add zenith.signal file
655 0 : let mut zenith_signal = String::new();
656 0 : if self.prev_record_lsn == Lsn(0) {
657 0 : if self.timeline.is_ancestor_lsn(self.lsn) {
658 0 : write!(zenith_signal, "PREV LSN: none")
659 0 : .map_err(|e| BasebackupError::Server(e.into()))?;
660 : } else {
661 0 : write!(zenith_signal, "PREV LSN: invalid")
662 0 : .map_err(|e| BasebackupError::Server(e.into()))?;
663 : }
664 : } else {
665 0 : write!(zenith_signal, "PREV LSN: {}", self.prev_record_lsn)
666 0 : .map_err(|e| BasebackupError::Server(e.into()))?;
667 : }
668 0 : self.ar
669 0 : .append(
670 0 : &new_tar_header("zenith.signal", zenith_signal.len() as u64)?,
671 0 : zenith_signal.as_bytes(),
672 : )
673 0 : .await
674 0 : .map_err(BasebackupError::Client)?;
675 :
676 0 : let checkpoint_bytes = self
677 0 : .timeline
678 0 : .get_checkpoint(self.lsn, self.ctx)
679 0 : .await
680 0 : .context("failed to get checkpoint bytes")?;
681 0 : let pg_control_bytes = self
682 0 : .timeline
683 0 : .get_control_file(self.lsn, self.ctx)
684 0 : .await
685 0 : .context("failed get control bytes")?;
686 :
687 0 : let (pg_control_bytes, system_identifier) = postgres_ffi::generate_pg_control(
688 0 : &pg_control_bytes,
689 0 : &checkpoint_bytes,
690 0 : self.lsn,
691 0 : self.timeline.pg_version,
692 0 : )?;
693 :
694 : //send pg_control
695 0 : let header = new_tar_header("global/pg_control", pg_control_bytes.len() as u64)?;
696 0 : self.ar
697 0 : .append(&header, &pg_control_bytes[..])
698 0 : .await
699 0 : .map_err(BasebackupError::Client)?;
700 :
701 : //send wal segment
702 0 : let segno = self.lsn.segment_number(WAL_SEGMENT_SIZE);
703 0 : let wal_file_name = XLogFileName(PG_TLI, segno, WAL_SEGMENT_SIZE);
704 0 : let wal_file_path = format!("pg_wal/{}", wal_file_name);
705 0 : let header = new_tar_header(&wal_file_path, WAL_SEGMENT_SIZE as u64)?;
706 :
707 0 : let wal_seg = postgres_ffi::generate_wal_segment(
708 0 : segno,
709 0 : system_identifier,
710 0 : self.timeline.pg_version,
711 0 : self.lsn,
712 0 : )
713 0 : .map_err(|e| anyhow!(e).context("Failed generating wal segment"))?;
714 0 : if wal_seg.len() != WAL_SEGMENT_SIZE {
715 0 : return Err(BasebackupError::Server(anyhow!(
716 0 : "wal_seg.len() != WAL_SEGMENT_SIZE, wal_seg.len()={}",
717 0 : wal_seg.len()
718 0 : )));
719 0 : }
720 0 : self.ar
721 0 : .append(&header, &wal_seg[..])
722 0 : .await
723 0 : .map_err(BasebackupError::Client)?;
724 0 : Ok(())
725 0 : }
726 : }
727 :
728 : //
729 : // Create new tarball entry header
730 : //
731 0 : fn new_tar_header(path: &str, size: u64) -> anyhow::Result<Header> {
732 0 : let mut header = Header::new_gnu();
733 0 : header.set_size(size);
734 0 : header.set_path(path)?;
735 0 : header.set_mode(0b110000000); // -rw-------
736 0 : header.set_mtime(
737 0 : // use currenttime as last modified time
738 0 : SystemTime::now()
739 0 : .duration_since(SystemTime::UNIX_EPOCH)
740 0 : .unwrap()
741 0 : .as_secs(),
742 0 : );
743 0 : header.set_cksum();
744 0 : Ok(header)
745 0 : }
746 :
747 0 : fn new_tar_header_dir(path: &str) -> anyhow::Result<Header> {
748 0 : let mut header = Header::new_gnu();
749 0 : header.set_size(0);
750 0 : header.set_path(path)?;
751 0 : header.set_mode(0o755); // -rw-------
752 0 : header.set_entry_type(EntryType::dir());
753 0 : header.set_mtime(
754 0 : // use currenttime as last modified time
755 0 : SystemTime::now()
756 0 : .duration_since(SystemTime::UNIX_EPOCH)
757 0 : .unwrap()
758 0 : .as_secs(),
759 0 : );
760 0 : header.set_cksum();
761 0 : Ok(header)
762 0 : }
|