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;
use crate::stop::{StopTarget, StopWaits, TreeCall};
pub(crate) trait Waits: StopWaits {
fn child(&self) -> &Child;
async fn stop(&self, target: &StopTarget<'_>) -> Result<(), Error>;
async fn tree_drained(&self, grace: Duration) -> Result<TreeDrain, 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(crate) &'a Child);
impl StopWaits for BlockingDriver<'_> {
async fn root_exited(&self, within: Duration) -> Result<bool, Error> {
self.0.proc.exited_by(crate::wait::deadline_from(within))
}
#[cfg(windows)]
type Proxy = Child;
#[cfg(windows)]
async fn start_proxy(
&self,
exe: &std::path::Path,
args: &crate::stop::proxy::protocol::ProxyArgs,
) -> Result<(u32, Child), Error> {
let mut command = crate::Command::new();
crate::stop::proxy::configure_start(&mut command, exe, args)?;
let proxy = command.spawn()?;
Ok((proxy.pid(), proxy))
}
#[cfg(windows)]
async fn wait_proxy(
&self,
proxy: &mut Child,
after: Duration,
late: impl FnOnce(Duration) + Send,
) -> Result<std::process::ExitStatus, Error> {
proxy.wait_saying(after, late)
}
}
impl Waits for BlockingDriver<'_> {
fn child(&self) -> &Child {
self.0
}
async fn stop(&self, target: &StopTarget<'_>) -> Result<(), Error> {
self.0.stop.run(target)
}
async fn tree_drained(&self, grace: Duration) -> Result<TreeDrain, Error> {
self.0.wait_tree_timeout(grace)
}
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 terminate<W: Waits>(w: &W) -> Result<(), Error> {
w.stop(&StopTarget::root(w.child())).await
}
pub(crate) async fn terminate_tree<W: Waits>(w: &W) -> Result<(), Error> {
w.child().require_contained()?;
w.stop(&StopTarget::tree(w.child(), TreeCall::SignalOnly)).await
}
pub(crate) async fn stop_root<W: Waits>(w: &W) -> (Result<(), Error>, String) {
let target = StopTarget::root(w.child());
let stopped = w.stop(&target).await;
w.child().after_root_stop(target, stopped)
}
pub(crate) async fn signal_tree_cooperatively<W: Waits>(w: &W) -> SignalTreeCooperativelyOutcome {
#[cfg(test)]
if let Some(forced) = w.child().forced_in_place_of_the_stop() {
return forced;
}
let call = crate::containment::treewalk::WalkToken::new();
let target = StopTarget::tree(w.child(), TreeCall::Shutdown(&call));
let acted = w.stop(&target).await;
w.child().after_tree_stop(target, acted)
}
pub(crate) async fn shutdown_lone<W: Waits>(w: &mut W, grace: Duration) -> Result<ExitStatus, Error> {
let (stopped, earlier) = stop_root(&*w).await;
stopped?;
#[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(&earlier))
})?;
#[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 signal_tree_cooperatively(&*w).await {
SignalTreeCooperativelyOutcome::Sent { result, earlier, walk } => (result, earlier, walk),
SignalTreeCooperativelyOutcome::End(e) => return Err(e),
#[cfg(target_os = "linux")]
SignalTreeCooperativelyOutcome::RootThroughPidfd(skip, started, sig, acted) => {
let ended = root_through_pidfd(w, &skip, started, sig, grace).await;
return Err(ended_with(w, ended, acted));
}
#[cfg(unix)]
SignalTreeCooperativelyOutcome::HoldersOnly(skip, sig, acted) => {
let ended = holders_only(w, skip, sig, grace).await;
return Err(ended_with(w, ended, acted));
}
};
#[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.as_deref(), 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(unix)]
fn ended_with<W: Waits>(w: &W, ended: Error, acted: Option<Error>) -> Error {
crate::graceful::joined(&format!("graceful_shutdown_tree({})", w.child().pid()), ended, acted)
}
#[cfg(target_os = "linux")]
pub(crate) async fn root_through_pidfd<W: Waits>(
w: &W,
skip: &crate::containment::Skip,
shutdown: super::PidfdShutdown,
sig: crate::signal::Sig,
grace: Duration,
) -> Error {
let child = w.child();
let call = child.skip_call("graceful_shutdown_tree", sig, None);
#[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,
sig: crate::signal::Sig,
grace: Duration,
) -> Error {
let child = w.child();
let call = child.skip_call("graceful_shutdown_tree", sig, 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;