LCOV - code coverage report
Current view: top level - pageserver/src - import_datadir.rs (source / functions) Coverage Total Hit
Test: 2a9d99866121f170b43760bd62e1e2431e597707.info Lines: 64.3 % 420 270
Test Date: 2024-09-02 14:10:37 Functions: 41.2 % 34 14

            Line data    Source code
       1              : //!
       2              : //! Import data and WAL from a PostgreSQL data directory and WAL segments into
       3              : //! a neon Timeline.
       4              : //!
       5              : use std::path::{Path, PathBuf};
       6              : 
       7              : use anyhow::{bail, ensure, Context, Result};
       8              : use bytes::Bytes;
       9              : use camino::Utf8Path;
      10              : use futures::StreamExt;
      11              : use pageserver_api::key::rel_block_to_key;
      12              : use tokio::io::{AsyncRead, AsyncReadExt};
      13              : use tokio_tar::Archive;
      14              : use tracing::*;
      15              : use walkdir::WalkDir;
      16              : 
      17              : use crate::context::RequestContext;
      18              : use crate::metrics::WAL_INGEST;
      19              : use crate::pgdatadir_mapping::*;
      20              : use crate::tenant::Timeline;
      21              : use crate::walingest::WalIngest;
      22              : use crate::walrecord::DecodedWALRecord;
      23              : use pageserver_api::reltag::{RelTag, SlruKind};
      24              : use postgres_ffi::pg_constants;
      25              : use postgres_ffi::relfile_utils::*;
      26              : use postgres_ffi::waldecoder::WalStreamDecoder;
      27              : use postgres_ffi::ControlFileData;
      28              : use postgres_ffi::DBState_DB_SHUTDOWNED;
      29              : use postgres_ffi::Oid;
      30              : use postgres_ffi::XLogFileName;
      31              : use postgres_ffi::{BLCKSZ, WAL_SEGMENT_SIZE};
      32              : use utils::lsn::Lsn;
      33              : 
      34              : // Returns checkpoint LSN from controlfile
      35            6 : pub fn get_lsn_from_controlfile(path: &Utf8Path) -> Result<Lsn> {
      36            6 :     // Read control file to extract the LSN
      37            6 :     let controlfile_path = path.join("global").join("pg_control");
      38            6 :     let controlfile_buf = std::fs::read(&controlfile_path)
      39            6 :         .with_context(|| format!("reading controlfile: {controlfile_path}"))?;
      40            6 :     let controlfile = ControlFileData::decode(&controlfile_buf)?;
      41            6 :     let lsn = controlfile.checkPoint;
      42            6 : 
      43            6 :     Ok(Lsn(lsn))
      44            6 : }
      45              : 
      46              : ///
      47              : /// Import all relation data pages from local disk into the repository.
      48              : ///
      49              : /// This is currently only used to import a cluster freshly created by initdb.
      50              : /// The code that deals with the checkpoint would not work right if the
      51              : /// cluster was not shut down cleanly.
      52            6 : pub async fn import_timeline_from_postgres_datadir(
      53            6 :     tline: &Timeline,
      54            6 :     pgdata_path: &Utf8Path,
      55            6 :     pgdata_lsn: Lsn,
      56            6 :     ctx: &RequestContext,
      57            6 : ) -> Result<()> {
      58            6 :     let mut pg_control: Option<ControlFileData> = None;
      59            6 : 
      60            6 :     // TODO this shoud be start_lsn, which is not necessarily equal to end_lsn (aka lsn)
      61            6 :     // Then fishing out pg_control would be unnecessary
      62            6 :     let mut modification = tline.begin_modification(pgdata_lsn);
      63            6 :     modification.init_empty()?;
      64              : 
      65              :     // Import all but pg_wal
      66            6 :     let all_but_wal = WalkDir::new(pgdata_path)
      67            6 :         .into_iter()
      68         5940 :         .filter_entry(|entry| !entry.path().ends_with("pg_wal"));
      69         5940 :     for entry in all_but_wal {
      70         5934 :         let entry = entry?;
      71         5934 :         let metadata = entry.metadata().expect("error getting dir entry metadata");
      72         5934 :         if metadata.is_file() {
      73         5790 :             let absolute_path = entry.path();
      74         5790 :             let relative_path = absolute_path.strip_prefix(pgdata_path)?;
      75              : 
      76         5790 :             let mut file = tokio::fs::File::open(absolute_path).await?;
      77         5790 :             let len = metadata.len() as usize;
      78            6 :             if let Some(control_file) =
      79        22116 :                 import_file(&mut modification, relative_path, &mut file, len, ctx).await?
      80            6 :             {
      81            6 :                 pg_control = Some(control_file);
      82         5784 :             }
      83         5790 :             modification.flush(ctx).await?;
      84          144 :         }
      85              :     }
      86              : 
      87              :     // We're done importing all the data files.
      88         1044 :     modification.commit(ctx).await?;
      89              : 
      90              :     // We expect the Postgres server to be shut down cleanly.
      91            6 :     let pg_control = pg_control.context("pg_control file not found")?;
      92            6 :     ensure!(
      93            6 :         pg_control.state == DBState_DB_SHUTDOWNED,
      94            0 :         "Postgres cluster was not shut down cleanly"
      95              :     );
      96            6 :     ensure!(
      97            6 :         pg_control.checkPointCopy.redo == pgdata_lsn.0,
      98            0 :         "unexpected checkpoint REDO pointer"
      99              :     );
     100              : 
     101              :     // Import WAL. This is needed even when starting from a shutdown checkpoint, because
     102              :     // this reads the checkpoint record itself, advancing the tip of the timeline to
     103              :     // *after* the checkpoint record. And crucially, it initializes the 'prev_lsn'.
     104            6 :     import_wal(
     105            6 :         &pgdata_path.join("pg_wal"),
     106            6 :         tline,
     107            6 :         Lsn(pg_control.checkPointCopy.redo),
     108            6 :         pgdata_lsn,
     109            6 :         ctx,
     110            6 :     )
     111            6 :     .await?;
     112              : 
     113            6 :     Ok(())
     114            6 : }
     115              : 
     116              : // subroutine of import_timeline_from_postgres_datadir(), to load one relation file.
     117         5676 : async fn import_rel(
     118         5676 :     modification: &mut DatadirModification<'_>,
     119         5676 :     path: &Path,
     120         5676 :     spcoid: Oid,
     121         5676 :     dboid: Oid,
     122         5676 :     reader: &mut (impl AsyncRead + Unpin),
     123         5676 :     len: usize,
     124         5676 :     ctx: &RequestContext,
     125         5676 : ) -> anyhow::Result<()> {
     126         5676 :     // Does it look like a relation file?
     127         5676 :     trace!("importing rel file {}", path.display());
     128              : 
     129         5676 :     let filename = &path
     130         5676 :         .file_name()
     131         5676 :         .expect("missing rel filename")
     132         5676 :         .to_string_lossy();
     133         5676 :     let (relnode, forknum, segno) = parse_relfilename(filename).map_err(|e| {
     134            0 :         warn!("unrecognized file in postgres datadir: {:?} ({})", path, e);
     135            0 :         e
     136         5676 :     })?;
     137              : 
     138         5676 :     let mut buf: [u8; 8192] = [0u8; 8192];
     139         5676 : 
     140         5676 :     ensure!(len % BLCKSZ as usize == 0);
     141         5676 :     let nblocks = len / BLCKSZ as usize;
     142         5676 : 
     143         5676 :     let rel = RelTag {
     144         5676 :         spcnode: spcoid,
     145         5676 :         dbnode: dboid,
     146         5676 :         relnode,
     147         5676 :         forknum,
     148         5676 :     };
     149         5676 : 
     150         5676 :     let mut blknum: u32 = segno * (1024 * 1024 * 1024 / BLCKSZ as u32);
     151              : 
     152              :     // Call put_rel_creation for every segment of the relation,
     153              :     // because there is no guarantee about the order in which we are processing segments.
     154              :     // ignore "relation already exists" error
     155              :     //
     156              :     // FIXME: Keep track of which relations we've already created?
     157              :     // https://github.com/neondatabase/neon/issues/3309
     158         5676 :     if let Err(e) = modification
     159         5676 :         .put_rel_creation(rel, nblocks as u32, ctx)
     160            0 :         .await
     161              :     {
     162            0 :         match e {
     163              :             RelationError::AlreadyExists => {
     164            0 :                 debug!("Relation {} already exist. We must be extending it.", rel)
     165              :             }
     166            0 :             _ => return Err(e.into()),
     167              :         }
     168         5676 :     }
     169              : 
     170              :     loop {
     171        21996 :         let r = reader.read_exact(&mut buf).await;
     172        21996 :         match r {
     173              :             Ok(_) => {
     174        16320 :                 let key = rel_block_to_key(rel, blknum);
     175        16320 :                 if modification.tline.get_shard_identity().is_key_local(&key) {
     176        16320 :                     modification.put_rel_page_image(rel, blknum, Bytes::copy_from_slice(&buf))?;
     177            0 :                 }
     178              :             }
     179              : 
     180              :             // TODO: UnexpectedEof is expected
     181         5676 :             Err(err) => match err.kind() {
     182              :                 std::io::ErrorKind::UnexpectedEof => {
     183              :                     // reached EOF. That's expected.
     184         5676 :                     let relative_blknum = blknum - segno * (1024 * 1024 * 1024 / BLCKSZ as u32);
     185         5676 :                     ensure!(relative_blknum == nblocks as u32, "unexpected EOF");
     186         5676 :                     break;
     187              :                 }
     188              :                 _ => {
     189            0 :                     bail!("error reading file {}: {:#}", path.display(), err);
     190              :                 }
     191              :             },
     192              :         };
     193        16320 :         blknum += 1;
     194              :     }
     195              : 
     196              :     // Update relation size
     197              :     //
     198              :     // If we process rel segments out of order,
     199              :     // put_rel_extend will skip the update.
     200         5676 :     modification.put_rel_extend(rel, blknum, ctx).await?;
     201              : 
     202         5676 :     Ok(())
     203         5676 : }
     204              : 
     205              : /// Import an SLRU segment file
     206              : ///
     207           18 : async fn import_slru(
     208           18 :     modification: &mut DatadirModification<'_>,
     209           18 :     slru: SlruKind,
     210           18 :     path: &Path,
     211           18 :     reader: &mut (impl AsyncRead + Unpin),
     212           18 :     len: usize,
     213           18 :     ctx: &RequestContext,
     214           18 : ) -> anyhow::Result<()> {
     215           18 :     info!("importing slru file {path:?}");
     216              : 
     217           18 :     let mut buf: [u8; 8192] = [0u8; 8192];
     218           18 :     let filename = &path
     219           18 :         .file_name()
     220           18 :         .with_context(|| format!("missing slru filename for path {path:?}"))?
     221           18 :         .to_string_lossy();
     222           18 :     let segno = u32::from_str_radix(filename, 16)?;
     223              : 
     224           18 :     ensure!(len % BLCKSZ as usize == 0); // we assume SLRU block size is the same as BLCKSZ
     225           18 :     let nblocks = len / BLCKSZ as usize;
     226           18 : 
     227           18 :     ensure!(nblocks <= pg_constants::SLRU_PAGES_PER_SEGMENT as usize);
     228              : 
     229           18 :     modification
     230           18 :         .put_slru_segment_creation(slru, segno, nblocks as u32, ctx)
     231            0 :         .await?;
     232              : 
     233           18 :     let mut rpageno = 0;
     234              :     loop {
     235           36 :         let r = reader.read_exact(&mut buf).await;
     236           36 :         match r {
     237              :             Ok(_) => {
     238           18 :                 modification.put_slru_page_image(
     239           18 :                     slru,
     240           18 :                     segno,
     241           18 :                     rpageno,
     242           18 :                     Bytes::copy_from_slice(&buf),
     243           18 :                 )?;
     244              :             }
     245              : 
     246              :             // TODO: UnexpectedEof is expected
     247           18 :             Err(err) => match err.kind() {
     248              :                 std::io::ErrorKind::UnexpectedEof => {
     249              :                     // reached EOF. That's expected.
     250           18 :                     ensure!(rpageno == nblocks as u32, "unexpected EOF");
     251           18 :                     break;
     252              :                 }
     253              :                 _ => {
     254            0 :                     bail!("error reading file {}: {:#}", path.display(), err);
     255              :                 }
     256              :             },
     257              :         };
     258           18 :         rpageno += 1;
     259              :     }
     260              : 
     261           18 :     Ok(())
     262           18 : }
     263              : 
     264              : /// Scan PostgreSQL WAL files in given directory and load all records between
     265              : /// 'startpoint' and 'endpoint' into the repository.
     266            6 : async fn import_wal(
     267            6 :     walpath: &Utf8Path,
     268            6 :     tline: &Timeline,
     269            6 :     startpoint: Lsn,
     270            6 :     endpoint: Lsn,
     271            6 :     ctx: &RequestContext,
     272            6 : ) -> anyhow::Result<()> {
     273            6 :     let mut waldecoder = WalStreamDecoder::new(startpoint, tline.pg_version);
     274            6 : 
     275            6 :     let mut segno = startpoint.segment_number(WAL_SEGMENT_SIZE);
     276            6 :     let mut offset = startpoint.segment_offset(WAL_SEGMENT_SIZE);
     277            6 :     let mut last_lsn = startpoint;
     278              : 
     279            6 :     let mut walingest = WalIngest::new(tline, startpoint, ctx).await?;
     280              : 
     281           12 :     while last_lsn <= endpoint {
     282              :         // FIXME: assume postgresql tli 1 for now
     283            6 :         let filename = XLogFileName(1, segno, WAL_SEGMENT_SIZE);
     284            6 :         let mut buf = Vec::new();
     285            6 : 
     286            6 :         // Read local file
     287            6 :         let mut path = walpath.join(&filename);
     288            6 : 
     289            6 :         // It could be as .partial
     290            6 :         if !PathBuf::from(&path).exists() {
     291            0 :             path = walpath.join(filename + ".partial");
     292            6 :         }
     293              : 
     294              :         // Slurp the WAL file
     295            6 :         let mut file = std::fs::File::open(&path)?;
     296              : 
     297            6 :         if offset > 0 {
     298              :             use std::io::Seek;
     299            6 :             file.seek(std::io::SeekFrom::Start(offset as u64))?;
     300            0 :         }
     301              : 
     302              :         use std::io::Read;
     303            6 :         let nread = file.read_to_end(&mut buf)?;
     304            6 :         if nread != WAL_SEGMENT_SIZE - offset {
     305              :             // Maybe allow this for .partial files?
     306            0 :             error!("read only {} bytes from WAL file", nread);
     307            6 :         }
     308              : 
     309            6 :         waldecoder.feed_bytes(&buf);
     310            6 : 
     311            6 :         let mut nrecords = 0;
     312            6 :         let mut modification = tline.begin_modification(last_lsn);
     313            6 :         let mut decoded = DecodedWALRecord::default();
     314           12 :         while last_lsn <= endpoint {
     315            6 :             if let Some((lsn, recdata)) = waldecoder.poll_decode()? {
     316            6 :                 walingest
     317            6 :                     .ingest_record(recdata, lsn, &mut modification, &mut decoded, ctx)
     318            3 :                     .await?;
     319            6 :                 WAL_INGEST.records_committed.inc();
     320            6 : 
     321            6 :                 modification.commit(ctx).await?;
     322            6 :                 last_lsn = lsn;
     323            6 : 
     324            6 :                 nrecords += 1;
     325            6 : 
     326            6 :                 trace!("imported record at {} (end {})", lsn, endpoint);
     327            0 :             }
     328              :         }
     329              : 
     330            6 :         debug!("imported {} records up to {}", nrecords, last_lsn);
     331              : 
     332            6 :         segno += 1;
     333            6 :         offset = 0;
     334              :     }
     335              : 
     336            6 :     if last_lsn != startpoint {
     337            6 :         info!("reached end of WAL at {}", last_lsn);
     338              :     } else {
     339            0 :         info!("no WAL to import at {}", last_lsn);
     340              :     }
     341              : 
     342            6 :     Ok(())
     343            6 : }
     344              : 
     345            0 : pub async fn import_basebackup_from_tar(
     346            0 :     tline: &Timeline,
     347            0 :     reader: &mut (impl AsyncRead + Send + Sync + Unpin),
     348            0 :     base_lsn: Lsn,
     349            0 :     ctx: &RequestContext,
     350            0 : ) -> Result<()> {
     351            0 :     info!("importing base at {base_lsn}");
     352            0 :     let mut modification = tline.begin_modification(base_lsn);
     353            0 :     modification.init_empty()?;
     354              : 
     355            0 :     let mut pg_control: Option<ControlFileData> = None;
     356              : 
     357              :     // Import base
     358            0 :     let mut entries = Archive::new(reader).entries()?;
     359            0 :     while let Some(base_tar_entry) = entries.next().await {
     360            0 :         let mut entry = base_tar_entry?;
     361            0 :         let header = entry.header();
     362            0 :         let len = header.entry_size()? as usize;
     363            0 :         let file_path = header.path()?.into_owned();
     364            0 : 
     365            0 :         match header.entry_type() {
     366              :             tokio_tar::EntryType::Regular => {
     367            0 :                 if let Some(res) =
     368            0 :                     import_file(&mut modification, file_path.as_ref(), &mut entry, len, ctx).await?
     369            0 :                 {
     370            0 :                     // We found the pg_control file.
     371            0 :                     pg_control = Some(res);
     372            0 :                 }
     373            0 :                 modification.flush(ctx).await?;
     374              :             }
     375              :             tokio_tar::EntryType::Directory => {
     376            0 :                 debug!("directory {:?}", file_path);
     377              :             }
     378              :             _ => {
     379            0 :                 bail!(
     380            0 :                     "entry {} in backup tar archive is of unexpected type: {:?}",
     381            0 :                     file_path.display(),
     382            0 :                     header.entry_type()
     383            0 :                 );
     384              :             }
     385              :         }
     386              :     }
     387              : 
     388              :     // sanity check: ensure that pg_control is loaded
     389            0 :     let _pg_control = pg_control.context("pg_control file not found")?;
     390              : 
     391            0 :     modification.commit(ctx).await?;
     392            0 :     Ok(())
     393            0 : }
     394              : 
     395            0 : pub async fn import_wal_from_tar(
     396            0 :     tline: &Timeline,
     397            0 :     reader: &mut (impl AsyncRead + Send + Sync + Unpin),
     398            0 :     start_lsn: Lsn,
     399            0 :     end_lsn: Lsn,
     400            0 :     ctx: &RequestContext,
     401            0 : ) -> Result<()> {
     402            0 :     // Set up walingest mutable state
     403            0 :     let mut waldecoder = WalStreamDecoder::new(start_lsn, tline.pg_version);
     404            0 :     let mut segno = start_lsn.segment_number(WAL_SEGMENT_SIZE);
     405            0 :     let mut offset = start_lsn.segment_offset(WAL_SEGMENT_SIZE);
     406            0 :     let mut last_lsn = start_lsn;
     407            0 :     let mut walingest = WalIngest::new(tline, start_lsn, ctx).await?;
     408              : 
     409              :     // Ingest wal until end_lsn
     410            0 :     info!("importing wal until {}", end_lsn);
     411            0 :     let mut pg_wal_tar = Archive::new(reader);
     412            0 :     let mut pg_wal_entries = pg_wal_tar.entries()?;
     413            0 :     while last_lsn <= end_lsn {
     414            0 :         let bytes = {
     415            0 :             let mut entry = pg_wal_entries
     416            0 :                 .next()
     417            0 :                 .await
     418            0 :                 .ok_or_else(|| anyhow::anyhow!("expected more wal"))??;
     419            0 :             let header = entry.header();
     420            0 :             let file_path = header.path()?.into_owned();
     421            0 : 
     422            0 :             match header.entry_type() {
     423              :                 tokio_tar::EntryType::Regular => {
     424              :                     // FIXME: assume postgresql tli 1 for now
     425            0 :                     let expected_filename = XLogFileName(1, segno, WAL_SEGMENT_SIZE);
     426            0 :                     let file_name = file_path
     427            0 :                         .file_name()
     428            0 :                         .expect("missing wal filename")
     429            0 :                         .to_string_lossy();
     430            0 :                     ensure!(expected_filename == file_name);
     431              : 
     432            0 :                     debug!("processing wal file {:?}", file_path);
     433            0 :                     read_all_bytes(&mut entry).await?
     434              :                 }
     435              :                 tokio_tar::EntryType::Directory => {
     436            0 :                     debug!("directory {:?}", file_path);
     437            0 :                     continue;
     438              :                 }
     439              :                 _ => {
     440            0 :                     bail!(
     441            0 :                         "entry {} in WAL tar archive is of unexpected type: {:?}",
     442            0 :                         file_path.display(),
     443            0 :                         header.entry_type()
     444            0 :                     );
     445              :                 }
     446              :             }
     447              :         };
     448              : 
     449            0 :         waldecoder.feed_bytes(&bytes[offset..]);
     450            0 : 
     451            0 :         let mut modification = tline.begin_modification(last_lsn);
     452            0 :         let mut decoded = DecodedWALRecord::default();
     453            0 :         while last_lsn <= end_lsn {
     454            0 :             if let Some((lsn, recdata)) = waldecoder.poll_decode()? {
     455            0 :                 walingest
     456            0 :                     .ingest_record(recdata, lsn, &mut modification, &mut decoded, ctx)
     457            0 :                     .await?;
     458            0 :                 modification.commit(ctx).await?;
     459            0 :                 last_lsn = lsn;
     460            0 : 
     461            0 :                 debug!("imported record at {} (end {})", lsn, end_lsn);
     462            0 :             }
     463              :         }
     464              : 
     465            0 :         debug!("imported records up to {}", last_lsn);
     466            0 :         segno += 1;
     467            0 :         offset = 0;
     468              :     }
     469              : 
     470            0 :     if last_lsn != start_lsn {
     471            0 :         info!("reached end of WAL at {}", last_lsn);
     472              :     } else {
     473            0 :         info!("there was no WAL to import at {}", last_lsn);
     474              :     }
     475              : 
     476              :     // Log any extra unused files
     477            0 :     while let Some(e) = pg_wal_entries.next().await {
     478            0 :         let entry = e?;
     479            0 :         let header = entry.header();
     480            0 :         let file_path = header.path()?.into_owned();
     481            0 :         info!("skipping {:?}", file_path);
     482              :     }
     483              : 
     484            0 :     Ok(())
     485            0 : }
     486              : 
     487         5790 : async fn import_file(
     488         5790 :     modification: &mut DatadirModification<'_>,
     489         5790 :     file_path: &Path,
     490         5790 :     reader: &mut (impl AsyncRead + Send + Sync + Unpin),
     491         5790 :     len: usize,
     492         5790 :     ctx: &RequestContext,
     493         5790 : ) -> Result<Option<ControlFileData>> {
     494         5790 :     let file_name = match file_path.file_name() {
     495         5790 :         Some(name) => name.to_string_lossy(),
     496            0 :         None => return Ok(None),
     497              :     };
     498              : 
     499         5790 :     if file_name.starts_with('.') {
     500              :         // tar archives on macOs, created without COPYFILE_DISABLE=1 env var
     501              :         // will contain "fork files", skip them.
     502            0 :         return Ok(None);
     503         5790 :     }
     504         5790 : 
     505         5790 :     if file_path.starts_with("global") {
     506          360 :         let spcnode = postgres_ffi::pg_constants::GLOBALTABLESPACE_OID;
     507          360 :         let dbnode = 0;
     508          360 : 
     509          360 :         match file_name.as_ref() {
     510          360 :             "pg_control" => {
     511           60 :                 let bytes = read_all_bytes(reader).await?;
     512              : 
     513              :                 // Extract the checkpoint record and import it separately.
     514            6 :                 let pg_control = ControlFileData::decode(&bytes[..])?;
     515            6 :                 let checkpoint_bytes = pg_control.checkPointCopy.encode()?;
     516            6 :                 modification.put_checkpoint(checkpoint_bytes)?;
     517            6 :                 debug!("imported control file");
     518              : 
     519              :                 // Import it as ControlFile
     520            6 :                 modification.put_control_file(bytes)?;
     521            6 :                 return Ok(Some(pg_control));
     522              :             }
     523          354 :             "pg_filenode.map" => {
     524           36 :                 let bytes = read_all_bytes(reader).await?;
     525            6 :                 modification
     526            6 :                     .put_relmap_file(spcnode, dbnode, bytes, ctx)
     527            0 :                     .await?;
     528            6 :                 debug!("imported relmap file")
     529              :             }
     530          348 :             "PG_VERSION" => {
     531            0 :                 debug!("ignored PG_VERSION file");
     532              :             }
     533              :             _ => {
     534          705 :                 import_rel(modification, file_path, spcnode, dbnode, reader, len, ctx).await?;
     535          348 :                 debug!("imported rel creation");
     536              :             }
     537              :         }
     538         5430 :     } else if file_path.starts_with("base") {
     539         5364 :         let spcnode = pg_constants::DEFAULTTABLESPACE_OID;
     540         5364 :         let dbnode: u32 = file_path
     541         5364 :             .iter()
     542         5364 :             .nth(1)
     543         5364 :             .expect("invalid file path, expected dbnode")
     544         5364 :             .to_string_lossy()
     545         5364 :             .parse()?;
     546              : 
     547         5364 :         match file_name.as_ref() {
     548         5364 :             "pg_filenode.map" => {
     549          106 :                 let bytes = read_all_bytes(reader).await?;
     550           18 :                 modification
     551           18 :                     .put_relmap_file(spcnode, dbnode, bytes, ctx)
     552            0 :                     .await?;
     553           18 :                 debug!("imported relmap file")
     554              :             }
     555         5346 :             "PG_VERSION" => {
     556           18 :                 debug!("ignored PG_VERSION file");
     557              :             }
     558              :             _ => {
     559        21173 :                 import_rel(modification, file_path, spcnode, dbnode, reader, len, ctx).await?;
     560         5328 :                 debug!("imported rel creation");
     561              :             }
     562              :         }
     563           66 :     } else if file_path.starts_with("pg_xact") {
     564            6 :         let slru = SlruKind::Clog;
     565            6 : 
     566           12 :         import_slru(modification, slru, file_path, reader, len, ctx).await?;
     567            6 :         debug!("imported clog slru");
     568           60 :     } else if file_path.starts_with("pg_multixact/offsets") {
     569            6 :         let slru = SlruKind::MultiXactOffsets;
     570            6 : 
     571           12 :         import_slru(modification, slru, file_path, reader, len, ctx).await?;
     572            6 :         debug!("imported multixact offsets slru");
     573           54 :     } else if file_path.starts_with("pg_multixact/members") {
     574            6 :         let slru = SlruKind::MultiXactMembers;
     575            6 : 
     576           12 :         import_slru(modification, slru, file_path, reader, len, ctx).await?;
     577            6 :         debug!("imported multixact members slru");
     578           48 :     } else if file_path.starts_with("pg_twophase") {
     579            0 :         let xid = u32::from_str_radix(file_name.as_ref(), 16)?;
     580              : 
     581            0 :         let bytes = read_all_bytes(reader).await?;
     582            0 :         modification
     583            0 :             .put_twophase_file(xid, Bytes::copy_from_slice(&bytes[..]), ctx)
     584            0 :             .await?;
     585            0 :         debug!("imported twophase file");
     586           48 :     } else if file_path.starts_with("pg_wal") {
     587            0 :         debug!("found wal file in base section. ignore it");
     588           48 :     } else if file_path.starts_with("zenith.signal") {
     589              :         // Parse zenith signal file to set correct previous LSN
     590            0 :         let bytes = read_all_bytes(reader).await?;
     591              :         // zenith.signal format is "PREV LSN: prev_lsn"
     592              :         // TODO write serialization and deserialization in the same place.
     593            0 :         let zenith_signal = std::str::from_utf8(&bytes)?.trim();
     594            0 :         let prev_lsn = match zenith_signal {
     595            0 :             "PREV LSN: none" => Lsn(0),
     596            0 :             "PREV LSN: invalid" => Lsn(0),
     597            0 :             other => {
     598            0 :                 let split = other.split(':').collect::<Vec<_>>();
     599            0 :                 split[1]
     600            0 :                     .trim()
     601            0 :                     .parse::<Lsn>()
     602            0 :                     .context("can't parse zenith.signal")?
     603              :             }
     604              :         };
     605              : 
     606              :         // zenith.signal is not necessarily the last file, that we handle
     607              :         // but it is ok to call `finish_write()`, because final `modification.commit()`
     608              :         // will update lsn once more to the final one.
     609            0 :         let writer = modification.tline.writer().await;
     610            0 :         writer.finish_write(prev_lsn);
     611            0 : 
     612            0 :         debug!("imported zenith signal {}", prev_lsn);
     613           48 :     } else if file_path.starts_with("pg_tblspc") {
     614              :         // TODO Backups exported from neon won't have pg_tblspc, but we will need
     615              :         // this to import arbitrary postgres databases.
     616            0 :         bail!("Importing pg_tblspc is not implemented");
     617              :     } else {
     618           48 :         debug!(
     619            0 :             "ignoring unrecognized file \"{}\" in tar archive",
     620            0 :             file_path.display()
     621              :         );
     622              :     }
     623              : 
     624         5784 :     Ok(None)
     625         5790 : }
     626              : 
     627           30 : async fn read_all_bytes(reader: &mut (impl AsyncRead + Unpin)) -> Result<Bytes> {
     628           30 :     let mut buf: Vec<u8> = vec![];
     629          202 :     reader.read_to_end(&mut buf).await?;
     630           30 :     Ok(Bytes::from(buf))
     631           30 : }
        

Generated by: LCOV version 2.1-beta