LCOV - code coverage report
Current view: top level - safekeeper/src - control_file.rs (source / functions) Coverage Total Hit
Test: b4ae4c4857f9ef3e144e982a35ee23bc84c71983.info Lines: 83.5 % 212 177
Test Date: 2024-10-22 22:13:45 Functions: 70.8 % 24 17

            Line data    Source code
       1              : //! Control file serialization, deserialization and persistence.
       2              : 
       3              : use anyhow::{bail, ensure, Context, Result};
       4              : use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
       5              : use camino::{Utf8Path, Utf8PathBuf};
       6              : use tokio::fs::File;
       7              : use tokio::io::AsyncWriteExt;
       8              : use utils::crashsafe::durable_rename;
       9              : 
      10              : use std::future::Future;
      11              : use std::io::Read;
      12              : use std::ops::Deref;
      13              : use std::path::Path;
      14              : use std::time::Instant;
      15              : 
      16              : use crate::control_file_upgrade::downgrade_v9_to_v8;
      17              : use crate::metrics::PERSIST_CONTROL_FILE_SECONDS;
      18              : use crate::state::{EvictionState, TimelinePersistentState};
      19              : use crate::{control_file_upgrade::upgrade_control_file, timeline::get_timeline_dir};
      20              : use utils::{bin_ser::LeSer, id::TenantTimelineId};
      21              : 
      22              : use crate::SafeKeeperConf;
      23              : 
      24              : pub const SK_MAGIC: u32 = 0xcafeceefu32;
      25              : pub const SK_FORMAT_VERSION: u32 = 9;
      26              : 
      27              : // contains persistent metadata for safekeeper
      28              : pub const CONTROL_FILE_NAME: &str = "safekeeper.control";
      29              : // needed to atomically update the state using `rename`
      30              : const CONTROL_FILE_NAME_PARTIAL: &str = "safekeeper.control.partial";
      31              : pub const CHECKSUM_SIZE: usize = size_of::<u32>();
      32              : 
      33              : /// Storage should keep actual state inside of it. It should implement Deref
      34              : /// trait to access state fields and have persist method for updating that state.
      35              : pub trait Storage: Deref<Target = TimelinePersistentState> {
      36              :     /// Persist safekeeper state on disk and update internal state.
      37              :     fn persist(&mut self, s: &TimelinePersistentState) -> impl Future<Output = Result<()>> + Send;
      38              : 
      39              :     /// Timestamp of last persist.
      40              :     fn last_persist_at(&self) -> Instant;
      41              : }
      42              : 
      43              : #[derive(Debug)]
      44              : pub struct FileStorage {
      45              :     // save timeline dir to avoid reconstructing it every time
      46              :     timeline_dir: Utf8PathBuf,
      47              :     no_sync: bool,
      48              : 
      49              :     /// Last state persisted to disk.
      50              :     state: TimelinePersistentState,
      51              :     /// Not preserved across restarts.
      52              :     last_persist_at: Instant,
      53              : }
      54              : 
      55              : impl FileStorage {
      56              :     /// Initialize storage by loading state from disk.
      57            2 :     pub fn restore_new(ttid: &TenantTimelineId, conf: &SafeKeeperConf) -> Result<FileStorage> {
      58            2 :         let timeline_dir = get_timeline_dir(conf, ttid);
      59            2 :         let state = Self::load_control_file_from_dir(&timeline_dir)?;
      60              : 
      61            1 :         Ok(FileStorage {
      62            1 :             timeline_dir,
      63            1 :             no_sync: conf.no_sync,
      64            1 :             state,
      65            1 :             last_persist_at: Instant::now(),
      66            1 :         })
      67            2 :     }
      68              : 
      69              :     /// Create file storage for a new timeline, but don't persist it yet.
      70            2 :     pub fn create_new(
      71            2 :         timeline_dir: Utf8PathBuf,
      72            2 :         conf: &SafeKeeperConf,
      73            2 :         state: TimelinePersistentState,
      74            2 :     ) -> Result<FileStorage> {
      75            2 :         // we don't support creating new timelines in offloaded state
      76            2 :         assert!(matches!(state.eviction_state, EvictionState::Present));
      77              : 
      78            2 :         let store = FileStorage {
      79            2 :             timeline_dir,
      80            2 :             no_sync: conf.no_sync,
      81            2 :             state,
      82            2 :             last_persist_at: Instant::now(),
      83            2 :         };
      84            2 : 
      85            2 :         Ok(store)
      86            2 :     }
      87              : 
      88              :     /// Check the magic/version in the on-disk data and deserialize it, if possible.
      89            2 :     fn deser_sk_state(buf: &mut &[u8]) -> Result<TimelinePersistentState> {
      90              :         // Read the version independent part
      91            2 :         let magic = ReadBytesExt::read_u32::<LittleEndian>(buf)?;
      92            2 :         if magic != SK_MAGIC {
      93            0 :             bail!(
      94            0 :                 "bad control file magic: {:X}, expected {:X}",
      95            0 :                 magic,
      96            0 :                 SK_MAGIC
      97            0 :             );
      98            2 :         }
      99            2 :         let version = ReadBytesExt::read_u32::<LittleEndian>(buf)?;
     100            2 :         if version == SK_FORMAT_VERSION {
     101            0 :             let res = TimelinePersistentState::des(buf)?;
     102            0 :             return Ok(res);
     103            2 :         }
     104            2 :         // try to upgrade
     105            2 :         upgrade_control_file(buf, version)
     106            2 :     }
     107              : 
     108              :     /// Load control file from given directory.
     109            3 :     fn load_control_file_from_dir(timeline_dir: &Utf8Path) -> Result<TimelinePersistentState> {
     110            3 :         let path = timeline_dir.join(CONTROL_FILE_NAME);
     111            3 :         Self::load_control_file(path)
     112            3 :     }
     113              : 
     114              :     /// Read in the control file.
     115            3 :     pub fn load_control_file<P: AsRef<Path>>(
     116            3 :         control_file_path: P,
     117            3 :     ) -> Result<TimelinePersistentState> {
     118            3 :         let mut control_file = std::fs::OpenOptions::new()
     119            3 :             .read(true)
     120            3 :             .write(true)
     121            3 :             .open(&control_file_path)
     122            3 :             .with_context(|| {
     123            0 :                 format!(
     124            0 :                     "failed to open control file at {}",
     125            0 :                     control_file_path.as_ref().display(),
     126            0 :                 )
     127            3 :             })?;
     128              : 
     129            3 :         let mut buf = Vec::new();
     130            3 :         control_file
     131            3 :             .read_to_end(&mut buf)
     132            3 :             .context("failed to read control file")?;
     133              : 
     134            3 :         let calculated_checksum = crc32c::crc32c(&buf[..buf.len() - CHECKSUM_SIZE]);
     135              : 
     136            3 :         let expected_checksum_bytes: &[u8; CHECKSUM_SIZE] =
     137            3 :             buf[buf.len() - CHECKSUM_SIZE..].try_into()?;
     138            3 :         let expected_checksum = u32::from_le_bytes(*expected_checksum_bytes);
     139            3 : 
     140            3 :         ensure!(
     141            3 :             calculated_checksum == expected_checksum,
     142            1 :             format!(
     143            1 :                 "safekeeper control file checksum mismatch: expected {} got {}",
     144            1 :                 expected_checksum, calculated_checksum
     145            1 :             )
     146              :         );
     147              : 
     148            2 :         let state = FileStorage::deser_sk_state(&mut &buf[..buf.len() - CHECKSUM_SIZE])
     149            2 :             .with_context(|| {
     150            0 :                 format!(
     151            0 :                     "while reading control file {}",
     152            0 :                     control_file_path.as_ref().display(),
     153            0 :                 )
     154            2 :             })?;
     155            2 :         Ok(state)
     156            3 :     }
     157              : }
     158              : 
     159              : impl Deref for FileStorage {
     160              :     type Target = TimelinePersistentState;
     161              : 
     162            0 :     fn deref(&self) -> &Self::Target {
     163            0 :         &self.state
     164            0 :     }
     165              : }
     166              : 
     167              : impl TimelinePersistentState {
     168            2 :     pub(crate) fn write_to_buf(&self) -> Result<Vec<u8>> {
     169            2 :         let mut buf: Vec<u8> = Vec::new();
     170            2 :         WriteBytesExt::write_u32::<LittleEndian>(&mut buf, SK_MAGIC)?;
     171              : 
     172            2 :         if self.eviction_state == EvictionState::Present {
     173            2 :             // temp hack for forward compatibility
     174            2 :             const PREV_FORMAT_VERSION: u32 = 8;
     175            2 :             let prev = downgrade_v9_to_v8(self);
     176            2 :             WriteBytesExt::write_u32::<LittleEndian>(&mut buf, PREV_FORMAT_VERSION)?;
     177            2 :             prev.ser_into(&mut buf)?;
     178              :         } else {
     179              :             // otherwise, we write the current format version
     180            0 :             WriteBytesExt::write_u32::<LittleEndian>(&mut buf, SK_FORMAT_VERSION)?;
     181            0 :             self.ser_into(&mut buf)?;
     182              :         }
     183              : 
     184              :         // calculate checksum before resize
     185            2 :         let checksum = crc32c::crc32c(&buf);
     186            2 :         buf.extend_from_slice(&checksum.to_le_bytes());
     187            2 :         Ok(buf)
     188            2 :     }
     189              : }
     190              : 
     191              : impl Storage for FileStorage {
     192              :     /// Persists state durably to the underlying storage.
     193              :     ///
     194              :     /// For a description, see <https://lwn.net/Articles/457667/>.
     195            2 :     async fn persist(&mut self, s: &TimelinePersistentState) -> Result<()> {
     196            2 :         let _timer = PERSIST_CONTROL_FILE_SECONDS.start_timer();
     197            2 : 
     198            2 :         // write data to safekeeper.control.partial
     199            2 :         let control_partial_path = self.timeline_dir.join(CONTROL_FILE_NAME_PARTIAL);
     200            2 :         let mut control_partial = File::create(&control_partial_path).await.with_context(|| {
     201            0 :             format!(
     202            0 :                 "failed to create partial control file at: {}",
     203            0 :                 &control_partial_path
     204            0 :             )
     205            2 :         })?;
     206              : 
     207            2 :         let buf: Vec<u8> = s.write_to_buf()?;
     208              : 
     209            2 :         control_partial.write_all(&buf).await.with_context(|| {
     210            0 :             format!(
     211            0 :                 "failed to write safekeeper state into control file at: {}",
     212            0 :                 control_partial_path
     213            0 :             )
     214            2 :         })?;
     215            2 :         control_partial.flush().await.with_context(|| {
     216            0 :             format!(
     217            0 :                 "failed to flush safekeeper state into control file at: {}",
     218            0 :                 control_partial_path
     219            0 :             )
     220            2 :         })?;
     221              : 
     222            2 :         let control_path = self.timeline_dir.join(CONTROL_FILE_NAME);
     223           14 :         durable_rename(&control_partial_path, &control_path, !self.no_sync).await?;
     224              : 
     225              :         // update internal state
     226            2 :         self.state = s.clone();
     227            2 :         Ok(())
     228            2 :     }
     229              : 
     230            0 :     fn last_persist_at(&self) -> Instant {
     231            0 :         self.last_persist_at
     232            0 :     }
     233              : }
     234              : 
     235              : #[cfg(test)]
     236              : mod test {
     237              :     use super::*;
     238              :     use tokio::fs;
     239              :     use utils::lsn::Lsn;
     240              : 
     241            2 :     fn stub_conf() -> SafeKeeperConf {
     242            2 :         let workdir = camino_tempfile::tempdir().unwrap().into_path();
     243            2 :         SafeKeeperConf {
     244            2 :             workdir,
     245            2 :             ..SafeKeeperConf::dummy()
     246            2 :         }
     247            2 :     }
     248              : 
     249            2 :     async fn load_from_control_file(
     250            2 :         conf: &SafeKeeperConf,
     251            2 :         ttid: &TenantTimelineId,
     252            2 :     ) -> Result<(FileStorage, TimelinePersistentState)> {
     253            2 :         let timeline_dir = get_timeline_dir(conf, ttid);
     254            2 :         fs::create_dir_all(&timeline_dir)
     255            2 :             .await
     256            2 :             .expect("failed to create timeline dir");
     257            2 :         Ok((
     258            2 :             FileStorage::restore_new(ttid, conf)?,
     259            1 :             FileStorage::load_control_file_from_dir(&timeline_dir)?,
     260              :         ))
     261            2 :     }
     262              : 
     263            2 :     async fn create(
     264            2 :         conf: &SafeKeeperConf,
     265            2 :         ttid: &TenantTimelineId,
     266            2 :     ) -> Result<(FileStorage, TimelinePersistentState)> {
     267            2 :         let timeline_dir = get_timeline_dir(conf, ttid);
     268            2 :         fs::create_dir_all(&timeline_dir)
     269            2 :             .await
     270            2 :             .expect("failed to create timeline dir");
     271            2 :         let state = TimelinePersistentState::empty();
     272            2 :         let storage = FileStorage::create_new(timeline_dir, conf, state.clone())?;
     273            2 :         Ok((storage, state))
     274            2 :     }
     275              : 
     276              :     #[tokio::test]
     277            1 :     async fn test_read_write_safekeeper_state() {
     278            1 :         let conf = stub_conf();
     279            1 :         let ttid = TenantTimelineId::generate();
     280            1 :         {
     281            1 :             let (mut storage, mut state) =
     282            1 :                 create(&conf, &ttid).await.expect("failed to create state");
     283            1 :             // change something
     284            1 :             state.commit_lsn = Lsn(42);
     285            1 :             storage
     286            1 :                 .persist(&state)
     287            9 :                 .await
     288            1 :                 .expect("failed to persist state");
     289            1 :         }
     290            1 : 
     291            1 :         let (_, state) = load_from_control_file(&conf, &ttid)
     292            1 :             .await
     293            1 :             .expect("failed to read state");
     294            1 :         assert_eq!(state.commit_lsn, Lsn(42));
     295            1 :     }
     296              : 
     297              :     #[tokio::test]
     298            1 :     async fn test_safekeeper_state_checksum_mismatch() {
     299            1 :         let conf = stub_conf();
     300            1 :         let ttid = TenantTimelineId::generate();
     301            1 :         {
     302            1 :             let (mut storage, mut state) =
     303            1 :                 create(&conf, &ttid).await.expect("failed to read state");
     304            1 : 
     305            1 :             // change something
     306            1 :             state.commit_lsn = Lsn(42);
     307            1 :             storage
     308            1 :                 .persist(&state)
     309            9 :                 .await
     310            1 :                 .expect("failed to persist state");
     311            1 :         }
     312            1 :         let control_path = get_timeline_dir(&conf, &ttid).join(CONTROL_FILE_NAME);
     313            1 :         let mut data = fs::read(&control_path).await.unwrap();
     314            1 :         data[0] += 1; // change the first byte of the file to fail checksum validation
     315            1 :         fs::write(&control_path, &data)
     316            1 :             .await
     317            1 :             .expect("failed to write control file");
     318            1 : 
     319            1 :         match load_from_control_file(&conf, &ttid).await {
     320            1 :             Err(err) => assert!(err
     321            1 :                 .to_string()
     322            1 :                 .contains("safekeeper control file checksum mismatch")),
     323            1 :             Ok(_) => panic!("expected error"),
     324            1 :         }
     325            1 :     }
     326              : }
        

Generated by: LCOV version 2.1-beta