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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! The tree a [`Child`](crate::Child) owns: none, a nested member's (delegated), or contained by one
//! mechanism, with where that tree stands after the kills that settled it. Everything the child does to
//! its tree goes through [`Tree`], which asks its mechanism only through [`Contains`].
use crate::containment::dispatch::{Settled, SweepFailure, TreeKillOutcome, TreeKilled};
use crate::containment::drain_edge::DrainEdge;
#[cfg(unix)]
use crate::containment::mechanism::Release;
use crate::containment::mechanism::{Contains, Mechanism};
use crate::containment::{Containment, Root, TerminateOutcome, TreeKill};
use crate::error::Error;
/// Owns the OS containment resource for a spawned child. `killed` is where the tree stands after the
/// kills and drops that settled it ([`TreeKilled`]); it is the handle's, whatever it holds, and
/// outlives the mechanism's [`release`](Self::release).
#[derive(Debug, Default)]
pub(crate) struct Tree {
holder: Holder,
killed: TreeKilled,
/// Whether [`release`](Self::release) ran: a released tree is not one to send to or wait on,
/// whether or not its mechanism stays.
released: bool,
/// The containment a released cgroup leaf or marker had, so the tree still reports it; `None`
/// while the mechanism stays.
released_as: Option<Containment>,
}
/// What holds the tree.
#[derive(Debug, Default)]
#[allow(
clippy::large_enum_variant,
reason = "one per child, held inline: a leaf is the largest mechanism, and boxing it would add an allocation to every contained spawn"
)]
enum Holder {
/// Uncontained: lone-process semantics. Also what a tree holds once its mechanism is consumed by
/// a release.
#[default]
None,
/// A nested containment member: it joined an ancestor's group/job and owns no teardown mechanism
/// of its own (the outermost root tears the tree down). Distinct from `None` (genuinely
/// uncontained) so `_tree` ops can error honestly.
Delegated,
/// Contained by this mechanism.
Contained(Mechanism),
}
impl Tree {
/// An uncontained tree, never settled.
pub(crate) fn none() -> Tree {
Tree::default()
}
/// A nested member's tree, never settled.
pub(crate) fn delegated() -> Tree {
Tree {
holder: Holder::Delegated,
..Tree::default()
}
}
/// A tree contained by `mechanism`, never settled.
pub(crate) fn contained(mechanism: Mechanism) -> Tree {
Tree {
holder: Holder::Contained(mechanism),
..Tree::default()
}
}
/// The teardown mechanism this tree achieved (queried via `Child::containment()`): the one source
/// of it, and the same after the mechanism's [`release`](Self::release).
pub(crate) fn containment(&self) -> Containment {
match &self.holder {
Holder::None => self.released_as.unwrap_or(Containment::None),
Holder::Delegated => Containment::Delegated,
Holder::Contained(mechanism) => mechanism.kind(),
}
}
/// Guard for the `_tree` operations (single-sourced with the async `Child`): they act on the
/// containment group's teardown mechanism, so a child that holds none has no tree to act on.
pub(crate) fn require_contained(&self) -> Result<(), Error> {
let contained = !self.released && matches!(self.holder, Holder::Contained(_));
if !self.released {
debug_assert_eq!(
self.containment().can_teardown(),
contained,
"`can_teardown` disagrees with the holder of {:?}",
self.containment()
);
}
if contained {
return Ok(());
}
Err(Error::Unsupported {
op: "tree teardown (kill_tree / terminate_tree)".into(),
platform: std::env::consts::OS,
detail: "this child holds no actionable tree-teardown mechanism (uncontained, \
or a nested member of an ancestor's containment group). Use kill() for a \
lone process, or tear down the tree via the outermost .contain()ed handle."
.into(),
source: None,
})
}
/// The tree's own drain edge, for `wait_tree`/`wait_tree_timeout` and a graceful shutdown's grace
/// (single-sourced with the async `Child`): only a mechanism with a real kernel edge can answer
/// "has the whole tree exited" without polling. `None` for everything else (an uncontained child,
/// a nested `Delegated` member, or a teardown-only mechanism like a process group or a walk).
pub(crate) fn drain_edge(&self) -> Option<DrainEdge<'_>> {
let edge = match &self.holder {
Holder::Contained(mechanism) if !self.released => mechanism.drain_edge(),
Holder::Contained(_) | Holder::None | Holder::Delegated => None,
};
if !self.released {
debug_assert_eq!(
self.containment().can_observe_drain(),
edge.is_some(),
"`can_observe_drain` disagrees with the drain edge of {:?}",
self.containment()
);
}
edge
}
/// What a call that needs the tree's drain edge answers when it has none.
fn no_drain_edge(&self) -> Error {
Error::Unsupported {
op: "wait for the contained tree to drain (wait_tree / wait_tree_timeout)".into(),
platform: std::env::consts::OS,
detail: format!(
"this child's containment mechanism ({containment}) exposes no kernel edge for \
tree drain — only cgroup v2, a Windows job object, and the macOS fd marker do. \
Use kill_tree()/terminate_tree() for teardown, or wait() to watch the root alone.",
containment = self.containment()
),
source: None,
}
}
/// Block until every member has exited, or until `deadline`, through the tree's drain edge
/// ([`DrainEdge::wait`]); `Unsupported` where it has none.
pub(crate) fn wait_drained(
&self,
deadline: Option<std::time::Instant>,
) -> Result<crate::containment::TreeDrain, Error> {
self.drain_edge().ok_or_else(|| self.no_drain_edge())?.wait(deadline)
}
/// [`wait_drained`](Self::wait_drained), awaited ([`DrainEdge::wait_async`]).
#[cfg(feature = "tokio")]
pub(crate) async fn wait_drained_async(
&self,
deadline: Option<std::time::Instant>,
) -> Result<crate::containment::TreeDrain, Error> {
self.drain_edge()
.ok_or_else(|| self.no_drain_edge())?
.wait_async(deadline)
.await
}
/// Hard-kill the contained tree (best-effort; a member that is already gone is success), as the
/// mechanism's [`kill`](Contains::kill) decides it from `root`. A tree that is none or delegated
/// has nothing to kill. The [`TreeKill`] has what the kill reached, for a caller that waits; one
/// that does not calls [`send_kill`](Self::send_kill).
pub(crate) fn kill(&self, root: Option<&dyn Root>) -> TreeKill<'_> {
match &self.holder {
Holder::None | Holder::Delegated => {
debug_assert!(!self.released, "a send on a released tree");
TreeKill::of(TreeKillOutcome::Ran(Ok(())))
}
Holder::Contained(mechanism) => {
debug_assert!(!self.released, "a send on a released tree");
mechanism.kill(root)
}
}
}
/// [`kill`](Self::kill) for a caller that waits for nothing: it names no member first, which a
/// cgroup leaf and a Job Object otherwise do ([`Contains::send_kill`]).
pub(crate) fn send_kill(&self, root: Option<&dyn Root>) -> TreeKillOutcome {
match &self.holder {
Holder::None | Holder::Delegated => {
debug_assert!(!self.released, "a send on a released tree");
TreeKillOutcome::Ran(Ok(()))
}
Holder::Contained(mechanism) => {
debug_assert!(!self.released, "a send on a released tree");
mechanism.send_kill(root)
}
}
}
/// [`send_kill`](Self::send_kill) for a caller with no root to kill after it, settled and
/// reported as [`settle_for_kill_tree`](Self::settle_for_kill_tree) does, with the root not
/// ended.
#[cfg(unix)]
pub(crate) fn kill_settled(&self, root: Option<&dyn Root>) -> Result<(), Error> {
self.settle_for_kill_tree(self.send_kill(root), false).answer
}
/// Send the graceful termination signal to the tree (signal-only), as [`kill`](Self::kill) decides
/// it from `root`: the outcome says what went out, or what was skipped and what the caller does
/// about it.
pub(crate) fn terminate(&self, pid: u32, root: Option<&dyn Root>) -> TerminateOutcome {
match &self.holder {
Holder::None | Holder::Delegated => {
debug_assert!(false, "Tree::terminate on a tree that is not contained");
TerminateOutcome::NotSent(Error::Unsupported {
op: "terminate on a non-actionable mechanism".into(),
platform: std::env::consts::OS,
detail: "internal invariant: a non-actionable mechanism reached terminate".into(),
source: None,
})
}
Holder::Contained(mechanism) => {
debug_assert!(!self.released, "a send on a released tree");
mechanism.send_terminate(pid, root)
}
}
}
/// Whether a kill sent through the mechanism would reach `pid` whatever its credentials (see
/// [`Contains::would_reach`]): `false` for a tree that is none or delegated.
#[cfg(unix)]
pub(crate) fn would_reach(&self, pid: u32, pidfd: Option<std::os::fd::BorrowedFd<'_>>) -> std::io::Result<bool> {
match &self.holder {
Holder::None | Holder::Delegated => {
debug_assert!(!self.released, "a send on a released tree");
Ok(false)
}
Holder::Contained(mechanism) => {
debug_assert!(!self.released, "a send on a released tree");
mechanism.would_reach(pid, pidfd)
}
}
}
/// Apply a handle's `kill_on_drop` decision to the containment resource, once its spawn is
/// committed.
///
/// `Child::drop` returning early on `kill_on_drop == false` skips only ITS teardown. The
/// resource is a field of that handle and drops with it regardless — and a `CgroupLeaf`'s
/// `Drop` fires `cgroup.kill` over an occupied leaf, a Job Object's close fires
/// `KILL_ON_JOB_CLOSE`. So the opt-out has to reach the resource as well, which is what
/// [`disarm`](Self::disarm) is for.
///
/// Called as spawn hands the handle over, not earlier (a later spawn failure must still tear the
/// tree down) and not in `Drop` (a supervisor exiting without destructors still has its Job
/// closed by the OS, and `KILL_ON_JOB_CLOSE` is the kill).
///
/// # Errors
///
/// The refusal of the disarm (Windows: `SetInformationJobObject`), when the handle opted out
/// of `kill_on_drop`: the resource is then still armed, and the caller must not hand the child
/// over as one cosca no longer kills.
pub(crate) fn honor_kill_on_drop(&self, kill_on_drop: bool) -> std::io::Result<()> {
if kill_on_drop {
Ok(())
} else {
self.disarm()
}
}
/// Neutralize teardown so `detach()` leaves the tree running (see [`Contains::disarm`]). A tree
/// that is none or delegated owns nothing to neutralize.
pub(crate) fn disarm(&self) -> std::io::Result<()> {
match &self.holder {
Holder::None | Holder::Delegated => {
debug_assert!(!self.released, "a send on a released tree");
Ok(())
}
Holder::Contained(mechanism) => {
debug_assert!(!self.released, "a send on a released tree");
mechanism.disarm()
}
}
}
/// The end of the tree's resource (see [`Contains::release`]): a mechanism whose release owns it
/// (a cgroup leaf, a marker) leaves the tree and its [`Release`] holds it until its wait; any
/// other stays, so the tree still asks it (a walk's settlement re-kills its held members). A
/// released tree is sent nothing and has no drain edge, whichever stays. What the kills left
/// stays the tree's ([`TreeKilled`]), and so does what a consumed mechanism was
/// ([`containment`](Self::containment)).
#[cfg(unix)]
#[must_use = "the resource is released only by its wait"]
pub(crate) fn release(&mut self) -> Release {
self.released = true;
match std::mem::take(&mut self.holder) {
Holder::Contained(mechanism) => {
let kind = mechanism.kind();
let (release, kept) = mechanism.release();
match kept {
Some(mechanism) => self.holder = Holder::Contained(mechanism),
None => self.released_as = Some(kind),
}
release
}
unowned @ (Holder::None | Holder::Delegated) => {
self.holder = unowned;
Release::nothing()
}
}
}
/// The awaitable steps of the mechanism's release ([`Contains::awaitable_release`]) with the
/// resource left in the tree; a no-op for a tree whose mechanism has none.
#[cfg(all(feature = "tokio", target_os = "linux"))]
pub(crate) async fn await_release_steps(&self, child: u32) {
if let Some(steps) = self.named_by().and_then(Contains::awaitable_release) {
steps.wait(child).await;
}
}
/// What names this mechanism's tree in a message about its teardown (see [`Contains::subject`]).
#[cfg(unix)]
pub(crate) fn teardown_subject(&self) -> String {
match &self.holder {
Holder::None => "None".to_owned(),
_ if self.released => "None".to_owned(),
Holder::Delegated => "Delegated".to_owned(),
Holder::Contained(mechanism) => mechanism.subject(),
}
}
/// Whether this handle already killed the tree completely, as the settlement left it.
#[cfg(unix)]
pub(crate) fn is_killed(&self) -> bool {
self.killed.is_set()
}
/// What names the tree, for its settlement ([`TreeKilled`]) to ask: `None` for a tree that is
/// none or delegated, or whose mechanism a release consumed.
fn named_by(&self) -> Option<&Mechanism> {
match &self.holder {
Holder::Contained(mechanism) => Some(mechanism),
Holder::None | Holder::Delegated => None,
}
}
/// What a tree kill's `outcome` comes to once the root's own handle has had its say
/// ([`TreeKilled::settle`]). Only a Unix cleanup reads the answer itself.
#[cfg(unix)]
pub(crate) fn settle(&self, outcome: impl Into<TreeKillOutcome>, root_ended: bool) -> Settled {
self.killed.settle(self.named_by(), outcome, root_ended)
}
/// [`settle`](Self::settle) for a `kill_tree` call: the error holds every member left.
pub(crate) fn settle_for_kill_tree(
&self,
outcome: impl Into<TreeKillOutcome>,
root_ended: bool,
) -> Settled<Result<(), Error>> {
self.killed.settle_for_kill_tree(self.named_by(), outcome, root_ended)
}
/// [`Contains::root_left`] of this tree's mechanism. A tree that holds none is not reached:
/// `kill_tree` requires one ([`require_contained`](Self::require_contained)).
pub(crate) fn root_left(&self, root: Error) -> Error {
match self.named_by() {
Some(mechanism) => mechanism.root_left(root),
None => {
debug_assert!(false, "a tree kill's backstop failed on a tree that holds no mechanism");
crate::containment::mechanism::root_left_alone(root)
}
}
}
/// `outcome` for a `kill_tree` that goes on to the root's backstop (see
/// [`TreeKilled::unless_unwalked`]).
pub(crate) fn unless_unwalked(&self, outcome: TreeKillOutcome) -> Result<TreeKillOutcome, Settled<SweepFailure>> {
self.killed.unless_unwalked(self.named_by(), outcome)
}
/// [`settle`](Self::settle) for a drop: what is left when the tree is not settled, worded here and
/// only when it will be logged ([`TreeKilled::settle_for_drop`]).
pub(crate) fn settle_for_drop(
&self,
outcome: impl Into<TreeKillOutcome>,
root_ended: bool,
) -> Option<crate::containment::dispatch::TreeLeft> {
self.killed.settle_for_drop(self.named_by(), outcome, root_ended)
}
}
/// Whether the tree kill of this mechanism reached the child ([`Contains::reached`]): `false` for a
/// tree that is none or delegated.
#[cfg(unix)]
impl crate::child::owned::teardown::Reach for Tree {
fn reached(&self, child: &crate::child::owned::OwnedChild) -> std::io::Result<bool> {
match &self.holder {
Holder::None | Holder::Delegated => Ok(false),
_ if self.released => Ok(false),
Holder::Contained(mechanism) => mechanism.reached(child),
}
}
}
// Test accessors -----
//
// The `pub` accessors of `Child` that integration tests reach forward to them.
#[cfg(windows)]
impl Tree {
/// Whether `pid` is inside this tree's Job Object (see
/// [`job_contains_pid`](crate::containment::windows::job_contains_pid)). `false` for any other
/// tree.
pub(crate) fn job_contains_for_test(&self, pid: u32) -> bool {
match self.job_for_test() {
Some(job) => crate::containment::windows::job_contains_pid(job, pid),
None => false,
}
}
/// Whether this tree's Job Object kills its members when its last handle closes. `false` for any
/// other tree. Panics, naming the cause, when the query fails.
pub(crate) fn job_kills_on_close_for_test(&self) -> bool {
match self.job_for_test() {
Some(job) => crate::containment::windows::job_kills_on_close(job),
None => false,
}
}
/// The Job Object of this tree, if it is contained by one.
pub(crate) fn job_for_test(&self) -> Option<&crate::containment::windows::JobHandle> {
match &self.holder {
Holder::Contained(Mechanism::Job(job)) => Some(job),
_ => None,
}
}
}
#[cfg(target_os = "linux")]
impl Tree {
/// The cgroup leaf of this tree, if it is contained by one.
#[cfg(test)]
pub(crate) fn cgroup_leaf_for_test(&self) -> Option<&crate::containment::cgroup::CgroupLeaf> {
match &self.holder {
Holder::Contained(Mechanism::Cgroup(leaf)) => Some(leaf),
_ => None,
}
}
}
#[cfg(all(test, unix))]
impl Tree {
/// Whether this tree signals a process group named by the root's pid: a process group, and a
/// macOS fd marker whose mode made a group.
pub(crate) fn signals_a_group_for_test(&self) -> bool {
match &self.holder {
Holder::Contained(Mechanism::Group(_)) => true,
#[cfg(target_os = "macos")]
Holder::Contained(Mechanism::Marker(m)) => m.pgid().is_some(),
_ => false,
}
}
/// The root a tree walk walks from; `None` for any other tree.
pub(crate) fn walk_root_for_test(&self) -> Option<crate::identity::ProcessId> {
match &self.holder {
Holder::Contained(Mechanism::Walk(walk)) => Some(walk.root()),
_ => None,
}
}
}
#[cfg(target_os = "macos")]
impl Tree {
/// The fd-marker descriptor's number in the child, so this crate's OWN integration tests
/// (`tests/*.rs`, which cannot name a `pub(crate)` item) can be TOLD the exact number rather than
/// inferring it from ambient process state. `None` for any tree not contained by a marker.
pub(crate) fn marker_fd_for_test(&self) -> Option<i32> {
match &self.holder {
Holder::Contained(Mechanism::Marker(m)) => Some(m.own_fd()),
_ => None,
}
}
/// The marker pipe's kernel identity, for tests that must sweep this tree.
#[cfg(test)]
pub(crate) fn marker_handle_for_test(&self) -> Option<u64> {
match &self.holder {
Holder::Contained(Mechanism::Marker(m)) => Some(m.handle()),
_ => None,
}
}
/// The root an fd marker's ppid-walk channel starts from.
#[cfg(test)]
pub(crate) fn marker_root_for_test(&self) -> Option<crate::identity::ProcessId> {
match &self.holder {
Holder::Contained(Mechanism::Marker(m)) => m.root(),
_ => None,
}
}
/// Force the fd marker's process-group id, so a test can drive `containment::unix::signal_group`'s
/// real `pgid <= 0` guard through the real `kill_tree`/`terminate_tree`/`Drop` path. Panics for a
/// tree not contained by a marker: a misuse of this seam, not a case to silently no-op past.
#[cfg(test)]
pub(crate) fn force_marker_pgid_for_test(&mut self, pgid: i32) {
match &mut self.holder {
Holder::Contained(Mechanism::Marker(m)) => m.force_pgid_for_test(pgid),
other => panic!("force_marker_pgid_for_test called on a tree no marker contains: {other:?}"),
}
}
}
#[cfg(test)]
#[path = "tree_tests.rs"]
mod tree_tests;