use std::io;
use std::sync::Arc;
use std::time::Duration;
use super::OwnedChild;
use crate::child::lifecycle::{wait_to_exit, Settlement, Wording};
use crate::error::{ChildFate, Error, Failures};
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,
}
impl FrontLook {
pub(crate) fn ended(settlement: Settlement, id: Option<ProcessId>) -> FrontLook {
FrontLook {
fate: settlement.fate(id),
look: LookOutcome::Ended(settlement),
}
}
}
#[derive(Debug)]
pub(crate) struct TeardownOutcome {
fate: ChildFate,
said: Option<Wording>,
refused_look: Option<Box<Settlement>>,
refused: Option<io::ErrorKind>,
failures: Vec<Arc<Error>>,
}
#[derive(Debug, Clone)]
pub(crate) struct Remains {
pub(crate) fate: ChildFate,
pub(crate) uncollected: bool,
pub(crate) refused: Option<io::ErrorKind>,
pub(crate) failures: Option<Failures>,
}
impl Remains {
pub(crate) fn after_tree_kill(mut self, failure: Option<Error>) -> Remains {
self.failures = Failures::merged(Failures::collect(failure.map(Arc::new)), self.failures);
self
}
#[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,
failures: 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,
failures: Vec::new(),
}
}
#[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,
failures: Vec::new(),
}
}
pub(crate) fn failing(mut self, failures: impl IntoIterator<Item = Arc<Error>>) -> TeardownOutcome {
self.failures.extend(failures);
self
}
#[cfg(unix)]
pub(crate) fn failing_first(mut self, failure: Option<Arc<Error>>) -> TeardownOutcome {
self.failures.splice(0..0, failure);
self
}
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)),
)
.failing(settlement.failure())
}
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,
failures: Failures::collect(self.failures.iter().cloned()),
}
}
#[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()
}
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 one_warn = self.said_in_the_one_warn(why);
let remains = self.remains();
let Some(said) = self.said else {
return (None, remains);
};
let text = said.text();
if one_warn {
return (Some(format!("{label}: {}", why.fold(text))), remains);
}
log::log!(said.level(), "{label}: {text}");
(None, remains)
}
#[cfg(any(target_os = "linux", windows))]
pub(crate) fn said_in_the_one_warn(&self, why: &crate::child::spawn::Diagnosis) -> bool {
self.said
.as_ref()
.is_some_and(|said| said.level() == log::Level::Warn || why.is_owed())
}
}
#[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(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(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,
failures: _,
} = *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 {
#[cfg_attr(
not(any(target_os = "linux", windows)),
allow(
dead_code,
reason = "only the Linux and Windows spawns tear a child down through this wrapper"
)
)]
pub(crate) fn tear_down(
&self,
id: Option<ProcessId>,
kill: Kill<'_>,
warn_after: Option<Duration>,
) -> TeardownOutcome {
match self.begin_tear_down(id, kill, warn_after) {
BeginOutcome::Done(torn) => torn,
BeginOutcome::Wait(wait) => wait.settle(self),
}
}
pub(crate) fn begin_tear_down(
&self,
id: Option<ProcessId>,
kill: Kill<'_>,
warn_after: Option<Duration>,
) -> BeginOutcome<TeardownOutcome, TeardownWait> {
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 wait = TeardownWait::new(
self,
warn_after,
matches!(sent, Sent::Delivered),
id,
self.teardown_subject(),
disposition,
);
if self.is_reaped() {
let settlement = Settlement::new(self.wait(None), wait.pending.reached);
return BeginOutcome::Done(wait.outcome(self, &settlement));
}
BeginOutcome::Wait(wait)
}
Err(refused) => match tree.map(|tree| tree.reached(self)) {
Some(Ok(true)) => BeginOutcome::Wait(self.begin_reap_after_tree_kill(
id,
self.teardown_subject(),
disposition,
warn_after,
)),
_ => BeginOutcome::Done(self.look_after_refused_kill(id, refused, disposition)),
},
}
}
#[cfg_attr(
not(unix),
allow(dead_code, reason = "only a Unix teardown reaps a front a tree kill ended")
)]
pub(crate) fn begin_reap_after_tree_kill(
&self,
id: Option<ProcessId>,
subject: String,
disposition: Disposition,
warn_after: Option<Duration>,
) -> TeardownWait {
#[cfg(test)]
crate::child::spawn::fault::run_between_kill_and_wait();
TeardownWait::new(self, warn_after, true, id, subject, 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(&crate::error::Report(&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.failures.insert(0, Arc::new(refused.in_step("killing the child")));
torn
}
#[cfg_attr(
not(target_os = "linux"),
allow(dead_code, reason = "only the Linux spawn looks at a front through this wrapper")
)]
pub(crate) fn look_at_front(
&self,
id: Option<ProcessId>,
reach: Result<Option<&dyn Reach>, io::Error>,
warn_after: Option<Duration>,
) -> FrontLook {
match self.begin_look_at_front(id, reach, warn_after) {
BeginOutcome::Done(look) => look,
BeginOutcome::Wait(wait) => wait.settle(self),
}
}
#[cfg_attr(
windows,
allow(dead_code, reason = "no Windows teardown looks at a front through this yet")
)]
pub(crate) fn begin_look_at_front(
&self,
id: Option<ProcessId>,
reach: Result<Option<&dyn Reach>, io::Error>,
warn_after: Option<Duration>,
) -> BeginOutcome<FrontLook, FrontWait> {
let looked = Settlement::new(self.wait(Some(crate::wait::now())), false);
if looked.ended() {
return BeginOutcome::Done(FrontLook::ended(looked, id));
}
let running = |look| FrontLook {
fate: ChildFate::Running { id },
look,
};
let reach = match reach {
Err(e) => return BeginOutcome::Done(running(LookOutcome::SubtreeUnreadable(e))),
Ok(None) => return BeginOutcome::Done(running(LookOutcome::LeftRunning)),
Ok(Some(reach)) => reach,
};
match reach.reached(self) {
Ok(false) => BeginOutcome::Done(running(LookOutcome::LeftRunning)),
Err(e) => BeginOutcome::Done(running(LookOutcome::PlaceUnreadable(e))),
Ok(true) => {
#[cfg(test)]
crate::child::spawn::fault::run_between_kill_and_wait();
BeginOutcome::Wait(FrontWait {
pending: Pending::new(self, warn_after, true),
id,
})
}
}
}
}
#[must_use = "a pending wait that is dropped leaves the child unreaped"]
#[derive(Debug)]
pub(crate) enum BeginOutcome<D, W> {
Done(D),
Wait(W),
}
#[derive(Debug)]
struct Pending {
handle: usize,
warn_after: Option<Duration>,
reached: bool,
}
impl Pending {
fn new(child: &OwnedChild, warn_after: Option<Duration>, reached: bool) -> Pending {
Pending {
handle: child.handle_id(),
warn_after,
reached,
}
}
fn settle(&self, child: &OwnedChild) -> Settlement {
debug_assert_eq!(
self.handle,
child.handle_id(),
"a wait is settled on the child it began on"
);
Settlement::new(wait_to_exit(child, Due::in_(self.warn_after)), self.reached)
}
#[cfg(feature = "tokio")]
async fn settle_async(&self, child: &mut OwnedChild) -> Settlement {
debug_assert_eq!(
self.handle,
child.handle_id(),
"a wait is settled on the child it began on"
);
Settlement::new(child.wait_async().await, self.reached)
}
}
#[must_use = "a pending wait that is dropped leaves the child unreaped"]
#[derive(Debug)]
pub(crate) struct TeardownWait {
pending: Pending,
id: Option<ProcessId>,
subject: String,
disposition: Disposition,
}
impl TeardownWait {
fn new(
child: &OwnedChild,
warn_after: Option<Duration>,
reached: bool,
id: Option<ProcessId>,
subject: String,
disposition: Disposition,
) -> TeardownWait {
TeardownWait {
pending: Pending::new(child, warn_after, reached),
id,
subject,
disposition,
}
}
pub(crate) fn settle(self, child: &OwnedChild) -> TeardownOutcome {
let settlement = self.pending.settle(child);
self.outcome(child, &settlement)
}
#[cfg(feature = "tokio")]
pub(crate) async fn settle_async(&self, child: &mut OwnedChild) -> TeardownOutcome {
let settlement = self.pending.settle_async(child).await;
self.outcome(child, &settlement)
}
#[cfg_attr(
not(test),
allow(unused_variables, reason = "only the test recorder reads the child")
)]
fn outcome(&self, child: &OwnedChild, settlement: &Settlement) -> TeardownOutcome {
#[cfg(test)]
if let Some(status) = settlement.status() {
crate::child::spawn::fault::record_teardown_reap(child.pid().unwrap_or(0), status);
}
TeardownOutcome::of_settlement(settlement, self.id, &self.subject, None, self.disposition)
}
}
#[must_use = "a pending wait that is dropped leaves the front unreaped"]
#[derive(Debug)]
pub(crate) struct FrontWait {
pending: Pending,
id: Option<ProcessId>,
}
impl FrontWait {
pub(crate) fn settle(self, child: &OwnedChild) -> FrontLook {
FrontLook::ended(self.pending.settle(child), self.id)
}
#[cfg(all(feature = "tokio", unix))]
pub(crate) async fn settle_async(&self, child: &mut OwnedChild) -> FrontLook {
FrontLook::ended(self.pending.settle_async(child).await, self.id)
}
}
#[cfg(test)]
#[path = "teardown_tests.rs"]
mod teardown_tests;