use std::io::Read as _;
use crate::test_child::Console;
use crate::send_log::{Capture, GroupStep, Route};
use crate::test_child::member::{await_started, Member, RELEASE_FD, ROOT_WITH_A_MEMBER};
use crate::test_child::reaped_elsewhere::{foreign_reaped_group_root, kill_own_child, reap_behind};
use crate::test_groups::{pidfd_group_signal, stray_signal, Group};
pub(crate) fn root_with_a_member() -> (crate::Child, Member) {
let (stdio, started, member) = Member::pipes();
let child = {
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(ROOT_WITH_A_MEMBER);
cmd.contain_with(crate::ContainMode::Session);
cmd.stdin(stdio.stdin).expect("set stdin");
cmd.stdout(stdio.stdout).expect("set stdout");
cmd.stderr(stdio.stderr).expect("set stderr");
cmd.fd(RELEASE_FD, stdio.release).expect("set the release fd");
cmd.spawn().expect("spawn")
};
await_started(started);
(child, member)
}
pub(crate) struct EndedAtTheSigterm {
said: std::rc::Rc<std::cell::RefCell<Option<String>>>,
hook: crate::oneshot_hook::Armed,
}
impl EndedAtTheSigterm {
pub(crate) fn new(member: Member) -> EndedAtTheSigterm {
let said = std::rc::Rc::new(std::cell::RefCell::new(None));
let hook = crate::graceful_hooks::at(crate::graceful_hooks::HookPoint::AfterTerminate, {
let said = said.clone();
move || *said.borrow_mut() = Some(member.end())
});
EndedAtTheSigterm { said, hook }
}
#[track_caller]
pub(crate) fn assert_killed_by_the_sigterm(self) {
let EndedAtTheSigterm { said, hook } = self;
drop(hook);
let said = said.take().expect("the shutdown reached the end of its SIGTERM");
assert!(
!said.contains("survived"),
"the group's member outlived the SIGTERM: {said:?}"
);
}
}
#[skuld::test]
fn kill_tree_kills_the_group_of_a_root_reaped_elsewhere(#[fixture(pidfd_group_signal)] _group: &Group) {
let (child, member) = root_with_a_member();
let pid = child.pid();
kill_own_child(pid);
reap_behind(pid);
let capture = Capture::start();
let result = child.kill_tree();
let steps = capture.group_steps();
result.expect("the group is killed through the root's pidfd");
assert_eq!(
steps.first(),
Some(&GroupStep::Group(Route::Pidfd, libc::SIGKILL)),
"{steps:?}"
);
member.assert_killed();
}
#[skuld::test]
fn kill_tree_of_a_root_reaped_elsewhere_with_no_member_left_sends_nothing(
#[fixture(pidfd_group_signal)] _group: &Group,
#[fixture(stray_signal)] _stray: &Group,
) {
let (child, _pgid) = foreign_reaped_group_root();
let capture = Capture::start();
let result = child.kill_tree();
let steps = capture.group_steps();
result.expect("an empty group is killed already");
assert_eq!(steps, [], "nothing was sent");
}
#[skuld::test]
fn kill_tree_below_6_9_sends_nothing_to_the_group_after_this_handles_own_reap() {
let (child, member) = root_with_a_member();
kill_own_child(child.pid());
child.wait().expect("this handle reaps the root");
let old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
let refused = crate::containment::unix::fault::refuse_group_sends();
let groups = crate::containment::unix::fault::record_kill_group();
let capture = Capture::start();
let result = child.kill_tree();
let steps = capture.group_steps();
drop((old_kernel, refused));
assert_eq!(groups.killed(), Vec::<i32>::new(), "no kill of the group by its number");
let err = result.expect_err("a group the pid no longer names is not assessable");
assert!(
err.to_string()
.contains(crate::child::drop_report::END_THEM_BEFORE_WAIT),
"{err}"
);
assert_eq!(steps, [], "nothing was sent to the group");
member.assert_survived();
}
#[skuld::test]
fn kill_tree_after_this_handles_own_reap_kills_the_group_through_the_pidfd_while_it_has_a_member(
#[fixture(pidfd_group_signal)] _group: &Group,
) {
let (child, member) = root_with_a_member();
kill_own_child(child.pid());
child.wait().expect("this handle reaps the root");
let _gone = crate::child::fault::force_root_reads(crate::identity::Resolved::Gone);
let capture = Capture::start();
let result = child.kill_tree();
let steps = capture.group_steps();
result.expect("the group is killed through the root's pidfd");
assert_eq!(
steps.first(),
Some(&GroupStep::Group(Route::Pidfd, libc::SIGKILL)),
"{steps:?}"
);
member.assert_killed();
}
#[skuld::test]
fn kill_tree_of_a_root_its_handle_cannot_read_kills_its_group_through_the_pidfd(
#[fixture(pidfd_group_signal)] _group: &Group,
) {
let (mut child, member) = root_with_a_member();
let capture = Capture::start();
let fake = child
.proc
.script_over(|f| f.peeks([Err(std::io::Error::other("forced peek failure"))]));
let result = child.kill_tree();
fake.assert_peeks_exhausted();
let steps = capture.group_steps();
result.expect("the group is killed through the root's pidfd");
assert_eq!(
steps.first(),
Some(&GroupStep::Group(Route::Pidfd, libc::SIGKILL)),
"{steps:?}"
);
member.assert_killed();
}
pub(crate) struct EmptiedGroup {
root: crate::Child,
stdin: crate::PipeWriter,
stdout: crate::PipeReader,
stderr: crate::PipeReader,
other: std::process::Child,
}
impl EmptiedGroup {
pub(crate) fn new() -> EmptiedGroup {
use crate::test_child::{await_member_ready, member_command};
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args([
"sh",
"-c",
r#"exec 3<&0; sh -c 'read _ <&3; exec setsid sh -c "echo left; exec cat <&3 3<&- >/dev/null"' & echo started; exec cat 3<&- 2>/dev/null"#,
]);
cmd.contain_with(crate::ContainMode::Session);
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 root = cmd.spawn().expect("spawn the root");
let mut stdout = root.stdout().expect("stdout pipe");
let mut started = [0u8; 8];
stdout.read_exact(&mut started).expect("read `started`");
assert_eq!(&started, b"started\n");
let (stdin, stderr) = (root.stdin().expect("stdin pipe"), root.stderr().expect("stderr pipe"));
let pid = root.pid();
kill_own_child(pid);
reap_behind(pid);
let mut other = crate::test_spawn::spawn(&mut member_command(0)).expect("spawn the other group's leader");
await_member_ready(&mut other);
EmptiedGroup {
root,
stdin,
stdout,
stderr,
other,
}
}
pub(crate) fn arm(self) -> (crate::Child, Armed) {
use std::io::Write as _;
let EmptiedGroup {
root,
stdin,
mut stdout,
stderr,
other,
} = self;
let refused = crate::containment::unix::fault::refuse_group_sends();
let listed = crate::containment::unix::fault::list_instead(other.id() as i32);
let mut tell = stdin.try_clone().expect("clone stdin");
let left = crate::containment::unix::fault::set_after_listing(move || {
tell.write_all(b"\n").expect("tell the member to leave");
let mut left = [0u8; 5];
stdout.read_exact(&mut left).expect("read `left`");
assert_eq!(&left, b"left\n");
});
let armed = Armed {
guard: Box::new((refused, listed, left)),
stdin,
stderr,
other,
};
(root, armed)
}
}
pub(crate) struct Armed {
guard: Box<dyn std::any::Any>,
stdin: crate::PipeWriter,
stderr: crate::PipeReader,
other: std::process::Child,
}
impl Armed {
pub(crate) fn finish(self) {
use std::os::unix::process::ExitStatusExt as _;
let Armed {
guard,
stdin,
mut stderr,
mut other,
} = self;
drop(guard);
drop(other.stdin.take());
let status = other.wait().expect("reap the other group's leader");
drop(stdin);
let mut rest = Vec::new();
stderr.read_to_end(&mut rest).expect("read stderr to the member's end");
assert_eq!(
status.signal(),
None,
"the other group's leader was signalled: {status:?}"
);
}
}
#[skuld::test]
fn kill_tree_leaves_alone_a_group_that_took_the_number_of_its_emptied_group(
#[fixture(pidfd_group_signal)] _group: &Group,
) {
let (child, armed) = EmptiedGroup::new().arm();
let root = child.pid();
let capture = Capture::start();
let result = child.kill_tree();
let sent = capture.by_identity();
armed.finish();
result.expect("the tree is gone");
assert!(
sent.iter().all(|&(pid, _)| pid == root),
"nothing was resent to a member: {sent:?}"
);
}
#[skuld::test]
fn terminate_tree_leaves_alone_a_group_that_took_the_number_of_its_emptied_group(
#[fixture(pidfd_group_signal)] _group: &Group,
) {
let (child, armed) = EmptiedGroup::new().arm();
let refusing = crate::containment::unix::fault::refuse_probes();
let result = child.terminate_tree();
drop(refusing);
armed.finish();
result.expect("the tree is gone");
}
pub(crate) const STATUS_REAPED_ELSEWHERE: &str = "exit status cannot be collected: the root was reaped elsewhere";
#[track_caller]
pub(crate) fn assert_down_without_status(result: Result<std::process::ExitStatus, crate::error::Error>, mark: usize) {
match result {
Err(crate::error::Error::Unassessable {
detail,
source: Some(cause),
}) => {
assert!(detail.contains(STATUS_REAPED_ELSEWHERE), "{detail}");
assert_eq!(crate::error::first_os_code(&*cause), Some(libc::ECHILD), "{cause:?}");
}
other => panic!("expected the tree down without the root's status, got {other:?}"),
}
let mut warns = crate::log_capture::warns_since(mark, "");
warns.retain(|warn| !warn.contains("forgetting tokio's handle for it leaks"));
assert_eq!(warns, Vec::<String>::new(), "nothing was left behind");
}
#[skuld::test]
fn terminate_tree_signals_the_group_of_a_root_reaped_elsewhere(#[fixture(pidfd_group_signal)] _group: &Group) {
let (child, member) = root_with_a_member();
let pid = child.pid();
kill_own_child(pid);
reap_behind(pid);
let capture = Capture::start();
let result = child.terminate_tree();
let steps = capture.group_steps();
result.expect("the group is signalled through the root's pidfd");
assert_eq!(
steps.first(),
Some(&GroupStep::Group(Route::Pidfd, libc::SIGTERM)),
"{steps:?}"
);
member.assert_killed();
}
#[skuld::test]
fn terminate_tree_of_a_root_reaped_elsewhere_with_no_member_left_sends_nothing(
#[fixture(pidfd_group_signal)] _group: &Group,
#[fixture(stray_signal)] _stray: &Group,
) {
let (child, _pgid) = foreign_reaped_group_root();
let capture = Capture::start();
let result = child.terminate_tree();
let steps = capture.group_steps();
result.expect("an empty group has nothing to signal");
assert_eq!(steps, [], "nothing was sent");
}
#[skuld::test]
fn graceful_shutdown_tree_shuts_down_the_group_of_a_root_reaped_elsewhere(
#[fixture(pidfd_group_signal)] _group: &Group,
) {
crate::log_capture::install();
let (child, member) = root_with_a_member();
let pid = child.pid();
kill_own_child(pid);
reap_behind(pid);
let mark = crate::log_capture::mark();
let ended = EndedAtTheSigterm::new(member);
let capture = Capture::start();
let result = child.graceful_shutdown_tree(std::time::Duration::from_secs(1));
let steps = capture.group_steps();
assert_eq!(
steps.first(),
Some(&GroupStep::Group(Route::Pidfd, libc::SIGTERM)),
"{steps:?}"
);
ended.assert_killed_by_the_sigterm();
assert_down_without_status(result, mark);
}
#[skuld::test]
fn graceful_shutdown_tree_of_a_root_reaped_elsewhere_with_no_member_left_sends_nothing(
#[fixture(pidfd_group_signal)] _group: &Group,
#[fixture(stray_signal)] _stray: &Group,
) {
crate::log_capture::install();
let (child, _pgid) = foreign_reaped_group_root();
let mark = crate::log_capture::mark();
let capture = Capture::start();
let result = child.graceful_shutdown_tree(std::time::Duration::from_secs(1));
let steps = capture.group_steps();
assert_eq!(steps, [], "nothing was sent");
assert_down_without_status(result, mark);
}