use std::cell::RefCell;
use super::SignalTreeCooperativelyOutcome;
use crate::child::owned::slot::ChildSlot;
use crate::child::owned::OwnedChild;
use crate::containment::fake::FakeContains;
use crate::containment::{Containment, Refusal, Skip, SkipCall, TerminateOutcome, Why};
use crate::elevation::front::{Front, TrackedKind};
use crate::error::{ElevationErrorKind, Error};
use crate::log_capture::warns_since;
use crate::os_process::child::PeekOutcome;
use crate::os_process::fake::{FakeProcess, SignalAnswer};
use crate::signal::Sent;
use crate::signal::Sig;
use crate::test_child::over_fake::child_with;
use crate::test_child::reaped_elsewhere::{ROOT_KILLED_BY_PIDFD, ROOT_TERMED_BY_PIDFD};
const PGID: i32 = 999_999;
fn graceful_call() -> SkipCall<'static> {
SkipCall {
op: "graceful_shutdown_tree",
pid: PGID as u32,
signal: Sig::Graceful(crate::signal::Signal::Term),
earlier: None,
}
}
fn skip() -> Skip {
Skip {
action: format!("signal its process group (pgid {PGID})"),
why: Why::MayNameAnother(
Refusal::Unsure(PGID as u32, std::sync::Arc::new(std::io::Error::other("forced"))),
None,
),
root_alone: true,
holders: None,
}
}
fn assert_names_the_skip(err: &Error) {
let Error::Unassessable { detail, .. } = err else {
panic!("{err:?}")
};
let said = format!(
"graceful_shutdown_tree(): the root's own handle could not say whether it (pid {PGID}) was reaped, \
so its number may name another process; it did not signal its process group (pgid {PGID}), and "
);
assert!(detail.starts_with(&said), "{detail}");
assert!(!detail.contains("forced"), "{detail}");
assert!(crate::error::said(err).contains("forced"), "{err:?}");
}
#[derive(Clone, Copy)]
enum LiveBox {
Own,
Osascript,
SudoOutsideACgroup,
}
fn run(
kind: LiveBox,
term: SignalAnswer,
exited: Option<Result<bool, std::io::Error>>,
kill: Result<Sent, Error>,
) -> (Error, Vec<&'static str>, Vec<String>) {
crate::log_capture::install();
let call = graceful_call();
let sent = RefCell::new(Vec::new());
let mark = crate::log_capture::mark();
let root = FakeProcess::new([])
.peeks_always(|| Ok(PeekOutcome::Running))
.with_exact_consume(false)
.signals([term]);
let (tree, _) = FakeContains::new(Containment::Session, false);
let mut child = child_with(
&root,
tree.answering_terminates([TerminateOutcome::RootThroughPidfd(skip())]),
);
child.proc = ChildSlot::new(OwnedChild::new(
Box::new(root.clone().with_pid(child.pid())),
match kind {
LiveBox::Own => TrackedKind::Own,
LiveBox::Osascript => TrackedKind::Front(Front::Osascript),
LiveBox::SudoOutsideACgroup => TrackedKind::Front(Front::Sudo),
},
));
let outcome = super::shutdown::run_ready(super::shutdown::signal_tree_cooperatively(
&super::shutdown::BlockingDriver(&child),
));
if !root.signal_calls().is_empty() {
sent.borrow_mut().push("term");
}
let SignalTreeCooperativelyOutcome::RootThroughPidfd(skip, shutdown, _, acted) = outcome else {
let SignalTreeCooperativelyOutcome::End(refused) = outcome else {
panic!("the stop ended neither on its pidfd nor on a refusal");
};
return (refused, sent.into_inner(), warns_since(mark, ""));
};
assert!(acted.is_none(), "the default action answered Ok: {acted:?}");
let waited = shutdown.needs_grace().then(|| {
sent.borrow_mut().push("grace");
exited.unwrap_or(Ok(true)).map_err(Error::Io)
});
let err = shutdown.finish(&call, &skip, waited, || match kind {
LiveBox::SudoOutsideACgroup => child.proc.kill_root_only(None),
LiveBox::Own | LiveBox::Osascript => {
sent.borrow_mut().push("kill");
kill
}
});
(err, sent.into_inner(), warns_since(mark, ""))
}
#[skuld::test]
fn a_front_the_sigterm_may_not_reach_is_refused_with_nothing_sent() {
let (err, sent, warns) = run(
LiveBox::Osascript,
Ok(Sent::Delivered),
Some(Ok(true)),
Ok(Sent::Delivered),
);
assert!(
matches!(&err, Error::Elevation { kind: ElevationErrorKind::Unkillable, detail, .. }
if detail.contains("is osascript") && detail.contains("no signal was sent")),
"{err:?}"
);
assert_eq!(sent, Vec::<&str>::new());
assert_eq!(warns, Vec::<String>::new());
}
#[skuld::test]
fn a_failed_grace_wait_kills_the_root_at_once_and_is_in_the_answer() {
let (err, sent, warns) = run(
LiveBox::Own,
Ok(Sent::Delivered),
Some(Err(std::io::Error::other("forced wait failure"))),
Ok(Sent::Delivered),
);
assert_names_the_skip(&err);
assert_eq!(sent, ["term", "grace", "kill"]);
assert_eq!(warns.len(), 1, "{warns:?}");
assert!(warns[0].contains(ROOT_KILLED_BY_PIDFD), "{warns:?}");
let below = err.failures_below();
assert!(
matches!(&below[..], [cause, watch]
if crate::error::said(*cause).contains("forced")
&& crate::error::said(*watch) == crate::error::io_said("forced wait failure")),
"{below:?}"
);
}
#[skuld::test]
fn a_failed_grace_wait_and_a_failed_kill_are_both_in_the_answer_in_order() {
let (err, sent, _) = run(
LiveBox::Own,
Ok(Sent::Delivered),
Some(Err(std::io::Error::other("forced wait failure"))),
Err(Error::Io(std::io::Error::other("forced kill failure"))),
);
assert_eq!(sent, ["term", "grace", "kill"]);
assert!(
matches!(&err, Error::Unassessable { detail, .. }
if detail.contains("then the kill of the root through its pidfd failed")
&& !detail.contains("forced kill failure")),
"the failure is below the answer, not in its words: {err:?}"
);
let below: Vec<_> = err
.failures_below()
.into_iter()
.map(|failure| crate::error::said(failure))
.collect();
assert_eq!(below.len(), 3, "{below:?}");
assert!(below[0].contains("forced"), "{below:?}");
assert_eq!(below[1], crate::error::io_said("forced kill failure"), "{below:?}");
assert_eq!(below[2], crate::error::io_said("forced wait failure"), "{below:?}");
}
#[skuld::test]
fn a_front_the_kill_may_not_reach_is_refused_after_the_grace() {
let (err, sent, warns) = run(
LiveBox::SudoOutsideACgroup,
Ok(Sent::Delivered),
Some(Ok(false)),
Ok(Sent::Delivered),
);
assert!(
matches!(&err, Error::Elevation { kind: ElevationErrorKind::Unkillable, detail, .. }
if detail.contains("sudo")
&& detail.contains("no kill was sent.")
&& detail.contains("Only a cgroup (Linux containment) that holds it reaches the program.")),
"{err:?}"
);
assert_eq!(sent, ["term", "grace"]);
assert_eq!(warns.len(), 1, "{warns:?}");
assert!(
warns[0].contains("then the kill of the root through its pidfd failed"),
"{warns:?}"
);
}
#[skuld::test]
fn a_failed_sigterm_waits_no_grace_and_is_the_error() {
let forced = || std::io::Error::other("forced term failure");
let (err, sent, warns) = run(LiveBox::Own, Err(forced()), None, Ok(Sent::Delivered));
assert!(
matches!(&err, Error::Unassessable { detail, .. }
if detail.contains("the SIGTERM to the root through its pidfd failed")
&& !detail.contains("forced term failure")),
"the failure is below the answer, not in its words: {err:?}"
);
assert!(
matches!(err.failures_below().get(1), Some(Error::Io(e)) if e.to_string() == "forced term failure"),
"{err:?}"
);
assert_eq!(sent, ["term"]);
assert_eq!(warns.len(), 1, "{warns:?}");
let said = format!(
"sent nothing: the SIGTERM to the root through its pidfd failed ({})",
crate::error::said(&Error::Io(forced()))
);
assert!(warns[0].contains(&said), "{warns:?}");
}
#[skuld::test]
fn a_sigterm_that_reached_nothing_waits_no_grace() {
for (term, says) in [
(Sent::Gone, "sent nothing: the root's pidfd shows it is gone"),
(Sent::Unverified, "sent nothing: the root's handle no longer reaches it"),
] {
let (err, sent, warns) = run(LiveBox::Own, Ok(term), None, Ok(Sent::Delivered));
assert_names_the_skip(&err);
assert_eq!(sent, ["term"], "{says}");
assert_eq!(warns.len(), 1, "{says}: {warns:?}");
assert!(warns[0].contains(says), "{warns:?}");
assert!(!warns[0].contains(ROOT_TERMED_BY_PIDFD), "{warns:?}");
}
}
#[skuld::test]
fn a_kill_that_finds_the_root_gone_says_so() {
let (err, sent, warns) = run(LiveBox::Own, Ok(Sent::Delivered), Some(Ok(false)), Ok(Sent::Gone));
assert_names_the_skip(&err);
assert_eq!(sent, ["term", "grace", "kill"]);
assert_eq!(warns.len(), 1, "{warns:?}");
assert!(
warns[0].contains("its pidfd showed it gone after the grace"),
"{warns:?}"
);
assert!(!warns[0].contains(ROOT_KILLED_BY_PIDFD), "{warns:?}");
}