use std::time::Duration;
use crate::test_child::Console;
#[cfg(target_os = "linux")]
use crate::test_groups::{cgroup, Group};
use super::fault as term_fault;
use crate::wait::fault;
fn blocker() -> (crate::Child, crate::PipeWriter) {
crate::test_child::held_contained_blocker_on_console(crate::Stdio::pipe())
}
#[cfg(unix)]
type Held = crate::PipeWriter;
#[cfg(windows)]
type Held = std::net::TcpStream;
fn kill_only_blocker() -> (crate::Child, Held) {
#[cfg(unix)]
{
crate::test_child::term_ignoring_blocker()
}
#[cfg(windows)]
{
crate::test_child::ctrl_break::spawn_ignoring_root()
}
}
fn assert_still_running(child: &mut crate::Child, mut stdin: crate::PipeWriter) {
#[cfg(unix)]
{
let mut stdout = child.stdout().expect("piped stdout");
crate::test_child::assert_echoes(&mut stdin, &mut stdout);
}
#[cfg(windows)]
{
use std::io::{Read as _, Write as _};
stdin.write_all(b"x\r\n").expect("write to the blocker");
drop(stdin); let mut output = Vec::new();
child
.stdout()
.expect("piped stdout")
.read_to_end(&mut output)
.expect("read stdout to EOF");
let status = child.wait().expect("the blocker must exit after stdin closes");
assert!(status.success(), "the blocker must exit 0 on EOF, got {status:?}");
assert!(
output.windows(1).any(|w| w == b"x"),
"the blocker's stdout must contain the echoed line, got {output:?}"
);
}
}
fn cleanup(child: &mut crate::Child) {
#[cfg(unix)]
{
child.kill_tree().expect("cleanup sweep");
child.wait().expect("reap");
}
#[cfg(windows)]
{
_ = child.kill_tree();
_ = child.wait();
}
}
#[skuld::test]
fn graceful_tree_watch_error_still_sweeps_and_reaps() {
let (child, stdin) = kill_only_blocker();
fault::set_force_watch_error(true);
let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, stdin);
let err = child
.graceful_shutdown_tree(Duration::from_secs(30))
.expect_err("the watch error must surface");
assert!(
!fault::armed(),
"seam not consumed — the watch did not run on this thread"
);
assert!(matches!(err, crate::error::Error::Io(_)), "got {err:?}");
assert!(
child.proc.exit_seen(),
"root must be swept AND its exit seen despite the watch error"
);
let status = child.wait().expect("cached status — already seen by the graceful op");
crate::test_child::assert_killed("the swept root", status);
}
#[cfg(unix)]
#[skuld::test]
fn graceful_lone_watch_error_still_escalates_and_reaps() {
let (child, stdin) = kill_only_blocker();
fault::set_force_watch_error(true);
let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, stdin);
let err = child
.graceful_shutdown(Duration::from_secs(30))
.expect_err("the watch error must surface");
assert!(
!fault::armed(),
"seam not consumed — the watch did not run on this thread"
);
assert!(matches!(err, crate::error::Error::Io(_)), "got {err:?}");
assert!(
child.proc.exit_seen(),
"child must be killed AND its exit seen despite the watch error"
);
let status = child.wait().expect("cached status — already seen by the graceful op");
crate::test_child::assert_killed("the escalated child", status);
}
#[cfg(unix)]
#[skuld::test]
fn a_failed_lone_reap_is_the_answer_and_the_watch_failure_a_warn_naming_the_call() {
use crate::child::spawn::failure::seams;
use crate::error::Error;
crate::log_capture::install();
let mark = crate::log_capture::mark();
let (child, stdin) = kill_only_blocker();
fault::set_force_watch_error(true);
let _armed = seams::fail_the_next_wait();
let err = child.graceful_shutdown(Duration::ZERO).expect_err("the reap failed");
assert!(
matches!(&err, Error::Io(e) if e.to_string().contains(seams::FAILURE)),
"{err:?}"
);
let logged = crate::log_capture::records_since_on_current_thread(mark, "forced grace-watch failure");
let call = format!("graceful_shutdown({})", child.pid());
assert!(
matches!(&logged[..], [(log::Level::Warn, line)] if line.starts_with(&call)),
"{logged:?}"
);
let status = child.wait().expect("reap the killed child");
crate::test_child::assert_killed("the escalated child", status);
drop(stdin);
}
#[cfg(unix)]
#[skuld::test]
fn graceful_lone_shutdown_of_a_root_reaped_elsewhere_answers_unassessable_with_the_reaps_echild() {
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use crate::test_child::reaped_elsewhere::{kill_own_child, reap_behind, session_cat};
crate::log_capture::install();
let mut child = session_cat().spawn().expect("spawn");
let _stdin = child.stdin().expect("stdin pipe");
let pid = child.pid();
kill_own_child(pid);
reap_behind(pid);
let escalated = Arc::new(AtomicBool::new(false));
let _hook = term_fault::at(term_fault::HookPoint::BeforeEscalation, {
let escalated = Arc::clone(&escalated);
move || escalated.store(true, Ordering::Relaxed)
});
let mark = crate::log_capture::mark();
let err = child
.graceful_shutdown(Duration::ZERO)
.expect_err("a root reaped elsewhere has no exit status");
assert!(
matches!(&err, crate::error::Error::Unassessable { detail, .. }
if detail.contains("exit status cannot be collected: the root was reaped elsewhere")
&& detail.contains("graceful_shutdown sent its signals")),
"{err:?}"
);
assert_eq!(crate::error::first_os_code(&err), Some(libc::ECHILD), "{err:?}");
assert!(
!escalated.load(Ordering::Relaxed),
"a root the watch saw exit was escalated against"
);
assert_eq!(crate::log_capture::warns_since(mark, ""), Vec::<String>::new());
}
#[cfg(unix)]
#[skuld::test]
fn graceful_lone_shutdown_answers_every_foreign_reap_as_unassessable_with_the_echild() {
use crate::os_process::child::Foreign;
use crate::os_process::fake::{Answer, ReapAnswer};
use crate::test_child::over_fake::{child_over, root_looking};
crate::log_capture::install();
for foreign in [Foreign::Gone, Foreign::Other] {
let mark = crate::log_capture::mark();
let root = root_looking([Answer::Exited]).reaps([ReapAnswer::Foreign(foreign)]);
let child = child_over(&root);
let err = child
.graceful_shutdown(Duration::from_secs(3600))
.expect_err("a root reaped elsewhere has no exit status");
assert!(
matches!(&err, crate::error::Error::Unassessable { detail, .. }
if detail.contains("exit status cannot be collected: the root was reaped elsewhere")),
"{foreign:?}: {err:?}"
);
assert_eq!(
crate::error::first_os_code(&err),
Some(libc::ECHILD),
"{foreign:?}: {err:?}"
);
assert_eq!(
root.signal_calls(),
vec![crate::signal::Sig::Term],
"{foreign:?}: no kill"
);
assert_eq!(
crate::log_capture::warns_since(mark, ""),
Vec::<String>::new(),
"{foreign:?}"
);
}
}
#[cfg(unix)]
#[skuld::test]
fn child_graceful_shutdown_graceful_path() {
use std::os::unix::process::ExitStatusExt;
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
let mut child = cmd.spawn().expect("spawn");
let stdin = child.stdin().expect("piped stdin");
let _release = term_fault::release_at(term_fault::HookPoint::AfterTerminate, stdin);
let status = child
.graceful_shutdown(Duration::from_secs(30))
.expect("graceful_shutdown");
assert_eq!(
status.signal(),
Some(libc::SIGTERM),
"graceful path must exit via SIGTERM, got {status:?}"
);
}
#[cfg(unix)]
#[skuld::test]
fn child_graceful_shutdown_tree_graceful_root_sigterm() {
let _warns = crate::log_capture::warn_watch();
use std::os::unix::process::ExitStatusExt;
let (child, stdin) = crate::test_child::held_contained_blocker_without_cgroup(crate::Stdio::pipe());
let _release = term_fault::release_at(term_fault::HookPoint::AfterTerminate, stdin);
let status = child
.graceful_shutdown_tree(Duration::from_secs(30))
.expect("tree graceful");
assert_eq!(
status.signal(),
Some(libc::SIGTERM),
"root must exit via SIGTERM, got {status:?}"
);
}
#[cfg(unix)]
#[skuld::test]
fn child_graceful_shutdown_tree_tears_down_tree() {
let _warns = crate::log_capture::warn_watch();
use std::io::Read as _;
use std::os::unix::process::ExitStatusExt;
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args([
"sh",
"-c",
"exec 3<&0; sh -c 'echo r; read -r _; echo leaf' <&3 3<&- & exec cat",
]);
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
cmd.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
crate::test_child::contain_without_cgroup(&mut cmd);
let mut child = cmd.spawn().expect("spawn");
let stdin = child.stdin().expect("piped stdin");
let mut stdout = child.stdout().expect("piped stdout");
let mut ready = [0u8; 2];
stdout.read_exact(&mut ready).expect("readiness line");
assert_eq!(&ready, b"r\n");
let _release = term_fault::release_at(term_fault::HookPoint::AfterTerminate, stdin);
let status = child
.graceful_shutdown_tree(Duration::from_secs(30))
.expect("tree graceful");
assert_eq!(
status.signal(),
Some(libc::SIGTERM),
"root must exit via SIGTERM, got {status:?}"
);
let mut rest = Vec::new();
stdout
.read_to_end(&mut rest)
.expect("both members are gone, so the pipe ends");
assert!(rest.is_empty(), "nothing was written: {rest:?}");
}
#[cfg(unix)]
#[skuld::test]
fn child_graceful_shutdown_tree_sweeps_survivor_after_graceful_root_exit() {
let _warns = crate::log_capture::warn_watch();
use std::io::Read as _;
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(crate::test_child::TERM_SURVIVOR_TREE_ARGV.iter().copied());
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
cmd.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
crate::test_child::contain_without_cgroup(&mut cmd);
let mut child = cmd.spawn().expect("spawn");
let stdin = child.stdin().expect("piped stdin");
let mut stdout = child.stdout().expect("piped stdout");
let mut ready = [0u8; 2];
stdout.read_exact(&mut ready).expect("readiness line");
assert_eq!(&ready, b"r\n");
let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, stdin);
child
.graceful_shutdown_tree(Duration::from_secs(1))
.expect("tree graceful with survivor");
let mut rest = Vec::new();
stdout
.read_to_end(&mut rest)
.expect("every member is gone, so the pipe ends");
assert!(rest.is_empty(), "the sweep missed a survivor: {rest:?}");
}
#[cfg(unix)]
#[skuld::test]
fn child_graceful_shutdown_escalates() {
let (child, stdin) = crate::test_child::term_ignoring_blocker();
let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, stdin);
let status = child
.graceful_shutdown(Duration::ZERO)
.expect("graceful_shutdown escalates");
crate::test_child::assert_killed("the SIGTERM-ignoring child", status);
}
#[cfg(unix)]
#[skuld::test]
fn child_graceful_shutdown_tree_escalates_with_a_surviving_grandchild() {
let _warns = crate::log_capture::warn_watch();
use std::io::Read as _;
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(crate::test_child::TERM_IGNORING_TREE_ARGV.iter().copied());
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
cmd.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
crate::test_child::contain_without_cgroup(&mut cmd);
let mut child = cmd.spawn().expect("spawn");
let stdin = child.stdin().expect("piped stdin");
let mut stdout = child.stdout().expect("piped stdout");
let mut ready = [0u8; 2];
stdout.read_exact(&mut ready).expect("readiness line");
assert_eq!(
&ready,
b"r
"
);
let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, stdin);
let status = child.graceful_shutdown_tree(Duration::ZERO).expect("tree escalates");
crate::test_child::assert_killed("the SIGTERM-ignoring root", status);
let mut rest = Vec::new();
stdout
.read_to_end(&mut rest)
.expect("every member is gone, so the pipe ends");
assert!(rest.is_empty(), "the sweep missed a grandchild: {rest:?}");
}
#[skuld::test]
fn graceful_tree_terminate_refusal_still_sweeps_and_reaps() {
let (child, stdin) = kill_only_blocker();
let id = child.id().expect(crate::test_child::IDENTITY_READ);
crate::log_capture::install();
let mark = crate::log_capture::mark();
term_fault::set_force_terminate(term_fault::Forced::Containment);
let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, stdin);
let status = child
.graceful_shutdown_tree(std::time::Duration::ZERO)
.expect("a successful sweep must supersede the forced terminate refusal");
crate::test_child::assert_killed("the root", status);
assert!(
crate::log_capture::contains_since(
mark,
&format!(
"graceful_shutdown_tree({pid}): tree confirmed clear; discarding the superseded terminate_tree refusal",
pid = id.pid()
)
),
"the refusal must be logged as discarded, not silently dropped"
);
assert!(
child.proc.exit_seen(),
"root must be swept AND its exit seen despite the forced terminate refusal"
);
}
#[skuld::test]
fn graceful_tree_unassessable_per_member_still_sweeps_and_reaps() {
let (child, stdin) = kill_only_blocker();
let id = child.id().expect(crate::test_child::IDENTITY_READ);
crate::log_capture::install();
let mark = crate::log_capture::mark();
term_fault::set_force_terminate(term_fault::Forced::UnassessablePerMember);
let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, stdin);
let status = child
.graceful_shutdown_tree(std::time::Duration::ZERO)
.expect("a successful sweep must supersede the forced unassessable state");
crate::test_child::assert_killed("the root", status);
assert!(
crate::log_capture::contains_since(
mark,
&format!(
"graceful_shutdown_tree({pid}): tree confirmed clear; discarding the superseded terminate_tree refusal",
pid = id.pid()
)
),
"the refusal must be logged as discarded, not silently dropped"
);
assert!(
child.proc.exit_seen(),
"root must be swept AND its exit seen despite the forced unassessable state"
);
}
#[skuld::test]
fn graceful_tree_unassessable_with_a_source_still_sweeps_and_reaps() {
let (child, stdin) = kill_only_blocker();
term_fault::set_force_terminate(term_fault::Forced::UnassessableMechanism);
let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, stdin);
let status = child
.graceful_shutdown_tree(std::time::Duration::ZERO)
.expect("a successful sweep must supersede the forced check failure");
crate::test_child::assert_killed("the root", status);
assert!(
child.proc.exit_seen(),
"root must be swept AND its exit seen despite the forced check failure"
);
}
#[skuld::test]
fn graceful_tree_io_sweep_error_stays_the_answer_and_the_refusal_and_the_watch_error_are_warns() {
use crate::error::Error;
crate::log_capture::install();
let mark = crate::log_capture::mark();
let (mut child, stdin) = kill_only_blocker();
term_fault::set_force_terminate(term_fault::Forced::Containment);
fault::set_force_watch_error(true);
let _armed = term_fault::ArmedKillTreeError::arm();
let err = child
.graceful_shutdown_tree(Duration::ZERO)
.expect_err("the sweep failed");
assert!(
matches!(&err, Error::Io(e) if e.to_string().contains("forced kill_tree failure")),
"{err:?}"
);
let call = format!("graceful_shutdown_tree({})", child.pid());
let logged = crate::log_capture::records_since_on_current_thread(mark, &call);
assert!(
matches!(&logged[..], [(log::Level::Warn, refusal), (log::Level::Warn, watch)]
if refusal.contains("forced term_group refusal") && watch.contains("forced grace-watch failure")),
"{logged:?}"
);
cleanup(&mut child);
drop(stdin);
}
#[cfg(all(unix, not(target_os = "macos")))]
#[skuld::test]
fn graceful_tree_that_left_members_carries_the_refusal_and_the_watch_error_in_others() {
use crate::containment::treewalk::fault::{self as walk_fault, LeftBehind};
use crate::error::Error;
use std::io::Read as _;
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(crate::test_child::TERM_IGNORING_BLOCKER_ARGV.iter().copied());
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
cmd.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
cmd.contain_with(crate::ContainMode::TreeWalk);
let mut child = cmd.spawn().expect("spawn");
let _stdin = child.stdin().expect("piped stdin");
let mut readiness = [0u8; 1];
child
.stdout()
.expect("piped stdout")
.read_exact(&mut readiness)
.expect("readiness byte");
walk_fault::force_incomplete_once(LeftBehind::Descendant);
term_fault::set_force_terminate(term_fault::Forced::Containment);
fault::set_force_watch_error(true);
let err = child
.graceful_shutdown_tree(Duration::from_millis(200))
.expect_err("a descendant was left");
let Error::MembersLeft { members, others } = &err else {
panic!("expected MembersLeft, got {err:?}");
};
assert!(
members.iter().all(|m| matches!(**m, Error::MemberNotKilled { .. })),
"{err:?}"
);
let Some(Error::Several(others)) = others.as_deref() else {
panic!("expected the refusal and the watch failure in others: {err:?}");
};
let others: Vec<&Error> = others.iter().map(|e| &**e).collect();
assert!(
matches!(others[..], [Error::Containment { .. }, watch]
if crate::error::said(watch).contains("forced grace-watch failure")),
"{others:?}"
);
}
#[skuld::test]
fn a_refused_terminate_is_logged_when_the_reap_fails_after_a_clean_sweep() {
use crate::containment::fake::FakeContains;
use crate::containment::Containment;
use crate::error::Error;
use crate::os_process::fake::{Answer, ReapAnswer};
use crate::test_child::over_fake::{child_with, root_looking};
crate::log_capture::install();
let mark = crate::log_capture::mark();
let root = root_looking([Answer::Exited; 4]).reaps([ReapAnswer::Err(std::io::ErrorKind::PermissionDenied)]);
#[cfg(all(unix, not(target_os = "macos")))]
let root = root.peeks(std::iter::repeat_with(|| Ok(crate::os_process::child::PeekOutcome::Running)).take(32));
let (fake, _) = FakeContains::new(Containment::Session, false);
let child = child_with(&root, fake);
term_fault::set_force_terminate(term_fault::Forced::Containment);
let err = child
.graceful_shutdown_tree(Duration::ZERO)
.expect_err("the reap failed");
assert!(
matches!(&err, Error::Io(e) if e.kind() == std::io::ErrorKind::PermissionDenied),
"{err:?}"
);
let logged = crate::log_capture::records_since_on_current_thread(mark, "forced term_group refusal");
let call = format!("graceful_shutdown_tree({})", child.pid());
assert!(
matches!(&logged[..], [(log::Level::Warn, line)] if line.starts_with(&call)),
"{logged:?}"
);
}
#[cfg(unix)]
#[skuld::test]
fn a_best_effort_reap_that_fails_after_a_failed_sweep_is_logged_once_at_warn() {
use crate::containment::fake::FakeContains;
use crate::containment::Containment;
use crate::error::Error;
use crate::os_process::fake::{Answer, ReapAnswer};
use crate::test_child::over_fake::{child_with, root_looking};
crate::log_capture::install();
let mark = crate::log_capture::mark();
let root = root_looking([Answer::Exited; 4]).reaps([ReapAnswer::Err(std::io::ErrorKind::PermissionDenied)]);
let (fake, _) = FakeContains::new(Containment::Session, false);
let child = child_with(&root, fake);
let _armed = term_fault::ArmedKillTreeError::arm();
let err = child
.graceful_shutdown_tree(Duration::ZERO)
.expect_err("the sweep failed");
assert!(
matches!(&err, Error::Io(e) if e.to_string().contains("forced kill_tree failure")),
"{err:?}"
);
let logged = crate::log_capture::records_since_on_current_thread(mark, "best-effort reap");
assert!(
matches!(&logged[..], [(log::Level::Warn, line)] if line.contains("graceful_shutdown_tree(")),
"{logged:?}"
);
}
#[cfg(unix)]
#[skuld::test]
fn a_best_effort_reap_that_is_not_ready_after_a_failed_sweep_leaves_the_zombie_with_the_handle() {
use crate::containment::fake::FakeContains;
use crate::containment::Containment;
use crate::error::Error;
use crate::os_process::fake::{Answer, ReapAnswer};
use crate::test_child::over_fake::{child_with, root_looking};
crate::log_capture::install();
let mark = crate::log_capture::mark();
let root = root_looking([Answer::Exited; 4]).reaps([ReapAnswer::Recheck]);
let (fake, _) = FakeContains::new(Containment::Session, false);
let child = child_with(&root, fake);
let _armed = term_fault::ArmedKillTreeError::arm();
let err = child
.graceful_shutdown_tree(Duration::ZERO)
.expect_err("the sweep failed");
assert!(
matches!(&err, Error::Io(e) if e.to_string().contains("forced kill_tree failure")),
"{err:?}"
);
assert_eq!(
crate::log_capture::records_since_on_current_thread(mark, "best-effort reap"),
Vec::<(log::Level, String)>::new()
);
}
fn drained_tree_sweep_decision(contain: impl FnOnce(&mut crate::Command), expected: crate::Containment) {
use std::io::Read;
let mut cmd = crate::test_child::command(Console::Asked);
#[cfg(unix)]
{
cmd.args(["sh", "-c", "echo r; exec cat"]);
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
cmd.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
}
#[cfg(windows)]
let (listener, addr) = crate::test_child::registration_rendezvous();
#[cfg(windows)]
{
cmd.executable(std::env::current_exe().expect("current_exe"))
.args(crate::test_child::fixture_argv(
crate::test_child::FIXTURE_REGISTERS_THEN_BLOCKS_TEST,
));
cmd.env(crate::test_child::FIXTURE_REGISTERS_THEN_BLOCKS_ADDR_ENV, addr);
crate::test_reexec::scrub_env(|var| _ = cmd.env_remove(var));
cmd.env(crate::test_child::ack::ACK_ENV, "1");
}
contain(&mut cmd);
#[cfg_attr(
windows,
allow(
unused_mut,
reason = "on windows only .containment()/.graceful_shutdown_tree() are called below, both &self; unix's child.stdout() needs &mut"
)
)]
let mut child = cmd.spawn().expect("spawn");
assert_eq!(child.containment(), expected);
#[cfg(unix)]
let stdin = child.stdin().expect("piped stdin");
#[cfg(unix)]
{
let mut readiness = [0u8; 1];
child
.stdout()
.expect("piped stdout")
.read_exact(&mut readiness)
.expect("readiness byte");
}
#[cfg(windows)]
let _sock = {
let mut sock = crate::test_child::accept_or_die(&listener, child.id().expect(crate::test_child::IDENTITY_READ));
let mut tag = [0u8; 1];
sock.read_exact(&mut tag).expect("registration tag");
sock
};
let authoritative = matches!(
expected,
crate::containment::Containment::CgroupV2 | crate::containment::Containment::JobObject
);
let armed = term_fault::ArmedKillTreeError::arm();
#[cfg(unix)]
let _release = term_fault::release_at(term_fault::HookPoint::AfterTerminate, stdin);
#[cfg(windows)]
let check = {
let pid = child.pid();
term_fault::at_checked(term_fault::HookPoint::AfterTerminate, move || {
crate::test_child::ctrl_break::assert_break_sent_to(pid)
})
};
let result = child.graceful_shutdown_tree(Duration::from_secs(30));
#[cfg(windows)]
check.assert_fired();
if authoritative {
let status = result.expect("an authoritatively-drained tree must not invoke the sweep at all");
assert!(
term_fault::kill_tree_armed(),
"the forced kill_tree failure must still be armed — the sweep was never entered"
);
drop(armed); #[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
assert_eq!(
status.signal(),
Some(libc::SIGTERM),
"graceful root exit, got {status:?}"
);
}
#[cfg(windows)]
assert_eq!(
status.code(),
Some(0xC000013A_u32 as i32),
"the root must die to the console event, not to a loader-init kill or the sweep, got {status:?}"
);
} else {
let err = result.expect_err("a non-authoritative mechanism must always run the sweep");
assert!(
!term_fault::kill_tree_armed(),
"the sweep must have consumed the forced-failure seam"
);
drop(armed); assert!(matches!(err, crate::error::Error::Io(_)), "got {err:?}");
_ = child.kill_tree(); let status = child.wait().expect("the root was observed exited, so it is reaped");
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
assert_eq!(
status.signal(),
Some(libc::SIGTERM),
"the root must die to the SIGTERM, not exit on its own, got {status:?}"
);
}
#[cfg(windows)]
assert_eq!(
status.code(),
Some(0xC000013A_u32 as i32),
"the root must die to the console event, not to the cleanup sweep, got {status:?}"
);
}
}
#[cfg(windows)]
#[skuld::test]
fn graceful_tree_drained_skips_sweep_in_a_job_object() {
drained_tree_sweep_decision(|cmd| _ = cmd.contain(), crate::Containment::JobObject);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn graceful_tree_drained_skips_sweep_in_a_cgroup(#[fixture(cgroup)] _group: &Group) {
drained_tree_sweep_decision(|cmd| _ = cmd.contain(), crate::Containment::CgroupV2);
}
#[cfg(unix)]
#[skuld::test]
fn graceful_tree_drained_still_sweeps_without_an_authoritative_mechanism() {
drained_tree_sweep_decision(
|cmd| _ = crate::test_child::contain_without_cgroup(cmd),
crate::test_child::contain_without_cgroup_gives(),
);
}
#[cfg(unix)]
fn members_remain_still_reaps_an_already_exited_root(mode: crate::ContainMode, swept: impl FnOnce(&crate::Child)) {
use std::io::{Read, Write};
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args([
"sh",
"-c",
"trap '' TERM; exec 3<&0; cat <&3 >/dev/null 3<&- & echo r; read _ <&4; exit 0",
]);
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
cmd.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
cmd.fd(4, crate::Stdio::pipe_in()).expect("set exit-gate pipe");
cmd.contain_with(mode);
let mut child = cmd.spawn().expect("spawn");
let stdin = child.stdin().expect("piped stdin");
let mut exit_gate = child.fd_write_end(4.into()).expect("exit-gate write end");
let mut readiness = [0u8; 1];
child
.stdout()
.expect("piped stdout")
.read_exact(&mut readiness)
.expect("readiness byte");
let id = child.id().expect(crate::test_child::IDENTITY_READ);
exit_gate.write_all(b"x\n").expect("release the root's exit 0");
drop(exit_gate);
assert!(
child.proc.exited_by(None).expect("the root must exit"),
"exited_by must observe the exit, not a timeout (None means unbounded)"
);
assert_eq!(
id.exists(),
crate::identity::Existence::Present,
"the exited root must still be an unreaped zombie before graceful_shutdown_tree runs"
);
term_fault::set_force_kill_tree_error(true);
let err = child
.graceful_shutdown_tree(Duration::from_secs(2))
.expect_err("the forced sweep failure must surface");
assert!(matches!(err, crate::error::Error::Io(_)), "got {err:?}");
assert!(
!term_fault::kill_tree_armed(),
"the sweep must have consumed the forced-failure seam"
);
assert!(
child.proc.exit_seen(),
"an already-exited root's exit must be seen even when the sweep fails"
);
swept(&child);
drop(stdin);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn graceful_tree_members_remain_still_reaps_an_already_exited_root_in_a_cgroup(#[fixture(cgroup)] _group: &Group) {
members_remain_still_reaps_an_already_exited_root(crate::ContainMode::Strongest, |child| {
assert_eq!(child.containment(), crate::containment::Containment::CgroupV2);
child.kill_tree().expect("the leaf is swept by its own handle");
});
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn graceful_tree_with_only_unprovable_members_still_sweeps_in_a_cgroup(#[fixture(cgroup)] _group: &Group) {
use crate::containment::cgroup::fault::{fail_terminate_once, TerminateStep};
let (child, stdin) = kill_only_blocker();
assert_eq!(child.containment(), crate::containment::Containment::CgroupV2);
let _pin = fail_terminate_once(TerminateStep::Pin, libc::EMFILE);
let _release = term_fault::release_at(term_fault::HookPoint::BeforeReap, stdin);
let status = child
.graceful_shutdown_tree(Duration::ZERO)
.expect("the sweep ends the tree the unprovable member left");
crate::test_child::assert_killed("the root", status);
assert!(child.proc.exit_seen(), "the root's exit is seen");
}
#[cfg(unix)]
#[skuld::test]
fn graceful_tree_members_remain_still_reaps_an_already_exited_root_in_a_process_group() {
members_remain_still_reaps_an_already_exited_root(crate::ContainMode::Session, |child| {
assert_eq!(child.containment(), crate::test_child::session_gives());
#[cfg(target_os = "linux")]
let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
child
.kill_tree()
.expect("the root's zombie pins the group's number: the group is killed by it");
});
}
#[cfg(all(unix, not(target_os = "macos")))]
#[skuld::test]
fn graceful_tree_that_left_a_descendant_reaps_the_root_the_backstop_killed_and_returns_the_error() {
use std::io::Read as _;
use crate::containment::treewalk::fault::{self, LeftBehind};
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(crate::test_child::TERM_IGNORING_BLOCKER_ARGV.iter().copied());
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
cmd.stdout(crate::Stdio::pipe()).expect("set stdout pipe");
cmd.contain_with(crate::ContainMode::TreeWalk);
let mut child = cmd.spawn().expect("spawn");
let _stdin = child.stdin().expect("piped stdin");
let mut readiness = [0u8; 1];
child
.stdout()
.expect("piped stdout")
.read_exact(&mut readiness)
.expect("readiness byte");
let id = child.id().expect(crate::test_child::IDENTITY_READ);
assert_eq!(
id.exists(),
crate::identity::Existence::Present,
"precondition: the root runs"
);
fault::force_incomplete_once(LeftBehind::Descendant);
let err = child
.graceful_shutdown_tree(Duration::from_millis(200))
.expect_err("a descendant was left");
assert!(matches!(err, crate::error::Error::MembersLeft { .. }), "{err:?}");
assert!(
child.proc.exit_seen(),
"the root the backstop killed must have its exit seen before the error returns"
);
crate::test_child::assert_killed("the root", child.wait().expect("the root's status is kept"));
}
#[cfg(windows)]
#[skuld::test]
fn windows_graceful_tree_members_remain_surfaces_the_forced_sweep_failure() {
use std::io::Read;
use std::net::TcpListener;
let listener = TcpListener::bind("127.0.0.1:0").expect("bind readiness listener");
let addr = listener.local_addr().expect("local_addr").to_string();
let mut cmd = crate::test_child::command(Console::Asked);
cmd.executable(std::env::current_exe().expect("current_exe"))
.args(crate::test_child::fixture_argv(
crate::test_child::FIXTURE_SURVIVES_GROUP_SIGNAL_TEST,
));
cmd.env(crate::test_child::FIXTURE_SURVIVES_GROUP_SIGNAL_ADDR_ENV, addr);
crate::test_reexec::scrub_env(|var| _ = cmd.env_remove(var));
cmd.env(crate::test_child::ack::ACK_ENV, "1");
cmd.contain();
let child = std::sync::Arc::new(cmd.spawn().expect("spawn"));
let drained = std::sync::Arc::new(crate::test_child::DrainSignal::new());
{
let (child, drained) = (child.clone(), drained.clone());
std::thread::spawn(move || drained.watch(|| child.wait_tree()));
}
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let mut sock = crate::test_child::accept_or_signalled(&listener, &drained);
let mut tag = [0u8; 1];
sock.read_exact(&mut tag).expect("readiness tag");
term_fault::set_force_kill_tree_error(true);
let err = child
.graceful_shutdown_tree(Duration::from_secs(2))
.expect_err("the forced sweep failure must surface");
assert!(matches!(err, crate::error::Error::Io(_)), "got {err:?}");
assert!(
!term_fault::kill_tree_armed(),
"the sweep must have consumed the forced-failure seam"
);
}));
if let Err(e) = child.kill_tree() {
let unwinding = outcome.as_ref().err().map(|p| {
p.downcast_ref::<String>()
.cloned()
.or_else(|| p.downcast_ref::<&str>().map(|s| s.to_string()))
.unwrap_or_default()
});
panic!("cleanup kill_tree failed ({e}); unwinding from: {unwinding:?}");
}
if let Err(payload) = outcome {
std::panic::resume_unwind(payload);
}
}
#[cfg(windows)]
#[skuld::test]
fn death_watch_windows_accept_or_signalled_panics_when_the_tree_drains_before_anything_connects() {
use std::net::TcpListener;
let listener = TcpListener::bind("127.0.0.1:0").expect("bind readiness listener");
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.executable(std::env::current_exe().expect("current_exe"))
.args(crate::test_child::fixture_argv("test_child::__no_such_test__"));
cmd.contain();
let child = cmd.spawn().expect("spawn");
let drained = crate::test_child::DrainSignal::new();
let result = std::thread::scope(|scope| {
scope.spawn(|| drained.watch(|| child.wait_tree()));
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
crate::test_child::accept_or_signalled(&listener, &drained)
}))
});
let payload = result.expect_err("a drained job with no connection must panic");
let message = payload
.downcast_ref::<String>()
.cloned()
.or_else(|| payload.downcast_ref::<&str>().map(|s| s.to_string()))
.expect("string panic payload");
assert!(
message.starts_with("the tree drained (") && message.ends_with(") before anything connected"),
"got: {message:?}"
);
child.wait().expect("reap the root");
}
#[skuld::test]
fn graceful_tree_non_containment_terminate_error_fails_fast() {
let (mut child, stdin) = blocker();
term_fault::set_force_terminate(term_fault::Forced::Unsupported);
let err = child
.graceful_shutdown_tree(std::time::Duration::ZERO)
.expect_err("the forced Unsupported error must surface immediately");
assert!(matches!(err, crate::error::Error::Unsupported { .. }), "got {err:?}");
assert_still_running(&mut child, stdin);
cleanup(&mut child);
}
#[cfg(target_os = "linux")]
struct TreeStandIn<'a> {
child: &'a mut crate::Child,
own: Option<crate::containment::Tree>,
}
#[cfg(target_os = "linux")]
impl<'a> TreeStandIn<'a> {
fn new(child: &'a mut crate::Child, stand_in: crate::containment::Tree) -> TreeStandIn<'a> {
stand_in.disarm().expect("disarm the stand-in");
let own = std::mem::replace(&mut child.tree, stand_in);
TreeStandIn { child, own: Some(own) }
}
}
#[cfg(target_os = "linux")]
impl Drop for TreeStandIn<'_> {
fn drop(&mut self) {
if let Some(own) = self.own.take() {
self.child.tree = own;
}
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn graceful_tree_over_a_leaf_whose_procs_cannot_be_read_fails_fast() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-unreadable-procs-leaf");
std::fs::create_dir_all(leaf_path.join("cgroup.procs")).expect("make cgroup.procs a directory");
let (mut child, stdin) = blocker();
let in_place = TreeStandIn::new(
&mut child,
crate::containment::Tree::contained(crate::containment::Mechanism::Cgroup(
crate::containment::cgroup::test_support::entered_leaf_at(leaf_path),
)),
);
let err = in_place
.child
.graceful_shutdown_tree(std::time::Duration::ZERO)
.expect_err("a leaf that cannot list its members sent nothing");
drop(in_place);
assert_eq!(crate::error::first_os_code(&err), Some(libc::EISDIR), "{err:?}");
assert_still_running(&mut child, stdin);
cleanup(&mut child);
}
#[cfg(unix)]
#[skuld::test]
fn a_holders_only_escalation_whose_wait_fails_answers_the_holders_only_error() {
use crate::containment::fake::FakeContains;
use crate::containment::Containment;
use crate::os_process::fake::Answer;
use crate::test_child::over_fake::{child_with, holders_only_skip, root_looking};
crate::log_capture::install();
let mark = crate::log_capture::mark();
let root = root_looking([Answer::Exited]);
let (fake, _) = FakeContains::new(Containment::Session, false);
let child = child_with(&root, fake.reaching_unobserved(4242));
let skip = holders_only_skip(&child);
let error = super::shutdown::run_ready(super::shutdown::holders_only(
&super::shutdown::BlockingDriver(&child),
skip,
std::time::Duration::ZERO,
));
assert!(
matches!(&error, crate::error::Error::Unassessable { detail, .. }
if detail.contains("sent the SIGTERM only to the marker holders")),
"the answer is the holders-only error: {error}"
);
assert!(
matches!(error.failures_below()[..], [crate::error::Error::Unsupported { .. }]),
"the holders' grace wait's failure is its cause: {error:?}"
);
let waited = crate::log_capture::records_since_on_current_thread(mark, "the wait after a holders-only shutdown");
assert!(
matches!(&waited[..], [(log::Level::Warn, line)]
if line.contains("pid 4242 was killed, but its exit cannot be observed")),
"the member was waited for, and its failure is logged once, at warn: {waited:?}"
);
}