[control] Atomic writes: a temporary name unique per write (pid, counter, random), so two writers of one file never collide; same for edge's epoch floor

This commit is contained in:
2026-11-07 19:57:06 +01:00
parent 7863202e3a
commit afc3477b5c
2 changed files with 33 additions and 2 deletions
+26 -1
View File
@@ -62,7 +62,12 @@ pub fn write_atomic(path: &Path, data: &[u8], mode: u32) -> std::io::Result<()>
.unwrap_or(Path::new("."));
std::fs::create_dir_all(dir)?;
let mut name = path.file_name().unwrap_or_default().to_os_string();
name.push(format!(".tmp-{}", std::process::id()));
// Unique per write (process, counter, random), so two writers of the same file never
// share a temporary file.
static WRITES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = WRITES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let r = random::<4>().map(|b| hex(&b))?;
name.push(format!(".tmp-{}-{n}-{r}", std::process::id()));
let tmp = dir.join(name);
{
let mut opts = std::fs::OpenOptions::new();
@@ -133,6 +138,26 @@ mod tests {
assert!(!ct_eq(b"abc", b"ab"));
}
#[test]
fn concurrent_atomic_writes_of_one_file_all_succeed() {
let d = std::env::temp_dir().join(format!("ianitor-util-c-{}", std::process::id()));
let p = d.join("paused.json");
let threads: Vec<_> = (0..16)
.map(|i| {
let p = p.clone();
std::thread::spawn(move || {
(0..50).all(|_| write_atomic(&p, format!("{i}").as_bytes(), 0o600).is_ok())
})
})
.collect();
for t in threads {
assert!(t.join().unwrap(), "a write failed");
}
let left: Vec<_> = std::fs::read_dir(&d).unwrap().collect();
assert_eq!(left.len(), 1, "no temporary files left");
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn atomic_write_replaces() {
let d = std::env::temp_dir().join(format!("ianitor-util-{}", std::process::id()));
+7 -1
View File
@@ -463,7 +463,13 @@ fn write_epoch_floor(rt: &Runtime, epoch: u32) -> std::io::Result<()> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let tmp = path.with_extension("tmp");
// Unique per write: the admin socket and the poller can both reload the revocations.
static WRITES: AtomicU64 = AtomicU64::new(0);
let tmp = path.with_extension(format!(
"tmp-{}-{}",
std::process::id(),
WRITES.fetch_add(1, Ordering::Relaxed)
));
{
use std::io::Write;
let mut f = std::fs::File::create(&tmp)?;