diff --git a/AGENTS.md b/AGENTS.md index e8065bba..9c8837c1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,8 @@ review bots read and write at the same time, written in Rust. shared by every component. - `crates/origin-platform`: everything that differs between platforms (durable writes, file locks, copy-on-write clones, positioned reads, - refusing network file systems), behind traits. It is the only place whose + refusing network file systems, killing process groups), behind traits. + It is the only place whose code differs by target OS. `std::os::unix`, which every supported platform has, may be used anywhere. - `crates/origin-client`: the SDK, a typed client for origin servers. Each diff --git a/Cargo.toml b/Cargo.toml index a471af07..fdcb89a0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,7 +36,7 @@ reflink-copy = "0.1.30" # No TLS yet: remotes are plain HTTP in the prototype. reqwest = { version = "0.13.5", default-features = false, features = ["json", "query"] } # Only in origin-platform. The version and features reflink-copy uses on Linux. -rustix = { version = "1.1.6", default-features = false, features = ["fs", "std"] } +rustix = { version = "1.1.6", default-features = false, features = ["fs", "process", "std"] } serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" similar = "3.2.0" diff --git a/crates/origin-platform/src/lib.rs b/crates/origin-platform/src/lib.rs index aec0e893..f17532d5 100644 --- a/crates/origin-platform/src/lib.rs +++ b/crates/origin-platform/src/lib.rs @@ -1,6 +1,7 @@ //! File operations that differ between platforms: durable writes, file //! locks, copy-on-write clones, positioned reads, and telling local file -//! systems from network ones. +//! systems from network ones. And stopping commands whole, with what they +//! started. //! //! Each operation is a trait. Every supported platform implements them in its //! own module under [`native`], and [`Native`] picks the one for the build @@ -16,6 +17,7 @@ mod error; mod file_system; mod lock; pub mod native; +mod process; mod read; pub use clone::{CloneError, CloneFile}; @@ -24,6 +26,7 @@ pub use error::{Error, Op}; pub use file_system::{FileSystem, FsKind, WritableError}; pub use lock::{FileLock, LockMode, LockedFile}; pub use native::Native; +pub use process::Processes; pub use read::ReadAt; /// Everything origin needs from the platform it runs on, shared by all the diff --git a/crates/origin-platform/src/native/linux.rs b/crates/origin-platform/src/native/linux.rs index 6b337cfc..13843f9e 100644 --- a/crates/origin-platform/src/native/linux.rs +++ b/crates/origin-platform/src/native/linux.rs @@ -1,14 +1,16 @@ //! Linux: `fdatasync` and `fsync`, `syncfs` for large batches, `flock`, -//! clones with the `FICLONE` ioctl (Btrfs, XFS, bcachefs), `pread`, and file -//! systems told apart by their `statfs` magic number. +//! clones with the `FICLONE` ioctl (Btrfs, XFS, bcachefs), `pread`, file +//! systems told apart by their `statfs` magic number, and the files a +//! process group holds read from `/proc`. -use std::fs::File; +use std::fs::{self, File}; use std::io::{self, ErrorKind}; +use std::os::unix::fs::MetadataExt; use std::panic; use std::path::Path; use std::thread; -use crate::{CloneFile, Durability, Error, FileLock, FileSystem, FsKind, Op, ReadAt}; +use crate::{CloneFile, Durability, Error, FileLock, FileSystem, FsKind, Op, Processes, ReadAt}; /// The Linux implementation of [`Platform`](crate::Platform). #[derive(Clone, Copy, Debug, Default)] @@ -100,6 +102,46 @@ impl Durability for Linux { impl FileLock for Linux {} +impl Processes for Linux { + /// Reads `/proc`: each process's group from its `stat`, then the files + /// it holds from its `fd`. Processes that end meanwhile, or whose files + /// may not be read, are skipped. + fn group_holds(&self, id: u32, path: &Path) -> io::Result { + let held = fs::metadata(path)?; + for process in fs::read_dir("/proc")? { + let process = process?.path(); + let pid = process + .file_name() + .and_then(|name| name.to_str()?.parse().ok()); + if pid.and_then(Self::group_of) != Some(id) { + continue; + } + let Ok(files) = fs::read_dir(process.join("fd")) else { + continue; + }; + let holds = |file: fs::DirEntry| { + fs::metadata(file.path()) + .is_ok_and(|open| (open.dev(), open.ino()) == (held.dev(), held.ino())) + }; + if files.flatten().any(holds) { + return Ok(true); + } + } + Ok(false) + } +} + +impl Linux { + /// The process group of the process `pid`, unless it ended or may not + /// be read: the fifth field of `/proc//stat`, the third after its + /// command's name, which is in parentheses and may hold any character. + fn group_of(pid: u32) -> Option { + let stat = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; + let (_, after) = stat.rsplit_once(')')?; + after.split_whitespace().nth(2)?.parse().ok() + } +} + impl ReadAt for Linux {} impl CloneFile for Linux { @@ -127,6 +169,38 @@ impl FileSystem for Linux { mod tests { use super::*; + #[test] + fn groups_hold_the_files_their_processes_hold() { + use std::os::unix::process::CommandExt; + use std::process::{Command, Stdio}; + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("held"); + fs::write(&path, "").unwrap(); + let mut holder = Command::new("sleep") + .arg("60") + .process_group(0) + .stdin(File::open(&path).unwrap()) + .spawn() + .unwrap(); + let mut other = Command::new("sleep") + .arg("60") + .process_group(0) + .stdin(Stdio::null()) + .spawn() + .unwrap(); + assert!(Linux.group_holds(holder.id(), &path).unwrap()); + assert!( + !Linux.group_holds(other.id(), &path).unwrap(), + "another group" + ); + for child in [&mut holder, &mut other] { + child.kill().unwrap(); + child.wait().unwrap(); + } + assert!(!Linux.group_holds(holder.id(), &path).unwrap(), "it ended"); + } + #[test] fn classifies_file_systems_by_magic_number() { assert_eq!(Linux::classify(0xEF53), FsKind::Local, "ext4"); diff --git a/crates/origin-platform/src/native/macos.rs b/crates/origin-platform/src/native/macos.rs index 9eafb778..e5203495 100644 --- a/crates/origin-platform/src/native/macos.rs +++ b/crates/origin-platform/src/native/macos.rs @@ -6,7 +6,7 @@ use std::fs::File; use std::io::{self, ErrorKind}; use std::path::Path; -use crate::{CloneFile, Durability, Error, FileLock, FileSystem, FsKind, Op, ReadAt}; +use crate::{CloneFile, Durability, Error, FileLock, FileSystem, FsKind, Op, Processes, ReadAt}; /// The macOS implementation of [`Platform`](crate::Platform). #[derive(Clone, Copy, Debug, Default)] @@ -61,6 +61,16 @@ impl Durability for MacOs { impl FileLock for MacOs {} +impl Processes for MacOs { + const SEES_HELD_FILES: bool = false; + + /// macOS lists the files a process holds only through `libproc`, + /// which needs `unsafe`: never sure, it says no. + fn group_holds(&self, _id: u32, _path: &Path) -> io::Result { + Ok(false) + } +} + impl ReadAt for MacOs {} impl CloneFile for MacOs { diff --git a/crates/origin-platform/src/process.rs b/crates/origin-platform/src/process.rs new file mode 100644 index 00000000..41ffd363 --- /dev/null +++ b/crates/origin-platform/src/process.rs @@ -0,0 +1,64 @@ +use std::fs::File; +use std::io; +use std::path::Path; + +use rustix::io::FdFlags; +use rustix::process::{Pid, Signal}; + +/// What tells a command's processes apart, and stops them: process groups, +/// so a command started in a group of its own +/// (`CommandExt::process_group(0)`) is stopped whole, with whatever it +/// started and left running, which joins its group; and files they +/// inherit open, so a lock stays held while any of them lives. +/// +/// The default methods use POSIX's `kill` and `fcntl`, which every +/// supported platform has. +pub trait Processes { + /// Whether [`Processes::group_holds`] can see the files a group holds: + /// where it can't, it always says no, so what a command leaves running + /// is never killed. + const SEES_HELD_FILES: bool = true; + + /// Whether a process of the group `id` holds the file at `path` open: + /// so a group that ended, whose number another group took since, is + /// told apart from one that still runs what it started with the file. + /// `false` where no reliable way to tell exists: then the group is left + /// running rather than risk killing another. + /// + /// # Errors + /// + /// Fails if the file cannot be inspected, or the processes listed. + fn group_holds(&self, id: u32, path: &Path) -> io::Result; + + /// Kills every process of the group `id`, if any is left. + /// + /// # Errors + /// + /// Fails if `id` names no group of its own, as 0 and 1 don't, or the + /// group's processes may not be signalled. + fn kill_group(&self, id: u32) -> io::Result<()> { + // `kill(-1)` would signal every process. + let pid = i32::try_from(id) + .ok() + .filter(|&id| id > 1) + .and_then(Pid::from_raw) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "not a process group"))?; + match rustix::process::kill_process_group(pid, Signal::KILL) { + Err(rustix::io::Errno::SRCH) => Ok(()), + killed => Ok(killed?), + } + } + + /// Has the commands started from now on inherit `file`, open, and their + /// processes the ones they start, unless they close it: then a lock it + /// holds stays held while any of them lives. Commands other threads + /// start meanwhile inherit it too. + /// + /// # Errors + /// + /// Fails if the file's descriptor cannot be changed. + fn inherit(&self, file: &File) -> io::Result<()> { + let flags = rustix::io::fcntl_getfd(file)?; + Ok(rustix::io::fcntl_setfd(file, flags - FdFlags::CLOEXEC)?) + } +} diff --git a/crates/origin-platform/tests/conformance.rs b/crates/origin-platform/tests/conformance.rs index 7b1824e4..ce212adb 100644 --- a/crates/origin-platform/tests/conformance.rs +++ b/crates/origin-platform/tests/conformance.rs @@ -30,6 +30,9 @@ conformance!( temp_dirs_are_local, inspecting_a_missing_path_fails, positioned_reads_share_a_file, + process_groups_are_killed_whole, + inherited_locks_are_held_by_what_holds_them, + groups_never_hold_files_they_do_not_hold, ); mod suite { @@ -42,8 +45,11 @@ mod suite { use std::thread; use std::time::Duration; + use std::os::unix::process::{CommandExt, ExitStatusExt}; + use origin_platform::{ - CloneError, DurableWrite, Error, FsKind, LockMode, LockedFile, Op, Platform, WritableError, + CloneError, DurableWrite, Error, FileLock, FsKind, LockMode, LockedFile, Op, Platform, + Processes, WritableError, }; /// Stages a batch from several threads, large enough to be renamed from @@ -259,4 +265,81 @@ mod suite { .unwrap_err(); assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof); } + + /// A command in a group of its own is killed with what it started, + /// and a group with nothing left is no error. + pub fn process_groups_are_killed_whole(platform: &impl Processes) { + let mut shell = Command::new("sh") + .args(["-c", "sleep 60 & echo $!; wait"]) + .process_group(0) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let mut started = String::new(); + BufReader::new(shell.stdout.take().unwrap()) + .read_line(&mut started) + .unwrap(); + platform.kill_group(shell.id()).unwrap(); + assert_eq!(shell.wait().unwrap().signal(), Some(9)); + // Once its new parent reaps it, the sleep is gone too. + let alive = || { + let mut probe = Command::new("kill"); + probe.args(["-0", started.trim()]).stderr(Stdio::null()); + probe.status().unwrap().success() + }; + let mut tries = 0; + while alive() { + tries += 1; + assert!(tries < 100, "the sleep it started still runs"); + thread::sleep(Duration::from_millis(10)); + } + platform.kill_group(shell.id()).unwrap(); + assert!(platform.kill_group(1).is_err(), "not every process"); + } + + /// A group is never said to hold a file none of its processes holds: + /// where unsure, a platform says no. + pub fn groups_never_hold_files_they_do_not_hold(platform: &impl Processes) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("held"); + fs::write(&path, "").unwrap(); + let mut other = Command::new("sleep") + .arg("60") + .process_group(0) + .stdin(Stdio::null()) + .spawn() + .unwrap(); + assert!(!platform.group_holds(other.id(), &path).unwrap()); + other.kill().unwrap(); + other.wait().unwrap(); + } + + /// A lock a command inherits stays held while it runs, after its + /// starter let go of it. + pub fn inherited_locks_are_held_by_what_holds_them(platform: &(impl Processes + FileLock)) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("held"); + let held = LockedFile::open(platform, &path, LockMode::Exclusive).unwrap(); + platform.inherit(&held).unwrap(); + let mut shell = Command::new("sh") + .args(["-c", "sleep 60 & wait"]) + .process_group(0) + .spawn() + .unwrap(); + drop(held); + let free = || { + LockedFile::try_open(platform, &path, LockMode::Exclusive) + .unwrap() + .is_some() + }; + assert!(!free(), "the command holds it"); + platform.kill_group(shell.id()).unwrap(); + shell.wait().unwrap(); + let mut tries = 0; + while !free() { + tries += 1; + assert!(tries < 100, "the sleep it started still holds it"); + thread::sleep(Duration::from_millis(10)); + } + } }