use std::future::Future;
use std::pin::pin;
use std::process::ExitStatus;
use std::task::{Context, Poll, Waker};
use std::time::Duration;
#[cfg(test)]
use super::fault;
use super::{take_forced_sweep, take_forced_watch_error, Child, SignalTreeCooperativelyOutcome};
use crate::child::owned::ChildWaitOutcome;
use crate::containment::dispatch::{SweepFailure, Swept};
use crate::containment::TreeDrain;
use crate::error::Error;
#[cfg(target_os = "macos")]
use crate::os_process::child::Foreign;
pub(crate) trait Waits {
fn child(&self) -> &Child;
async fn tree_drained(&self, grace: Duration) -> Result<TreeDrain, Error>;
async fn root_exited(&self, within: Duration) -> Result<bool, Error>;
async fn sweep(&self, swept: Swept<'_>) -> Result<(), SweepFailure>;
async fn reap(&mut self) -> Result<ChildWaitOutcome, Error>;
#[cfg(unix)]
async fn holders_finish(&self, shutdown: super::HoldersShutdown<'_>) -> Error;
}
pub(crate) struct BlockingDriver<'a>(pub(super) &'a Child);
impl Waits for BlockingDriver<'_> {
fn child(&self) -> &Child {
self.0
}
async fn tree_drained(&self, grace: Duration) -> Result<TreeDrain, Error> {
self.0.wait_tree_timeout(grace)
}
async fn root_exited(&self, within: Duration) -> Result<bool, Error> {
self.0.proc.exited_by(crate::wait::deadline_from(within))
}
async fn sweep(&self, swept: Swept<'_>) -> Result<(), SweepFailure> {
swept.wait()
}
async fn reap(&mut self) -> Result<ChildWaitOutcome, Error> {
self.0.reap_outcome()
}
#[cfg(unix)]
async fn holders_finish(&self, shutdown: super::HoldersShutdown<'_>) -> Error {
shutdown.finish()
}
}
pub(crate) fn run_ready<F: Future>(f: F) -> F::Output {
match pin!(f).poll(&mut Context::from_waker(Waker::noop())) {
Poll::Ready(output) => output,
Poll::Pending => panic!("run_ready: the future is pending, but a blocking driver's waits are all ready"),
}
}
fn graceful_status_of_reap(pid: u32, op: &str, outcome: Result<ChildWaitOutcome, Error>) -> Result<ExitStatus, Error> {
use crate::child::lifecycle::{echild, unbounded_status, Orphaned};
match outcome? {
ChildWaitOutcome::Foreign(foreign) => {
#[cfg(target_os = "macos")]
if foreign == Foreign::Orphaned {
return Err(crate::signal::unpinned_status(pid, op));
}
let _ = foreign;
log::debug!("{op}({pid}): the root was reaped elsewhere");
Err(Error::Unassessable {
detail: format!(
"pid {pid}: {op} sent its signals, but its exit status cannot be collected: the root was \
reaped elsewhere"
),
source: Some(std::sync::Arc::new(Error::Io(echild()))),
})
}
reaped => unbounded_status(Some(pid), reaped, Orphaned::Quiet),
}
}
pub(crate) async fn shutdown_lone<W: Waits>(w: &mut W, grace: Duration) -> Result<ExitStatus, Error> {
w.child().terminate()?;
#[cfg(test)]
fault::run_hook(fault::HookPoint::AfterTerminate);
let pid = w.child().pid();
let call = || format!("graceful_shutdown({pid})");
let watch = w.root_exited(grace).await;
let watch = crate::graceful::after_grace(call, watch, || {
#[cfg(test)]
fault::run_hook(fault::HookPoint::BeforeEscalation);
w.child().kill_after(Some("the SIGTERM"))
})?;
#[cfg(test)]
fault::run_hook(fault::HookPoint::BeforeReap);
let waited = graceful_status_of_reap(pid, "graceful_shutdown", w.reap().await);
crate::graceful::after_reap(call, waited, None, watch)
}
pub(crate) async fn shutdown_tree<W: Waits>(w: &mut W, grace: Duration) -> Result<ExitStatus, Error> {
w.child().require_contained()?;
let (term, earlier, walk) = match w.child().signal_tree_cooperatively() {
SignalTreeCooperativelyOutcome::Sent { result, earlier, walk } => (result, earlier, walk),
SignalTreeCooperativelyOutcome::End(e) => return Err(e),
#[cfg(target_os = "linux")]
SignalTreeCooperativelyOutcome::RootThroughPidfd(skip) => {
return Err(root_through_pidfd(w, &skip, grace).await);
}
#[cfg(unix)]
SignalTreeCooperativelyOutcome::HoldersOnly(skip) => {
return Err(holders_only(w, skip, grace).await);
}
};
#[cfg(test)]
fault::run_hook(fault::HookPoint::AfterTerminate);
let pid = w.child().pid();
let call = || format!("graceful_shutdown_tree({pid})");
let (drained, root_exited, watch_err) = if let Some(e) = take_forced_watch_error() {
(false, false, Some(e))
} else if w.child().tree.drain_edge().is_some() {
match w.tree_drained(grace).await {
Ok(verdict) if verdict.permits_skipping_sweep() => (true, true, None),
Ok(_) => match w.root_exited(Duration::ZERO).await {
Ok(exited) => (false, exited, None),
Err(e) => (false, false, Some(e)),
},
Err(e) => (false, false, Some(e)),
}
} else {
match w.root_exited(grace).await {
Ok(exited) => (false, exited, None),
Err(e) => (false, false, Some(e)),
}
};
if !drained {
let sweep_result = match take_forced_sweep() {
Some(failure) => Err(failure),
None => {
w.sweep(
w.child()
.kill_tree_after("graceful_shutdown_tree", earlier, walk.as_ref()),
)
.await
}
};
if let Err(sweep) = sweep_result {
if root_exited || sweep.root_ended {
if let Err(e) = w.child().proc.wait(Some(crate::wait::now())) {
log::warn!(
"graceful_shutdown_tree({pid}): the best-effort reap after a swept, exited root also failed: {report}",
report = crate::error::Report(&e)
);
}
}
return Err(crate::graceful::joined(
&call(),
sweep.error,
term.err().into_iter().chain(watch_err),
));
}
}
#[cfg(test)]
fault::run_hook(fault::HookPoint::BeforeReap);
let waited = graceful_status_of_reap(pid, "graceful_shutdown_tree", w.reap().await);
if let (Ok(_), Err(e)) = (&waited, &term) {
log::debug!(
"graceful_shutdown_tree({pid}): tree confirmed clear; discarding the superseded terminate_tree refusal: {report}",
report = crate::error::Report(e)
);
}
crate::graceful::after_reap(call, waited, term.err(), watch_err)
}
#[cfg(target_os = "linux")]
pub(crate) async fn root_through_pidfd<W: Waits>(w: &W, skip: &crate::containment::Skip, grace: Duration) -> Error {
let child = w.child();
let call = child.skip_call(
"graceful_shutdown_tree",
crate::containment::dispatch::TreeSignal::Term,
None,
);
let shutdown = match super::PidfdShutdown::start(&child.proc, || child.proc.signal(crate::signal::Sig::Term)) {
Ok(shutdown) => shutdown,
Err(unkillable) => return unkillable,
};
#[cfg(test)]
fault::run_hook(fault::HookPoint::AfterTerminate);
let exited = if shutdown.needs_grace() {
Some(w.root_exited(grace).await)
} else {
None
};
shutdown.finish(&call, skip, exited, || child.proc.kill_root_only(Some(&child.tree)))
}
#[cfg(unix)]
pub(crate) async fn holders_only<W: Waits>(w: &W, skip: crate::containment::Skip, grace: Duration) -> Error {
let child = w.child();
let call = child.skip_call(
"graceful_shutdown_tree",
crate::containment::dispatch::TreeSignal::Term,
None,
);
let watch = w.tree_drained(grace).await.err();
let label = format!("graceful_shutdown_tree({})", child.pid());
crate::graceful::joined(
&label,
w.holders_finish(child.holders_shutdown(&call, skip)).await,
watch,
)
}
#[cfg(test)]
#[path = "shutdown_tests.rs"]
mod shutdown_tests;