1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
//! Foreign `Process` graceful shutdown — the soft-then-hard escalation trio over a process
//! the crate does not own (no stdio, no reap). Lone ops are identity-bound and surface real
//! failures; tree ops are best-effort identity-walk sweeps (the `TreeWalk` contract). A tree op
//! sends the root its signal through the held handle, with no second open of it.
use std::sync::Arc;
use std::time::Duration;
use super::Process;
use crate::containment::dispatch::Keeping;
use crate::containment::mechanism::Mechanism;
use crate::containment::treewalk::{Listing, WalkToken, Walker};
use crate::containment::{SendOutcome, Tree};
use crate::error::Error;
use crate::identity::SpawnKernel;
impl Process {
/// Send `SIGTERM` to the process — a cooperative request to exit. Signal-only. Bound to the
/// process this handle opened, as for [`kill`](Process::kill). Already-dead ⇒ `Ok`; a real
/// failure (`EPERM`) ⇒ `Err`.
///
/// **Windows: `Unsupported`.** `GenerateConsoleCtrlEvent` takes a raw pid, and Win32 exposes
/// no way to learn whether a foreign pid leads a console process group, so a non-leader would
/// silently signal *its* leader's whole group instead. An owned [`Child`](crate::Child) has
/// no such problem: it created its group, so the pid can only ever name that child's own
/// group.
pub fn terminate(&self) -> Result<(), Error> {
crate::os_process::terminate(&*self.os)
}
/// Cooperative-then-forced lone shutdown of the process: `SIGTERM`, wait up to
/// `grace` for it to exit, then `SIGKILL` if it has not. No `ExitStatus` — the kernel hands
/// exit status only to the real parent. Escalation proceeds even if `SIGTERM` is ignored.
/// Unix only; Windows returns `Unsupported`. `grace` is relative; `ZERO` signals, polls
/// once, then escalates.
///
/// A watch failure surfaces only after the kill runs. A kill error is the call's error, and the
/// watch failure joins it as a peer (`Error::with_peers_or_warn`).
pub fn graceful_shutdown(&self, grace: Duration) -> Result<(), Error> {
self.terminate()?;
#[cfg(test)]
crate::graceful_hooks::run_hook(crate::graceful_hooks::HookPoint::AfterTerminate);
let call = || format!("graceful_shutdown({})", self.id.pid());
crate::graceful::after_grace(call, self.wait_timeout(grace), || self.kill())?.map_or(Ok(()), Err)
}
/// Best-effort hard sweep of the foreign process's tree: an identity-walk that re-verifies
/// each `(pid, ppid)` before `SIGKILL`/`TerminateProcess`, root then descendants. The root is
/// killed through this handle, each descendant through a handle opened by its identity. Cannot be
/// atomic against a forking tree — the `TreeWalk` contract. All platforms. A member it
/// leaves running is an error. For a single-process kill that surfaces a failure use
/// [`kill`](Process::kill).
///
/// # Errors
///
/// [`Error::Unassessable`] when the process table cannot be read, or the root exists but cannot
/// be queried: nothing is killed, the root included. Also when the root's exit has begun (a zombie,
/// a root reaped or no longer holding its pid, or one still exiting), or whether it has cannot be
/// read: its children are reparented at its exit, so a walk from its pid says nothing of the tree.
/// Members found are killed all the same, and nothing is vouched for; with none found, nothing was
/// killed, and a retry can read an unreadable flag.
///
/// [`Error::MembersLeft`] when the walk killed what it could and left members running, each a
/// [`Error::MemberNotKilled`] naming it and why: its identity could not be read, or its kill was
/// refused.
///
/// **`Ok` means every member the walk killed has exited**, and so has the root: the call waits
/// for each, with no deadline. A member forked after the walk's snapshot is not seen, and a parent
/// that exits during the call, the root included, hides its children from the walk. On Linux
/// below 6.9 a member that was killed and reaped, and whose pid was taken again within its own
/// start tick, is waited for in its successor's place. A member whose exit cannot be observed is
/// an [`Error::Unassessable`] naming it, returned once the others have been waited for. [`send_kill_tree`](Process::send_kill_tree) only sends.
pub fn kill_tree(&self) -> Result<(), Error> {
self.kill_tree_with("kill_tree", &crate::identity::HostKernel)
}
/// [`kill_tree`](Self::kill_tree) that sends and does not wait: `Ok` says every member the walk
/// found was sent its kill, not that any has exited.
pub fn send_kill_tree(&self) -> Result<(), Error> {
self.send_kill_tree_with(&crate::identity::HostKernel)
}
/// [`kill_tree`](Self::kill_tree) for the call `op`, which a warn about its failed wait names,
/// reading through `kernel`.
pub(crate) fn kill_tree_with(&self, op: &str, kernel: &dyn crate::identity::Kernel) -> Result<(), Error> {
self.kill_tree_swept(op, kernel, None)
}
/// [`kill_tree_with`](Self::kill_tree_with) for a graceful call, which keeps the members its
/// `SIGTERM` walk reached in a settlement of its own (see [`sweep`](Self::sweep)).
pub(crate) fn kill_tree_settling(&self, op: &str, settling: &Settling) -> Result<(), Error> {
self.kill_tree_swept(op, settling.kernel(), Some(settling))
}
fn kill_tree_swept(
&self,
op: &str,
kernel: &dyn crate::identity::Kernel,
call: Option<&Settling>,
) -> Result<(), Error> {
let (answer, wait) = self.sweep(kernel, call);
let waited = wait.wait();
crate::containment::tree_kill::answer_after_wait(op, answer, waited, |error| error)
}
/// [`kill_tree_with`](Self::kill_tree_with), awaited, with no runtime thread blocked.
#[cfg(feature = "tokio")]
pub(crate) async fn kill_tree_with_async(
&self,
op: &str,
kernel: &dyn crate::identity::Kernel,
) -> Result<(), Error> {
self.kill_tree_swept_async(op, kernel, None).await
}
/// [`kill_tree_settling`](Self::kill_tree_settling), awaited, with no runtime thread blocked.
#[cfg(feature = "tokio")]
pub(crate) async fn kill_tree_settling_async(&self, op: &str, settling: &Settling) -> Result<(), Error> {
self.kill_tree_swept_async(op, settling.kernel(), Some(settling)).await
}
#[cfg(feature = "tokio")]
async fn kill_tree_swept_async(
&self,
op: &str,
kernel: &dyn crate::identity::Kernel,
call: Option<&Settling>,
) -> Result<(), Error> {
let (answer, wait) = self.sweep(kernel, call);
let waited = wait.wait_async().await;
crate::containment::tree_kill::answer_after_wait(op, answer, waited, |error| error)
}
/// [`send_kill_tree`](Self::send_kill_tree), reading through `kernel`.
pub(crate) fn send_kill_tree_with(&self, kernel: &dyn crate::identity::Kernel) -> Result<(), Error> {
self.sweep(kernel, None).0
}
/// The walk's kills, the answer they come to, and the wait for what they reached: the members, and
/// the root through this handle once its kill landed.
///
/// A root whose exit has begun, reaped or not, answers [`Error::Unassessable`] whether or not its
/// walk finds members (which are killed). `call`: a graceful call's settlement, which
/// settles the walk as a `Child`'s tree does ([`TreeKilled::settle`](crate::containment::dispatch::TreeKilled::settle)).
fn sweep<'a>(
&'a self,
kernel: &'a dyn crate::identity::Kernel,
call: Option<&Settling>,
) -> (Result<(), Error>, crate::containment::KillWait<'a>) {
let (outcome, mut wait) = crate::containment::treewalk::hard_kill(kernel, self.id, self).split();
let landed = wait.root_killed();
// No handle backstop: the root is left as any member is, and the error holds every member.
let answer = match call {
Some(Settling { tree, walk, .. }) => {
// A foreign handle has no retry of its own to keep anything for.
let settled = tree.settle_for_kill_tree(outcome.in_call(walk.as_ref()), landed, Keeping::Nothing);
wait.reaching(settled.killed_again);
settled.answer
}
None => outcome.into_result().or_else(|left| left.unsettled(false)),
};
(answer, wait.with_root(&*self.os, self.id.pid(), landed))
}
/// Best-effort graceful (`SIGTERM`) sweep of the foreign process's tree (identity-walk, root
/// then descendants; the root through this handle). Signal-only. Unix only: on Windows this rests on
/// [`terminate`](Process::terminate), whose absence — no way to learn whether a foreign
/// pid leads a group — applies here too, so it returns `Unsupported`
/// (use [`kill_tree`](Process::kill_tree) for a hard sweep).
///
/// # Errors
///
/// [`Error::Unassessable`] when the process table cannot be read, or the root exists but cannot
/// be queried: nothing is signalled. Also when the root's exit has begun (a zombie, a root reaped,
/// or one still exiting), or whether it has cannot be read, and its walk finds no member: its
/// children were reparented at its exit, so a walk from its pid says nothing of the tree.
///
/// A walk that finds members signals them whatever the flag says, and the call is `Ok` (a signal
/// settles nothing), but the members it found are not taken for the whole tree, and a graceful
/// shutdown's sweep does not stand on them.
pub fn terminate_tree(&self) -> Result<(), Error> {
self.terminate_tree_with(&crate::identity::HostKernel)
}
/// [`terminate_tree`](Self::terminate_tree), reading through `kernel`.
pub(crate) fn terminate_tree_with(&self, kernel: &dyn crate::identity::Kernel) -> Result<(), Error> {
self.terminate_walk(kernel).0.into_tree_result()
}
/// The `SIGTERM` walk of [`terminate_tree`](Self::terminate_tree), with what it found: the members it
/// listed, which a graceful shutdown stands on ([`sweep`](Self::sweep)).
pub(crate) fn terminate_walk(&self, kernel: &dyn crate::identity::Kernel) -> (SendOutcome, Option<Listing>) {
#[cfg(unix)]
{
crate::containment::treewalk::terminate(kernel, self.id, self, crate::containment::TreeStop::default())
}
#[cfg(windows)]
{
let _ = (kernel, self.id);
(
SendOutcome::NotSent(Error::Unsupported {
op: "foreign tree graceful terminate".into(),
platform: "windows",
detail: "Windows has no per-process graceful signal, and a foreign process \
shares no addressable process group with us; use kill_tree for a hard \
identity-walk sweep"
.into(),
source: None,
}),
None,
)
}
#[cfg(not(any(unix, windows)))]
{
let _ = (kernel, self.id);
(
SendOutcome::Sent(Ok(())),
Some(Listing {
members: Vec::new(),
complete: true,
}),
)
}
}
/// The `SIGTERM` walk of a graceful shutdown through `kernel`, and the call-local settlement
/// ([`Settling`]) its sweep answers to.
///
/// # Errors
///
/// As [`terminate_tree`](Process::terminate_tree) for a walk that could not be made: nothing is
/// signalled. Windows: `Unsupported`.
pub(crate) fn begin_graceful(&self, kernel: &crate::identity::SpawnKernel) -> Result<Settling, Error> {
let (sent, listing) = self.terminate_walk(&**kernel);
let contained = || Tree::contained(Mechanism::Walk(Walker::new(self.id, Arc::clone(kernel))));
let (tree, walk) = match sent {
SendOutcome::NotSent(not_sent) => return Err(not_sent),
SendOutcome::Sent(Err(failed)) => {
debug_assert!(false, "a walk's send is never `Sent(Err)`: {failed}");
return Err(failed);
}
SendOutcome::Sent(Ok(())) => {
debug_assert!(listing.is_some(), "a walk that sent returns its listing");
let tree = contained();
let walk = listing.and_then(|listing| tree.hold_walked(listing, Some(&WalkToken::new())));
(tree, walk)
}
SendOutcome::RootExited(exited) => {
log::debug!(
"graceful_shutdown_tree({}): sent no SIGTERM: {report}",
self.id.pid(),
report = crate::error::Report(&exited)
);
(contained(), None)
}
};
Ok(Settling {
tree,
walk,
kernel: Arc::clone(kernel),
})
}
/// Cooperative-then-forced shutdown of the foreign process's tree: `SIGTERM`-walk, wait up
/// to `grace` for the **root** to exit, then a hard identity-walk sweep. Best-effort (the
/// `TreeWalk` contract); no `ExitStatus`. Unix only (Windows `terminate_tree` is
/// `Unsupported`).
///
/// A grace-watch failure does not strand the tree between the soft signal and the sweep:
/// the hard sweep still runs (an unobservable grace escalates immediately), and the watch
/// error is surfaced afterward. A sweep failure is the call's error, and the watch failure joins
/// it as a peer, as for [`graceful_shutdown`](Process::graceful_shutdown). The sweep's errors
/// are those of [`kill_tree`](Process::kill_tree); one that left members running carries the watch
/// failure in its `others`.
///
/// As for a `Child` on a `TreeWalk` tree ([`Child::graceful_shutdown_tree`](crate::Child::graceful_shutdown_tree)): the members the call's
/// own `SIGTERM` walk found are killed by identity if the root exits within the grace, and the call
/// is `Ok` when every one is gone. A root that had exited before the call is
/// [`Error::Unassessable`]. A foreign handle keeps nothing for a retry: the members the call's own
/// `SIGTERM` walk found are killed by identity on every sweep, walked or not. When the sweep's walk
/// cannot be made (the process table cannot be read), they are killed and waited for, the root's
/// reparented ones included, and the call is the walk's error. Children one of them forked after
/// that walk are not seen (the limit of [`kill_tree`](Process::kill_tree)). The root is not
/// killed, and a retry walks from it.
pub fn graceful_shutdown_tree(&self, grace: Duration) -> Result<(), Error> {
let kernel = crate::identity::spawn_kernel(crate::identity::HostKernel);
let settling = self.begin_graceful(&kernel)?;
#[cfg(test)]
crate::graceful_hooks::run_hook(crate::graceful_hooks::HookPoint::AfterTerminate);
let call = format!("graceful_shutdown_tree({})", self.id.pid());
crate::graceful::after_tree_grace(&call, self.wait_timeout(grace), || {
self.kill_tree_settling("graceful_shutdown_tree", &settling)
})
}
}
/// A graceful shutdown's settlement ([`Process::begin_graceful`]): the tree its `SIGTERM` walk held its
/// members in, and the token of that walk, if it read every candidate. It holds the walk's kernel for the
/// sweep.
pub(crate) struct Settling {
tree: Tree,
walk: Option<WalkToken>,
kernel: SpawnKernel,
}
impl Settling {
fn kernel(&self) -> &dyn crate::identity::Kernel {
&*self.kernel
}
}
#[cfg(test)]
#[path = "graceful_tests.rs"]
mod graceful_tests;