LCOV - code coverage report
Current view: top level - safekeeper/src - wal_storage.rs (source / functions) Coverage Total Hit
Test: 53437f7e869ac68c86c7d3e4c20964c0156f158c.info Lines: 0.0 % 462 0
Test Date: 2024-09-20 16:14:12 Functions: 0.0 % 47 0

            Line data    Source code
       1              : //! This module has everything to deal with WAL -- reading and writing to disk.
       2              : //!
       3              : //! Safekeeper WAL is stored in the timeline directory, in format similar to pg_wal.
       4              : //! PG timeline is always 1, so WAL segments are usually have names like this:
       5              : //! - 000000010000000000000001
       6              : //! - 000000010000000000000002.partial
       7              : //!
       8              : //! Note that last file has `.partial` suffix, that's different from postgres.
       9              : 
      10              : use anyhow::{bail, Context, Result};
      11              : use bytes::Bytes;
      12              : use camino::{Utf8Path, Utf8PathBuf};
      13              : use futures::future::BoxFuture;
      14              : use postgres_ffi::v14::xlog_utils::{IsPartialXLogFileName, IsXLogFileName, XLogFromFileName};
      15              : use postgres_ffi::{dispatch_pgversion, XLogSegNo, PG_TLI};
      16              : use remote_storage::RemotePath;
      17              : use std::cmp::{max, min};
      18              : use std::future::Future;
      19              : use std::io::{self, SeekFrom};
      20              : use std::pin::Pin;
      21              : use tokio::fs::{self, remove_file, File, OpenOptions};
      22              : use tokio::io::{AsyncRead, AsyncWriteExt};
      23              : use tokio::io::{AsyncReadExt, AsyncSeekExt};
      24              : use tracing::*;
      25              : use utils::crashsafe::durable_rename;
      26              : 
      27              : use crate::metrics::{
      28              :     time_io_closure, WalStorageMetrics, REMOVED_WAL_SEGMENTS, WAL_STORAGE_OPERATION_SECONDS,
      29              : };
      30              : use crate::state::TimelinePersistentState;
      31              : use crate::wal_backup::{read_object, remote_timeline_path};
      32              : use crate::SafeKeeperConf;
      33              : use postgres_ffi::waldecoder::WalStreamDecoder;
      34              : use postgres_ffi::XLogFileName;
      35              : use postgres_ffi::XLOG_BLCKSZ;
      36              : use pq_proto::SystemId;
      37              : use utils::{id::TenantTimelineId, lsn::Lsn};
      38              : 
      39              : pub trait Storage {
      40              :     // Last written LSN.
      41              :     fn write_lsn(&self) -> Lsn;
      42              :     /// LSN of last durably stored WAL record.
      43              :     fn flush_lsn(&self) -> Lsn;
      44              : 
      45              :     /// Initialize segment by creating proper long header at the beginning of
      46              :     /// the segment and short header at the page of given LSN. This is only used
      47              :     /// for timeline initialization because compute will stream data only since
      48              :     /// init_lsn. Other segment headers are included in compute stream.
      49              :     fn initialize_first_segment(
      50              :         &mut self,
      51              :         init_lsn: Lsn,
      52              :     ) -> impl Future<Output = Result<()>> + Send;
      53              : 
      54              :     /// Write piece of WAL from buf to disk, but not necessarily sync it.
      55              :     fn write_wal(&mut self, startpos: Lsn, buf: &[u8]) -> impl Future<Output = Result<()>> + Send;
      56              : 
      57              :     /// Truncate WAL at specified LSN, which must be the end of WAL record.
      58              :     fn truncate_wal(&mut self, end_pos: Lsn) -> impl Future<Output = Result<()>> + Send;
      59              : 
      60              :     /// Durably store WAL on disk, up to the last written WAL record.
      61              :     fn flush_wal(&mut self) -> impl Future<Output = Result<()>> + Send;
      62              : 
      63              :     /// Remove all segments <= given segno. Returns function doing that as we
      64              :     /// want to perform it without timeline lock.
      65              :     fn remove_up_to(&self, segno_up_to: XLogSegNo) -> BoxFuture<'static, anyhow::Result<()>>;
      66              : 
      67              :     /// Release resources associated with the storage -- technically, close FDs.
      68              :     /// Currently we don't remove timelines until restart (#3146), so need to
      69              :     /// spare descriptors. This would be useful for temporary tli detach as
      70              :     /// well.
      71            0 :     fn close(&mut self) {}
      72              : 
      73              :     /// Get metrics for this timeline.
      74              :     fn get_metrics(&self) -> WalStorageMetrics;
      75              : }
      76              : 
      77              : /// PhysicalStorage is a storage that stores WAL on disk. Writes are separated from flushes
      78              : /// for better performance. Storage is initialized in the constructor.
      79              : ///
      80              : /// WAL is stored in segments, each segment is a file. Last segment has ".partial" suffix in
      81              : /// its filename and may be not fully flushed.
      82              : ///
      83              : /// Relationship of LSNs:
      84              : /// `write_lsn` >= `write_record_lsn` >= `flush_record_lsn`
      85              : ///
      86              : /// When storage is created first time, all LSNs are zeroes and there are no segments on disk.
      87              : pub struct PhysicalStorage {
      88              :     metrics: WalStorageMetrics,
      89              :     timeline_dir: Utf8PathBuf,
      90              :     conf: SafeKeeperConf,
      91              : 
      92              :     /// Size of WAL segment in bytes.
      93              :     wal_seg_size: usize,
      94              :     pg_version: u32,
      95              :     system_id: u64,
      96              : 
      97              :     /// Written to disk, but possibly still in the cache and not fully persisted.
      98              :     /// Also can be ahead of record_lsn, if happen to be in the middle of a WAL record.
      99              :     write_lsn: Lsn,
     100              : 
     101              :     /// The LSN of the last WAL record written to disk. Still can be not fully
     102              :     /// flushed.
     103              :     ///
     104              :     /// Note: Normally it (and flush_record_lsn) is <= write_lsn, but after xlog
     105              :     /// switch ingest the reverse is true because we don't bump write_lsn up to
     106              :     /// the next segment: WAL stream from the compute doesn't have the gap and
     107              :     /// for simplicity / as a sanity check we disallow any non-sequential
     108              :     /// writes, so write zeros as is.
     109              :     ///
     110              :     /// Similar effect is in theory possible due to LSN alignment: if record
     111              :     /// ends at *2, decoder will report end lsn as *8 even though we haven't
     112              :     /// written these zeros yet. In practice compute likely never sends
     113              :     /// non-aligned chunks of data.
     114              :     write_record_lsn: Lsn,
     115              : 
     116              :     /// The LSN of the last WAL record flushed to disk.
     117              :     flush_record_lsn: Lsn,
     118              : 
     119              :     /// Decoder is required for detecting boundaries of WAL records.
     120              :     decoder: WalStreamDecoder,
     121              : 
     122              :     /// Cached open file for the last segment.
     123              :     ///
     124              :     /// If Some(file) is open, then it always:
     125              :     /// - has ".partial" suffix
     126              :     /// - points to write_lsn, so no seek is needed for writing
     127              :     /// - doesn't point to the end of the segment
     128              :     file: Option<File>,
     129              : 
     130              :     /// When false, we have just initialized storage using the LSN from find_end_of_wal().
     131              :     /// In this case, [`write_lsn`] can be less than actually written WAL on disk. In particular,
     132              :     /// there can be a case with unexpected .partial file.
     133              :     ///
     134              :     /// Imagine the following:
     135              :     /// - 000000010000000000000001
     136              :     ///   - it was fully written, but the last record is split between 2 segments
     137              :     ///   - after restart, `find_end_of_wal()` returned 0/1FFFFF0, which is in the end of this segment
     138              :     ///   - `write_lsn`, `write_record_lsn` and `flush_record_lsn` were initialized to 0/1FFFFF0
     139              :     /// - 000000010000000000000002.partial
     140              :     ///   - it has only 1 byte written, which is not enough to make a full WAL record
     141              :     ///
     142              :     /// Partial segment 002 has no WAL records, and it will be removed by the next truncate_wal().
     143              :     /// This flag will be set to true after the first truncate_wal() call.
     144              :     ///
     145              :     /// [`write_lsn`]: Self::write_lsn
     146              :     is_truncated_after_restart: bool,
     147              : }
     148              : 
     149              : impl PhysicalStorage {
     150              :     /// Create new storage. If commit_lsn is not zero, flush_lsn is tried to be restored from
     151              :     /// the disk. Otherwise, all LSNs are set to zero.
     152            0 :     pub fn new(
     153            0 :         ttid: &TenantTimelineId,
     154            0 :         timeline_dir: Utf8PathBuf,
     155            0 :         conf: &SafeKeeperConf,
     156            0 :         state: &TimelinePersistentState,
     157            0 :     ) -> Result<PhysicalStorage> {
     158            0 :         let wal_seg_size = state.server.wal_seg_size as usize;
     159              : 
     160              :         // Find out where stored WAL ends, starting at commit_lsn which is a
     161              :         // known recent record boundary (unless we don't have WAL at all).
     162              :         //
     163              :         // NB: find_end_of_wal MUST be backwards compatible with the previously
     164              :         // written WAL. If find_end_of_wal fails to read any WAL written by an
     165              :         // older version of the code, we could lose data forever.
     166            0 :         let write_lsn = if state.commit_lsn == Lsn(0) {
     167            0 :             Lsn(0)
     168              :         } else {
     169            0 :             let version = state.server.pg_version / 10000;
     170            0 : 
     171            0 :             dispatch_pgversion!(
     172            0 :                 version,
     173            0 :                 pgv::xlog_utils::find_end_of_wal(
     174            0 :                     timeline_dir.as_std_path(),
     175            0 :                     wal_seg_size,
     176            0 :                     state.commit_lsn,
     177            0 :                 )?,
     178            0 :                 bail!("unsupported postgres version: {}", version)
     179              :             )
     180              :         };
     181              : 
     182              :         // note: this assumes we fsync'ed whole datadir on start.
     183            0 :         let flush_lsn = write_lsn;
     184            0 : 
     185            0 :         debug!(
     186            0 :             "initialized storage for timeline {}, flush_lsn={}, commit_lsn={}, peer_horizon_lsn={}",
     187              :             ttid.timeline_id, flush_lsn, state.commit_lsn, state.peer_horizon_lsn,
     188              :         );
     189            0 :         if flush_lsn < state.commit_lsn || flush_lsn < state.peer_horizon_lsn {
     190            0 :             warn!("timeline {} potential data loss: flush_lsn by find_end_of_wal is less than either commit_lsn or peer_horizon_lsn from control file", ttid.timeline_id);
     191            0 :         }
     192              : 
     193            0 :         Ok(PhysicalStorage {
     194            0 :             metrics: WalStorageMetrics::default(),
     195            0 :             timeline_dir,
     196            0 :             conf: conf.clone(),
     197            0 :             wal_seg_size,
     198            0 :             pg_version: state.server.pg_version,
     199            0 :             system_id: state.server.system_id,
     200            0 :             write_lsn,
     201            0 :             write_record_lsn: write_lsn,
     202            0 :             flush_record_lsn: flush_lsn,
     203            0 :             decoder: WalStreamDecoder::new(write_lsn, state.server.pg_version / 10000),
     204            0 :             file: None,
     205            0 :             is_truncated_after_restart: false,
     206            0 :         })
     207            0 :     }
     208              : 
     209              :     /// Get all known state of the storage.
     210            0 :     pub fn internal_state(&self) -> (Lsn, Lsn, Lsn, bool) {
     211            0 :         (
     212            0 :             self.write_lsn,
     213            0 :             self.write_record_lsn,
     214            0 :             self.flush_record_lsn,
     215            0 :             self.file.is_some(),
     216            0 :         )
     217            0 :     }
     218              : 
     219              :     /// Call fdatasync if config requires so.
     220            0 :     async fn fdatasync_file(&mut self, file: &File) -> Result<()> {
     221            0 :         if !self.conf.no_sync {
     222            0 :             self.metrics
     223            0 :                 .observe_flush_seconds(time_io_closure(file.sync_data()).await?);
     224            0 :         }
     225            0 :         Ok(())
     226            0 :     }
     227              : 
     228              :     /// Open or create WAL segment file. Caller must call seek to the wanted position.
     229              :     /// Returns `file` and `is_partial`.
     230            0 :     async fn open_or_create(&mut self, segno: XLogSegNo) -> Result<(File, bool)> {
     231            0 :         let (wal_file_path, wal_file_partial_path) =
     232            0 :             wal_file_paths(&self.timeline_dir, segno, self.wal_seg_size);
     233              : 
     234              :         // Try to open already completed segment
     235            0 :         if let Ok(file) = OpenOptions::new().write(true).open(&wal_file_path).await {
     236            0 :             Ok((file, false))
     237            0 :         } else if let Ok(file) = OpenOptions::new()
     238            0 :             .write(true)
     239            0 :             .open(&wal_file_partial_path)
     240            0 :             .await
     241              :         {
     242              :             // Try to open existing partial file
     243            0 :             Ok((file, true))
     244              :         } else {
     245              :             // Create and fill new partial file
     246              :             //
     247              :             // We're using fdatasync during WAL writing, so file size must not
     248              :             // change; to this end it is filled with zeros here. To avoid using
     249              :             // half initialized segment, first bake it under tmp filename and
     250              :             // then rename.
     251            0 :             let tmp_path = self.timeline_dir.join("waltmp");
     252            0 :             let mut file = File::create(&tmp_path)
     253            0 :                 .await
     254            0 :                 .with_context(|| format!("Failed to open tmp wal file {:?}", &tmp_path))?;
     255              : 
     256            0 :             write_zeroes(&mut file, self.wal_seg_size).await?;
     257              : 
     258              :             // Note: this doesn't get into observe_flush_seconds metric. But
     259              :             // segment init should be separate metric, if any.
     260            0 :             if let Err(e) =
     261            0 :                 durable_rename(&tmp_path, &wal_file_partial_path, !self.conf.no_sync).await
     262              :             {
     263              :                 // Probably rename succeeded, but fsync of it failed. Remove
     264              :                 // the file then to avoid using it.
     265            0 :                 remove_file(wal_file_partial_path)
     266            0 :                     .await
     267            0 :                     .or_else(utils::fs_ext::ignore_not_found)?;
     268            0 :                 return Err(e.into());
     269            0 :             }
     270            0 :             Ok((file, true))
     271              :         }
     272            0 :     }
     273              : 
     274              :     /// Write WAL bytes, which are known to be located in a single WAL segment.
     275            0 :     async fn write_in_segment(&mut self, segno: u64, xlogoff: usize, buf: &[u8]) -> Result<()> {
     276            0 :         let mut file = if let Some(file) = self.file.take() {
     277            0 :             file
     278              :         } else {
     279            0 :             let (mut file, is_partial) = self.open_or_create(segno).await?;
     280            0 :             assert!(is_partial, "unexpected write into non-partial segment file");
     281            0 :             file.seek(SeekFrom::Start(xlogoff as u64)).await?;
     282            0 :             file
     283              :         };
     284              : 
     285            0 :         file.write_all(buf).await?;
     286              :         // Note: flush just ensures write above reaches the OS (this is not
     287              :         // needed in case of sync IO as Write::write there calls directly write
     288              :         // syscall, but needed in case of async). It does *not* fsyncs the file.
     289            0 :         file.flush().await?;
     290              : 
     291            0 :         if xlogoff + buf.len() == self.wal_seg_size {
     292              :             // If we reached the end of a WAL segment, flush and close it.
     293            0 :             self.fdatasync_file(&file).await?;
     294              : 
     295              :             // Rename partial file to completed file
     296            0 :             let (wal_file_path, wal_file_partial_path) =
     297            0 :                 wal_file_paths(&self.timeline_dir, segno, self.wal_seg_size);
     298            0 :             fs::rename(wal_file_partial_path, wal_file_path).await?;
     299            0 :         } else {
     300            0 :             // otherwise, file can be reused later
     301            0 :             self.file = Some(file);
     302            0 :         }
     303              : 
     304            0 :         Ok(())
     305            0 :     }
     306              : 
     307              :     /// Writes WAL to the segment files, until everything is writed. If some segments
     308              :     /// are fully written, they are flushed to disk. The last (partial) segment can
     309              :     /// be flushed separately later.
     310              :     ///
     311              :     /// Updates `write_lsn`.
     312            0 :     async fn write_exact(&mut self, pos: Lsn, mut buf: &[u8]) -> Result<()> {
     313            0 :         if self.write_lsn != pos {
     314              :             // need to flush the file before discarding it
     315            0 :             if let Some(file) = self.file.take() {
     316            0 :                 self.fdatasync_file(&file).await?;
     317            0 :             }
     318              : 
     319            0 :             self.write_lsn = pos;
     320            0 :         }
     321              : 
     322            0 :         while !buf.is_empty() {
     323              :             // Extract WAL location for this block
     324            0 :             let xlogoff = self.write_lsn.segment_offset(self.wal_seg_size);
     325            0 :             let segno = self.write_lsn.segment_number(self.wal_seg_size);
     326              : 
     327              :             // If crossing a WAL boundary, only write up until we reach wal segment size.
     328            0 :             let bytes_write = if xlogoff + buf.len() > self.wal_seg_size {
     329            0 :                 self.wal_seg_size - xlogoff
     330              :             } else {
     331            0 :                 buf.len()
     332              :             };
     333              : 
     334            0 :             self.write_in_segment(segno, xlogoff, &buf[..bytes_write])
     335            0 :                 .await?;
     336            0 :             self.write_lsn += bytes_write as u64;
     337            0 :             buf = &buf[bytes_write..];
     338              :         }
     339              : 
     340            0 :         Ok(())
     341            0 :     }
     342              : }
     343              : 
     344              : impl Storage for PhysicalStorage {
     345              :     // Last written LSN.
     346            0 :     fn write_lsn(&self) -> Lsn {
     347            0 :         self.write_lsn
     348            0 :     }
     349              :     /// flush_lsn returns LSN of last durably stored WAL record.
     350            0 :     fn flush_lsn(&self) -> Lsn {
     351            0 :         self.flush_record_lsn
     352            0 :     }
     353              : 
     354            0 :     async fn initialize_first_segment(&mut self, init_lsn: Lsn) -> Result<()> {
     355            0 :         let _timer = WAL_STORAGE_OPERATION_SECONDS
     356            0 :             .with_label_values(&["initialize_first_segment"])
     357            0 :             .start_timer();
     358            0 : 
     359            0 :         let segno = init_lsn.segment_number(self.wal_seg_size);
     360            0 :         let (mut file, _) = self.open_or_create(segno).await?;
     361            0 :         let major_pg_version = self.pg_version / 10000;
     362            0 :         let wal_seg =
     363            0 :             postgres_ffi::generate_wal_segment(segno, self.system_id, major_pg_version, init_lsn)?;
     364            0 :         file.seek(SeekFrom::Start(0)).await?;
     365            0 :         file.write_all(&wal_seg).await?;
     366            0 :         file.flush().await?;
     367            0 :         info!("initialized segno {} at lsn {}", segno, init_lsn);
     368              :         // note: file is *not* fsynced
     369            0 :         Ok(())
     370            0 :     }
     371              : 
     372              :     /// Write WAL to disk.
     373            0 :     async fn write_wal(&mut self, startpos: Lsn, buf: &[u8]) -> Result<()> {
     374            0 :         // Disallow any non-sequential writes, which can result in gaps or overwrites.
     375            0 :         // If we need to move the pointer, use truncate_wal() instead.
     376            0 :         if self.write_lsn > startpos {
     377            0 :             bail!(
     378            0 :                 "write_wal rewrites WAL written before, write_lsn={}, startpos={}",
     379            0 :                 self.write_lsn,
     380            0 :                 startpos
     381            0 :             );
     382            0 :         }
     383            0 :         if self.write_lsn < startpos && self.write_lsn != Lsn(0) {
     384            0 :             bail!(
     385            0 :                 "write_wal creates gap in written WAL, write_lsn={}, startpos={}",
     386            0 :                 self.write_lsn,
     387            0 :                 startpos
     388            0 :             );
     389            0 :         }
     390              : 
     391            0 :         let write_seconds = time_io_closure(self.write_exact(startpos, buf)).await?;
     392              :         // WAL is written, updating write metrics
     393            0 :         self.metrics.observe_write_seconds(write_seconds);
     394            0 :         self.metrics.observe_write_bytes(buf.len());
     395            0 : 
     396            0 :         // figure out last record's end lsn for reporting (if we got the
     397            0 :         // whole record)
     398            0 :         if self.decoder.available() != startpos {
     399            0 :             info!(
     400            0 :                 "restart decoder from {} to {}",
     401            0 :                 self.decoder.available(),
     402              :                 startpos,
     403              :             );
     404            0 :             let pg_version = self.decoder.pg_version;
     405            0 :             self.decoder = WalStreamDecoder::new(startpos, pg_version);
     406            0 :         }
     407            0 :         self.decoder.feed_bytes(buf);
     408              :         loop {
     409            0 :             match self.decoder.poll_decode()? {
     410            0 :                 None => break, // no full record yet
     411            0 :                 Some((lsn, _rec)) => {
     412            0 :                     self.write_record_lsn = lsn;
     413            0 :                 }
     414              :             }
     415              :         }
     416              : 
     417            0 :         Ok(())
     418            0 :     }
     419              : 
     420            0 :     async fn flush_wal(&mut self) -> Result<()> {
     421            0 :         if self.flush_record_lsn == self.write_record_lsn {
     422              :             // no need to do extra flush
     423            0 :             return Ok(());
     424            0 :         }
     425              : 
     426            0 :         if let Some(unflushed_file) = self.file.take() {
     427            0 :             self.fdatasync_file(&unflushed_file).await?;
     428            0 :             self.file = Some(unflushed_file);
     429              :         } else {
     430              :             // We have unflushed data (write_lsn != flush_lsn), but no file.
     431              :             // This should only happen if last file was fully written and flushed,
     432              :             // but haven't updated flush_lsn yet.
     433            0 :             if self.write_lsn.segment_offset(self.wal_seg_size) != 0 {
     434            0 :                 bail!(
     435            0 :                     "unexpected unflushed data with no open file, write_lsn={}, flush_lsn={}",
     436            0 :                     self.write_lsn,
     437            0 :                     self.flush_record_lsn
     438            0 :                 );
     439            0 :             }
     440              :         }
     441              : 
     442              :         // everything is flushed now, let's update flush_lsn
     443            0 :         self.flush_record_lsn = self.write_record_lsn;
     444            0 :         Ok(())
     445            0 :     }
     446              : 
     447              :     /// Truncate written WAL by removing all WAL segments after the given LSN.
     448              :     /// end_pos must point to the end of the WAL record.
     449            0 :     async fn truncate_wal(&mut self, end_pos: Lsn) -> Result<()> {
     450            0 :         let _timer = WAL_STORAGE_OPERATION_SECONDS
     451            0 :             .with_label_values(&["truncate_wal"])
     452            0 :             .start_timer();
     453            0 : 
     454            0 :         // Streaming must not create a hole, so truncate cannot be called on
     455            0 :         // non-written lsn.
     456            0 :         if self.write_record_lsn != Lsn(0) && end_pos > self.write_record_lsn {
     457            0 :             bail!(
     458            0 :                 "truncate_wal called on non-written WAL, write_record_lsn={}, end_pos={}",
     459            0 :                 self.write_record_lsn,
     460            0 :                 end_pos
     461            0 :             );
     462            0 :         }
     463            0 : 
     464            0 :         // Quick exit if nothing to do to avoid writing up to 16 MiB of zeros on
     465            0 :         // disk (this happens on each connect).
     466            0 :         if self.is_truncated_after_restart
     467            0 :             && end_pos == self.write_lsn
     468            0 :             && end_pos == self.flush_record_lsn
     469              :         {
     470            0 :             return Ok(());
     471            0 :         }
     472              : 
     473              :         // Close previously opened file, if any
     474            0 :         if let Some(unflushed_file) = self.file.take() {
     475            0 :             self.fdatasync_file(&unflushed_file).await?;
     476            0 :         }
     477              : 
     478            0 :         let xlogoff = end_pos.segment_offset(self.wal_seg_size);
     479            0 :         let segno = end_pos.segment_number(self.wal_seg_size);
     480            0 : 
     481            0 :         // Remove all segments after the given LSN.
     482            0 :         remove_segments_from_disk(&self.timeline_dir, self.wal_seg_size, |x| x > segno).await?;
     483              : 
     484            0 :         let (mut file, is_partial) = self.open_or_create(segno).await?;
     485              : 
     486              :         // Fill end with zeroes
     487            0 :         file.seek(SeekFrom::Start(xlogoff as u64)).await?;
     488            0 :         write_zeroes(&mut file, self.wal_seg_size - xlogoff).await?;
     489            0 :         self.fdatasync_file(&file).await?;
     490              : 
     491            0 :         if !is_partial {
     492              :             // Make segment partial once again
     493            0 :             let (wal_file_path, wal_file_partial_path) =
     494            0 :                 wal_file_paths(&self.timeline_dir, segno, self.wal_seg_size);
     495            0 :             fs::rename(wal_file_path, wal_file_partial_path).await?;
     496            0 :         }
     497              : 
     498              :         // Update LSNs
     499            0 :         self.write_lsn = end_pos;
     500            0 :         self.write_record_lsn = end_pos;
     501            0 :         self.flush_record_lsn = end_pos;
     502            0 :         self.is_truncated_after_restart = true;
     503            0 :         Ok(())
     504            0 :     }
     505              : 
     506            0 :     fn remove_up_to(&self, segno_up_to: XLogSegNo) -> BoxFuture<'static, anyhow::Result<()>> {
     507            0 :         let timeline_dir = self.timeline_dir.clone();
     508            0 :         let wal_seg_size = self.wal_seg_size;
     509            0 :         Box::pin(async move {
     510            0 :             remove_segments_from_disk(&timeline_dir, wal_seg_size, |x| x <= segno_up_to).await
     511            0 :         })
     512            0 :     }
     513              : 
     514            0 :     fn close(&mut self) {
     515            0 :         // close happens in destructor
     516            0 :         let _open_file = self.file.take();
     517            0 :     }
     518              : 
     519            0 :     fn get_metrics(&self) -> WalStorageMetrics {
     520            0 :         self.metrics.clone()
     521            0 :     }
     522              : }
     523              : 
     524              : /// Remove all WAL segments in timeline_dir that match the given predicate.
     525            0 : async fn remove_segments_from_disk(
     526            0 :     timeline_dir: &Utf8Path,
     527            0 :     wal_seg_size: usize,
     528            0 :     remove_predicate: impl Fn(XLogSegNo) -> bool,
     529            0 : ) -> Result<()> {
     530            0 :     let _timer = WAL_STORAGE_OPERATION_SECONDS
     531            0 :         .with_label_values(&["remove_segments_from_disk"])
     532            0 :         .start_timer();
     533            0 : 
     534            0 :     let mut n_removed = 0;
     535            0 :     let mut min_removed = u64::MAX;
     536            0 :     let mut max_removed = u64::MIN;
     537              : 
     538            0 :     let mut entries = fs::read_dir(timeline_dir).await?;
     539            0 :     while let Some(entry) = entries.next_entry().await? {
     540            0 :         let entry_path = entry.path();
     541            0 :         let fname = entry_path.file_name().unwrap();
     542            0 :         /* Ignore files that are not XLOG segments */
     543            0 :         if !IsXLogFileName(fname) && !IsPartialXLogFileName(fname) {
     544            0 :             continue;
     545            0 :         }
     546            0 :         let (segno, _) = XLogFromFileName(fname, wal_seg_size)?;
     547            0 :         if remove_predicate(segno) {
     548            0 :             remove_file(entry_path).await?;
     549            0 :             n_removed += 1;
     550            0 :             min_removed = min(min_removed, segno);
     551            0 :             max_removed = max(max_removed, segno);
     552            0 :             REMOVED_WAL_SEGMENTS.inc();
     553            0 :         }
     554              :     }
     555              : 
     556            0 :     if n_removed > 0 {
     557            0 :         info!(
     558            0 :             "removed {} WAL segments [{}; {}]",
     559              :             n_removed, min_removed, max_removed
     560              :         );
     561            0 :     }
     562            0 :     Ok(())
     563            0 : }
     564              : 
     565              : pub struct WalReader {
     566              :     remote_path: RemotePath,
     567              :     timeline_dir: Utf8PathBuf,
     568              :     wal_seg_size: usize,
     569              :     pos: Lsn,
     570              :     wal_segment: Option<Pin<Box<dyn AsyncRead + Send + Sync>>>,
     571              : 
     572              :     // S3 will be used to read WAL if LSN is not available locally
     573              :     enable_remote_read: bool,
     574              : 
     575              :     // We don't have WAL locally if LSN is less than local_start_lsn
     576              :     local_start_lsn: Lsn,
     577              :     // We will respond with zero-ed bytes before this Lsn as long as
     578              :     // pos is in the same segment as timeline_start_lsn.
     579              :     timeline_start_lsn: Lsn,
     580              :     // integer version number of PostgreSQL, e.g. 14; 15; 16
     581              :     pg_version: u32,
     582              :     system_id: SystemId,
     583              :     timeline_start_segment: Option<Bytes>,
     584              : }
     585              : 
     586              : impl WalReader {
     587            0 :     pub fn new(
     588            0 :         ttid: &TenantTimelineId,
     589            0 :         timeline_dir: Utf8PathBuf,
     590            0 :         state: &TimelinePersistentState,
     591            0 :         start_pos: Lsn,
     592            0 :         enable_remote_read: bool,
     593            0 :     ) -> Result<Self> {
     594            0 :         if state.server.wal_seg_size == 0 || state.local_start_lsn == Lsn(0) {
     595            0 :             bail!("state uninitialized, no data to read");
     596            0 :         }
     597            0 : 
     598            0 :         // TODO: Upgrade to bail!() once we know this couldn't possibly happen
     599            0 :         if state.timeline_start_lsn == Lsn(0) {
     600            0 :             warn!("timeline_start_lsn uninitialized before initializing wal reader");
     601            0 :         }
     602              : 
     603            0 :         if start_pos
     604            0 :             < state
     605            0 :                 .timeline_start_lsn
     606            0 :                 .segment_lsn(state.server.wal_seg_size as usize)
     607              :         {
     608            0 :             bail!(
     609            0 :                 "Requested streaming from {}, which is before the start of the timeline {}, and also doesn't start at the first segment of that timeline",
     610            0 :                 start_pos,
     611            0 :                 state.timeline_start_lsn
     612            0 :             );
     613            0 :         }
     614            0 : 
     615            0 :         Ok(Self {
     616            0 :             remote_path: remote_timeline_path(ttid)?,
     617            0 :             timeline_dir,
     618            0 :             wal_seg_size: state.server.wal_seg_size as usize,
     619            0 :             pos: start_pos,
     620            0 :             wal_segment: None,
     621            0 :             enable_remote_read,
     622            0 :             local_start_lsn: state.local_start_lsn,
     623            0 :             timeline_start_lsn: state.timeline_start_lsn,
     624            0 :             pg_version: state.server.pg_version / 10000,
     625            0 :             system_id: state.server.system_id,
     626            0 :             timeline_start_segment: None,
     627              :         })
     628            0 :     }
     629              : 
     630              :     /// Read WAL at current position into provided buf, returns number of bytes
     631              :     /// read. It can be smaller than buf size only if segment boundary is
     632              :     /// reached.
     633            0 :     pub async fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
     634            0 :         // If this timeline is new, we may not have a full segment yet, so
     635            0 :         // we pad the first bytes of the timeline's first WAL segment with 0s
     636            0 :         if self.pos < self.timeline_start_lsn {
     637            0 :             debug_assert_eq!(
     638            0 :                 self.pos.segment_number(self.wal_seg_size),
     639            0 :                 self.timeline_start_lsn.segment_number(self.wal_seg_size)
     640              :             );
     641              : 
     642              :             // All bytes after timeline_start_lsn are in WAL, but those before
     643              :             // are not, so we manually construct an empty segment for the bytes
     644              :             // not available in this timeline.
     645            0 :             if self.timeline_start_segment.is_none() {
     646            0 :                 let it = postgres_ffi::generate_wal_segment(
     647            0 :                     self.timeline_start_lsn.segment_number(self.wal_seg_size),
     648            0 :                     self.system_id,
     649            0 :                     self.pg_version,
     650            0 :                     self.timeline_start_lsn,
     651            0 :                 )?;
     652            0 :                 self.timeline_start_segment = Some(it);
     653            0 :             }
     654              : 
     655            0 :             assert!(self.timeline_start_segment.is_some());
     656            0 :             let segment = self.timeline_start_segment.take().unwrap();
     657            0 : 
     658            0 :             let seg_bytes = &segment[..];
     659            0 : 
     660            0 :             // How much of the current segment have we already consumed?
     661            0 :             let pos_seg_offset = self.pos.segment_offset(self.wal_seg_size);
     662            0 : 
     663            0 :             // How many bytes may we consume in total?
     664            0 :             let tl_start_seg_offset = self.timeline_start_lsn.segment_offset(self.wal_seg_size);
     665            0 : 
     666            0 :             debug_assert!(seg_bytes.len() > pos_seg_offset);
     667            0 :             debug_assert!(seg_bytes.len() > tl_start_seg_offset);
     668              : 
     669              :             // Copy as many bytes as possible into the buffer
     670            0 :             let len = (tl_start_seg_offset - pos_seg_offset).min(buf.len());
     671            0 :             buf[0..len].copy_from_slice(&seg_bytes[pos_seg_offset..pos_seg_offset + len]);
     672            0 : 
     673            0 :             self.pos += len as u64;
     674            0 : 
     675            0 :             // If we're done with the segment, we can release it's memory.
     676            0 :             // However, if we're not yet done, store it so that we don't have to
     677            0 :             // construct the segment the next time this function is called.
     678            0 :             if self.pos < self.timeline_start_lsn {
     679            0 :                 self.timeline_start_segment = Some(segment);
     680            0 :             }
     681              : 
     682            0 :             return Ok(len);
     683            0 :         }
     684              : 
     685            0 :         let mut wal_segment = match self.wal_segment.take() {
     686            0 :             Some(reader) => reader,
     687            0 :             None => self.open_segment().await?,
     688              :         };
     689              : 
     690              :         // How much to read and send in message? We cannot cross the WAL file
     691              :         // boundary, and we don't want send more than provided buffer.
     692            0 :         let xlogoff = self.pos.segment_offset(self.wal_seg_size);
     693            0 :         let send_size = min(buf.len(), self.wal_seg_size - xlogoff);
     694            0 : 
     695            0 :         // Read some data from the file.
     696            0 :         let buf = &mut buf[0..send_size];
     697            0 :         let send_size = wal_segment.read_exact(buf).await?;
     698            0 :         self.pos += send_size as u64;
     699            0 : 
     700            0 :         // Decide whether to reuse this file. If we don't set wal_segment here
     701            0 :         // a new reader will be opened next time.
     702            0 :         if self.pos.segment_offset(self.wal_seg_size) != 0 {
     703            0 :             self.wal_segment = Some(wal_segment);
     704            0 :         }
     705              : 
     706            0 :         Ok(send_size)
     707            0 :     }
     708              : 
     709              :     /// Open WAL segment at the current position of the reader.
     710            0 :     async fn open_segment(&self) -> Result<Pin<Box<dyn AsyncRead + Send + Sync>>> {
     711            0 :         let xlogoff = self.pos.segment_offset(self.wal_seg_size);
     712            0 :         let segno = self.pos.segment_number(self.wal_seg_size);
     713            0 :         let wal_file_name = XLogFileName(PG_TLI, segno, self.wal_seg_size);
     714            0 : 
     715            0 :         // Try to open local file, if we may have WAL locally
     716            0 :         if self.pos >= self.local_start_lsn {
     717            0 :             let res = open_wal_file(&self.timeline_dir, segno, self.wal_seg_size).await;
     718            0 :             match res {
     719            0 :                 Ok((mut file, _)) => {
     720            0 :                     file.seek(SeekFrom::Start(xlogoff as u64)).await?;
     721            0 :                     return Ok(Box::pin(file));
     722              :                 }
     723            0 :                 Err(e) => {
     724            0 :                     let is_not_found = e.chain().any(|e| {
     725            0 :                         if let Some(e) = e.downcast_ref::<io::Error>() {
     726            0 :                             e.kind() == io::ErrorKind::NotFound
     727              :                         } else {
     728            0 :                             false
     729              :                         }
     730            0 :                     });
     731            0 :                     if !is_not_found {
     732            0 :                         return Err(e);
     733            0 :                     }
     734              :                     // NotFound is expected, fall through to remote read
     735              :                 }
     736              :             };
     737            0 :         }
     738              : 
     739              :         // Try to open remote file, if remote reads are enabled
     740            0 :         if self.enable_remote_read {
     741            0 :             let remote_wal_file_path = self.remote_path.join(&wal_file_name);
     742            0 :             return read_object(&remote_wal_file_path, xlogoff as u64).await;
     743            0 :         }
     744            0 : 
     745            0 :         bail!("WAL segment is not found")
     746            0 :     }
     747              : }
     748              : 
     749              : /// Zero block for filling created WAL segments.
     750              : const ZERO_BLOCK: &[u8] = &[0u8; XLOG_BLCKSZ];
     751              : 
     752              : /// Helper for filling file with zeroes.
     753            0 : async fn write_zeroes(file: &mut File, mut count: usize) -> Result<()> {
     754            0 :     fail::fail_point!("sk-write-zeroes", |_| {
     755            0 :         info!("write_zeroes hit failpoint");
     756            0 :         Err(anyhow::anyhow!("failpoint: sk-write-zeroes"))
     757            0 :     });
     758              : 
     759            0 :     while count >= XLOG_BLCKSZ {
     760            0 :         file.write_all(ZERO_BLOCK).await?;
     761            0 :         count -= XLOG_BLCKSZ;
     762              :     }
     763            0 :     file.write_all(&ZERO_BLOCK[0..count]).await?;
     764            0 :     file.flush().await?;
     765            0 :     Ok(())
     766            0 : }
     767              : 
     768              : /// Helper function for opening WAL segment `segno` in `dir`. Returns file and
     769              : /// whether it is .partial.
     770            0 : pub(crate) async fn open_wal_file(
     771            0 :     timeline_dir: &Utf8Path,
     772            0 :     segno: XLogSegNo,
     773            0 :     wal_seg_size: usize,
     774            0 : ) -> Result<(tokio::fs::File, bool)> {
     775            0 :     let (wal_file_path, wal_file_partial_path) = wal_file_paths(timeline_dir, segno, wal_seg_size);
     776            0 : 
     777            0 :     // First try to open the .partial file.
     778            0 :     let mut partial_path = wal_file_path.to_owned();
     779            0 :     partial_path.set_extension("partial");
     780            0 :     if let Ok(opened_file) = tokio::fs::File::open(&wal_file_partial_path).await {
     781            0 :         return Ok((opened_file, true));
     782            0 :     }
     783              : 
     784              :     // If that failed, try it without the .partial extension.
     785            0 :     let pf = tokio::fs::File::open(&wal_file_path)
     786            0 :         .await
     787            0 :         .with_context(|| format!("failed to open WAL file {:#}", wal_file_path))
     788            0 :         .map_err(|e| {
     789            0 :             warn!("{}", e);
     790            0 :             e
     791            0 :         })?;
     792              : 
     793            0 :     Ok((pf, false))
     794            0 : }
     795              : 
     796              : /// Helper returning full path to WAL segment file and its .partial brother.
     797            0 : pub fn wal_file_paths(
     798            0 :     timeline_dir: &Utf8Path,
     799            0 :     segno: XLogSegNo,
     800            0 :     wal_seg_size: usize,
     801            0 : ) -> (Utf8PathBuf, Utf8PathBuf) {
     802            0 :     let wal_file_name = XLogFileName(PG_TLI, segno, wal_seg_size);
     803            0 :     let wal_file_path = timeline_dir.join(wal_file_name.clone());
     804            0 :     let wal_file_partial_path = timeline_dir.join(wal_file_name + ".partial");
     805            0 :     (wal_file_path, wal_file_partial_path)
     806            0 : }
        

Generated by: LCOV version 2.1-beta