use std::io;
use super::OwnedChild;
use crate::child::lifecycle::{wait_to_exit, Settlement, Wording};
use crate::error::{ChildFate, Error};
use crate::identity::ProcessId;
use crate::os_process::child::KillRefusal;
use crate::os_process::child_named;
use crate::signal::{Sent, Sig};
use crate::wait::teardown_warn::Due;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Disposition {
Leave,
HandBack,
}
impl Disposition {
pub(crate) fn hands_back(self, torn: &Remains) -> bool {
self == Disposition::HandBack && torn.uncollected
}
pub(crate) fn suffix(self, uncollected: bool) -> &'static str {
match (self, uncollected) {
(Disposition::HandBack, true) => "; handed back to the caller in the error",
(Disposition::Leave, true) => LEFT,
(_, false) => "",
}
}
}
pub(crate) const LEFT: &str = if cfg!(unix) {
"; left unreaped"
} else {
"; nothing waits for it"
};
pub(crate) const LEAVING_RUNNING: &str = if cfg!(unix) {
"; leaving it running and unreaped"
} else {
"; leaving it running"
};
pub(crate) fn kill_refused(refused: &impl std::fmt::Display) -> String {
format!("could not be terminated ({refused})")
}
pub(crate) struct Kill<'a> {
pub(crate) disposition: Disposition,
pub(crate) tree: Option<&'a dyn Reach>,
}
pub(crate) trait Reach {
fn reached(&self, child: &OwnedChild) -> io::Result<bool>;
}
#[derive(Debug)]
#[cfg_attr(
windows,
allow(dead_code, reason = "no Windows teardown words a front it looked at yet")
)]
pub(crate) enum LookOutcome {
Ended(Settlement),
LeftRunning,
PlaceUnreadable(io::Error),
SubtreeUnreadable(io::Error),
}
#[cfg_attr(
windows,
allow(dead_code, reason = "no Windows teardown looks at a front through this yet")
)]
#[derive(Debug)]
pub(crate) struct FrontLook {
pub(crate) fate: ChildFate,
pub(crate) look: LookOutcome,
}
#[derive(Debug)]
pub(crate) struct TeardownOutcome {
fate: ChildFate,
said: Option<Wording>,
refused_look: Option<Box<Settlement>>,
refused: Option<io::ErrorKind>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Remains {
pub(crate) fate: ChildFate,
pub(crate) uncollected: bool,
pub(crate) refused: Option<io::ErrorKind>,
}
impl Remains {
#[cfg(unix)]
pub(crate) fn collected(fate: ChildFate) -> Remains {
debug_assert!(
!matches!(fate, ChildFate::Running { .. }),
"a running child is not collected"
);
Remains {
fate,
uncollected: false,
refused: None,
}
}
}
impl TeardownOutcome {
#[cfg(unix)]
pub(crate) fn collected(fate: ChildFate) -> TeardownOutcome {
debug_assert!(
!matches!(fate, ChildFate::Running { .. }),
"a running child is not collected"
);
TeardownOutcome {
fate,
said: None,
refused_look: None,
refused: None,
}
}
#[cfg(unix)]
pub(crate) fn left_uncollected(fate: ChildFate, warn: String) -> TeardownOutcome {
TeardownOutcome::new(fate, Wording::Uncollected(warn))
}
pub(crate) fn new(fate: ChildFate, said: Wording) -> TeardownOutcome {
TeardownOutcome {
fate,
said: Some(said),
refused_look: None,
refused: None,
}
}
pub(crate) fn of_settlement(
settlement: &Settlement,
id: Option<ProcessId>,
subject: &str,
running: Option<&str>,
disposition: Disposition,
) -> TeardownOutcome {
TeardownOutcome::new(
settlement.fate(id),
settlement.wording(subject, running, Some(disposition)),
)
}
#[cfg_attr(
not(feature = "tokio"),
allow(dead_code, reason = "only the async child reads the fate of a second teardown")
)]
pub(crate) fn fate(&self) -> ChildFate {
self.fate
}
pub(crate) fn uncollected(&self) -> bool {
matches!(self.said, Some(Wording::Uncollected(_)))
}
pub(crate) fn remains(&self) -> Remains {
Remains {
fate: self.fate,
uncollected: self.uncollected(),
refused: self.refused,
}
}
#[cfg_attr(
not(unix),
allow(dead_code, reason = "only a Unix cleanup words a refused kill's look")
)]
pub(crate) fn refused_look(&self) -> Option<&Settlement> {
self.refused_look.as_deref()
}
#[cfg_attr(
not(feature = "tokio"),
allow(
dead_code,
reason = "only the async child words a second teardown's clause into its own"
)
)]
pub(crate) fn said(&self) -> Option<&Wording> {
self.said.as_ref()
}
#[cfg_attr(
not(target_os = "linux"),
allow(dead_code, reason = "only the Linux spawn hands an uncollected child on")
)]
pub(crate) fn into_uncollected(self) -> Result<String, TeardownOutcome> {
match self.said {
Some(Wording::Uncollected(warn)) => Ok(warn),
said => Err(TeardownOutcome { said, ..self }),
}
}
pub(crate) fn take_warn(self, label: &str) -> (Option<String>, Remains) {
let remains = self.remains();
let warn = match self.said {
Some(Wording::Uncollected(text) | Wording::Collected(log::Level::Warn, text)) => Some(text),
Some(Wording::Collected(level, text)) => {
log::log!(level, "{label}: {text}");
None
}
None => None,
};
(warn, remains)
}
#[cfg(any(target_os = "linux", windows))]
pub(crate) fn failed_spawn_line(self, why: &mut crate::child::spawn::Diagnosis) -> (Option<String>, Remains) {
let label = crate::containment::dispatch::TeardownCaller::FailedSpawn.label();
let remains = self.remains();
let Some(said) = self.said else {
return (None, remains);
};
let level = said.level();
let text = said.text();
if level == log::Level::Warn || why.is_owed() {
return (Some(format!("{label}: {}", why.fold(text))), remains);
}
log::log!(level, "{label}: {text}");
(None, remains)
}
}
#[cfg_attr(
not(any(target_os = "linux", windows)),
allow(
dead_code,
reason = "only the Linux and Windows spawns tear a child down over a handle"
)
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Past {
Clean,
WaitMayFail,
Unexecuted,
}
#[cfg_attr(
not(any(target_os = "linux", windows)),
allow(
dead_code,
reason = "only the Linux and Windows spawns tear a child down over a handle"
)
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Expect {
pub(crate) refusal: KillRefusal,
pub(crate) past: Past,
}
#[cfg(any(target_os = "linux", windows))]
impl Expect {
pub(crate) fn of(child: &OwnedChild, past: Past) -> Expect {
Expect {
refusal: child.kill_refusal(),
past,
}
}
}
#[cfg_attr(
not(any(target_os = "linux", windows)),
allow(
dead_code,
reason = "only the Linux and Windows spawns tear a child down over a handle"
)
)]
#[derive(Debug)]
pub(crate) struct HandleTeardown {
pub(crate) outcome: TeardownOutcome,
pub(crate) expect: Expect,
}
#[cfg_attr(
not(any(target_os = "linux", windows)),
allow(
dead_code,
reason = "only the Linux and Windows spawns tear a child down over a handle"
)
)]
impl HandleTeardown {
pub(crate) fn new(outcome: TeardownOutcome, expect: Expect) -> HandleTeardown {
HandleTeardown { outcome, expect }
}
#[cfg_attr(
not(target_os = "linux"),
allow(dead_code, reason = "only the Linux spawn hands a pidfd teardown's abandonment on")
)]
pub(crate) fn uncollected(self) -> Result<Left, HandleTeardown> {
let expect = self.expect;
let remains = self.outcome.remains();
self.outcome
.into_uncollected()
.map(|clause| Left {
clause,
remains,
expect,
})
.map_err(|outcome| HandleTeardown { outcome, expect })
}
#[cfg(any(target_os = "linux", windows))]
pub(crate) fn say_as_failed_spawn(self, why: &mut crate::child::spawn::Diagnosis) -> Remains {
let (line, remains) = self.outcome.failed_spawn_line(why);
warn_teardown(line.as_deref(), &remains, self.expect);
remains
}
#[cfg_attr(
not(feature = "tokio"),
allow(
dead_code,
reason = "only the async child folds a second teardown's clause into its own line"
)
)]
pub(crate) fn warn(&self, line: Option<&str>) {
warn_teardown(line, &self.outcome.remains(), self.expect);
}
}
#[cfg_attr(
not(target_os = "linux"),
allow(dead_code, reason = "only the Linux spawn tears a child down through a pidfd")
)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Left {
pub(crate) clause: String,
pub(crate) remains: Remains,
pub(crate) expect: Expect,
}
#[cfg_attr(
not(target_os = "linux"),
allow(dead_code, reason = "only the Linux spawn tears a child down through a pidfd")
)]
impl Left {
#[cfg_attr(
not(feature = "tokio"),
allow(dead_code, reason = "only the tokio spawn logs the warn of an abandoned child")
)]
pub(crate) fn warn(&self, line: &str) {
warn_teardown(Some(line), &self.remains, self.expect);
}
}
#[cfg_attr(
not(any(target_os = "linux", windows)),
allow(
dead_code,
reason = "only the Linux and Windows spawns tear a child down over a handle"
)
)]
fn warn_teardown(line: Option<&str>, remains: &Remains, expect: Expect) {
let Remains {
fate,
uncollected,
refused,
} = *remains;
let Expect { refusal, past } = expect;
if let Some(line) = line {
log::warn!("{line}");
}
debug_assert!(
!uncollected || past == Past::WaitMayFail || matches!(fate, ChildFate::Running { .. }),
"a wait on a child's own handle failed: {fate:?}"
);
debug_assert!(
past != Past::Unexecuted || !matches!(fate, ChildFate::Running { .. }),
"the kill of a child that never ran the program was refused"
);
debug_assert!(
refusal != KillRefusal::Never || refused.is_none(),
"the kill of a handle that is never refused was refused: {refused:?}"
);
debug_assert!(
refused.is_none_or(|kind| kind == io::ErrorKind::PermissionDenied),
"the kill of a child's own handle was refused for a reason other than permission: {refused:?}"
);
}
fn refusal_kind(refused: &Error) -> io::ErrorKind {
match refused {
Error::Io(e) => e.kind(),
_ => io::ErrorKind::Other,
}
}
impl OwnedChild {
pub(crate) fn tear_down(&self, id: Option<ProcessId>, kill: Kill<'_>, due: Option<Due>) -> TeardownOutcome {
let Kill { disposition, tree } = kill;
#[cfg(test)]
super::seams::note_root_teardown();
match self.signal(Sig::Kill) {
Ok(sent) => {
#[cfg(test)]
crate::graceful_hooks::run_hook(crate::graceful_hooks::HookPoint::AfterDropKill);
let settlement = Settlement::new(wait_to_exit(self, due), matches!(sent, Sent::Delivered));
#[cfg(test)]
if let Some(status) = settlement.status() {
crate::child::spawn::fault::record_teardown_reap(self.pid().unwrap_or(0), status);
}
TeardownOutcome::of_settlement(&settlement, id, &self.teardown_subject(), None, disposition)
}
Err(refused) => match tree.map(|tree| tree.reached(self)) {
Some(Ok(true)) => self.reap_after_tree_kill(&self.teardown_subject(), disposition),
_ => self.look_after_refused_kill(id, refused, disposition),
},
}
}
pub(crate) fn reap_after_tree_kill(&self, subject: &str, disposition: Disposition) -> TeardownOutcome {
#[cfg(test)]
crate::child::spawn::fault::run_between_kill_and_wait();
let settlement = Settlement::new(wait_to_exit(self, None), true);
TeardownOutcome::of_settlement(&settlement, None, subject, None, disposition)
}
pub(crate) fn teardown_subject(&self) -> String {
format!("teardown of {}", child_named(self.pid()))
}
pub(crate) fn look_after_refused_kill(
&self,
id: Option<ProcessId>,
refused: Error,
disposition: Disposition,
) -> TeardownOutcome {
let settlement = Settlement::new(self.wait(Some(crate::wait::now())), false);
let refused_kind = refusal_kind(&refused);
let subject = format!("{} {}", child_named(self.pid()), kill_refused(&refused));
let running = match disposition {
Disposition::Leave => format!("{subject}{LEAVING_RUNNING}"),
Disposition::HandBack => format!("{subject}{}", Disposition::HandBack.suffix(true)),
};
let mut torn = TeardownOutcome::of_settlement(&settlement, id, &subject, Some(&running), disposition);
torn.refused_look = settlement.ended().then(|| Box::new(settlement));
torn.refused = Some(refused_kind);
torn
}
#[cfg_attr(
windows,
allow(dead_code, reason = "no Windows teardown looks at a front through this yet")
)]
pub(crate) fn look_at_front(
&self,
id: Option<ProcessId>,
reach: Result<Option<&dyn Reach>, io::Error>,
due: Option<Due>,
) -> FrontLook {
let ended = |settlement: Settlement| FrontLook {
fate: settlement.fate(id),
look: LookOutcome::Ended(settlement),
};
let looked = Settlement::new(self.wait(Some(crate::wait::now())), false);
if looked.ended() {
return ended(looked);
}
let running = |look| FrontLook {
fate: ChildFate::Running { id },
look,
};
let reach = match reach {
Err(e) => return running(LookOutcome::SubtreeUnreadable(e)),
Ok(None) => return running(LookOutcome::LeftRunning),
Ok(Some(reach)) => reach,
};
match reach.reached(self) {
Ok(false) => running(LookOutcome::LeftRunning),
Err(e) => running(LookOutcome::PlaceUnreadable(e)),
Ok(true) => {
#[cfg(test)]
crate::child::spawn::fault::run_between_kill_and_wait();
ended(Settlement::new(wait_to_exit(self, due), true))
}
}
}
}