LCOV - code coverage report
Current view: top level - pageserver/src - basebackup.rs (source / functions) Coverage Total Hit
Test: 553e39c2773e5840c720c90d86e56f89a4330d43.info Lines: 0.0 % 520 0
Test Date: 2025-06-13 20:01:21 Functions: 0.0 % 231 0

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

Generated by: LCOV version 2.1-beta