Files
leleka/control-plane/src/immutable_directory.rs
T

223 lines
8.4 KiB
Rust

//! Atomic publication of a new immutable directory. Existence checks alone
//! cannot protect an empty destination created immediately before rename.
use std::{io, path::Path};
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(crate) fn publish(source: &Path, destination: &Path) -> io::Result<()> {
use std::{ffi::CString, os::unix::ffi::OsStrExt};
let source = CString::new(source.as_os_str().as_bytes())?;
let destination = CString::new(destination.as_os_str().as_bytes())?;
if rename_no_replace(&source, &destination) == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
#[cfg(target_os = "linux")]
fn rename_no_replace(source: &std::ffi::CStr, destination: &std::ffi::CStr) -> libc::c_long {
unsafe {
// Rust's bundled musl exposes no renameat2 wrapper. Use the same
// kernel primitive through syscall, with the target's syscall ID.
libc::syscall(
libc::SYS_renameat2,
libc::AT_FDCWD,
source.as_ptr(),
libc::AT_FDCWD,
destination.as_ptr(),
libc::RENAME_NOREPLACE,
)
}
}
#[cfg(target_os = "macos")]
fn rename_no_replace(source: &std::ffi::CStr, destination: &std::ffi::CStr) -> libc::c_int {
unsafe { libc::renamex_np(source.as_ptr(), destination.as_ptr(), libc::RENAME_EXCL) }
}
// Windows: MoveFileExW without MOVEFILE_REPLACE_EXISTING never replaces anything (std::fs::rename may replace an
// empty directory), which is the same atomic no-replace guarantee.
#[cfg(target_os = "windows")]
pub(crate) fn publish(source: &Path, destination: &Path) -> io::Result<()> {
use std::os::windows::ffi::OsStrExt;
let wide =
|path: &Path| -> Vec<u16> { path.as_os_str().encode_wide().chain(Some(0)).collect() };
let (from, to) = (wide(source), wide(destination));
// SAFETY: both buffers are NUL-terminated UTF-16 that outlive the call.
if unsafe {
windows_sys::Win32::Storage::FileSystem::MoveFileExW(from.as_ptr(), to.as_ptr(), 0)
} != 0
{
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
pub(crate) fn publish(source: &Path, destination: &Path) -> io::Result<()> {
let _ = (source, destination);
Err(io::Error::new(
io::ErrorKind::Unsupported,
"atomic no-replace directory publication requires Linux or macOS",
))
}
#[cfg(all(test, target_os = "windows"))]
mod windows_tests {
use super::*;
#[test]
fn a_second_publication_onto_the_same_destination_is_refused() {
let root = std::env::temp_dir().join(format!("strata-publish-win-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("a")).unwrap();
std::fs::create_dir_all(root.join("b")).unwrap();
publish(&root.join("a"), &root.join("dest")).unwrap();
assert!(publish(&root.join("b"), &root.join("dest")).is_err());
assert!(root.join("b").is_dir() && root.join("dest").is_dir());
std::fs::remove_dir_all(&root).unwrap();
}
}
#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
mod tests {
use super::*;
use std::{
fs,
os::unix::fs::{MetadataExt, symlink},
path::PathBuf,
sync::{Arc, Barrier},
};
struct Temporary(PathBuf);
impl Temporary {
fn new() -> Self {
let path = std::env::temp_dir().join(format!(
"strata-publish-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir(&path).unwrap();
Self(path)
}
}
impl Drop for Temporary {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// Creates `target` as a conflicting destination of the given kind next to `source`.
fn make_conflict(kind: &str, root: &Temporary, source: &Path, target: &Path) {
match kind {
"empty" => fs::create_dir(target).unwrap(),
"nonempty" => {
fs::create_dir(target).unwrap();
fs::write(target.join("original"), b"keep").unwrap();
}
"file" => fs::write(target, b"keep").unwrap(),
"symlink" => symlink(source, target).unwrap(),
_ => symlink(root.0.join("absent"), target).unwrap(),
}
}
fn assert_conflict_untouched(kind: &str, target: &Path) {
match kind {
"empty" => assert_eq!(fs::read_dir(target).unwrap().count(), 0),
"nonempty" => assert_eq!(fs::read(target.join("original")).unwrap(), b"keep"),
"file" => assert_eq!(fs::read(target).unwrap(), b"keep"),
_ => assert!(
fs::symlink_metadata(target)
.unwrap()
.file_type()
.is_symlink()
),
}
}
#[test]
fn conflicts_preserve_even_empty_destination_and_source() {
let root = Temporary::new();
let source = root.0.join("stage");
fs::create_dir(&source).unwrap();
fs::write(source.join("payload"), b"complete bytes").unwrap();
for kind in ["empty", "nonempty", "file", "symlink", "dangling"] {
let target = root.0.join(kind);
make_conflict(kind, &root, &source, &target);
let before = fs::symlink_metadata(&target).unwrap();
assert_eq!(
publish(&source, &target).unwrap_err().kind(),
io::ErrorKind::AlreadyExists
);
assert_eq!(fs::symlink_metadata(&target).unwrap().ino(), before.ino());
assert_eq!(fs::read(source.join("payload")).unwrap(), b"complete bytes");
assert_conflict_untouched(kind, &target);
}
#[cfg(target_os = "linux")]
let target = {
use std::os::unix::ffi::OsStringExt;
root.0
.join(std::ffi::OsString::from_vec(b"pack-\xff".to_vec()))
};
// APFS rejects invalid UTF-8 filenames independently of rename flags.
#[cfg(target_os = "macos")]
let target = root.0.join("pack-версія one");
publish(&source, &target).unwrap();
assert!(!source.exists());
assert_eq!(fs::read(target.join("payload")).unwrap(), b"complete bytes");
}
#[test]
fn concurrent_publish_has_one_complete_winner() {
let root = Temporary::new();
let target = root.0.join("version");
let results = race_two_publications(&root, &target);
assert_eq!(results.iter().filter(|(_, _, r)| r.is_ok()).count(), 1);
let (winner, source, _) = results.iter().find(|(_, _, r)| r.is_ok()).unwrap();
assert!(!source.exists());
assert_eq!(
fs::read(target.join("payload")).unwrap(),
vec![*winner; 1024]
);
assert_eq!(fs::read(target.join("receipt")).unwrap(), [*winner]);
let (loser, source, error) = results.iter().find(|(_, _, r)| r.is_err()).unwrap();
assert_eq!(
error.as_ref().unwrap_err().kind(),
io::ErrorKind::AlreadyExists
);
assert_eq!(
fs::read(source.join("payload")).unwrap(),
vec![*loser; 1024]
);
assert_eq!(fs::read(source.join("receipt")).unwrap(), [*loser]);
}
type Publication = (u8, PathBuf, io::Result<()>);
/// Two staged directories published onto `target` at the same moment.
fn race_two_publications(root: &Temporary, target: &Path) -> Vec<Publication> {
let barrier = Arc::new(Barrier::new(2));
let mut handles = Vec::new();
for number in 0..2u8 {
let source = root.0.join(format!("stage-{number}"));
fs::create_dir(&source).unwrap();
fs::write(source.join("payload"), vec![number; 1024]).unwrap();
fs::write(source.join("receipt"), [number]).unwrap();
let target = target.to_path_buf();
let barrier = barrier.clone();
handles.push(std::thread::spawn(move || {
barrier.wait();
(number, source.clone(), publish(&source, &target))
}));
}
handles
.into_iter()
.map(|h| h.join().unwrap())
.collect::<Vec<_>>()
}
}