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
//! What a contained tree is made of: the contract every way of naming a tree meets ([`Contains`]),
//! the closed set of them ([`Mechanism`]), and what a mechanism hands out: the end of its resource
//! ([`Release`]). Its drain edge is [`DrainEdge`](crate::containment::drain_edge::DrainEdge).
use std::fmt;
use std::sync::Arc;
use crate::containment::dispatch::{TreeKillOutcome, Unkilled};
use crate::containment::drain_edge::DrainEdge;
use crate::containment::treewalk::Left;
use crate::containment::{Containment, Root, TerminateOutcome, TreeKill};
use crate::error::Error;
use crate::identity::ProcessId;
/// What [`Contains::kill_left`] comes to.
pub(crate) struct KillLeftOutcome {
/// What the kill's result comes to once the members an earlier kill left are answered.
pub(crate) result: Result<(), Unkilled>,
/// The members it leaves now.
pub(crate) left: Vec<Left>,
/// The members it killed again, which the kill's wait goes on to wait for.
pub(crate) killed: Vec<ProcessId>,
}
/// [`Contains::kill_left`] of every mechanism but a tree walk: `result` as it is, with nothing held
/// and nothing killed again. Only a tree walk leaves the root alone (the root's own death then
/// settles it).
pub(crate) fn nothing_held(result: Result<(), Unkilled>) -> KillLeftOutcome {
debug_assert!(
!matches!(&result, Err(left) if left.root.is_some()),
"only a tree walk leaves the root alone"
);
KillLeftOutcome {
result,
left: Vec::new(),
killed: Vec::new(),
}
}
/// [`Contains::root_left`] of every mechanism but a tree walk.
pub(crate) fn root_left_alone(root: Error) -> Error {
Error::Containment {
detail: "the kill was delivered, but the kill of the root through its handle failed".to_owned(),
source: Some(Arc::new(root)),
}
}
/// One way the OS names a process tree. Implemented by the mechanism types (`CgroupLeaf`, `JobHandle`,
/// `Group`, `Marker`, `Walker`) and by the test fake; a [`Tree`](crate::containment::Tree) holds one
/// as a [`Mechanism`] and asks it nothing about which it is.
pub(crate) trait Contains: fmt::Debug {
/// Kill every member and return a [`TreeKill`] with the members reached and, for a kernel tree
/// (a cgroup leaf, a Job Object) whose kill landed, its drain edge.
/// A cgroup leaf and a Job Object list members first, which costs a pass over the tree; a caller
/// that waits for none uses [`send_kill`](Self::send_kill). `root` is read right before each send
/// by a mechanism that names its tree by the root's pid, which decides from it what to send; the
/// outcome says what was skipped and why ([`Skip`](crate::containment::Skip)). Others ignore it.
///
/// What `Ok` says depends on how the mechanism names the tree:
///
/// - A cgroup leaf and a Job Object name it in the kernel: `Ok` says the kernel killed every
/// member, however it was spawned. The members the kernel listed before the kill are waited for
/// by identity, and then the tree's edge. A member forked after the listing is not
/// seen by the first, and the edge waits for it only until it leaves the kernel's list. A kill
/// that fails names nothing: a member it did not kill is not waited for.
/// - A process group or session, and an fd marker, name it by a number or a pipe: `Ok` says every
/// member they list or find holding it was reached. A member outside it (one that left the
/// group, or on Linux one `hidepid` hides) is not.
/// - A tree walk names it by parentage: `Ok` says every descendant of the root at the walk's
/// snapshot was killed. A process already reparented away from the root (an orphan), or one the
/// snapshot did not list, is not a descendant to it and is not killed. A descendant it left
/// running is a [`Error::MemberNotKilled`](crate::error::Error::MemberNotKilled), and the
/// `kill_tree` that returns them returns an [`Error::MembersLeft`](crate::error::Error::MembersLeft).
fn kill(&self, root: Option<&dyn Root>) -> TreeKill<'_>;
/// [`kill`](Self::kill) for a caller that waits for nothing: the kill is sent and its outcome
/// returned, and no member is read first. Never waits. Only a cgroup leaf and a Job Object, whose
/// `kill` reads the tree before the kill, override it, with the bare kill their `kill` then
/// sends.
fn send_kill(&self, root: Option<&dyn Root>) -> TreeKillOutcome {
self.kill(root).outcome()
}
/// What a kill's `result` comes to once the members an earlier kill left (`left`, which only a
/// tree walk holds) are answered, the members it leaves now, and the members it killed again: the
/// tree's settlement calls it for every kill, under its one lock
/// ([`TreeKilled::settle`](crate::containment::TreeKilled::settle)).
/// A tree walk's root death reparents a member out of every later walk, so it kills again the
/// members whose identity it read ([`with_earlier`](crate::containment::treewalk::with_earlier)).
/// Default: [`nothing_held`].
fn kill_left(&self, result: Result<(), Unkilled>, _left: Vec<Left>) -> KillLeftOutcome {
nothing_held(result)
}
/// What a failed handle backstop, the kill of the root through its own handle, makes of a
/// `kill_tree`'s error when the kill left nothing else: for `root`, the root's `MemberNotKilled`,
/// a `MembersLeft` of it alone on a walk and an [`Error::Containment`] over it elsewhere. The
/// contract for every other case is stated on [`Child::kill_tree`](crate::Child::kill_tree).
fn root_left(&self, root: Error) -> Error {
root_left_alone(root)
}
/// The cooperative signal to every member it names, as [`send_kill`](Self::send_kill) decides it
/// from `root`: `SIGTERM`, or `CTRL_BREAK` to the root's group `pid` on Windows. Signal-only.
fn send_terminate(&self, pid: u32, root: Option<&dyn Root>) -> TerminateOutcome;
/// The tree's own kernel edge for "no member runs" (a cgroup's `populated`, a job's process
/// list, a marker pipe's EOF); `None` for a group, a session and a walk.
fn drain_edge(&self) -> Option<DrainEdge<'_>>;
/// What [`Child::containment`](crate::Child::containment) reports.
fn kind(&self) -> Containment;
/// What names the tree in a message about its teardown, which carries no kill's error to name it
/// (an unvouched tree): a cgroup leaf its path, every other mechanism what it is.
#[cfg(unix)]
fn subject(&self) -> String;
/// Neutralize the resource's own kill on drop (`detach`, `kill_on_drop(false)`): a Job Object's
/// `KILL_ON_JOB_CLOSE`, a cgroup leaf's `Drop` kill. `Ok` where there is none; only a Job's can
/// fail (the OS refuses `SetInformationJobObject`), and the resource is then still armed.
fn disarm(&self) -> std::io::Result<()>;
/// Whether a kill sent through it would reach `pid` (which `pidfd` names, when there is one)
/// whatever its credentials: only a cgroup's `cgroup.kill` does, and only while `pid` is in it. A
/// signal to a group or to walked members is subject to the kernel's permission check, so it is
/// `false` for every other mechanism. `pid` must be this process's unreaped child, so its number
/// is not reused.
#[cfg(unix)]
fn would_reach(&self, pid: u32, pidfd: Option<std::os::fd::BorrowedFd<'_>>) -> std::io::Result<bool>;
/// Whether a kill through it has landed and reached `child` (see
/// [`Reach`](crate::child::owned::teardown::Reach)): only then does the child's exit follow, so
/// only then may it be waited for. `false` for every mechanism whose kill is subject to the kernel's
/// permission check; an error where the child cannot be placed.
#[cfg(unix)]
fn reached(&self, child: &crate::child::owned::OwnedChild) -> std::io::Result<bool>;
/// The end of the resource it owns, which the caller's wait over the [`Release`] completes: a cgroup
/// leaf is killed through, drained and removed, and its release owns the leaf (`None`); a marker's
/// release closes its read end (`None`). A mechanism that owns no resource a release ends is given
/// back (`Some(self)`), so the tree that held it still asks it, as a walk's settlement does.
#[cfg(unix)]
#[must_use = "the resource is released only by its wait"]
fn release(self) -> (Release, Option<Self>)
where
Self: Sized;
/// The steps of [`release`](Self::release) that a caller can await instead of block on, taken with
/// the resource left where it is: only a cgroup leaf has any. `None` for every other mechanism.
#[cfg(all(feature = "tokio", target_os = "linux"))]
fn awaitable_release(&self) -> Option<AwaitableRelease<'_>>;
}
/// The awaitable steps of a mechanism's release ([`Contains::awaitable_release`]): a cgroup leaf's
/// first step and its drain (see
/// [`CgroupLeaf::step_and_await_drain`](crate::containment::cgroup::CgroupLeaf::step_and_await_drain)).
#[cfg(all(feature = "tokio", target_os = "linux"))]
pub(crate) struct AwaitableRelease<'a> {
leaf: &'a crate::containment::cgroup::CgroupLeaf,
}
#[cfg(all(feature = "tokio", target_os = "linux"))]
impl<'a> AwaitableRelease<'a> {
pub(crate) fn of_leaf(leaf: &'a crate::containment::cgroup::CgroupLeaf) -> AwaitableRelease<'a> {
AwaitableRelease { leaf }
}
/// Take the steps. A future dropped mid-await leaves the rest to the resource's release. `child`
/// names it in debug lines.
pub(crate) async fn wait(&self, child: u32) {
self.leaf.step_and_await_drain(child).await;
}
}
/// The closed set of mechanisms a [`Tree`](crate::containment::Tree) is contained by, each variant
/// cfg'd as its mechanism is. Only `impl Contains for Mechanism` and the tree's `_for_test`
/// accessors match on it; everything else goes through [`Contains`].
#[derive(Debug)]
pub(crate) enum Mechanism {
/// Linux cgroup v2 leaf + `cgroup.kill`.
#[cfg(target_os = "linux")]
Cgroup(crate::containment::cgroup::CgroupLeaf),
/// Windows Job Object + `KILL_ON_JOB_CLOSE`.
#[cfg(windows)]
Job(crate::containment::windows::JobHandle),
/// A Unix process group or session, named by the root's pid.
#[cfg(unix)]
Group(crate::containment::unix::Group),
/// macOS inherited-fd marker: membership survives `setsid`, `setpgid`, reparenting and `exec`.
/// Owns the supervisor's read end of the marker pipe, which keeps the pipe's kernel identity
/// from being re-issued, plus, when the mode created one, the pgid.
#[cfg(target_os = "macos")]
Marker(crate::containment::fdmarker::Marker),
/// Identity-aware tree-walk teardown (cross-platform): the root's identity is re-enumerated and
/// killed by identity at teardown. The universal fallback, and selectable on every OS.
Walk(crate::containment::treewalk::Walker),
/// A table of stated answers, for the tests of what consumes a tree.
#[cfg(test)]
Fake(crate::containment::fake::FakeContains),
}
impl Contains for Mechanism {
fn kill(&self, root: Option<&dyn Root>) -> TreeKill<'_> {
match self {
#[cfg(target_os = "linux")]
Mechanism::Cgroup(m) => m.kill(root),
#[cfg(windows)]
Mechanism::Job(m) => m.kill(root),
#[cfg(unix)]
Mechanism::Group(m) => m.kill(root),
#[cfg(target_os = "macos")]
Mechanism::Marker(m) => m.kill(root),
Mechanism::Walk(m) => m.kill(root),
#[cfg(test)]
Mechanism::Fake(m) => m.kill(root),
}
}
fn send_kill(&self, root: Option<&dyn Root>) -> TreeKillOutcome {
match self {
#[cfg(target_os = "linux")]
Mechanism::Cgroup(m) => m.send_kill(root),
#[cfg(windows)]
Mechanism::Job(m) => m.send_kill(root),
#[cfg(unix)]
Mechanism::Group(m) => m.send_kill(root),
#[cfg(target_os = "macos")]
Mechanism::Marker(m) => m.send_kill(root),
Mechanism::Walk(m) => m.send_kill(root),
#[cfg(test)]
Mechanism::Fake(m) => m.send_kill(root),
}
}
fn kill_left(&self, result: Result<(), Unkilled>, left: Vec<Left>) -> KillLeftOutcome {
match self {
#[cfg(target_os = "linux")]
Mechanism::Cgroup(m) => m.kill_left(result, left),
#[cfg(windows)]
Mechanism::Job(m) => m.kill_left(result, left),
#[cfg(unix)]
Mechanism::Group(m) => m.kill_left(result, left),
#[cfg(target_os = "macos")]
Mechanism::Marker(m) => m.kill_left(result, left),
Mechanism::Walk(m) => m.kill_left(result, left),
#[cfg(test)]
Mechanism::Fake(m) => m.kill_left(result, left),
}
}
fn root_left(&self, root: Error) -> Error {
match self {
#[cfg(target_os = "linux")]
Mechanism::Cgroup(m) => m.root_left(root),
#[cfg(windows)]
Mechanism::Job(m) => m.root_left(root),
#[cfg(unix)]
Mechanism::Group(m) => m.root_left(root),
#[cfg(target_os = "macos")]
Mechanism::Marker(m) => m.root_left(root),
Mechanism::Walk(m) => m.root_left(root),
#[cfg(test)]
Mechanism::Fake(m) => m.root_left(root),
}
}
fn send_terminate(&self, pid: u32, root: Option<&dyn Root>) -> TerminateOutcome {
match self {
#[cfg(target_os = "linux")]
Mechanism::Cgroup(m) => m.send_terminate(pid, root),
#[cfg(windows)]
Mechanism::Job(m) => m.send_terminate(pid, root),
#[cfg(unix)]
Mechanism::Group(m) => m.send_terminate(pid, root),
#[cfg(target_os = "macos")]
Mechanism::Marker(m) => m.send_terminate(pid, root),
Mechanism::Walk(m) => m.send_terminate(pid, root),
#[cfg(test)]
Mechanism::Fake(m) => m.send_terminate(pid, root),
}
}
fn drain_edge(&self) -> Option<DrainEdge<'_>> {
match self {
#[cfg(target_os = "linux")]
Mechanism::Cgroup(m) => m.drain_edge(),
#[cfg(windows)]
Mechanism::Job(m) => m.drain_edge(),
#[cfg(unix)]
Mechanism::Group(m) => m.drain_edge(),
#[cfg(target_os = "macos")]
Mechanism::Marker(m) => m.drain_edge(),
Mechanism::Walk(m) => m.drain_edge(),
#[cfg(test)]
Mechanism::Fake(m) => m.drain_edge(),
}
}
fn kind(&self) -> Containment {
match self {
#[cfg(target_os = "linux")]
Mechanism::Cgroup(m) => m.kind(),
#[cfg(windows)]
Mechanism::Job(m) => m.kind(),
#[cfg(unix)]
Mechanism::Group(m) => m.kind(),
#[cfg(target_os = "macos")]
Mechanism::Marker(m) => m.kind(),
Mechanism::Walk(m) => m.kind(),
#[cfg(test)]
Mechanism::Fake(m) => m.kind(),
}
}
#[cfg(unix)]
fn subject(&self) -> String {
match self {
#[cfg(target_os = "linux")]
Mechanism::Cgroup(m) => m.subject(),
Mechanism::Group(m) => m.subject(),
#[cfg(target_os = "macos")]
Mechanism::Marker(m) => m.subject(),
Mechanism::Walk(m) => m.subject(),
#[cfg(test)]
Mechanism::Fake(m) => m.subject(),
}
}
fn disarm(&self) -> std::io::Result<()> {
match self {
#[cfg(target_os = "linux")]
Mechanism::Cgroup(m) => Contains::disarm(m),
#[cfg(windows)]
Mechanism::Job(m) => Contains::disarm(m),
#[cfg(unix)]
Mechanism::Group(m) => m.disarm(),
#[cfg(target_os = "macos")]
Mechanism::Marker(m) => m.disarm(),
Mechanism::Walk(m) => m.disarm(),
#[cfg(test)]
Mechanism::Fake(m) => m.disarm(),
}
}
#[cfg(unix)]
fn would_reach(&self, pid: u32, pidfd: Option<std::os::fd::BorrowedFd<'_>>) -> std::io::Result<bool> {
match self {
#[cfg(target_os = "linux")]
Mechanism::Cgroup(m) => m.would_reach(pid, pidfd),
Mechanism::Group(m) => m.would_reach(pid, pidfd),
#[cfg(target_os = "macos")]
Mechanism::Marker(m) => m.would_reach(pid, pidfd),
Mechanism::Walk(m) => m.would_reach(pid, pidfd),
#[cfg(test)]
Mechanism::Fake(m) => m.would_reach(pid, pidfd),
}
}
#[cfg(unix)]
fn reached(&self, child: &crate::child::owned::OwnedChild) -> std::io::Result<bool> {
match self {
#[cfg(target_os = "linux")]
Mechanism::Cgroup(m) => m.reached(child),
Mechanism::Group(m) => m.reached(child),
#[cfg(target_os = "macos")]
Mechanism::Marker(m) => m.reached(child),
Mechanism::Walk(m) => m.reached(child),
#[cfg(test)]
Mechanism::Fake(m) => m.reached(child),
}
}
#[cfg(unix)]
fn release(self) -> (Release, Option<Mechanism>) {
match self {
#[cfg(target_os = "linux")]
Mechanism::Cgroup(m) => {
let (release, kept) = m.release();
(release, kept.map(Mechanism::Cgroup))
}
Mechanism::Group(m) => {
let (release, kept) = m.release();
(release, kept.map(Mechanism::Group))
}
#[cfg(target_os = "macos")]
Mechanism::Marker(m) => {
let (release, kept) = m.release();
(release, kept.map(Mechanism::Marker))
}
Mechanism::Walk(m) => {
let (release, kept) = m.release();
(release, kept.map(Mechanism::Walk))
}
#[cfg(test)]
Mechanism::Fake(m) => {
let (release, kept) = m.release();
(release, kept.map(Mechanism::Fake))
}
}
}
#[cfg(all(feature = "tokio", target_os = "linux"))]
fn awaitable_release(&self) -> Option<AwaitableRelease<'_>> {
match self {
Mechanism::Cgroup(m) => m.awaitable_release(),
Mechanism::Group(m) => m.awaitable_release(),
Mechanism::Walk(m) => m.awaitable_release(),
#[cfg(test)]
Mechanism::Fake(m) => m.awaitable_release(),
}
}
}
/// What places an elevation front once its leaf is gone: the leaf's subtree, or why it could not be
/// read. Linux only; elsewhere there is no leaf to read.
#[cfg(unix)]
pub(crate) struct FrontReach(
#[cfg(target_os = "linux")] pub(crate) std::io::Result<Option<crate::containment::cgroup::Subtree>>,
);
/// The end of a mechanism's resource, which [`wait`](Self::wait) completes by dropping it: a cgroup
/// leaf is killed through, drained and removed. [`front_reach`](Self::front_reach) reads what places
/// an elevation front before that, since the first step may remove the leaf.
#[cfg(unix)]
#[must_use = "the resource is released only by its wait"]
pub(crate) struct Release {
held: Held,
}
/// The resource a [`Release`] owns until its wait drops it.
#[cfg(unix)]
enum Held {
Nothing,
#[cfg(target_os = "linux")]
Leaf(crate::containment::cgroup::CgroupLeaf),
}
#[cfg(unix)]
impl Release {
/// The release of a mechanism that owns nothing a wait ends.
pub(crate) fn nothing() -> Release {
Release { held: Held::Nothing }
}
/// The release of a cgroup leaf.
#[cfg(target_os = "linux")]
pub(crate) fn leaf(leaf: crate::containment::cgroup::CgroupLeaf) -> Release {
Release { held: Held::Leaf(leaf) }
}
/// What places an elevation front once the resource is gone, read now: only a caller that looks
/// at a front asks, and it asks before the first step of the teardown.
pub(crate) fn front_reach(&self) -> FrontReach {
match &self.held {
Held::Nothing => {
#[cfg(target_os = "linux")]
{
FrontReach(Ok(None))
}
#[cfg(not(target_os = "linux"))]
{
FrontReach()
}
}
#[cfg(target_os = "linux")]
Held::Leaf(leaf) => FrontReach(leaf.subtree().map(Some)),
}
}
/// Drop the resource: a cgroup leaf is killed through if it is armed and occupied, drained
/// (blocking, warned past the leaf's threshold) and removed. After [`wait_async`](Self::wait_async)
/// it finds nothing left to wait for. It has no deadline: no caller needs one yet.
pub(crate) fn wait(self) {
match self.held {
Held::Nothing => {}
#[cfg(target_os = "linux")]
Held::Leaf(leaf) => drop(leaf),
}
}
/// The awaitable steps of [`wait`](Self::wait), through the resource's
/// [`awaitable_release`](Contains::awaitable_release); a future dropped mid-await leaves the rest
/// to `wait`. `child` names it in debug lines.
#[cfg(feature = "tokio")]
#[cfg_attr(
not(target_os = "linux"),
allow(unused_variables, reason = "only a Linux cgroup leaf has steps to await")
)]
pub(crate) async fn wait_async(&self, child: u32) {
#[cfg(target_os = "linux")]
if let Held::Leaf(leaf) = &self.held {
leaf.awaitable_release()
.expect("a cgroup leaf always has awaitable steps")
.wait(child)
.await;
}
}
}