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