use std::io;
use super::teardown::{child_with_an_unreadable_exit, exit, fake, id};
use crate::child::owned::teardown::{Disposition, TeardownOutcome};
pub(crate) use crate::child::owned::teardown::{LEAVING_RUNNING, LEFT};
use crate::child::owned::OwnedChild;
use crate::error::Error;
use crate::os_process::child::Foreign;
use crate::os_process::fake::ReapAnswer;
use crate::signal::Sent;
pub(crate) const PID: u32 = super::teardown::PID;
pub(crate) const HANDED_BACK: &str = "; handed back to the caller in the error";
const REFUSED: &str = "cosca-refused-5b0e";
pub(crate) fn wait_error() -> String {
crate::error::io_said("other error")
}
pub(crate) fn refusal() -> String {
crate::error::io_said(REFUSED)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Kill {
Delivered,
Nothing,
Refused,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Found {
Exited,
Unreadable,
ReapedElsewhere,
Orphaned,
WaitFailed,
Running,
}
pub(crate) struct Row {
pub(crate) kill: Kill,
pub(crate) found: Found,
pub(crate) level: log::Level,
pub(crate) uncollected: bool,
pub(crate) leave: String,
pub(crate) hand_back: String,
}
impl Row {
pub(crate) fn clause(&self, disposition: Disposition) -> &str {
match disposition {
Disposition::Leave => &self.leave,
Disposition::HandBack => &self.hand_back,
}
}
}
pub(crate) fn rows() -> Vec<Row> {
use log::Level::{Debug, Warn};
let after_a_kill = format!("teardown of child {PID}");
let after_a_refusal = format!("child {PID} could not be terminated ({})", refusal());
let unreadable = "the child's exit record was unreadable (si_code 7)";
let orphaned = "not ours to reap (launchd holds its zombie, because its tracer died)";
let failed = format!("the wait failed: {}", wait_error());
let same = |kill, found, level, clause: String| Row {
kill,
found,
level,
uncollected: false,
leave: clause.clone(),
hand_back: clause,
};
let by_disposition = |kill, found, clause: String| Row {
kill,
found,
level: Warn,
uncollected: true,
leave: format!("{clause}{LEFT}"),
hand_back: format!("{clause}{HANDED_BACK}"),
};
vec![
same(
Kill::Delivered,
Found::Exited,
Debug,
format!("{after_a_kill}: reaped it after the kill"),
),
same(
Kill::Delivered,
Found::Unreadable,
Warn,
format!("{after_a_kill}: reaped it after the kill; {unreadable}"),
),
same(
Kill::Delivered,
Found::ReapedElsewhere,
Debug,
format!("{after_a_kill}: reaped by someone else"),
),
same(
Kill::Delivered,
Found::Orphaned,
Warn,
format!("{after_a_kill}: {orphaned}"),
),
by_disposition(Kill::Delivered, Found::WaitFailed, format!("{after_a_kill}: {failed}")),
same(
Kill::Nothing,
Found::Exited,
Debug,
format!("{after_a_kill}: reaped it"),
),
same(
Kill::Nothing,
Found::Unreadable,
Warn,
format!("{after_a_kill}: reaped it; {unreadable}"),
),
same(
Kill::Nothing,
Found::ReapedElsewhere,
Debug,
format!("{after_a_kill}: reaped by someone else"),
),
same(
Kill::Nothing,
Found::Orphaned,
Warn,
format!("{after_a_kill}: {orphaned}"),
),
by_disposition(Kill::Nothing, Found::WaitFailed, format!("{after_a_kill}: {failed}")),
same(
Kill::Refused,
Found::Exited,
Debug,
format!("{after_a_refusal}: reaped it"),
),
same(
Kill::Refused,
Found::Unreadable,
Warn,
format!("{after_a_refusal}: reaped it; {unreadable}"),
),
same(
Kill::Refused,
Found::ReapedElsewhere,
Debug,
format!("{after_a_refusal}: reaped by someone else"),
),
same(
Kill::Refused,
Found::Orphaned,
Warn,
format!("{after_a_refusal}: {orphaned}"),
),
by_disposition(Kill::Refused, Found::WaitFailed, format!("{after_a_refusal}: {failed}")),
Row {
kill: Kill::Refused,
found: Found::Running,
level: Warn,
uncollected: true,
leave: format!("{after_a_refusal}{LEAVING_RUNNING}"),
hand_back: format!("{after_a_refusal}{HANDED_BACK}"),
},
]
}
pub(crate) fn said_of(torn: &TeardownOutcome) -> Option<(log::Level, String)> {
torn.said().map(|said| (said.level(), said.text().to_owned()))
}
pub(crate) fn outcome(row: &Row, disposition: Disposition) -> TeardownOutcome {
let kill = crate::child::owned::teardown::Kill {
disposition,
tree: None,
};
let refused = || io::Error::new(io::ErrorKind::PermissionDenied, REFUSED);
if row.found == Found::Unreadable {
let child = child_with_an_unreadable_exit();
return match row.kill {
Kill::Delivered => child.reap_after_tree_kill(&child.teardown_subject(), disposition, None),
Kill::Nothing => child.tear_down(Some(id()), kill, None),
Kill::Refused => child.look_after_refused_kill(Some(id()), Error::Io(refused()), disposition),
};
}
let signal = match row.kill {
Kill::Delivered => Ok(Sent::Delivered),
Kill::Nothing => Ok(Sent::Gone),
Kill::Refused => Err(refused()),
};
OwnedChild::new(Box::new(fake().reaps([reap_answer(row.found)]).signals([signal]))).tear_down(
Some(id()),
kill,
None,
)
}
fn reap_answer(found: Found) -> ReapAnswer {
match found {
Found::Exited => ReapAnswer::Reaped(exit()),
Found::ReapedElsewhere => ReapAnswer::Foreign(Foreign::Gone),
Found::Orphaned => ReapAnswer::Foreign(Foreign::Orphaned),
Found::WaitFailed => ReapAnswer::Err(io::ErrorKind::Other),
Found::Running => ReapAnswer::Running,
Found::Unreadable => unreachable!("the unreadable rows build their own child"),
}
}
pub(crate) fn outcome_after_a_tree_kill(row: &Row, subject: &str, disposition: Disposition) -> TeardownOutcome {
assert_eq!(row.kill, Kill::Delivered, "a tree kill reached the child");
let child = match row.found {
Found::Unreadable => child_with_an_unreadable_exit(),
found => OwnedChild::new(Box::new(fake().reaps([reap_answer(found)]))),
};
child.reap_after_tree_kill(subject, disposition, None)
}
const NEVER_SAID: [&str; 3] = ["not waited on", "torn down through", "left uncollected"];
fn fates() -> [&'static str; 3] {
[HANDED_BACK, LEFT, LEAVING_RUNNING]
}
#[track_caller]
fn assert_one_wording(clause: &str) {
let said: Vec<_> = fates().into_iter().filter(|fate| clause.contains(fate)).collect();
assert!(said.len() <= 1, "{clause:?} says {said:?}");
for old in NEVER_SAID {
assert!(!clause.contains(old), "{clause:?} says {old:?}");
}
if cfg!(windows) {
assert!(!clause.contains("unreaped"), "{clause:?}: Windows has no zombies");
}
}
#[skuld::test]
fn the_teardown_says_every_row_as_the_table_states_it() {
for row in rows() {
for disposition in [Disposition::Leave, Disposition::HandBack] {
let torn = outcome(&row, disposition);
let wanted = row.clause(disposition);
assert_one_wording(wanted);
assert_eq!(torn.uncollected(), row.uncollected, "{:?} {:?}", row.kill, row.found);
assert_eq!(
disposition.hands_back(&torn.remains()),
row.uncollected && disposition == Disposition::HandBack
);
assert_eq!(
said_of(&torn),
Some((row.level, wanted.to_owned())),
"{:?} {:?} {disposition:?}",
row.kill,
row.found
);
}
}
}
#[skuld::test]
fn the_reap_after_a_tree_kill_says_every_delivered_row_as_the_table_states_it() {
for row in rows().into_iter().filter(|row| row.kill == Kill::Delivered) {
for disposition in [Disposition::Leave, Disposition::HandBack] {
let torn = outcome_after_a_tree_kill(&row, &format!("teardown of child {PID}"), disposition);
assert_eq!(torn.uncollected(), row.uncollected, "{:?} {disposition:?}", row.found);
assert_eq!(
said_of(&torn),
Some((row.level, row.clause(disposition).to_owned())),
"{:?} {disposition:?}",
row.found
);
}
}
}
#[skuld::test]
fn the_reap_after_a_tree_kill_is_said_of_the_subject_its_caller_names() {
let plain = format!("teardown of child {PID}");
let front = crate::elevation::front::front_named(Some(PID));
assert_eq!(front, format!("elevation front pid {PID}"));
for row in rows().into_iter().filter(|row| row.kill == Kill::Delivered) {
for disposition in [Disposition::Leave, Disposition::HandBack] {
let torn = outcome_after_a_tree_kill(&row, &front, disposition);
assert_eq!(
said_of(&torn),
Some((row.level, row.clause(disposition).replacen(&plain, &front, 1))),
"{:?} {disposition:?}",
row.found
);
}
}
}
#[skuld::test]
fn every_caller_says_every_row_as_one_line_under_its_own_name() {
crate::log_capture::install();
for row in rows() {
for disposition in [Disposition::Leave, Disposition::HandBack] {
for (label, say) in callers() {
let torn = outcome(&row, disposition);
let mark = crate::log_capture::mark();
say(torn);
assert_eq!(
crate::log_capture::records_since_on_current_thread(mark, ""),
[(row.level, format!("{label}: {}", row.clause(disposition)))],
"{label} {:?} {:?} {disposition:?}",
row.kill,
row.found
);
}
}
}
}
type Say = fn(TeardownOutcome);
fn callers() -> Vec<(&'static str, Say)> {
use crate::containment::dispatch::TeardownCaller;
let mut callers: Vec<(&'static str, Say)> = Vec::new();
#[cfg(unix)]
{
callers.push((TeardownCaller::Drop.label(), |torn| {
say_in_a_report(TeardownCaller::Drop, torn)
}));
callers.push((TeardownCaller::FailedRun.label(), |torn| {
say_in_a_report(TeardownCaller::FailedRun, torn);
}));
callers.push((TeardownCaller::FinishElevated.label(), |torn| {
say_in_a_report(TeardownCaller::FinishElevated, torn);
}));
}
#[cfg(any(target_os = "linux", windows))]
callers.push((TeardownCaller::FailedSpawn.label(), |torn| {
use crate::child::owned::teardown::{Expect, HandleTeardown, Past};
use crate::os_process::child::KillRefusal;
let expect = Expect {
refusal: KillRefusal::Permission,
past: Past::WaitMayFail,
};
HandleTeardown::new(torn, expect).say_as_failed_spawn(&mut crate::child::spawn::Diagnosis::default());
}));
callers
}
#[cfg(unix)]
fn say_in_a_report(caller: crate::containment::dispatch::TeardownCaller, torn: TeardownOutcome) {
use crate::containment::dispatch::DropView;
use crate::signal::RootState;
let view = DropView {
caller,
root_pid: PID,
root: RootState::Unreaped,
tree_killed: false,
};
let mut report = crate::child::drop_report::DropReport::new(&view);
report.fold_clause(torn);
report.emit(&[]);
}