use std::sync::Mutex;
use std::time::Duration;
use crate::child::Child;
use crate::containment::treewalk::WalkToken;
use crate::containment::{Root, TerminateOutcome, TreeStop};
use crate::error::Error;
use crate::identity::ProcessId;
use crate::signal::Sig;
use crate::stop::StopWaits as _;
pub struct StopTarget<'a> {
child: &'a Child,
scope: Scope<'a>,
root_record: Mutex<Option<RootRecord>>,
tree_record: Mutex<Option<TreeRecord>>,
}
#[derive(Clone, Copy)]
pub(crate) enum Scope<'a> {
Root,
Tree(TreeCall<'a>),
}
#[derive(Clone, Copy)]
pub(crate) enum TreeCall<'a> {
SignalOnly,
Shutdown(&'a WalkToken),
}
pub(crate) enum RootRecord {
Sent(&'static str),
Refused(String),
}
pub(crate) enum TreeRecord {
Sent {
earlier: Option<String>,
walk: Option<WalkToken>,
},
NotSent(String),
#[cfg_attr(not(target_os = "linux"), allow(dead_code, reason = "only Linux has a pidfd"))]
RootThroughPidfd(crate::containment::Skip, Result<crate::signal::Sent, Error>, Sig),
#[cfg_attr(
not(unix),
allow(dead_code, reason = "only a Unix mechanism skips by the root's number")
)]
HoldersOnly(crate::containment::Skip, Sig),
}
impl TreeRecord {
fn not_sent(refusal: &Error) -> TreeRecord {
TreeRecord::NotSent(crate::error::Report(refusal).to_string())
}
}
impl<'a> StopTarget<'a> {
pub(crate) fn root(child: &'a Child) -> StopTarget<'a> {
StopTarget {
child,
scope: Scope::Root,
root_record: Mutex::new(None),
tree_record: Mutex::new(None),
}
}
pub(crate) fn tree(child: &'a Child, call: TreeCall<'a>) -> StopTarget<'a> {
StopTarget {
child,
scope: Scope::Tree(call),
root_record: Mutex::new(None),
tree_record: Mutex::new(None),
}
}
pub(crate) fn child(&self) -> &'a Child {
self.child
}
pub(crate) fn scope(&self) -> Scope<'a> {
self.scope
}
pub(crate) fn note_root_went_out(&self, name: &'static str) {
debug_assert!(!self.covers_tree(), "a tree target records its sends as tree records");
*lock(&self.root_record) = Some(RootRecord::Sent(name));
}
pub(crate) fn note_refused(&self, refusal: &Error) {
match self.scope {
Scope::Root => {
*lock(&self.root_record) = Some(RootRecord::Refused(crate::error::Report(refusal).to_string()));
}
Scope::Tree(_) => self.note_tree(TreeRecord::not_sent(refusal)),
}
}
fn note_tree(&self, record: TreeRecord) {
debug_assert!(self.covers_tree(), "a root target records its sends as root records");
*lock(&self.tree_record) = Some(record);
}
pub(crate) fn into_root_record(self) -> Option<RootRecord> {
debug_assert!(!self.covers_tree(), "a tree target holds a tree record");
self.root_record
.into_inner()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub(crate) fn into_tree_record(self) -> Option<TreeRecord> {
debug_assert!(self.covers_tree(), "a root target holds a root record");
self.tree_record
.into_inner()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub fn pid(&self) -> u32 {
self.child.pid()
}
pub fn id(&self) -> Option<ProcessId> {
self.child.id()
}
pub fn covers_tree(&self) -> bool {
matches!(self.scope, Scope::Tree(_))
}
pub fn wait_exit(&self, grace: Duration) -> Result<bool, Error> {
crate::child::graceful::shutdown::run_ready(
crate::child::graceful::shutdown::BlockingDriver(self.child).root_exited(grace),
)
}
#[cfg(windows)]
pub(crate) fn ctrl_proxy(&self) -> &crate::stop::proxy::CtrlProxy {
&self.child.ctrl_proxy
}
#[cfg(windows)]
pub fn leads_group_on_our_console(&self) -> bool {
self.child.console.group && self.created_on_our_console()
}
#[cfg(windows)]
pub(crate) fn created_on_our_console(&self) -> bool {
let console = self.child.console;
!console.own_console_flags && console.caller_had_console
}
pub(crate) fn send_tree(&self, call: TreeCall<'_>, how: TreeStop) -> Result<(), Error> {
let child = self.child;
let root_handle = child.proc.hold(child.pid());
let root: Option<&dyn Root> = Some(&root_handle);
let token = match call {
TreeCall::SignalOnly => None,
TreeCall::Shutdown(token) => Some(token),
};
let name = how.name();
#[cfg(unix)]
let sig = how.sig();
let (outcome, walk) = child.tree.terminate(child.pid(), root, token, how);
match call {
TreeCall::SignalOnly => self.signal_only_answer(
outcome,
#[cfg(unix)]
sig,
),
TreeCall::Shutdown(_) => self.shutdown_answer(
outcome,
walk,
name,
#[cfg(unix)]
sig,
),
}
}
fn signal_only_answer(&self, outcome: TerminateOutcome, #[cfg(unix)] sig: Sig) -> Result<(), Error> {
match outcome {
TerminateOutcome::Sent { result, .. } => result,
TerminateOutcome::NotSent(not_sent) | TerminateOutcome::RootExited(not_sent) => Err(not_sent),
#[cfg(unix)]
TerminateOutcome::End(skip) | TerminateOutcome::HoldersOnly(skip) => {
let call = self.child.skip_call("terminate_tree", sig, None);
call.answer(&self.child.tree, skip, None).answer
}
#[cfg(unix)]
TerminateOutcome::RootThroughPidfd(skip) => {
let call = self.child.skip_call("terminate_tree", sig, None);
let sent = self.child.proc.signal(sig);
call.answer(&self.child.tree, skip, Some(sent)).answer
}
#[cfg(not(unix))]
TerminateOutcome::End(_) | TerminateOutcome::HoldersOnly(_) | TerminateOutcome::RootThroughPidfd(_) => {
unreachable!("only a Unix mechanism skips by the root's number")
}
}
}
fn shutdown_answer(
&self,
outcome: TerminateOutcome,
walk: Option<WalkToken>,
name: &str,
#[cfg(unix)] sig: Sig,
) -> Result<(), Error> {
match outcome {
TerminateOutcome::Sent { result, earlier } => {
self.note_tree(TreeRecord::Sent { earlier, walk });
result
}
TerminateOutcome::NotSent(not_sent) => {
self.note_tree(TreeRecord::not_sent(¬_sent));
Err(not_sent)
}
TerminateOutcome::RootExited(exited) => {
log::debug!(
"graceful_shutdown_tree({}): sent no {name}: {report}",
self.child.pid(),
report = crate::error::Report(&exited)
);
self.note_tree(TreeRecord::Sent {
earlier: None,
walk: None,
});
Ok(())
}
#[cfg(unix)]
TerminateOutcome::End(skip) => {
let call = self.child.skip_call("graceful_shutdown_tree", sig, None);
let answer = call.answer(&self.child.tree, skip, None).answer;
self.note_tree(match &answer {
Ok(()) => TreeRecord::Sent {
earlier: None,
walk: None,
},
Err(refusal) => TreeRecord::not_sent(refusal),
});
answer
}
#[cfg(target_os = "linux")]
TerminateOutcome::RootThroughPidfd(skip) => {
self.note_tree(TreeRecord::RootThroughPidfd(skip, self.child.proc.signal(sig), sig));
Ok(())
}
#[cfg(all(unix, not(target_os = "linux")))]
TerminateOutcome::RootThroughPidfd(_) => unreachable!("only a Linux pidfd names the root exactly"),
#[cfg(unix)]
TerminateOutcome::HoldersOnly(mut skip) if skip.is_moot(&self.child.tree) => {
log::debug!(
"graceful_shutdown_tree({}): this handle already killed the tree, so the holders' grace is skipped",
self.child.pid()
);
self.note_tree(TreeRecord::Sent {
earlier: None,
walk: None,
});
skip.holders.take().unwrap_or(Ok(()))
}
#[cfg(unix)]
TerminateOutcome::HoldersOnly(skip) => {
self.note_tree(TreeRecord::HoldersOnly(skip, sig));
Ok(())
}
#[cfg(not(unix))]
TerminateOutcome::End(_) | TerminateOutcome::RootThroughPidfd(_) | TerminateOutcome::HoldersOnly(_) => {
unreachable!("only a Unix mechanism skips by the root's number")
}
}
}
}
fn lock<T>(cell: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
cell.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
impl<'a> From<&'a Child> for StopTarget<'a> {
fn from(child: &'a Child) -> StopTarget<'a> {
StopTarget::root(child)
}
}
#[cfg(feature = "tokio")]
impl<'a> From<&'a crate::tokio::Child> for StopTarget<'a> {
fn from(child: &'a crate::tokio::Child) -> StopTarget<'a> {
StopTarget::root(&child.inner)
}
}
impl std::fmt::Debug for StopTarget<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StopTarget")
.field("pid", &self.pid())
.field("covers_tree", &self.covers_tree())
.finish_non_exhaustive()
}
}
#[cfg(test)]
#[path = "target_tests.rs"]
mod target_tests;