LCOV - code coverage report
Current view: top level - safekeeper/tests/walproposer_sim - safekeeper_disk.rs (source / functions) Coverage Total Hit
Test: fabb29a6339542ee130cd1d32b534fafdc0be240.info Lines: 86.7 % 165 143
Test Date: 2024-06-25 13:20:00 Functions: 70.7 % 75 53

            Line data    Source code
       1              : use std::collections::HashMap;
       2              : use std::sync::Arc;
       3              : 
       4              : use parking_lot::Mutex;
       5              : use safekeeper::state::TimelinePersistentState;
       6              : use utils::id::TenantTimelineId;
       7              : 
       8              : use super::block_storage::BlockStorage;
       9              : 
      10              : use std::{ops::Deref, time::Instant};
      11              : 
      12              : use anyhow::Result;
      13              : use bytes::{Buf, BytesMut};
      14              : use futures::future::BoxFuture;
      15              : use postgres_ffi::{waldecoder::WalStreamDecoder, XLogSegNo};
      16              : use safekeeper::{control_file, metrics::WalStorageMetrics, wal_storage};
      17              : use tracing::{debug, info};
      18              : use utils::lsn::Lsn;
      19              : 
      20              : /// All safekeeper state that is usually saved to disk.
      21              : pub struct SafekeeperDisk {
      22              :     pub timelines: Mutex<HashMap<TenantTimelineId, Arc<TimelineDisk>>>,
      23              : }
      24              : 
      25              : impl Default for SafekeeperDisk {
      26            0 :     fn default() -> Self {
      27            0 :         Self::new()
      28            0 :     }
      29              : }
      30              : 
      31              : impl SafekeeperDisk {
      32        12048 :     pub fn new() -> Self {
      33        12048 :         SafekeeperDisk {
      34        12048 :             timelines: Mutex::new(HashMap::new()),
      35        12048 :         }
      36        12048 :     }
      37              : 
      38        11425 :     pub fn put_state(
      39        11425 :         &self,
      40        11425 :         ttid: &TenantTimelineId,
      41        11425 :         state: TimelinePersistentState,
      42        11425 :     ) -> Arc<TimelineDisk> {
      43        11425 :         self.timelines
      44        11425 :             .lock()
      45        11425 :             .entry(*ttid)
      46        11425 :             .and_modify(|e| {
      47            0 :                 let mut mu = e.state.lock();
      48            0 :                 *mu = state.clone();
      49        11425 :             })
      50        11425 :             .or_insert_with(|| {
      51        11425 :                 Arc::new(TimelineDisk {
      52        11425 :                     state: Mutex::new(state),
      53        11425 :                     wal: Mutex::new(BlockStorage::new()),
      54        11425 :                 })
      55        11425 :             })
      56        11425 :             .clone()
      57        11425 :     }
      58              : }
      59              : 
      60              : /// Control file state and WAL storage.
      61              : pub struct TimelineDisk {
      62              :     pub state: Mutex<TimelinePersistentState>,
      63              :     pub wal: Mutex<BlockStorage>,
      64              : }
      65              : 
      66              : /// Implementation of `control_file::Storage` trait.
      67              : pub struct DiskStateStorage {
      68              :     persisted_state: TimelinePersistentState,
      69              :     disk: Arc<TimelineDisk>,
      70              :     last_persist_at: Instant,
      71              : }
      72              : 
      73              : impl DiskStateStorage {
      74        69844 :     pub fn new(disk: Arc<TimelineDisk>) -> Self {
      75        69844 :         let guard = disk.state.lock();
      76        69844 :         let state = guard.clone();
      77        69844 :         drop(guard);
      78        69844 :         DiskStateStorage {
      79        69844 :             persisted_state: state,
      80        69844 :             disk,
      81        69844 :             last_persist_at: Instant::now(),
      82        69844 :         }
      83        69844 :     }
      84              : }
      85              : 
      86              : #[async_trait::async_trait]
      87              : impl control_file::Storage for DiskStateStorage {
      88              :     /// Persist safekeeper state on disk and update internal state.
      89        27047 :     async fn persist(&mut self, s: &TimelinePersistentState) -> Result<()> {
      90        27047 :         self.persisted_state = s.clone();
      91        27047 :         *self.disk.state.lock() = s.clone();
      92        27047 :         Ok(())
      93        27047 :     }
      94              : 
      95              :     /// Timestamp of last persist.
      96            0 :     fn last_persist_at(&self) -> Instant {
      97            0 :         // TODO: don't rely on it in tests
      98            0 :         self.last_persist_at
      99            0 :     }
     100              : }
     101              : 
     102              : impl Deref for DiskStateStorage {
     103              :     type Target = TimelinePersistentState;
     104              : 
     105      1882811 :     fn deref(&self) -> &Self::Target {
     106      1882811 :         &self.persisted_state
     107      1882811 :     }
     108              : }
     109              : 
     110              : /// Implementation of `wal_storage::Storage` trait.
     111              : pub struct DiskWALStorage {
     112              :     /// Written to disk, but possibly still in the cache and not fully persisted.
     113              :     /// Also can be ahead of record_lsn, if happen to be in the middle of a WAL record.
     114              :     write_lsn: Lsn,
     115              : 
     116              :     /// The LSN of the last WAL record written to disk. Still can be not fully flushed.
     117              :     write_record_lsn: Lsn,
     118              : 
     119              :     /// The LSN of the last WAL record flushed to disk.
     120              :     flush_record_lsn: Lsn,
     121              : 
     122              :     /// Decoder is required for detecting boundaries of WAL records.
     123              :     decoder: WalStreamDecoder,
     124              : 
     125              :     /// Bytes of WAL records that are not yet written to disk.
     126              :     unflushed_bytes: BytesMut,
     127              : 
     128              :     /// Contains BlockStorage for WAL.
     129              :     disk: Arc<TimelineDisk>,
     130              : }
     131              : 
     132              : impl DiskWALStorage {
     133        69844 :     pub fn new(disk: Arc<TimelineDisk>, state: &TimelinePersistentState) -> Result<Self> {
     134        69844 :         let write_lsn = if state.commit_lsn == Lsn(0) {
     135        65490 :             Lsn(0)
     136              :         } else {
     137         4354 :             Self::find_end_of_wal(disk.clone(), state.commit_lsn)?
     138              :         };
     139              : 
     140        69844 :         let flush_lsn = write_lsn;
     141        69844 :         Ok(DiskWALStorage {
     142        69844 :             write_lsn,
     143        69844 :             write_record_lsn: flush_lsn,
     144        69844 :             flush_record_lsn: flush_lsn,
     145        69844 :             decoder: WalStreamDecoder::new(flush_lsn, 16),
     146        69844 :             unflushed_bytes: BytesMut::new(),
     147        69844 :             disk,
     148        69844 :         })
     149        69844 :     }
     150              : 
     151         4354 :     fn find_end_of_wal(disk: Arc<TimelineDisk>, start_lsn: Lsn) -> Result<Lsn> {
     152         4354 :         let mut buf = [0; 8192];
     153         4354 :         let mut pos = start_lsn.0;
     154         4354 :         let mut decoder = WalStreamDecoder::new(start_lsn, 16);
     155         4354 :         let mut result = start_lsn;
     156         4354 :         loop {
     157         4354 :             disk.wal.lock().read(pos, &mut buf);
     158         4354 :             pos += buf.len() as u64;
     159         4354 :             decoder.feed_bytes(&buf);
     160              : 
     161              :             loop {
     162        22955 :                 match decoder.poll_decode() {
     163        18601 :                     Ok(Some(record)) => result = record.0,
     164         4354 :                     Err(e) => {
     165         4354 :                         debug!(
     166            0 :                             "find_end_of_wal reached end at {:?}, decode error: {:?}",
     167              :                             result, e
     168              :                         );
     169         4354 :                         return Ok(result);
     170              :                     }
     171            0 :                     Ok(None) => break, // need more data
     172              :                 }
     173              :             }
     174              :         }
     175         4354 :     }
     176              : }
     177              : 
     178              : #[async_trait::async_trait]
     179              : impl wal_storage::Storage for DiskWALStorage {
     180              :     /// LSN of last durably stored WAL record.
     181       136655 :     fn flush_lsn(&self) -> Lsn {
     182       136655 :         self.flush_record_lsn
     183       136655 :     }
     184              : 
     185         1044 :     async fn initialize_first_segment(&mut self, _init_lsn: Lsn) -> Result<()> {
     186         1044 :         Ok(())
     187         1044 :     }
     188              : 
     189              :     /// Write piece of WAL from buf to disk, but not necessarily sync it.
     190         3491 :     async fn write_wal(&mut self, startpos: Lsn, buf: &[u8]) -> Result<()> {
     191         3491 :         if self.write_lsn != startpos {
     192         3491 :             panic!("write_wal called with wrong startpos");
     193         3491 :         }
     194         3491 : 
     195         3491 :         self.unflushed_bytes.extend_from_slice(buf);
     196         3491 :         self.write_lsn += buf.len() as u64;
     197         3491 : 
     198         3491 :         if self.decoder.available() != startpos {
     199         3491 :             info!(
     200         3491 :                 "restart decoder from {} to {}",
     201            0 :                 self.decoder.available(),
     202         3491 :                 startpos,
     203         3491 :             );
     204         3491 :             self.decoder = WalStreamDecoder::new(startpos, 16);
     205         3491 :         }
     206         3491 :         self.decoder.feed_bytes(buf);
     207         3491 :         loop {
     208        59886 :             match self.decoder.poll_decode()? {
     209         3491 :                 None => break, // no full record yet
     210        56395 :                 Some((lsn, _rec)) => {
     211        56395 :                     self.write_record_lsn = lsn;
     212        56395 :                 }
     213         3491 :             }
     214         3491 :         }
     215         3491 : 
     216         3491 :         Ok(())
     217         3491 :     }
     218              : 
     219              :     /// Truncate WAL at specified LSN, which must be the end of WAL record.
     220         5262 :     async fn truncate_wal(&mut self, end_pos: Lsn) -> Result<()> {
     221         5262 :         if self.write_lsn != Lsn(0) && end_pos > self.write_lsn {
     222         5262 :             panic!(
     223            0 :                 "truncate_wal called on non-written WAL, write_lsn={}, end_pos={}",
     224            0 :                 self.write_lsn, end_pos
     225            0 :             );
     226         5262 :         }
     227         5262 : 
     228         5262 :         self.flush_wal().await?;
     229         5262 : 
     230         5262 :         // write zeroes to disk from end_pos until self.write_lsn
     231         5262 :         let buf = [0; 8192];
     232         5262 :         let mut pos = end_pos.0;
     233         5292 :         while pos < self.write_lsn.0 {
     234           30 :             self.disk.wal.lock().write(pos, &buf);
     235           30 :             pos += buf.len() as u64;
     236           30 :         }
     237         5262 : 
     238         5262 :         self.write_lsn = end_pos;
     239         5262 :         self.write_record_lsn = end_pos;
     240         5262 :         self.flush_record_lsn = end_pos;
     241         5262 :         self.unflushed_bytes.clear();
     242         5262 :         self.decoder = WalStreamDecoder::new(end_pos, 16);
     243         5262 : 
     244         5262 :         Ok(())
     245         5262 :     }
     246              : 
     247              :     /// Durably store WAL on disk, up to the last written WAL record.
     248        41860 :     async fn flush_wal(&mut self) -> Result<()> {
     249        41860 :         if self.flush_record_lsn == self.write_record_lsn {
     250        41860 :             // no need to do extra flush
     251        41860 :             return Ok(());
     252        41860 :         }
     253         3462 : 
     254         3462 :         let num_bytes = self.write_record_lsn.0 - self.flush_record_lsn.0;
     255         3462 : 
     256         3462 :         self.disk.wal.lock().write(
     257         3462 :             self.flush_record_lsn.0,
     258         3462 :             &self.unflushed_bytes[..num_bytes as usize],
     259         3462 :         );
     260         3462 :         self.unflushed_bytes.advance(num_bytes as usize);
     261         3462 :         self.flush_record_lsn = self.write_record_lsn;
     262         3462 : 
     263         3462 :         Ok(())
     264        41860 :     }
     265              : 
     266              :     /// Remove all segments <= given segno. Returns function doing that as we
     267              :     /// want to perform it without timeline lock.
     268            0 :     fn remove_up_to(&self, _segno_up_to: XLogSegNo) -> BoxFuture<'static, anyhow::Result<()>> {
     269            0 :         Box::pin(async move { Ok(()) })
     270            0 :     }
     271              : 
     272              :     /// Release resources associated with the storage -- technically, close FDs.
     273              :     /// Currently we don't remove timelines until restart (#3146), so need to
     274              :     /// spare descriptors. This would be useful for temporary tli detach as
     275              :     /// well.
     276            0 :     fn close(&mut self) {}
     277              : 
     278              :     /// Get metrics for this timeline.
     279            0 :     fn get_metrics(&self) -> WalStorageMetrics {
     280            0 :         WalStorageMetrics::default()
     281            0 :     }
     282              : }
        

Generated by: LCOV version 2.1-beta