use std::io;
use std::process::ExitStatus;
use std::time::{Duration, Instant};
use super::owned::teardown::Disposition;
use super::owned::{ChildWaitOutcome, OwnedChild};
use super::spawn::FrontFate;
use super::Child;
use crate::error::{ChildFate, Error};
use crate::identity::ProcessId;
use crate::os_process::child::{ExitRecord, Foreign};
use crate::os_process::PIDLESS_CHILD;
use crate::wait::teardown_warn::{wait_warning, Due};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Orphaned {
Warn,
Quiet,
}
pub(super) fn status_of_outcome(
pid: Option<u32>,
outcome: ChildWaitOutcome,
orphaned: Orphaned,
) -> Result<Option<ExitStatus>, Error> {
match outcome {
ChildWaitOutcome::Exited(ExitRecord::Status(status)) => Ok(Some(status)),
ChildWaitOutcome::Exited(ExitRecord::Unreadable { si_code }) => Err(Error::Io(io::Error::new(
io::ErrorKind::InvalidData,
unreadable(si_code),
))),
ChildWaitOutcome::Foreign(foreign) => {
if foreign == Foreign::Orphaned && orphaned == Orphaned::Warn {
log::warn!("{}", orphaned_note(pid));
}
Err(Error::Io(echild()))
}
ChildWaitOutcome::DeadlinePassed => Ok(None),
}
}
#[derive(Debug)]
pub(crate) struct Settlement {
answer: Result<ChildWaitOutcome, Error>,
killed: bool,
}
impl Settlement {
pub(crate) fn new(answer: Result<ChildWaitOutcome, Error>, killed: bool) -> Settlement {
debug_assert!(
!(killed && matches!(answer, Ok(ChildWaitOutcome::DeadlinePassed))),
"a kill is followed by a wait with no deadline"
);
Settlement { answer, killed }
}
pub(crate) fn fate(&self, id: Option<ProcessId>) -> ChildFate {
match &self.answer {
Ok(ChildWaitOutcome::Exited(_)) => ChildFate::Reaped,
Ok(ChildWaitOutcome::Foreign(foreign)) => foreign.fate(self.killed),
Err(_) if self.killed => ChildFate::Killed,
Err(_) => ChildFate::Unknown,
Ok(ChildWaitOutcome::DeadlinePassed) => ChildFate::Running { id },
}
}
#[cfg_attr(
not(target_os = "linux"),
allow(dead_code, reason = "only the Linux spawn words a front it looked at")
)]
pub(crate) fn front_fate(&self) -> FrontFate {
match &self.answer {
Ok(ChildWaitOutcome::Exited(_)) => FrontFate::Reaped,
Ok(ChildWaitOutcome::Foreign(_)) | Err(_) => FrontFate::Unaccounted,
Ok(ChildWaitOutcome::DeadlinePassed) => FrontFate::LeftUnreaped,
}
}
pub(crate) fn ended(&self) -> bool {
!matches!(self.answer, Ok(ChildWaitOutcome::DeadlinePassed))
}
pub(crate) fn status(&self) -> Option<ExitStatus> {
match &self.answer {
Ok(ChildWaitOutcome::Exited(ExitRecord::Status(status))) => Some(*status),
_ => None,
}
}
#[cfg(unix)]
pub(crate) fn unreadable_record(&self) -> Option<String> {
match &self.answer {
Ok(ChildWaitOutcome::Exited(ExitRecord::Unreadable { si_code })) => Some(unreadable(*si_code)),
_ => None,
}
}
pub(crate) fn wording(&self, subject: &str, running: Option<&str>, disposition: Option<Disposition>) -> Wording {
let after = if self.killed { " after the kill" } else { "" };
match &self.answer {
Ok(ChildWaitOutcome::Exited(ExitRecord::Status(_))) => {
Wording::Collected(log::Level::Debug, format!("{subject}: reaped it{after}"))
}
Ok(ChildWaitOutcome::Exited(ExitRecord::Unreadable { si_code })) => Wording::Collected(
log::Level::Warn,
format!("{subject}: reaped it{after}; {}", unreadable(*si_code)),
),
Ok(ChildWaitOutcome::Foreign(Foreign::Orphaned)) => {
Wording::Collected(log::Level::Warn, format!("{subject}: {ORPHANED}"))
}
Ok(ChildWaitOutcome::Foreign(_)) => {
Wording::Collected(log::Level::Debug, format!("{subject}: reaped by someone else"))
}
Err(e) => Wording::Uncollected(format!(
"{subject}: the wait failed: {e}{}",
disposition.map_or("", |disposition| disposition.suffix(true))
)),
Ok(ChildWaitOutcome::DeadlinePassed) => Wording::Uncollected(
running.map_or_else(|| format!("{subject}: its wait ended with no exit"), str::to_owned),
),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Wording {
Collected(log::Level, String),
Uncollected(String),
}
impl Wording {
pub(crate) fn level(&self) -> log::Level {
match self {
Wording::Collected(level, _) => *level,
Wording::Uncollected(_) => log::Level::Warn,
}
}
pub(crate) fn text(&self) -> &str {
match self {
Wording::Collected(_, text) | Wording::Uncollected(text) => text,
}
}
}
pub(super) fn wait_to_exit(proc: &OwnedChild, due: Option<Due>) -> Result<ChildWaitOutcome, Error> {
#[cfg(feature = "tokio")]
crate::bounded::assert_may_block("a wait for a child's exit");
let pid = proc.pid();
let answer = wait_warning(
(proc, None),
due,
|(proc, answer), until| {
let bounded = proc.wait(Some(until));
let ended = !matches!(bounded, Ok(ChildWaitOutcome::DeadlinePassed));
if ended {
*answer = Some(bounded);
}
ended
},
|after| crate::child::spawn::warn_still_waiting(pid, after),
|(proc, answer)| answer.unwrap_or_else(|| proc.wait(None)),
);
debug_assert!(
!matches!(answer, Ok(ChildWaitOutcome::DeadlinePassed)),
"an unbounded wait ended with no exit"
);
answer
}
pub(super) fn wait_for_status(proc: &OwnedChild, orphaned: Orphaned) -> Result<ExitStatus, Error> {
unbounded_status(proc.pid(), wait_to_exit(proc, None)?, orphaned)
}
pub(super) fn unbounded_status(
pid: Option<u32>,
outcome: ChildWaitOutcome,
orphaned: Orphaned,
) -> Result<ExitStatus, Error> {
status_of_outcome(pid, outcome, orphaned)?
.ok_or_else(|| Error::Io(io::Error::other("an unbounded wait ended with no exit")))
}
fn unreadable(si_code: i32) -> String {
format!("the child's exit record was unreadable (si_code {si_code})")
}
const ORPHANED: &str = "not ours to reap (launchd holds its zombie, because its tracer died)";
pub(super) fn orphaned_note(pid: Option<u32>) -> String {
format!(
"{}: {ORPHANED}",
pid.map_or_else(|| PIDLESS_CHILD.to_owned(), |pid| format!("pid {pid}"))
)
}
fn echild() -> io::Error {
#[cfg(unix)]
{
io::Error::from_raw_os_error(libc::ECHILD)
}
#[cfg(windows)]
{
io::Error::other("the child was already reaped elsewhere")
}
}
impl Child {
pub fn wait_timeout(&self, timeout: Duration) -> Result<Option<ExitStatus>, Error> {
self.wait_timeout_by(timeout, Orphaned::Warn)
}
#[cfg(unix)]
pub(crate) fn wait_timeout_quiet(&self, timeout: Duration) -> Result<Option<ExitStatus>, Error> {
self.wait_timeout_by(timeout, Orphaned::Quiet)
}
fn wait_timeout_by(&self, timeout: Duration, orphaned: Orphaned) -> Result<Option<ExitStatus>, Error> {
#[cfg(test)]
if crate::wait::fault::take_force_watch_error() {
return Err(crate::wait::fault::forced_watch_error());
}
self.wait_root(crate::wait::now().checked_add(timeout), orphaned)
}
pub fn wait_deadline(&self, deadline: Instant) -> Result<Option<ExitStatus>, Error> {
self.wait_root(Some(deadline), Orphaned::Warn)
}
pub(super) fn wait_root(&self, deadline: Option<Instant>, orphaned: Orphaned) -> Result<Option<ExitStatus>, Error> {
match deadline {
Some(deadline) => status_of_outcome(Some(self.pid()), self.proc.wait(Some(deadline))?, orphaned),
None => wait_for_status(&self.proc, orphaned).map(Some),
}
}
pub fn wait_tree(&self) -> Result<crate::containment::TreeDrain, Error> {
self.require_drainable()?;
self.attached.wait_drained(None)
}
pub fn wait_tree_timeout(&self, timeout: Duration) -> Result<crate::containment::TreeDrain, Error> {
self.require_drainable()?;
self.attached.wait_drained(crate::wait::deadline_from(timeout))
}
}
#[cfg(test)]
#[path = "lifecycle_tests.rs"]
mod lifecycle_tests;