use std::fs::{self, File};
use std::io;
use std::path::{Path, PathBuf};
use std::process::{Child, Command};
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
pub(crate) static STOPPED: AtomicUsize = AtomicUsize::new(0);
pub(crate) static NOT_STOPPED: AtomicUsize = AtomicUsize::new(0);
static STARTING: Mutex<()> = Mutex::new(());
const PATIENCE: Duration = Duration::from_secs(5);
const SETTLE: Duration = Duration::from_millis(50);
#[derive(Debug, Default, PartialEq)]
pub(crate) struct Swept {
pub(crate) stopped: usize,
pub(crate) left: bool,
}
pub(crate) struct Watch {
path: PathBuf,
started: bool,
}
impl Watch {
pub(crate) fn new(path: PathBuf) -> Self {
Self {
path,
started: false,
}
}
pub(crate) fn spawn(&mut self, command: &mut Command) -> io::Result<Child> {
let _one_at_a_time = STARTING.lock().unwrap_or_else(|e| e.into_inner());
#[cfg(unix)]
let file = {
use std::os::fd::AsRawFd;
use std::os::unix::process::CommandExt;
let file = File::open(&self.path)
.and_then(|file| crate::work_lock::lock_open_file(&file).map(|()| file))
.ok();
if let Some(file) = &file {
let fd = file.as_raw_fd();
unsafe { command.pre_exec(move || crate::work_lock::inherit_lock(fd)) };
self.started = true;
}
file
};
let child = command.spawn();
#[cfg(unix)]
drop(file);
child
}
pub(crate) fn finish(self, leave: bool) -> Swept {
let swept = if self.started && !leave {
sweep(&self.path)
} else {
Swept::default()
};
let _ = fs::remove_file(&self.path);
swept
}
}
pub(crate) fn count(swept: &Swept) {
STOPPED.fetch_add(swept.stopped, Ordering::Relaxed);
if swept.left {
NOT_STOPPED.fetch_add(1, Ordering::Relaxed);
}
}
pub(crate) fn leave() -> bool {
asked_to_leave(std::env::var_os("TMT_LEAVE_PROCESSES"))
}
fn asked_to_leave(setting: Option<std::ffi::OsString>) -> bool {
setting.is_some_and(|value| !value.is_empty())
}
#[cfg(unix)]
fn sweep(path: &Path) -> Swept {
let mut swept = Swept::default();
let mut stopped = std::collections::BTreeSet::new();
let deadline = Instant::now() + PATIENCE;
let mut settled = false;
loop {
match held(path) {
Ok(true) => {}
Ok(false) => break,
Err(_) => {
swept.left = true;
break;
}
}
if !settled {
std::thread::sleep(SETTLE);
settled = true;
continue;
}
let Ok(holders) = holders(path) else {
swept.left = true;
break;
};
for pid in holders {
if is_left(pid, std::process::id(), parent_of(pid)) {
stop(pid);
stopped.insert(pid);
}
}
if Instant::now() >= deadline {
swept.left = true;
break;
}
std::thread::sleep(Duration::from_millis(20));
}
swept.stopped = stopped.len();
swept
}
fn is_left(pid: u32, me: u32, parent: Option<u32>) -> bool {
pid != me && parent.is_some_and(|parent| parent != me)
}
#[cfg(target_os = "linux")]
fn parent_of(pid: u32) -> Option<u32> {
let stat = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
parent_in_stat(&stat)
}
#[cfg(any(test, target_os = "linux"))]
fn parent_in_stat(stat: &str) -> Option<u32> {
let after_name = &stat[stat.rfind(')')? + 1..];
after_name.split_whitespace().nth(1)?.parse().ok()
}
#[cfg(all(unix, not(target_os = "linux")))]
fn parent_of(pid: u32) -> Option<u32> {
let listed = Command::new("ps")
.args(["-o", "ppid=", "-p", &pid.to_string()])
.stdin(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.output()
.ok()?;
String::from_utf8_lossy(&listed.stdout).trim().parse().ok()
}
#[cfg(not(unix))]
fn sweep(_: &Path) -> Swept {
Swept::default()
}
#[cfg(unix)]
fn held(path: &Path) -> io::Result<bool> {
let file = File::open(path)?;
match crate::work_lock::lock_open_file(&file) {
Ok(()) => Ok(false),
Err(error) if crate::work_lock::contended(&error) => Ok(true),
Err(error) => Err(error),
}
}
#[cfg(target_os = "linux")]
fn holders(path: &Path) -> io::Result<Vec<u32>> {
use std::os::unix::fs::MetadataExt;
let wanted = fs::metadata(path)?;
let wanted = (wanted.dev(), wanted.ino());
let mut pids = vec![];
for process in fs::read_dir("/proc")?.flatten() {
let Some(pid) = process.file_name().to_str().and_then(|n| n.parse().ok()) else {
continue;
};
let Ok(files) = fs::read_dir(process.path().join("fd")) else {
continue;
};
let has = files.flatten().any(|file| {
fs::metadata(file.path()).is_ok_and(|open| (open.dev(), open.ino()) == wanted)
});
if has {
pids.push(pid);
}
}
Ok(pids)
}
#[cfg(all(unix, not(target_os = "linux")))]
fn holders(path: &Path) -> io::Result<Vec<u32>> {
let mut last = io::Error::from(io::ErrorKind::NotFound);
for lsof in ["lsof", "/usr/sbin/lsof", "/usr/bin/lsof"] {
match Command::new(lsof)
.arg("-t")
.arg("--")
.arg(path)
.stdin(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.output()
{
Ok(output) => return Ok(pids(&String::from_utf8_lossy(&output.stdout))),
Err(error) => last = error,
}
}
Err(last)
}
#[cfg(any(test, all(unix, not(target_os = "linux"))))]
fn pids(listing: &str) -> Vec<u32> {
listing
.lines()
.filter_map(|line| line.trim().parse().ok())
.filter(|pid| *pid > 1)
.collect()
}
#[cfg(unix)]
fn stop(pid: u32) {
unsafe extern "C" {
fn kill(pid: std::ffi::c_int, signal: std::ffi::c_int) -> std::ffi::c_int;
}
if let Ok(pid) = std::ffi::c_int::try_from(pid)
&& pid > 1
{
unsafe { kill(pid, 9) };
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use std::io::Read;
use std::process::Stdio;
static NEXT: AtomicUsize = AtomicUsize::new(0);
struct Scratch(PathBuf);
impl Scratch {
fn new() -> Self {
let dir = std::env::temp_dir().join(format!(
"tmt-leftovers-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
Self(dir)
}
fn file(&self) -> PathBuf {
let path = self.0.join("held");
fs::write(&path, "").unwrap();
path
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn leaving() -> Command {
let mut command = Command::new("sh");
command
.args([
"-c",
"set -m; (trap '' TERM HUP; i=0; while [ $i -lt 60 ]; do sleep 1; i=$((i+1)); done) \
>/dev/null 2>&1 & echo $!",
])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null());
command
}
fn left_by(mut child: Child) -> u32 {
let mut said = String::new();
child
.stdout
.take()
.unwrap()
.read_to_string(&mut said)
.unwrap();
assert!(child.wait().unwrap().success());
said.trim().parse().unwrap()
}
fn alive(pid: u32) -> bool {
let listed = Command::new("ps")
.args(["-o", "stat=", "-p", &pid.to_string()])
.output()
.unwrap();
let state = String::from_utf8_lossy(&listed.stdout);
!state.trim().is_empty() && !state.trim().starts_with('Z')
}
fn gone(pid: u32) -> bool {
let deadline = Instant::now() + Duration::from_secs(10);
while alive(pid) {
if Instant::now() >= deadline {
return false;
}
std::thread::sleep(Duration::from_millis(20));
}
true
}
struct Reaper(u32);
impl Drop for Reaper {
fn drop(&mut self) {
stop(self.0);
}
}
#[test]
fn what_a_run_left_in_another_group_is_stopped_after_it() {
let scratch = Scratch::new();
let path = scratch.file();
let mut watch = Watch::new(path.clone());
let left = Reaper(left_by(watch.spawn(&mut leaving()).unwrap()));
assert!(alive(left.0));
assert!(held(&path).unwrap());
let swept = watch.finish(false);
assert!(!swept.left, "{swept:?}");
assert!((1..=2).contains(&swept.stopped), "{swept:?}");
assert!(gone(left.0));
assert!(!path.exists());
}
#[test]
fn a_run_that_left_nothing_is_not_swept() {
let scratch = Scratch::new();
let path = scratch.file();
let mut watch = Watch::new(path.clone());
let mut child = watch
.spawn(Command::new("true").stdin(Stdio::null()))
.unwrap();
assert!(child.wait().unwrap().success());
assert_eq!(watch.finish(false), Swept::default());
assert!(!path.exists());
}
#[test]
fn only_those_with_the_file_of_the_run_are_stopped() {
let scratch = Scratch::new();
let path = scratch.file();
let other = Reaper(left_by(leaving().spawn().unwrap()));
let mut watch = Watch::new(path);
let left = Reaper(left_by(watch.spawn(&mut leaving()).unwrap()));
let swept = watch.finish(false);
assert!(!swept.left, "{swept:?}");
assert!(gone(left.0));
assert!(alive(other.0));
}
#[test]
fn leftovers_are_left_when_asked_and_a_run_that_did_not_start_has_none() {
let scratch = Scratch::new();
let path = scratch.file();
let mut watch = Watch::new(path.clone());
let left = Reaper(left_by(watch.spawn(&mut leaving()).unwrap()));
assert_eq!(watch.finish(true), Swept::default());
assert!(alive(left.0));
assert!(!path.exists());
let path = scratch.file();
let mut watch = Watch::new(path.clone());
assert!(
watch
.spawn(&mut Command::new(scratch.0.join("no such program")))
.is_err()
);
assert_eq!(watch.finish(false), Swept::default());
assert!(!path.exists());
}
#[test]
fn a_file_that_is_gone_is_reported_as_not_swept() {
let scratch = Scratch::new();
let path = scratch.file();
let mut watch = Watch::new(path.clone());
let left = Reaper(left_by(watch.spawn(&mut leaving()).unwrap()));
fs::remove_file(&path).unwrap();
let swept = watch.finish(false);
assert_eq!(
swept,
Swept {
stopped: 0,
left: true
}
);
assert!(alive(left.0));
}
#[test]
fn a_child_of_this_process_and_this_process_are_never_left_by_a_run() {
assert!(is_left(40, 7, Some(1)));
assert!(is_left(40, 7, Some(39)));
assert!(!is_left(40, 7, Some(7)));
assert!(!is_left(7, 7, Some(1)));
assert!(!is_left(40, 7, None));
assert_eq!(
parent_of(std::process::id()),
Some(std::os::unix::process::parent_id())
);
assert_eq!(parent_of(u32::MAX - 7), None);
}
#[test]
fn the_parent_is_read_after_a_name_that_may_contain_anything() {
assert_eq!(parent_in_stat("12 (sh) S 7 12 12 0"), Some(7));
assert_eq!(parent_in_stat("12 (a) b) 3 (x) R 1 12"), Some(1));
assert_eq!(parent_in_stat("12 (sh"), None);
assert_eq!(parent_in_stat("12 (sh) S"), None);
}
#[test]
fn leftovers_are_left_only_when_the_setting_says_something() {
assert!(!asked_to_leave(None));
assert!(!asked_to_leave(Some("".into())));
assert!(asked_to_leave(Some("1".into())));
assert!(asked_to_leave(Some("no".into())));
}
#[test]
fn a_sweep_is_counted_for_the_summary() {
let (stopped, not_stopped) = (
STOPPED.load(Ordering::Relaxed),
NOT_STOPPED.load(Ordering::Relaxed),
);
count(&Swept {
stopped: 3,
left: true,
});
assert!(STOPPED.load(Ordering::Relaxed) >= stopped + 3);
assert!(NOT_STOPPED.load(Ordering::Relaxed) > not_stopped);
let not_stopped = NOT_STOPPED.load(Ordering::Relaxed);
count(&Swept::default());
assert_eq!(NOT_STOPPED.load(Ordering::Relaxed), not_stopped);
}
#[test]
fn a_listing_gives_process_numbers_and_nothing_that_names_a_group() {
assert_eq!(
pids("120\n 77 \n\nlsof: warning\n0\n1\n2\n-5\n4000000000\n"),
[120, 77, 2, 4000000000]
);
assert!(pids("").is_empty());
}
}