cosca 0.8.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
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
//! Linux: a tree call on a process group whose root is reaped. On 6.9+ the root's pidfd names the
//! group exactly, whoever reaped the root; below 6.9 the root's own handle decides what goes out by
//! the group's number.

use std::io::Read as _;

use crate::test_child::Console;

use crate::send_log::{Capture, GroupStep, Route};
use crate::test_child::member::{await_started, Member, RELEASE_FD, ROOT_WITH_A_MEMBER};
use crate::test_child::reaped_elsewhere::{foreign_reaped_group_root, kill_own_child, reap_behind};
use crate::test_groups::{pidfd_group_signal, stray_signal, Group};

/// A [`ROOT_WITH_A_MEMBER`] spawn, once its member exists.
pub(crate) fn root_with_a_member() -> (crate::Child, Member) {
    let (stdio, started, member) = Member::pipes();
    let child = {
        let mut cmd = crate::test_child::command(Console::Hidden);
        cmd.args(ROOT_WITH_A_MEMBER);
        cmd.contain_with(crate::ContainMode::Session);
        cmd.stdin(stdio.stdin).expect("set stdin");
        cmd.stdout(stdio.stdout).expect("set stdout");
        cmd.stderr(stdio.stderr).expect("set stderr");
        cmd.fd(RELEASE_FD, stdio.release).expect("set the release fd");
        cmd.spawn().expect("spawn")
    };
    await_started(started);
    (child, member)
}

/// Ends `member` when a graceful shutdown on this thread reaches the end of its `SIGTERM`, before
/// any sweep, and keeps what it said.
pub(crate) struct EndedAtTheSigterm {
    said: std::rc::Rc<std::cell::RefCell<Option<String>>>,
    hook: crate::oneshot_hook::Armed,
}

impl EndedAtTheSigterm {
    pub(crate) fn new(member: Member) -> EndedAtTheSigterm {
        let said = std::rc::Rc::new(std::cell::RefCell::new(None));
        let hook = crate::graceful_hooks::at(crate::graceful_hooks::HookPoint::AfterTerminate, {
            let said = said.clone();
            move || *said.borrow_mut() = Some(member.end())
        });
        EndedAtTheSigterm { said, hook }
    }

    /// Asserts the `SIGTERM` killed the member: a sweep after it cannot. Without the hook's run, the
    /// member is ended here and the assertion fails.
    #[track_caller]
    pub(crate) fn assert_killed_by_the_sigterm(self) {
        let EndedAtTheSigterm { said, hook } = self;
        drop(hook);
        let said = said.take().expect("the shutdown reached the end of its SIGTERM");
        assert!(
            !said.contains("survived"),
            "the group's member outlived the SIGTERM: {said:?}"
        );
    }
}

/// 6.9+: a root reaped by another reaper still names its group through its pidfd, so `kill_tree`
/// kills the members left.
#[skuld::test]
fn kill_tree_kills_the_group_of_a_root_reaped_elsewhere(#[fixture(pidfd_group_signal)] _group: &Group) {
    let (child, member) = root_with_a_member();
    let pid = child.pid();
    kill_own_child(pid);
    reap_behind(pid);
    let capture = Capture::start();
    let result = child.kill_tree();
    let steps = capture.group_steps();
    result.expect("the group is killed through the root's pidfd");
    assert_eq!(
        steps.first(),
        Some(&GroupStep::Group(Route::Pidfd, libc::SIGKILL)),
        "{steps:?}"
    );
    member.assert_killed();
}

/// 6.9+: a root reaped by another reaper whose group has no member left has no tree to kill:
/// `kill_tree` sends nothing and succeeds. Mutants: "a group with no member left is still
/// unassessable", "it is signalled through the pidfd regardless".
#[skuld::test]
fn kill_tree_of_a_root_reaped_elsewhere_with_no_member_left_sends_nothing(
    #[fixture(pidfd_group_signal)] _group: &Group,
    #[fixture(stray_signal)] _stray: &Group,
) {
    let (child, _pgid) = foreign_reaped_group_root();
    let capture = Capture::start();
    let result = child.kill_tree();
    let steps = capture.group_steps();
    result.expect("an empty group is killed already");
    assert_eq!(steps, [], "nothing was sent");
}

/// Below 6.9, after this handle's own reap, a root pid that names no process may be taken once the
/// group has no member, so `kill_tree` sends nothing by it, answers `Unassessable` with how to end
/// the descendants, and the group's member lives on.
#[skuld::test]
fn kill_tree_below_6_9_sends_nothing_to_the_group_after_this_handles_own_reap() {
    let (child, member) = root_with_a_member();
    kill_own_child(child.pid());
    child.wait().expect("this handle reaps the root");
    let old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
    let refused = crate::containment::unix::fault::refuse_group_sends();
    let groups = crate::containment::unix::fault::record_kill_group();
    let capture = Capture::start();
    let result = child.kill_tree();
    let steps = capture.group_steps();
    drop((old_kernel, refused));
    assert_eq!(groups.killed(), Vec::<i32>::new(), "no kill of the group by its number");
    let err = result.expect_err("a group the pid no longer names is not assessable");
    assert!(
        err.to_string()
            .contains(crate::child::drop_report::END_THEM_BEFORE_WAIT),
        "{err}"
    );
    assert_eq!(steps, [], "nothing was sent to the group");
    member.assert_survived();
}

/// 6.9+: after this handle's own reap the root's pidfd still names its group exactly, so `kill_tree`
/// kills the members left through it, though the pid names no process.
#[skuld::test]
fn kill_tree_after_this_handles_own_reap_kills_the_group_through_the_pidfd_while_it_has_a_member(
    #[fixture(pidfd_group_signal)] _group: &Group,
) {
    let (child, member) = root_with_a_member();
    kill_own_child(child.pid());
    child.wait().expect("this handle reaps the root");
    let _gone = crate::child::fault::force_root_reads(crate::identity::Resolved::Gone);
    let capture = Capture::start();
    let result = child.kill_tree();
    let steps = capture.group_steps();
    result.expect("the group is killed through the root's pidfd");
    assert_eq!(
        steps.first(),
        Some(&GroupStep::Group(Route::Pidfd, libc::SIGKILL)),
        "{steps:?}"
    );
    member.assert_killed();
}

/// 6.9+: a root whose handle cannot say whether it was reaped still names its group exactly through
/// its pidfd, so `kill_tree` kills the group as usual. Mutant: "only a reaped root's group is
/// decided by the pidfd".
#[skuld::test]
fn kill_tree_of_a_root_its_handle_cannot_read_kills_its_group_through_the_pidfd(
    #[fixture(pidfd_group_signal)] _group: &Group,
) {
    let (mut child, member) = root_with_a_member();
    let capture = Capture::start();
    let fake = child
        .proc
        .script_over(|f| f.peeks([Err(std::io::Error::other("forced peek failure"))]));
    let result = child.kill_tree();
    fake.assert_peeks_exhausted();
    let steps = capture.group_steps();
    result.expect("the group is killed through the root's pidfd");
    assert_eq!(
        steps.first(),
        Some(&GroupStep::Group(Route::Pidfd, libc::SIGKILL)),
        "{steps:?}"
    );
    member.assert_killed();
}

/// A session root reaped elsewhere whose group keeps one member, and a process of this test that
/// leads a group of its own. Armed, the group's own send is refused, the member then leaves the
/// group, which leaves it empty, and the other group stands in for one that took its number before
/// `converge` lists it.
pub(crate) struct EmptiedGroup {
    root: crate::Child,
    stdin: crate::PipeWriter,
    stdout: crate::PipeReader,
    stderr: crate::PipeReader,
    other: std::process::Child,
}

impl EmptiedGroup {
    pub(crate) fn new() -> EmptiedGroup {
        use crate::test_child::{await_member_ready, member_command};
        // The member waits for a line on stdin, then leaves the group by `setsid`, says so, and holds
        // stderr's write end until stdin's EOF. The root, `exec cat`, reads the same stdin: nothing is
        // written to it until the root is dead, so no byte reaches the root instead of the member.
        let mut cmd = crate::test_child::command(Console::Hidden);
        cmd.args([
            "sh",
            "-c",
            r#"exec 3<&0; sh -c 'read _ <&3; exec setsid sh -c "echo left; exec cat <&3 3<&- >/dev/null"' & echo started; exec cat 3<&- 2>/dev/null"#,
        ]);
        cmd.contain_with(crate::ContainMode::Session);
        cmd.stdin(crate::Stdio::pipe_in()).expect("stdin pipe");
        cmd.stdout(crate::Stdio::pipe_out()).expect("stdout pipe");
        cmd.stderr(crate::Stdio::pipe_out()).expect("stderr pipe");
        let mut root = cmd.spawn().expect("spawn the root");
        let mut stdout = root.stdout().expect("stdout pipe");
        let mut started = [0u8; 8];
        stdout.read_exact(&mut started).expect("read `started`");
        assert_eq!(&started, b"started\n");
        let (stdin, stderr) = (root.stdin().expect("stdin pipe"), root.stderr().expect("stderr pipe"));
        let pid = root.pid();
        kill_own_child(pid);
        reap_behind(pid);
        let mut other = crate::test_spawn::spawn(&mut member_command(0)).expect("spawn the other group's leader");
        await_member_ready(&mut other);
        EmptiedGroup {
            root,
            stdin,
            stdout,
            stderr,
            other,
        }
    }

    /// Arms the refusal, the listing of the other group, and the member's leaving right after the
    /// listing. Returns the root, and what ends the test ([`Armed::finish`]).
    pub(crate) fn arm(self) -> (crate::Child, Armed) {
        use std::io::Write as _;
        let EmptiedGroup {
            root,
            stdin,
            mut stdout,
            stderr,
            other,
        } = self;
        let refused = crate::containment::unix::fault::refuse_group_sends();
        let listed = crate::containment::unix::fault::list_instead(other.id() as i32);
        let mut tell = stdin.try_clone().expect("clone stdin");
        let left = crate::containment::unix::fault::set_after_listing(move || {
            tell.write_all(b"\n").expect("tell the member to leave");
            let mut left = [0u8; 5];
            stdout.read_exact(&mut left).expect("read `left`");
            assert_eq!(&left, b"left\n");
        });
        let armed = Armed {
            guard: Box::new((refused, listed, left)),
            stdin,
            stderr,
            other,
        };
        (root, armed)
    }
}

/// An armed [`EmptiedGroup`] without its root.
pub(crate) struct Armed {
    guard: Box<dyn std::any::Any>,
    stdin: crate::PipeWriter,
    stderr: crate::PipeReader,
    other: std::process::Child,
}

impl Armed {
    /// Disarms, asserts the other group's leader was sent nothing and ends it, and ends the member
    /// that left the group.
    pub(crate) fn finish(self) {
        use std::os::unix::process::ExitStatusExt as _;
        let Armed {
            guard,
            stdin,
            mut stderr,
            mut other,
        } = self;
        drop(guard);
        // It exits at its stdin's EOF, so a signal that ended it shows in its status.
        drop(other.stdin.take());
        let status = other.wait().expect("reap the other group's leader");
        drop(stdin);
        let mut rest = Vec::new();
        stderr.read_to_end(&mut rest).expect("read stderr to the member's end");
        assert_eq!(
            status.signal(),
            None,
            "the other group's leader was signalled: {status:?}"
        );
    }
}

/// 6.9+: a process listed by the number of a group the root's pidfd shows has no member left is in
/// another group that took the number: it is sent nothing, and `kill_tree` succeeds. Mutant: "a
/// group with no member left leaves the listed process unassessable".
#[skuld::test]
fn kill_tree_leaves_alone_a_group_that_took_the_number_of_its_emptied_group(
    #[fixture(pidfd_group_signal)] _group: &Group,
) {
    let (child, armed) = EmptiedGroup::new().arm();
    let root = child.pid();
    let capture = Capture::start();
    let result = child.kill_tree();
    let sent = capture.by_identity();
    armed.finish();
    result.expect("the tree is gone");
    assert!(
        sent.iter().all(|&(pid, _)| pid == root),
        "nothing was resent to a member: {sent:?}"
    );
}

/// 6.9+: a process listed by the number of a group the root's pidfd shows has no member left is in
/// another group that took the number: one that refuses `terminate_tree`'s probe does not fail the
/// call. Mutant: "the probe asks no root check".
#[skuld::test]
fn terminate_tree_leaves_alone_a_group_that_took_the_number_of_its_emptied_group(
    #[fixture(pidfd_group_signal)] _group: &Group,
) {
    let (child, armed) = EmptiedGroup::new().arm();
    let refusing = crate::containment::unix::fault::refuse_probes();
    let result = child.terminate_tree();
    drop(refusing);
    armed.finish();
    result.expect("the tree is gone");
}

/// What `graceful_shutdown_tree` returns once the tree of a root reaped elsewhere is down.
pub(crate) const STATUS_REAPED_ELSEWHERE: &str = "exit status cannot be collected: the root was reaped elsewhere";

/// Asserts `result` is the answer of a shutdown that brought the tree down but could not collect the
/// root's status, and that it warned of nothing left behind but, for an async handle, tokio's own
/// handle of the root reaped elsewhere.
#[track_caller]
pub(crate) fn assert_down_without_status(result: Result<std::process::ExitStatus, crate::error::Error>, mark: usize) {
    match result {
        Err(crate::error::Error::Unassessable {
            detail,
            source: Some(cause),
        }) => {
            assert!(detail.contains(STATUS_REAPED_ELSEWHERE), "{detail}");
            assert_eq!(crate::error::first_os_code(&*cause), Some(libc::ECHILD), "{cause:?}");
        }
        other => panic!("expected the tree down without the root's status, got {other:?}"),
    }
    let mut warns = crate::log_capture::warns_since(mark, "");
    warns.retain(|warn| !warn.contains("forgetting tokio's handle for it leaks"));
    assert_eq!(warns, Vec::<String>::new(), "nothing was left behind");
}

/// 6.9+: `terminate_tree` of a root reaped elsewhere still signals its group through the root's
/// pidfd. Mutants: "the pidfd decides only `kill_tree`", "the send through the pidfd carries signal
/// 0", "it is recorded and not made".
#[skuld::test]
fn terminate_tree_signals_the_group_of_a_root_reaped_elsewhere(#[fixture(pidfd_group_signal)] _group: &Group) {
    let (child, member) = root_with_a_member();
    let pid = child.pid();
    kill_own_child(pid);
    reap_behind(pid);
    let capture = Capture::start();
    let result = child.terminate_tree();
    let steps = capture.group_steps();
    result.expect("the group is signalled through the root's pidfd");
    assert_eq!(
        steps.first(),
        Some(&GroupStep::Group(Route::Pidfd, libc::SIGTERM)),
        "{steps:?}"
    );
    member.assert_killed();
}

/// 6.9+: `terminate_tree` of a root reaped elsewhere whose group has no member left sends nothing
/// and succeeds. Mutants: "a group with no member left is still unassessable", "it is signalled
/// through the pidfd regardless".
#[skuld::test]
fn terminate_tree_of_a_root_reaped_elsewhere_with_no_member_left_sends_nothing(
    #[fixture(pidfd_group_signal)] _group: &Group,
    #[fixture(stray_signal)] _stray: &Group,
) {
    let (child, _pgid) = foreign_reaped_group_root();
    let capture = Capture::start();
    let result = child.terminate_tree();
    let steps = capture.group_steps();
    result.expect("an empty group has nothing to signal");
    assert_eq!(steps, [], "nothing was sent");
}

/// 6.9+: `graceful_shutdown_tree` of a root reaped elsewhere shuts its group down through the root's
/// pidfd, then answers that the root's status went to the other reaper. Mutants: "only the root is
/// shut down through its pidfd", "the shutdown ends on the root's lost status", "graceful sends no
/// `SIGTERM`".
#[skuld::test]
fn graceful_shutdown_tree_shuts_down_the_group_of_a_root_reaped_elsewhere(
    #[fixture(pidfd_group_signal)] _group: &Group,
) {
    crate::log_capture::install();
    let (child, member) = root_with_a_member();
    let pid = child.pid();
    kill_own_child(pid);
    reap_behind(pid);
    let mark = crate::log_capture::mark();
    let ended = EndedAtTheSigterm::new(member);
    let capture = Capture::start();
    let result = child.graceful_shutdown_tree(std::time::Duration::from_secs(1));
    let steps = capture.group_steps();
    assert_eq!(
        steps.first(),
        Some(&GroupStep::Group(Route::Pidfd, libc::SIGTERM)),
        "{steps:?}"
    );
    ended.assert_killed_by_the_sigterm();
    assert_down_without_status(result, mark);
}

/// 6.9+: `graceful_shutdown_tree` of a root reaped elsewhere whose group has no member left sends
/// nothing, and answers that the root's status went to the other reaper. Mutants: "a group with no
/// member left ends the call unassessable", "it is signalled through the pidfd regardless".
#[skuld::test]
fn graceful_shutdown_tree_of_a_root_reaped_elsewhere_with_no_member_left_sends_nothing(
    #[fixture(pidfd_group_signal)] _group: &Group,
    #[fixture(stray_signal)] _stray: &Group,
) {
    crate::log_capture::install();
    let (child, _pgid) = foreign_reaped_group_root();
    let mark = crate::log_capture::mark();
    let capture = Capture::start();
    let result = child.graceful_shutdown_tree(std::time::Duration::from_secs(1));
    let steps = capture.group_steps();
    assert_eq!(steps, [], "nothing was sent");
    assert_down_without_status(result, mark);
}