LCOV - code coverage report
Current view: top level - libs/utils/src - crashsafe.rs (source / functions) Coverage Total Hit
Test: 62212f4d57a7ad0f69dc82a04629a0bbd5f7c824.info Lines: 88.2 % 187 165
Test Date: 2025-03-17 10:41:39 Functions: 54.8 % 42 23

            Line data    Source code
       1              : use std::borrow::Cow;
       2              : use std::fs::{self, File};
       3              : use std::io::{self, Write};
       4              : use std::os::fd::AsRawFd;
       5              : 
       6              : use camino::{Utf8Path, Utf8PathBuf};
       7              : 
       8              : /// Similar to [`std::fs::create_dir`], except we fsync the
       9              : /// created directory and its parent.
      10          895 : pub fn create_dir(path: impl AsRef<Utf8Path>) -> io::Result<()> {
      11          895 :     let path = path.as_ref();
      12          895 : 
      13          895 :     fs::create_dir(path)?;
      14          893 :     fsync_file_and_parent(path)?;
      15          893 :     Ok(())
      16            3 : }
      17              : 
      18              : /// Similar to [`std::fs::create_dir_all`], except we fsync all
      19              : /// newly created directories and the pre-existing parent.
      20            5 : pub fn create_dir_all(path: impl AsRef<Utf8Path>) -> io::Result<()> {
      21            5 :     let mut path = path.as_ref();
      22            5 : 
      23            5 :     let mut dirs_to_create = Vec::new();
      24              : 
      25              :     // Figure out which directories we need to create.
      26              :     loop {
      27            8 :         match path.metadata() {
      28            4 :             Ok(metadata) if metadata.is_dir() => break,
      29              :             Ok(_) => {
      30            1 :                 return Err(io::Error::new(
      31            1 :                     io::ErrorKind::AlreadyExists,
      32            1 :                     format!("non-directory found in path: {path}"),
      33            1 :                 ));
      34              :             }
      35            4 :             Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
      36            1 :             Err(e) => return Err(e),
      37              :         }
      38              : 
      39            3 :         dirs_to_create.push(path);
      40            3 : 
      41            3 :         match path.parent() {
      42            3 :             Some(parent) => path = parent,
      43              :             None => {
      44            0 :                 return Err(io::Error::new(
      45            0 :                     io::ErrorKind::InvalidInput,
      46            0 :                     format!("can't find parent of path '{path}'"),
      47            0 :                 ));
      48              :             }
      49              :         }
      50              :     }
      51              : 
      52              :     // Create directories from parent to child.
      53            3 :     for &path in dirs_to_create.iter().rev() {
      54            3 :         fs::create_dir(path)?;
      55              :     }
      56              : 
      57              :     // Fsync the created directories from child to parent.
      58            3 :     for &path in dirs_to_create.iter() {
      59            3 :         fsync(path)?;
      60              :     }
      61              : 
      62              :     // If we created any new directories, fsync the parent.
      63            3 :     if !dirs_to_create.is_empty() {
      64            2 :         fsync(path)?;
      65            1 :     }
      66              : 
      67            3 :     Ok(())
      68            5 : }
      69              : 
      70              : /// Adds a suffix to the file(directory) name, either appending the suffix to the end of its extension,
      71              : /// or if there's no extension, creates one and puts a suffix there.
      72         6379 : pub fn path_with_suffix_extension(
      73         6379 :     original_path: impl AsRef<Utf8Path>,
      74         6379 :     suffix: &str,
      75         6379 : ) -> Utf8PathBuf {
      76         6379 :     let new_extension = match original_path.as_ref().extension() {
      77         3066 :         Some(extension) => Cow::Owned(format!("{extension}.{suffix}")),
      78         3313 :         None => Cow::Borrowed(suffix),
      79              :     };
      80         6379 :     original_path.as_ref().with_extension(new_extension)
      81         6379 : }
      82              : 
      83          893 : pub fn fsync_file_and_parent(file_path: &Utf8Path) -> io::Result<()> {
      84          893 :     let parent = file_path
      85          893 :         .parent()
      86          893 :         .ok_or_else(|| io::Error::other(format!("File {file_path:?} has no parent")))?;
      87              : 
      88          893 :     fsync(file_path)?;
      89          893 :     fsync(parent)?;
      90          893 :     Ok(())
      91          893 : }
      92              : 
      93         1791 : pub fn fsync(path: &Utf8Path) -> io::Result<()> {
      94         1791 :     File::open(path)
      95         1791 :         .map_err(|e| io::Error::new(e.kind(), format!("Failed to open the file {path:?}: {e}")))
      96         1791 :         .and_then(|file| {
      97         1791 :             file.sync_all().map_err(|e| {
      98            0 :                 io::Error::new(
      99            0 :                     e.kind(),
     100            0 :                     format!("Failed to sync file {path:?} data and metadata: {e}"),
     101            0 :                 )
     102         1791 :             })
     103         1791 :         })
     104         1791 :         .map_err(|e| io::Error::new(e.kind(), format!("Failed to fsync file {path:?}: {e}")))
     105         1791 : }
     106              : 
     107           44 : pub async fn fsync_async(path: impl AsRef<Utf8Path>) -> Result<(), std::io::Error> {
     108           44 :     tokio::fs::File::open(path.as_ref()).await?.sync_all().await
     109            0 : }
     110              : 
     111           48 : pub async fn fsync_async_opt(
     112           48 :     path: impl AsRef<Utf8Path>,
     113           48 :     do_fsync: bool,
     114           48 : ) -> Result<(), std::io::Error> {
     115           48 :     if do_fsync {
     116           40 :         fsync_async(path.as_ref()).await?;
     117            0 :     }
     118           48 :     Ok(())
     119            0 : }
     120              : 
     121              : /// Like postgres' durable_rename, renames a file and issues fsyncs to make it durable. After
     122              : /// returning, both the file and rename are guaranteed to be persisted. Both paths must be on the
     123              : /// same file system.
     124              : ///
     125              : /// Unlike postgres, it only fsyncs 1) the file to make contents durable, and 2) the directory to
     126              : /// make the rename durable. This sequence ensures the target file will never be incomplete.
     127              : ///
     128              : /// Postgres also:
     129              : ///
     130              : /// * Fsyncs the target file, if it exists, before the rename, to ensure either the new or existing
     131              : ///   file survives a crash. Current callers don't need this as it should already be fsynced if
     132              : ///   durability is needed.
     133              : ///
     134              : /// * Fsyncs the file after the rename. This can be required with certain OSes or file systems (e.g.
     135              : ///   NFS), but not on Linux with most common file systems like ext4 (which we currently use).
     136              : ///
     137              : /// An audit of 8 other databases found that none fsynced the file after a rename:
     138              : /// <https://github.com/neondatabase/neon/pull/9686#discussion_r1837180535>
     139              : ///
     140              : /// eBPF probes confirmed that this is sufficient with ext4, XFS, and ZFS, but possibly not Btrfs:
     141              : /// <https://github.com/neondatabase/neon/pull/9686#discussion_r1837926218>
     142              : ///
     143              : /// virtual_file.rs has similar code, but it doesn't use vfs.
     144              : ///
     145              : /// Useful links: <https://lwn.net/Articles/457667/>
     146              : /// <https://www.postgresql.org/message-id/flat/56583BDD.9060302%402ndquadrant.com>
     147              : /// <https://thunk.org/tytso/blog/2009/03/15/dont-fear-the-fsync/>
     148           24 : pub async fn durable_rename(
     149           24 :     old_path: impl AsRef<Utf8Path>,
     150           24 :     new_path: impl AsRef<Utf8Path>,
     151           24 :     do_fsync: bool,
     152           24 : ) -> io::Result<()> {
     153           24 :     // first fsync the file
     154           24 :     fsync_async_opt(old_path.as_ref(), do_fsync).await?;
     155              : 
     156              :     // Time to do the real deal.
     157           24 :     tokio::fs::rename(old_path.as_ref(), new_path.as_ref()).await?;
     158              : 
     159              :     // Now fsync the parent
     160           24 :     let parent = match new_path.as_ref().parent() {
     161           24 :         Some(p) => p,
     162            0 :         None => Utf8Path::new("./"), // assume current dir if there is no parent
     163              :     };
     164           24 :     fsync_async_opt(parent, do_fsync).await?;
     165              : 
     166           24 :     Ok(())
     167            0 : }
     168              : 
     169              : /// Writes a file to the specified `final_path` in a crash safe fasion, using [`std::fs`].
     170              : ///
     171              : /// The file is first written to the specified `tmp_path`, and in a second
     172              : /// step, the `tmp_path` is renamed to the `final_path`. Intermediary fsync
     173              : /// and atomic rename guarantee that, if we crash at any point, there will never
     174              : /// be a partially written file at `final_path` (but maybe at `tmp_path`).
     175              : ///
     176              : /// Callers are responsible for serializing calls of this function for a given `final_path`.
     177              : /// If they don't, there may be an error due to conflicting `tmp_path`, or there will
     178              : /// be no error and the content of `final_path` will be the "winner" caller's `content`.
     179              : /// I.e., the atomticity guarantees still hold.
     180           56 : pub fn overwrite(
     181           56 :     final_path: &Utf8Path,
     182           56 :     tmp_path: &Utf8Path,
     183           56 :     content: &[u8],
     184           56 : ) -> std::io::Result<()> {
     185           56 :     let Some(final_path_parent) = final_path.parent() else {
     186            0 :         return Err(std::io::Error::from_raw_os_error(
     187            0 :             nix::errno::Errno::EINVAL as i32,
     188            0 :         ));
     189              :     };
     190           56 :     std::fs::remove_file(tmp_path).or_else(crate::fs_ext::ignore_not_found)?;
     191           56 :     let mut file = std::fs::OpenOptions::new()
     192           56 :         .write(true)
     193           56 :         // Use `create_new` so that, if we race with ourselves or something else,
     194           56 :         // we bail out instead of causing damage.
     195           56 :         .create_new(true)
     196           56 :         .open(tmp_path)?;
     197           56 :     file.write_all(content)?;
     198           56 :     file.sync_all()?;
     199           56 :     drop(file); // don't keep the fd open for longer than we have to
     200           56 : 
     201           56 :     std::fs::rename(tmp_path, final_path)?;
     202              : 
     203           56 :     let final_parent_dirfd = std::fs::OpenOptions::new()
     204           56 :         .read(true)
     205           56 :         .open(final_path_parent)?;
     206              : 
     207           56 :     final_parent_dirfd.sync_all()?;
     208           56 :     Ok(())
     209           56 : }
     210              : 
     211              : /// Syncs the filesystem for the given file descriptor.
     212              : #[cfg_attr(target_os = "macos", allow(unused_variables))]
     213            0 : pub fn syncfs(fd: impl AsRawFd) -> anyhow::Result<()> {
     214              :     // Linux guarantees durability for syncfs.
     215              :     // POSIX doesn't have syncfs, and further does not actually guarantee durability of sync().
     216              :     #[cfg(target_os = "linux")]
     217            0 :     {
     218            0 :         use anyhow::Context;
     219            0 :         nix::unistd::syncfs(fd.as_raw_fd()).context("syncfs")?;
     220              :     }
     221              :     #[cfg(target_os = "macos")]
     222              :     {
     223              :         // macOS is not a production platform for Neon, don't even bother.
     224              :     }
     225              :     #[cfg(not(any(target_os = "linux", target_os = "macos")))]
     226              :     {
     227              :         compile_error!("Unsupported OS");
     228              :     }
     229            0 :     Ok(())
     230            0 : }
     231              : 
     232              : #[cfg(test)]
     233              : mod tests {
     234              : 
     235              :     use super::*;
     236              : 
     237              :     #[test]
     238            1 :     fn test_create_dir_fsyncd() {
     239            1 :         let dir = camino_tempfile::tempdir().unwrap();
     240            1 : 
     241            1 :         let existing_dir_path = dir.path();
     242            1 :         let err = create_dir(existing_dir_path).unwrap_err();
     243            1 :         assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
     244              : 
     245            1 :         let child_dir = existing_dir_path.join("child");
     246            1 :         create_dir(child_dir).unwrap();
     247            1 : 
     248            1 :         let nested_child_dir = existing_dir_path.join("child1").join("child2");
     249            1 :         let err = create_dir(nested_child_dir).unwrap_err();
     250            1 :         assert_eq!(err.kind(), io::ErrorKind::NotFound);
     251            1 :     }
     252              : 
     253              :     #[test]
     254            1 :     fn test_create_dir_all_fsyncd() {
     255            1 :         let dir = camino_tempfile::tempdir().unwrap();
     256            1 : 
     257            1 :         let existing_dir_path = dir.path();
     258            1 :         create_dir_all(existing_dir_path).unwrap();
     259            1 : 
     260            1 :         let child_dir = existing_dir_path.join("child");
     261            1 :         assert!(!child_dir.exists());
     262            1 :         create_dir_all(&child_dir).unwrap();
     263            1 :         assert!(child_dir.exists());
     264              : 
     265            1 :         let nested_child_dir = existing_dir_path.join("child1").join("child2");
     266            1 :         assert!(!nested_child_dir.exists());
     267            1 :         create_dir_all(&nested_child_dir).unwrap();
     268            1 :         assert!(nested_child_dir.exists());
     269              : 
     270            1 :         let file_path = existing_dir_path.join("file");
     271            1 :         std::fs::write(&file_path, b"").unwrap();
     272            1 : 
     273            1 :         let err = create_dir_all(&file_path).unwrap_err();
     274            1 :         assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
     275              : 
     276            1 :         let invalid_dir_path = file_path.join("folder");
     277            1 :         create_dir_all(invalid_dir_path).unwrap_err();
     278            1 :     }
     279              : 
     280              :     #[test]
     281            1 :     fn test_path_with_suffix_extension() {
     282            1 :         let p = Utf8PathBuf::from("/foo/bar");
     283            1 :         assert_eq!(
     284            1 :             &path_with_suffix_extension(p, "temp").to_string(),
     285            1 :             "/foo/bar.temp"
     286            1 :         );
     287            1 :         let p = Utf8PathBuf::from("/foo/bar");
     288            1 :         assert_eq!(
     289            1 :             &path_with_suffix_extension(p, "temp.temp").to_string(),
     290            1 :             "/foo/bar.temp.temp"
     291            1 :         );
     292            1 :         let p = Utf8PathBuf::from("/foo/bar.baz");
     293            1 :         assert_eq!(
     294            1 :             &path_with_suffix_extension(p, "temp.temp").to_string(),
     295            1 :             "/foo/bar.baz.temp.temp"
     296            1 :         );
     297            1 :         let p = Utf8PathBuf::from("/foo/bar.baz");
     298            1 :         assert_eq!(
     299            1 :             &path_with_suffix_extension(p, ".temp").to_string(),
     300            1 :             "/foo/bar.baz..temp"
     301            1 :         );
     302            1 :         let p = Utf8PathBuf::from("/foo/bar/dir/");
     303            1 :         assert_eq!(
     304            1 :             &path_with_suffix_extension(p, ".temp").to_string(),
     305            1 :             "/foo/bar/dir..temp"
     306            1 :         );
     307            1 :     }
     308              : }
        

Generated by: LCOV version 2.1-beta