use crate::containment::treewalk::fault::record_walks;
use crate::containment::unix::fault::record_kill_group;
#[cfg(target_os = "linux")]
use crate::test_groups::{cgroup, Group};
use crate::tokio::child::drop_fault;
use crate::tokio::Command;
use crate::{ContainMode, Containment};
const WARN: &str = "Child::drop: the root is already reaped";
#[cfg(target_os = "macos")]
const SESSION_CONTAINMENT: Containment = Containment::FdMarker;
#[cfg(not(target_os = "macos"))]
const SESSION_CONTAINMENT: Containment = Containment::Session;
fn session(argv: &[&str]) -> Command {
let mut cmd = Command::new();
cmd.args(argv.iter().copied());
cmd.contain_with(ContainMode::Session);
cmd
}
fn drop_warns_since(mark: usize) -> Vec<(log::Level, String)> {
crate::log_capture::records_since_on_current_thread(mark, WARN)
}
#[skuld::test]
async fn dropping_a_waited_on_process_group_child_sends_no_killpg_and_warns_with_the_pgid() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let recorder = record_kill_group();
let root = drop_fault::record();
let mut child = session(&["true"]).spawn().expect("spawn");
assert_eq!(child.containment(), SESSION_CONTAINMENT);
let pid = child.id().pid();
child.wait().await.expect("reap the root");
let mark = crate::log_capture::mark();
drop(child);
assert_eq!(
recorder.killed(),
Vec::<i32>::new(),
"a reaped root's number may name another group: no killpg"
);
assert_eq!(
(root.kills(), root.forgets()),
(0, 0),
"tokio reaped it; nothing is left to do"
);
let warns = drop_warns_since(mark);
assert_eq!(warns.len(), 1, "exactly one warn, got {warns:?}");
let (level, text) = &warns[0];
assert_eq!(*level, log::Level::Warn);
assert!(text.contains(&format!("pgid {pid}")), "the warn names the pgid: {text}");
assert!(
text.contains("kill_tree()") && text.contains("wait()"),
"the warn says how to end descendants: {text}"
);
}
#[skuld::test]
async fn dropping_a_running_process_group_child_still_kills_the_group_and_does_not_warn() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let recorder = record_kill_group();
let root = drop_fault::record();
let child = session(&["sleep", "300"]).spawn().expect("spawn");
let pid = child.id().pid();
let mark = crate::log_capture::mark();
drop(child);
recorder.assert_killed_only(pid as i32);
assert_eq!((root.kills(), root.forgets()), (1, 0));
assert_eq!(drop_warns_since(mark), []);
}
#[skuld::test]
async fn dropping_an_exited_but_unreaped_process_group_child_still_kills_the_group() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let recorder = record_kill_group();
let mut child = session(&["sleep", "300"]).spawn().expect("spawn");
let pid = child.id().pid();
child.kill().expect("kill the root");
crate::test_child::wait_until_zombie(pid);
let mark = crate::log_capture::mark();
drop(child);
recorder.assert_killed_only(pid as i32);
assert_eq!(drop_warns_since(mark), []);
}
#[skuld::test]
async fn dropping_a_waited_on_tree_walk_child_walks_nothing_and_warns_with_the_root_pid() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let walks = record_walks();
let mut cmd = Command::new();
cmd.args(["true"]);
cmd.contain_with(ContainMode::TreeWalk);
let mut child = cmd.spawn().expect("spawn");
let pid = child.id().pid();
child.wait().await.expect("reap the root");
let mark = crate::log_capture::mark();
drop(child);
assert_eq!(
walks.walked(),
Vec::<u32>::new(),
"a reaped root's number names no tree"
);
let warns = drop_warns_since(mark);
assert_eq!(warns.len(), 1, "exactly one warn, got {warns:?}");
assert_eq!(warns[0].0, log::Level::Warn);
assert!(
warns[0].1.contains(&format!("root pid {pid}")),
"the warn names the root: {warns:?}"
);
}
#[skuld::test]
async fn dropping_a_running_tree_walk_child_walks_from_its_pid_and_does_not_warn() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let walks = record_walks();
let mut cmd = Command::new();
cmd.args(["sleep", "300"]);
cmd.contain_with(ContainMode::TreeWalk);
let child = cmd.spawn().expect("spawn");
let pid = child.id().pid();
let mark = crate::log_capture::mark();
drop(child);
let walked = walks.walked();
assert!(!walked.is_empty() && walked.iter().all(|w| *w == pid), "{walked:?}");
assert_eq!(drop_warns_since(mark), []);
}
#[skuld::test]
async fn dropping_a_foreign_reaped_process_group_child_sends_no_killpg() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let recorder = record_kill_group();
let root = drop_fault::record();
let mut child = session(&["sleep", "300"]).spawn().expect("spawn");
let pid = child.id().pid();
child.kill().expect("kill the root");
crate::test_child::wait_until_zombie(pid);
let mut status = 0;
let reaped = unsafe { libc::waitpid(pid as libc::pid_t, &mut status, 0) };
assert_eq!(reaped, pid as libc::pid_t, "{}", std::io::Error::last_os_error());
let mark = crate::log_capture::mark();
drop(child);
assert_eq!(recorder.killed(), Vec::<i32>::new());
assert_eq!(
(root.kills(), root.forgets()),
(0, 1),
"the number may belong to another child by now: no kill, and tokio's `Child` is forgotten so \
its own drop cannot reap by pid"
);
assert_eq!(drop_warns_since(mark).len(), 1);
}
fn foreign_reaped(mut cmd: Command) -> crate::tokio::Child {
let mut child = cmd.spawn().expect("spawn");
let pid = child.id().pid();
child.kill().expect("kill the root");
crate::test_child::wait_until_zombie(pid);
let mut status = 0;
let reaped = unsafe { libc::waitpid(pid as libc::pid_t, &mut status, 0) };
assert_eq!(reaped, pid as libc::pid_t, "{}", std::io::Error::last_os_error());
child
}
#[skuld::test]
async fn a_detached_drop_after_a_foreign_reap_forgets_tokios_child() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let root = drop_fault::record();
let backend_drops = crate::tokio::child::fault::count_backend_drops();
let mut child = foreign_reaped(session(&["sleep", "300"]));
child.detach();
drop(child);
assert_eq!(
(root.kills(), root.forgets(), backend_drops.get()),
(0, 1, 0),
"a detached drop must not run tokio's `Child` drop, which reaps by the reused number"
);
}
#[skuld::test]
async fn a_kill_on_drop_false_drop_after_a_foreign_reap_forgets_tokios_child() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let root = drop_fault::record();
let backend_drops = crate::tokio::child::fault::count_backend_drops();
let mut cmd = session(&["sleep", "300"]);
cmd.kill_on_drop(false);
let child = foreign_reaped(cmd);
drop(child);
assert_eq!((root.kills(), root.forgets(), backend_drops.get()), (0, 1, 0));
}
#[skuld::test]
async fn drop_after_kill_tree_and_wait_skips_at_debug_and_does_not_warn() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let recorder = record_kill_group();
let mut child = session(&["true"]).spawn().expect("spawn");
let pid = child.id().pid();
child.kill_tree().expect("kill_tree");
child.wait().await.expect("reap the root");
recorder.assert_killed_only(pid as i32);
let sent = recorder.killed();
let mark = crate::log_capture::mark();
drop(child);
assert_eq!(recorder.killed(), sent, "the drop sends no further killpg");
assert_skipped_at_debug(mark);
}
#[skuld::test]
async fn drop_after_graceful_shutdown_tree_skips_at_debug_and_does_not_warn() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let recorder = record_kill_group();
let mut child = session(&["sleep", "300"]).spawn().expect("spawn");
let pid = child.id().pid();
child
.graceful_shutdown_tree(std::time::Duration::from_secs(60))
.await
.expect("graceful_shutdown_tree");
recorder.assert_killed_only(pid as i32);
let mark = crate::log_capture::mark();
drop(child);
assert_skipped_at_debug(mark);
}
#[skuld::test]
async fn a_failed_elevated_spawns_cleanup_drops_its_handle_without_a_warn() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let recorder = record_kill_group();
let child = session(&["sleep", "300"]).spawn().expect("spawn");
let pid = child.id().pid();
let mark = crate::log_capture::mark();
let (err, fate) = crate::tokio::spawn::finish_elevated(
child,
Err(crate::error::Error::Io(std::io::Error::other("no password"))),
)
.expect_err("the password write failed")
.expect_may_have_started_with();
assert!(matches!(err, crate::error::Error::Elevation { .. }), "{err:?}");
assert_eq!(
fate,
crate::error::ChildFate::Reaped,
"the group's kill and the root's reap"
);
recorder.assert_killed_only(pid as i32);
assert_skipped_at_debug(mark);
}
async fn waited_on_sleep_root() -> crate::tokio::Child {
let mut child = session(&["sleep", "300"]).spawn().expect("spawn");
child.kill().expect("kill the root");
child.wait().await.expect("reap the root");
child
}
#[skuld::test]
async fn dropping_a_waited_on_child_whose_number_reads_unknown_still_sends_no_killpg() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let recorder = record_kill_group();
let root = drop_fault::record();
let child = waited_on_sleep_root().await;
let _unknown = crate::child::fault::force_next_root_read(crate::identity::Resolved::Unknown);
let mark = crate::log_capture::mark();
drop(child);
assert_eq!(recorder.killed(), Vec::<i32>::new());
assert_eq!((root.kills(), root.forgets()), (0, 0));
assert_eq!(drop_warns_since(mark).len(), 1);
}
#[skuld::test]
async fn dropping_an_unreaped_child_whose_number_reads_unknown_kills_and_logs_the_failed_read() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let recorder = record_kill_group();
let root = drop_fault::record();
let child = session(&["sleep", "300"]).spawn().expect("spawn");
let pid = child.id().pid();
let _unknown = crate::child::fault::force_next_root_read(crate::identity::Resolved::Unknown);
let mark = crate::log_capture::mark();
drop(child);
recorder.assert_killed_only(pid as i32);
assert_eq!((root.kills(), root.forgets()), (1, 0));
assert_eq!(drop_warns_since(mark), []);
let reads = crate::log_capture::records_since_on_current_thread(mark, "could not be read");
assert_eq!(reads.len(), 1, "{reads:?}");
assert_eq!(reads[0].0, log::Level::Debug);
}
#[skuld::test]
async fn drop_after_a_failed_kill_tree_and_wait_still_warns() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let recorder = record_kill_group();
recorder.fail_with_unassessable();
let mut child = session(&["true"]).spawn().expect("spawn");
child.kill_tree().expect_err("the forced refusal");
child.wait().await.expect("reap the root");
let mark = crate::log_capture::mark();
drop(child);
let records = drop_warns_since(mark);
assert_eq!(records.len(), 1, "{records:?}");
assert_eq!(records[0].0, log::Level::Warn);
}
#[cfg(not(target_os = "macos"))]
#[skuld::test]
async fn drop_after_an_incomplete_tree_walk_kill_and_wait_still_warns() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let mut cmd = Command::new();
cmd.args(["sleep", "300"]);
cmd.contain_with(ContainMode::TreeWalk);
let mut child = cmd.spawn().expect("spawn");
crate::containment::treewalk::fault::force_incomplete_once();
child.kill_tree().expect("a tree walk reports Ok");
child.wait().await.expect("reap the root");
let mark = crate::log_capture::mark();
drop(child);
let records = drop_warns_since(mark);
assert_eq!(records.len(), 1, "{records:?}");
assert_eq!(records[0].0, log::Level::Warn);
}
#[cfg(target_os = "linux")]
#[path = "../../tests/common/cgroup.rs"]
#[allow(
dead_code,
reason = "this file needs `drain_and_remove_leaf` alone; the integration binaries use the rest"
)]
mod cgroup_common;
#[cfg(target_os = "linux")]
#[skuld::test]
async fn cgroup_drop_after_wait_still_kills_the_tree_and_does_not_warn(#[fixture(cgroup)] _group: &Group) {
crate::tokio::test_runtime::assert_current_thread();
use ::tokio::io::AsyncReadExt as _;
crate::log_capture::install();
let mut cmd = Command::new();
cmd.args(["sh", "-c", "exec 3<&0; cat <&3 3<&- & echo started; exit 0"]);
cmd.contain_with(ContainMode::Strongest);
cmd.stdin(crate::Stdio::pipe_in()).expect("stdin pipe");
cmd.stdout(crate::Stdio::pipe_out()).expect("stdout pipe");
cmd.stderr(crate::Stdio::pipe_out()).expect("stderr pipe");
let mut child = cmd.spawn().expect("spawn");
assert_eq!(child.containment(), Containment::CgroupV2);
let leaf = match &child.os.attached {
crate::containment::Attached::Cgroup(leaf) => leaf.path().to_path_buf(),
other => panic!("a cgroup child holds its leaf, got {other:?}"),
};
let mut started = [0u8; 8];
child
.stdout()
.expect("stdout pipe")
.read_exact(&mut started)
.await
.expect("read `started`");
let _stdin = child.stdin().expect("stdin pipe");
let mut stderr = child.stderr().expect("stderr pipe");
child.wait().await.expect("reap the root");
let mark = crate::log_capture::mark();
drop(child);
assert_eq!(drop_warns_since(mark), []);
let mut rest = Vec::new();
stderr
.read_to_end(&mut rest)
.await
.expect("the cgroup kill ended the cat, closing stderr, with stdin still held");
cgroup_common::drain_and_remove_leaf(&leaf);
}
#[track_caller]
fn assert_skipped_at_debug(mark: usize) {
let records = drop_warns_since(mark);
assert_eq!(records.len(), 1, "exactly one skip record, got {records:?}");
assert_eq!(records[0].0, log::Level::Debug, "{records:?}");
}
#[cfg(target_os = "macos")]
#[skuld::test]
async fn fd_marker_drop_after_wait_sweeps_the_marker_holders_but_names_nothing_by_the_roots_number() {
crate::tokio::test_runtime::assert_current_thread();
use ::tokio::io::AsyncReadExt as _;
crate::log_capture::install();
let recorder = record_kill_group();
let walks = record_walks();
let sweeps = crate::containment::fdmarker::fault::record_holder_kills();
let mut cmd = Command::new();
cmd.args(["sh", "-c", "exec 3<&0; cat <&3 3<&- >/dev/null & echo started; exit 0"]);
cmd.contain_with(ContainMode::Strongest);
cmd.stdin(crate::Stdio::pipe_in()).expect("stdin pipe");
cmd.stdout(crate::Stdio::pipe_out()).expect("stdout pipe");
cmd.stderr(crate::Stdio::pipe_out()).expect("stderr pipe");
let mut child = cmd.spawn().expect("spawn");
assert_eq!(child.containment(), Containment::FdMarker);
let mut out = String::new();
child
.stdout()
.expect("stdout pipe")
.read_to_string(&mut out)
.await
.expect("read stdout to the root's exit");
assert_eq!(out, "started\n");
let _stdin = child.stdin().expect("stdin pipe");
let mut stderr = child.stderr().expect("stderr pipe");
child.wait().await.expect("reap the root");
let mark = crate::log_capture::mark();
drop(child);
assert_eq!(recorder.killed(), Vec::<i32>::new(), "no killpg after the reap");
assert_eq!(walks.walked(), Vec::<u32>::new(), "no ppid walk from the reaped root");
assert!(!sweeps.killed().is_empty(), "the marker-holder sweep still runs");
assert_eq!(drop_warns_since(mark).len(), 1);
let mut rest = Vec::new();
stderr
.read_to_end(&mut rest)
.await
.expect("the sweep ended the cat, closing stderr, with stdin still held");
}
#[cfg(target_os = "macos")]
async fn reaped_sleep_root(mode: ContainMode) -> (u32, crate::tokio::Child) {
let mut cmd = Command::new();
cmd.args(["sleep", "300"]);
cmd.contain_with(mode);
let mut child = cmd.spawn().expect("spawn");
assert_eq!(child.containment(), Containment::FdMarker);
let pid = child.id().pid();
child.kill().expect("kill the root");
child.wait().await.expect("reap the root");
(pid, child)
}
#[cfg(target_os = "macos")]
#[skuld::test]
async fn fd_marker_without_a_group_drop_after_wait_only_sweeps_the_marker_holders() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let walks = record_walks();
let (pid, child) = reaped_sleep_root(ContainMode::TreeWalk).await;
let mark = crate::log_capture::mark();
drop(child);
assert_eq!(walks.walked(), Vec::<u32>::new(), "no ppid walk from the reaped root");
let warns = drop_warns_since(mark);
assert_eq!(warns.len(), 1, "{warns:?}");
assert!(warns[0].1.contains(&format!("root pid {pid}")), "{warns:?}");
}
#[cfg(target_os = "macos")]
#[skuld::test]
async fn fd_marker_with_a_group_drop_after_wait_neither_signals_the_group_nor_walks() {
crate::tokio::test_runtime::assert_current_thread();
crate::log_capture::install();
let recorder = record_kill_group();
let walks = record_walks();
let (pid, child) = reaped_sleep_root(ContainMode::Strongest).await;
let mark = crate::log_capture::mark();
drop(child);
assert_eq!(recorder.killed(), Vec::<i32>::new(), "no killpg after the reap");
assert_eq!(walks.walked(), Vec::<u32>::new(), "no ppid walk from the reaped root");
let warns = drop_warns_since(mark);
assert_eq!(warns.len(), 1, "{warns:?}");
assert!(warns[0].1.contains(&format!("pgid {pid}")), "{warns:?}");
}