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

Generated by: LCOV version 2.1-beta