use std::sync::{Arc, Mutex};
use std::time::Duration;
use super::graceful::fault as graceful_fault;
use super::unpinned_public_tests::{
assert_descendant_dies, assert_holders_only, assert_nothing_sent, assert_refused, assert_sent_by_identity,
assert_tree_refused, assert_tree_refused_caused_by, group_blocker, orphan, session_tree, walked_blocker, Cause,
Untrusted, BOTH,
};
use crate::error::Error;
use crate::log_capture::warns_since;
use crate::os_process::child::{Foreign, PeekOutcome};
use crate::os_process::fake::{FakeProcess, ReapAnswer};
use crate::send_log::{Capture, Via};
use crate::signal::Sig;
fn orphan_next_peek(fake: &FakeProcess) -> impl FnOnce() + 'static {
let fake = fake.clone();
move || drop(fake.peeks([Untrusted::Unpinned.result()]))
}
fn orphan_next_reap(fake: &FakeProcess) -> impl FnOnce() + 'static {
let fake = fake.clone();
move || drop(fake.reaps([ReapAnswer::Foreign(Foreign::Orphaned)]))
}
#[skuld::test]
fn graceful_shutdown_of_an_orphaned_root_sends_nothing() {
crate::log_capture::install();
let (mut child, writer) = walked_blocker();
let sends = Capture::start();
let mark = crate::log_capture::mark();
let fake = orphan(&mut child);
let err = child
.graceful_shutdown(Duration::ZERO)
.expect_err("a root this process does not pin is not shut down");
fake.assert_peeks_exhausted();
assert_refused(&err, "terminate");
assert_nothing_sent(&sends);
assert_eq!(warns_since(mark, ""), Vec::<String>::new());
child
.graceful_shutdown(Duration::ZERO)
.expect("a root that reads true is shut down");
assert_ne!(sends.by_identity(), vec![], "the second call sent nothing");
drop(writer);
}
#[skuld::test]
fn graceful_shutdown_does_not_escalate_to_a_root_orphaned_during_the_grace() {
crate::log_capture::install();
let (mut child, writer) = crate::test_child::term_ignoring_blocker();
let pid = child.pid();
let sends = Capture::start();
let mark = crate::log_capture::mark();
let fake = child.proc.script_over(|f| f);
let hook = crate::graceful_hooks::at(
crate::graceful_hooks::HookPoint::BeforeEscalation,
orphan_next_peek(&fake),
);
let err = child
.graceful_shutdown(Duration::ZERO)
.expect_err("a root this process does not pin is not killed");
fake.assert_peeks_exhausted();
assert_refused(&err, "kill");
assert!(
matches!(&err, Error::Unassessable { detail, .. } if detail.contains("though the SIGTERM was sent before it")),
"{err:?}"
);
assert_eq!(
sends.entries(),
vec![(pid, Sig::Graceful(crate::signal::Signal::Term), Via::Identity)],
"the escalation must send nothing to a root we do not pin: the terminate's SIGTERM is the only send"
);
assert_eq!(warns_since(mark, ""), Vec::<String>::new());
drop(hook);
let status = child
.graceful_shutdown(Duration::ZERO)
.expect("a root that reads true is escalated to");
crate::test_child::assert_killed("the term-ignoring root", status);
drop(writer);
}
#[skuld::test]
fn graceful_shutdown_words_a_callers_own_action_in_the_escalations_refusal() {
use crate::test_child::{command, Console, BLOCKER_ARGV};
crate::log_capture::install();
let mut cmd = command(Console::Hidden);
cmd.args(BLOCKER_ARGV.iter().copied());
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
cmd.stdout(crate::Stdio::null()).expect("set stdout null");
cmd.contain();
cmd.graceful_stop(|_| Ok(()));
let mut child = cmd.spawn().expect("spawn");
let writer = child.stdin().expect("piped stdin");
let fake = child.proc.script_over(|f| f);
let hook = crate::graceful_hooks::at(
crate::graceful_hooks::HookPoint::BeforeEscalation,
orphan_next_peek(&fake),
);
let err = child
.graceful_shutdown(Duration::ZERO)
.expect_err("a root this process does not pin is not killed");
fake.assert_peeks_exhausted();
assert_refused(&err, "kill");
assert!(
matches!(&err, Error::Unassessable { detail, .. } if detail.contains("though the stop action was sent before it")),
"{err:?}"
);
drop(hook);
let status = child
.graceful_shutdown(Duration::ZERO)
.expect("a root that reads true is escalated to");
crate::test_child::assert_killed("the blocker", status);
drop(writer);
}
#[skuld::test]
fn graceful_shutdown_of_an_exited_root_launchd_holds_is_refused_without_a_warn() {
use crate::os_process::fake::Answer;
use crate::test_child::over_fake::{child_over, root_looking};
crate::log_capture::install();
let mark = crate::log_capture::mark();
let root = root_looking([Answer::Exited]).reaps([ReapAnswer::Foreign(Foreign::Orphaned)]);
let child = child_over(&root);
let err = child
.graceful_shutdown(Duration::from_secs(3600))
.expect_err("the status of a zombie launchd holds cannot be collected");
assert!(
matches!(&err, Error::Unassessable { detail, source: None }
if detail.contains("graceful_shutdown sent its signals")
&& detail.contains("exit status cannot be collected")
&& detail.contains("launchd")),
"{err:?}"
);
assert_eq!(
root.signal_calls(),
vec![Sig::Graceful(crate::signal::Signal::Term)],
"only the SIGTERM was sent"
);
assert_eq!(root.looks(), 2, "one look at the exit, and the reap's");
assert_eq!(warns_since(mark, ""), Vec::<String>::new());
}
#[skuld::test]
fn wait_timeout_still_warns_of_an_orphaned_root() {
crate::log_capture::install();
let (mut child, writer) = walked_blocker();
let mark = crate::log_capture::mark();
let fake = child
.proc
.script_over(|f| f.reaps([ReapAnswer::Foreign(Foreign::Orphaned)]));
child
.wait_timeout(Duration::ZERO)
.expect_err("a zombie launchd holds is not reaped");
assert_eq!(fake.looks(), 1, "the wait looked once");
let warns = warns_since(mark, "");
assert_eq!(warns.len(), 1, "{warns:?}");
assert!(warns[0].contains("not ours to reap"), "{warns:?}");
drop(writer);
}
#[skuld::test]
fn graceful_shutdown_tree_of_an_untrusted_root_with_no_identity_channel_ends_up_front() {
crate::log_capture::install();
for state in BOTH {
for group in [false, true] {
let groups = crate::containment::unix::fault::record_term_group();
let (mut child, writer) = if group { group_blocker() } else { walked_blocker() };
let sends = Capture::start();
let mark = crate::log_capture::mark();
let hook = crate::graceful_hooks::at(crate::graceful_hooks::HookPoint::AfterTerminate, || {
panic!("the grace wait began on a root this process cannot vouch for")
});
let fake = state.script(&mut child);
let err = child
.graceful_shutdown_tree(Duration::from_secs(3600))
.expect_err("a root this process cannot vouch for is not shut down");
fake.assert_peeks_exhausted();
assert_tree_refused(&err, "graceful_shutdown_tree", state);
assert_nothing_sent(&sends);
assert_eq!(groups.termed(), Vec::<i32>::new(), "{state:?}, group: {group}");
assert_eq!(warns_since(mark, ""), Vec::<String>::new(), "{state:?}, group: {group}");
drop(hook);
child
.graceful_shutdown_tree(Duration::ZERO)
.expect("a root that reads true is shut down");
drop(writer);
}
}
}
#[skuld::test]
fn graceful_shutdown_tree_of_an_untrusted_session_root_signals_its_holders_only() {
crate::log_capture::install();
for state in BOTH {
let groups = crate::containment::unix::fault::record_term_group();
let _holders = crate::containment::fdmarker::fault::record_holder_kills();
let (mut child, writer, descendant, gone) = session_tree();
let sends = Capture::start();
let pid = child.pid();
let mark = crate::log_capture::mark();
let after_terminate: Arc<Mutex<Option<Vec<u32>>>> = Arc::default();
let hook = crate::graceful_hooks::at(crate::graceful_hooks::HookPoint::AfterTerminate, {
let seen = Arc::clone(&after_terminate);
move || {
*seen.lock().expect("the hook's slot") =
Some(crate::containment::fdmarker::fault::holder_kills_so_far())
}
});
let fake = child.proc.script_over(|f| f.peeks([state.result(), state.result()]));
let err = child
.graceful_shutdown_tree(Duration::ZERO)
.expect_err("the sweep reached the holders only, and skipped the rest of the tree");
fake.assert_peeks_exhausted();
assert_holders_only(&err, "graceful_shutdown_tree", state);
drop(hook);
assert_eq!(groups.termed(), Vec::<i32>::new(), "{state:?}");
let mut signalled = after_terminate
.lock()
.expect("the hook's slot")
.clone()
.expect("the terminate ran");
signalled.sort_unstable();
signalled.dedup();
let want = match state {
Untrusted::Unpinned => vec![descendant],
Untrusted::Unknown => {
let mut both = vec![pid, descendant];
both.sort_unstable();
both
}
};
assert_eq!(signalled, want, "{state:?}");
assert_sent_by_identity(&sends, libc::SIGTERM, &want, state);
assert_eq!(warns_since(mark, ""), Vec::<String>::new(), "{state:?}");
assert_descendant_dies(gone);
drop(writer);
}
}
#[skuld::test]
fn graceful_shutdown_tree_decides_its_signal_on_one_look_at_the_root() {
let _termed = crate::containment::unix::fault::record_term_group();
let _killed = crate::containment::unix::fault::record_kill_group();
let (mut child, writer) = group_blocker();
let left: Arc<Mutex<Option<usize>>> = Arc::default();
let fake = child
.proc
.script_over(|f| f.peeks([Ok(PeekOutcome::Running), Ok(PeekOutcome::Foreign(Foreign::Orphaned))]));
let _hook = crate::graceful_hooks::at(crate::graceful_hooks::HookPoint::AfterTerminate, {
let left = Arc::clone(&left);
let fake = fake.clone();
move || *left.lock().expect("the hook's slot") = Some(fake.peeks_left())
});
_ = child.graceful_shutdown_tree(Duration::ZERO);
assert_eq!(
*left.lock().expect("the hook's slot"),
Some(1),
"the signal's decision looked at the root twice"
);
drop(fake.peeks([]));
drop(writer);
}
#[skuld::test]
fn graceful_shutdown_tree_sweep_refuses_a_root_orphaned_during_the_grace() {
crate::log_capture::install();
let (mut child, writer) = walked_blocker();
let pid = child.pid();
let sends = Capture::start();
let mark = crate::log_capture::mark();
let fake = child.proc.script_over(|f| f);
let _hook = crate::graceful_hooks::at(
crate::graceful_hooks::HookPoint::AfterTerminate,
orphan_next_peek(&fake),
);
let err = child
.graceful_shutdown_tree(Duration::ZERO)
.expect_err("a root this process does not pin is not swept");
fake.assert_peeks_exhausted();
assert_tree_refused(&err, "graceful_shutdown_tree", Untrusted::Unpinned);
assert!(
matches!(&err, Error::Unassessable { detail, .. } if detail.contains("though the SIGTERM was sent before it")),
"{err:?}"
);
assert_eq!(
sends.entries(),
vec![(pid, Sig::Graceful(crate::signal::Signal::Term), Via::Identity)]
);
assert!(
!sends.by_identity().iter().any(|(_, signo)| *signo == libc::SIGKILL),
"{:?}",
sends.by_identity()
);
assert_eq!(warns_since(mark, ""), Vec::<String>::new());
drop(writer);
}
#[skuld::test]
fn graceful_shutdown_tree_does_not_reap_an_exited_orphaned_root_after_a_failed_sweep() {
crate::log_capture::install();
let (mut child, writer) = walked_blocker();
let pid = child.pid();
assert_eq!(unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) }, 0);
crate::test_child::wait_until_zombie(pid);
graceful_fault::set_force_terminate(graceful_fault::Forced::Containment);
let mark = crate::log_capture::mark();
let fake = child.proc.script_over(|f| {
f.peeks([Ok(PeekOutcome::Running), Ok(PeekOutcome::Foreign(Foreign::Orphaned))])
.reaps([ReapAnswer::Foreign(Foreign::Orphaned)])
});
let err = child
.graceful_shutdown_tree(Duration::ZERO)
.expect_err("a root this process does not pin is not swept");
fake.assert_peeks_exhausted();
assert_tree_refused_caused_by(&err, "graceful_shutdown_tree", Untrusted::Unpinned, Cause::ForcedTerm);
assert!(
crate::test_child::is_unreaped_child(pid),
"the zombie launchd holds was waited on"
);
assert_eq!(warns_since(mark, ""), Vec::<String>::new());
drop(writer);
}
#[skuld::test]
fn graceful_shutdown_tree_does_not_wait_for_a_root_orphaned_before_its_reap() {
crate::log_capture::install();
let (mut child, writer) = walked_blocker();
let pid = child.pid();
let mark = crate::log_capture::mark();
let fake = child.proc.script_over(|f| f);
let _hook = crate::graceful_hooks::at(crate::graceful_hooks::HookPoint::BeforeReap, orphan_next_reap(&fake));
let err = child
.graceful_shutdown_tree(Duration::ZERO)
.expect_err("the status of a zombie launchd holds cannot be collected");
fake.assert_peeks_exhausted();
assert!(
matches!(&err, Error::Unassessable { detail, source: None } if detail.contains("exit status cannot be collected")),
"{err:?}"
);
assert!(
crate::test_child::is_unreaped_child(pid),
"the zombie launchd holds was waited on"
);
assert_eq!(warns_since(mark, ""), Vec::<String>::new());
drop(writer);
}