cosca 0.10.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
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
//! macOS: the sync `Child`'s graceful shutdowns while the root's state is `Unpinned` (launchd holds
//! its zombie) or `Unknown`. The refusal is the one report: the waits on the way stay quiet and
//! never reap a zombie launchd holds. Each refusal is followed by a call on the same child once its
//! state reads true, which must send, so a refusal that never lets go fails too.

use std::sync::{Arc, Mutex};
use std::time::Duration;

use super::graceful::fault as graceful_fault;
use super::unpinned_public_tests::{
    assert_descendant_dies, assert_holders_only, assert_nothing_sent, assert_refused, assert_sent_by_identity,
    assert_tree_refused, assert_tree_refused_caused_by, group_blocker, orphan, session_tree, walked_blocker, Cause,
    Untrusted, BOTH,
};
use crate::error::Error;
use crate::log_capture::warns_since;
use crate::os_process::child::{Foreign, PeekOutcome};
use crate::os_process::fake::{FakeProcess, ReapAnswer};
use crate::send_log::{Capture, Via};
use crate::signal::Sig;

/// The hook that makes the next peek of `fake`'s root read `Orphaned`, for a test that flips the
/// state at a point of the shutdown.
fn orphan_next_peek(fake: &FakeProcess) -> impl FnOnce() + 'static {
    let fake = fake.clone();
    move || drop(fake.peeks([Untrusted::Unpinned.result()]))
}

/// The reap is where a root orphaned late is found out.
fn orphan_next_reap(fake: &FakeProcess) -> impl FnOnce() + 'static {
    let fake = fake.clone();
    move || drop(fake.reaps([ReapAnswer::Foreign(Foreign::Orphaned)]))
}

// graceful_shutdown =====

/// A root that is orphaned when the shutdown begins is refused by its `terminate`, with no grace
/// and no kill. Once it reads true the same call shuts it down.
///
/// Mutants: `terminate` sends without reading the root's state, so the shutdown goes on; the
/// refusal never lets go.
#[skuld::test]
fn graceful_shutdown_of_an_orphaned_root_sends_nothing() {
    crate::log_capture::install();
    let (mut child, writer) = walked_blocker();
    let sends = Capture::start();
    let mark = crate::log_capture::mark();
    let fake = orphan(&mut child);

    let err = child
        .graceful_shutdown(Duration::ZERO)
        .expect_err("a root this process does not pin is not shut down");

    fake.assert_peeks_exhausted();
    assert_refused(&err, "terminate");
    assert_nothing_sent(&sends);
    assert_eq!(warns_since(mark, ""), Vec::<String>::new());

    child
        .graceful_shutdown(Duration::ZERO)
        .expect("a root that reads true is shut down");
    assert_ne!(sends.by_identity(), vec![], "the second call sent nothing");
    drop(writer);
}

/// A root that goes orphaned during the grace is not killed by the escalation. The child ignores
/// `SIGTERM`, so the escalation is reached; the hook makes the next peek `Orphaned`. The refusal
/// says the `SIGTERM` was sent, and the `SIGTERM` is the only signal the root was sent. Once the
/// root reads true the escalation kills it.
///
/// Mutants: the escalation kills through the handle without reading the root's state; it says it
/// sent nothing at all; the refusal never lets go.
#[skuld::test]
fn graceful_shutdown_does_not_escalate_to_a_root_orphaned_during_the_grace() {
    crate::log_capture::install();
    let (mut child, writer) = crate::test_child::term_ignoring_blocker();
    let pid = child.pid();
    let sends = Capture::start();
    let mark = crate::log_capture::mark();
    let fake = child.proc.script_over(|f| f);
    let hook = crate::graceful_hooks::at(
        crate::graceful_hooks::HookPoint::BeforeEscalation,
        orphan_next_peek(&fake),
    );

    let err = child
        .graceful_shutdown(Duration::ZERO)
        .expect_err("a root this process does not pin is not killed");

    fake.assert_peeks_exhausted();
    assert_refused(&err, "kill");
    assert!(
        matches!(&err, Error::Unassessable { detail, .. } if detail.contains("though the SIGTERM was sent before it")),
        "{err:?}"
    );
    assert_eq!(
        sends.entries(),
        vec![(pid, Sig::Graceful(crate::signal::Signal::Term), Via::Identity)],
        "the escalation must send nothing to a root we do not pin: the terminate's SIGTERM is the only send"
    );
    assert_eq!(warns_since(mark, ""), Vec::<String>::new());
    drop(hook);

    let status = child
        .graceful_shutdown(Duration::ZERO)
        .expect("a root that reads true is escalated to");
    crate::test_child::assert_killed("the term-ignoring root", status);
    drop(writer);
}

/// [`graceful_shutdown_does_not_escalate_to_a_root_orphaned_during_the_grace`] for a caller's own action
/// that sent no prepared send: the refusal words what was sent before it as "the stop action", not as the
/// default's signal.
///
/// Mutants: the refusal names the `SIGTERM` whatever the action did; it says it sent nothing at all.
#[skuld::test]
fn graceful_shutdown_words_a_callers_own_action_in_the_escalations_refusal() {
    use crate::test_child::{command, Console, BLOCKER_ARGV};

    crate::log_capture::install();
    let mut cmd = command(Console::Hidden);
    cmd.args(BLOCKER_ARGV.iter().copied());
    cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
    cmd.stdout(crate::Stdio::null()).expect("set stdout null");
    cmd.contain();
    cmd.graceful_stop(|_| Ok(()));
    let mut child = cmd.spawn().expect("spawn");
    let writer = child.stdin().expect("piped stdin");
    let fake = child.proc.script_over(|f| f);
    let hook = crate::graceful_hooks::at(
        crate::graceful_hooks::HookPoint::BeforeEscalation,
        orphan_next_peek(&fake),
    );

    let err = child
        .graceful_shutdown(Duration::ZERO)
        .expect_err("a root this process does not pin is not killed");

    fake.assert_peeks_exhausted();
    assert_refused(&err, "kill");
    assert!(
        matches!(&err, Error::Unassessable { detail, .. } if detail.contains("though the stop action was sent before it")),
        "{err:?}"
    );
    drop(hook);

    let status = child
        .graceful_shutdown(Duration::ZERO)
        .expect("a root that reads true is escalated to");
    crate::test_child::assert_killed("the blocker", status);
    drop(writer);
}

/// A root that exited and is held by launchd is neither killed nor looked at before the reap, and
/// nothing warns that the zombie is not ours to reap: the grace watch ends at once on the exit, with
/// the grace unspent, and the reap's own answer, that launchd holds it, is the refusal, saying the
/// exit status cannot be collected. The root's exit watch reading past `NOTE_EXIT` for a parent that
/// is launchd is pinned beside `MacosChild::exited`.
///
/// Mutants: the grace watch or the reap warns that the zombie is not ours to reap; the call looks
/// at the root before the reap instead of asking the reap; the escalation kills an exited root; the
/// grace is spent on a root that has exited.
#[skuld::test]
fn graceful_shutdown_of_an_exited_root_launchd_holds_is_refused_without_a_warn() {
    use crate::os_process::fake::Answer;
    use crate::test_child::over_fake::{child_over, root_looking};

    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let root = root_looking([Answer::Exited]).reaps([ReapAnswer::Foreign(Foreign::Orphaned)]);
    let child = child_over(&root);

    let err = child
        .graceful_shutdown(Duration::from_secs(3600))
        .expect_err("the status of a zombie launchd holds cannot be collected");

    assert!(
        matches!(&err, Error::Unassessable { detail, source: None }
            if detail.contains("graceful_shutdown sent its signals")
                && detail.contains("exit status cannot be collected")
                && detail.contains("launchd")),
        "{err:?}"
    );
    assert_eq!(
        root.signal_calls(),
        vec![Sig::Graceful(crate::signal::Signal::Term)],
        "only the SIGTERM was sent"
    );
    assert_eq!(root.looks(), 2, "one look at the exit, and the reap's");
    assert_eq!(warns_since(mark, ""), Vec::<String>::new());
}

/// Control for the quiet wait: the public `wait_timeout` still reports a zombie launchd holds.
///
/// Mutant: every wait is quiet.
#[skuld::test]
fn wait_timeout_still_warns_of_an_orphaned_root() {
    crate::log_capture::install();
    let (mut child, writer) = walked_blocker();
    let mark = crate::log_capture::mark();
    // The wait's own look is a reap.
    let fake = child
        .proc
        .script_over(|f| f.reaps([ReapAnswer::Foreign(Foreign::Orphaned)]));

    child
        .wait_timeout(Duration::ZERO)
        .expect_err("a zombie launchd holds is not reaped");

    assert_eq!(fake.looks(), 1, "the wait looked once");
    let warns = warns_since(mark, "");
    assert_eq!(warns.len(), 1, "{warns:?}");
    assert!(warns[0].contains("not ours to reap"), "{warns:?}");
    drop(writer);
}

// graceful_shutdown_tree =====

/// Mechanisms with no channel by identity (a tree walk, a process group) have nothing to signal,
/// wait for or sweep: the shutdown ends up front, before the grace. The hook at the first point
/// after the terminate fails the test if the shutdown gets that far. Once the root reads true the
/// same call shuts the tree down.
///
/// Mutants: the check is dropped, or moved after the terminate or the grace wait; the refusal never
/// lets go; `Unknown` is let through.
#[skuld::test]
fn graceful_shutdown_tree_of_an_untrusted_root_with_no_identity_channel_ends_up_front() {
    crate::log_capture::install();
    for state in BOTH {
        for group in [false, true] {
            let groups = crate::containment::unix::fault::record_term_group();
            let (mut child, writer) = if group { group_blocker() } else { walked_blocker() };
            let sends = Capture::start();
            let mark = crate::log_capture::mark();
            let hook = crate::graceful_hooks::at(crate::graceful_hooks::HookPoint::AfterTerminate, || {
                panic!("the grace wait began on a root this process cannot vouch for")
            });
            let fake = state.script(&mut child);

            let err = child
                .graceful_shutdown_tree(Duration::from_secs(3600))
                .expect_err("a root this process cannot vouch for is not shut down");

            fake.assert_peeks_exhausted();
            assert_tree_refused(&err, "graceful_shutdown_tree", state);
            assert_nothing_sent(&sends);
            assert_eq!(groups.termed(), Vec::<i32>::new(), "{state:?}, group: {group}");
            assert_eq!(warns_since(mark, ""), Vec::<String>::new(), "{state:?}, group: {group}");
            drop(hook);

            child
                .graceful_shutdown_tree(Duration::ZERO)
                .expect("a root that reads true is shut down");
            drop(writer);
        }
    }
}

/// An fd marker still has its holders: they get the `SIGTERM` by identity, and no `killpg`. A hook
/// right after the terminate reads who was signalled, before the sweep: the descendant, and the
/// root only when it is `Unknown`, not `Unpinned`. The grace is zero, so the sweep follows at
/// once. The root reads the same to the sweep, which kills the holders and is `Unassessable`
/// all the same, as it skipped the rest of the tree.
///
/// Mutants: the terminate fires `killpg`; it signals the `Unpinned` root; it spares the `Unknown`
/// root; it signals no holder; the sweep does not look at the root; the sweep's answer is `Ok`.
#[skuld::test]
fn graceful_shutdown_tree_of_an_untrusted_session_root_signals_its_holders_only() {
    crate::log_capture::install();
    for state in BOTH {
        let groups = crate::containment::unix::fault::record_term_group();
        let _holders = crate::containment::fdmarker::fault::record_holder_kills();
        let (mut child, writer, descendant, gone) = session_tree();
        let sends = Capture::start();
        let pid = child.pid();
        let mark = crate::log_capture::mark();
        let after_terminate: Arc<Mutex<Option<Vec<u32>>>> = Arc::default();
        let hook = crate::graceful_hooks::at(crate::graceful_hooks::HookPoint::AfterTerminate, {
            let seen = Arc::clone(&after_terminate);
            move || {
                *seen.lock().expect("the hook's slot") =
                    Some(crate::containment::fdmarker::fault::holder_kills_so_far())
            }
        });
        // The terminate's look and the sweep's.
        let fake = child.proc.script_over(|f| f.peeks([state.result(), state.result()]));

        let err = child
            .graceful_shutdown_tree(Duration::ZERO)
            .expect_err("the sweep reached the holders only, and skipped the rest of the tree");
        fake.assert_peeks_exhausted();
        assert_holders_only(&err, "graceful_shutdown_tree", state);

        drop(hook);
        assert_eq!(groups.termed(), Vec::<i32>::new(), "{state:?}");
        let mut signalled = after_terminate
            .lock()
            .expect("the hook's slot")
            .clone()
            .expect("the terminate ran");
        signalled.sort_unstable();
        signalled.dedup();
        let want = match state {
            Untrusted::Unpinned => vec![descendant],
            Untrusted::Unknown => {
                let mut both = vec![pid, descendant];
                both.sort_unstable();
                both
            }
        };
        assert_eq!(signalled, want, "{state:?}");
        assert_sent_by_identity(&sends, libc::SIGTERM, &want, state);
        assert_eq!(warns_since(mark, ""), Vec::<String>::new(), "{state:?}");
        assert_descendant_dies(gone);
        drop(writer);
    }
}

/// The cooperative signal is decided on one look at the root's state, as `terminate_tree`'s is. The
/// hook right after it counts the looks left.
///
/// Mutant: the untrusted-root check and the reaped-root check each look, and the second look's
/// `Unpinned` is let through to the group signal.
#[skuld::test]
fn graceful_shutdown_tree_decides_its_signal_on_one_look_at_the_root() {
    let _termed = crate::containment::unix::fault::record_term_group();
    let _killed = crate::containment::unix::fault::record_kill_group();
    let (mut child, writer) = group_blocker();
    let left: Arc<Mutex<Option<usize>>> = Arc::default();
    let fake = child
        .proc
        .script_over(|f| f.peeks([Ok(PeekOutcome::Running), Ok(PeekOutcome::Foreign(Foreign::Orphaned))]));
    let _hook = crate::graceful_hooks::at(crate::graceful_hooks::HookPoint::AfterTerminate, {
        let left = Arc::clone(&left);
        let fake = fake.clone();
        move || *left.lock().expect("the hook's slot") = Some(fake.peeks_left())
    });

    // The sweep and the reap that follow are not under test.
    _ = child.graceful_shutdown_tree(Duration::ZERO);

    assert_eq!(
        *left.lock().expect("the hook's slot"),
        Some(1),
        "the signal's decision looked at the root twice"
    );
    // The answer left over must not reach the drop.
    drop(fake.peeks([]));
    drop(writer);
}

/// A root orphaned during the grace is refused by the sweep, which sends it nothing, and the
/// refusal says the `SIGTERM` was sent. The hook flips the next peek between the terminate and the
/// sweep.
///
/// Mutants: the sweep (`kill_tree`) does not read the root's state; it says it sent nothing at all.
#[skuld::test]
fn graceful_shutdown_tree_sweep_refuses_a_root_orphaned_during_the_grace() {
    crate::log_capture::install();
    let (mut child, writer) = walked_blocker();
    let pid = child.pid();
    let sends = Capture::start();
    let mark = crate::log_capture::mark();
    let fake = child.proc.script_over(|f| f);
    let _hook = crate::graceful_hooks::at(
        crate::graceful_hooks::HookPoint::AfterTerminate,
        orphan_next_peek(&fake),
    );

    let err = child
        .graceful_shutdown_tree(Duration::ZERO)
        .expect_err("a root this process does not pin is not swept");

    fake.assert_peeks_exhausted();
    assert_tree_refused(&err, "graceful_shutdown_tree", Untrusted::Unpinned);
    assert!(
        matches!(&err, Error::Unassessable { detail, .. } if detail.contains("though the SIGTERM was sent before it")),
        "{err:?}"
    );
    // The terminate sent the root its SIGTERM through the handle; the refused sweep sent it nothing.
    assert_eq!(
        sends.entries(),
        vec![(pid, Sig::Graceful(crate::signal::Signal::Term), Via::Identity)]
    );
    assert!(
        !sends.by_identity().iter().any(|(_, signo)| *signo == libc::SIGKILL),
        "{:?}",
        sends.by_identity()
    );
    assert_eq!(warns_since(mark, ""), Vec::<String>::new());
    drop(writer);
}

/// The best-effort reap after a failed sweep finds a root launchd holds out by asking the reap: it
/// is an exited zombie, so the root reads as exited, the reap answers `Orphaned`, and nothing warns
/// or waits. The root is a real zombie; the sweep's look reads it `Orphaned`, and the reap's answer
/// is stated.
///
/// Mutant: the best-effort reap waits on, or warns of, an `Unpinned` root.
#[skuld::test]
fn graceful_shutdown_tree_does_not_reap_an_exited_orphaned_root_after_a_failed_sweep() {
    crate::log_capture::install();
    let (mut child, writer) = walked_blocker();
    let pid = child.pid();
    // SAFETY: `pid` is this test's own child.
    assert_eq!(unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) }, 0);
    crate::test_child::wait_until_zombie(pid);
    graceful_fault::set_force_terminate(graceful_fault::Forced::Containment);
    let mark = crate::log_capture::mark();
    // The entry's read and the sweep's; the reap's answer.
    let fake = child.proc.script_over(|f| {
        f.peeks([Ok(PeekOutcome::Running), Ok(PeekOutcome::Foreign(Foreign::Orphaned))])
            .reaps([ReapAnswer::Foreign(Foreign::Orphaned)])
    });

    let err = child
        .graceful_shutdown_tree(Duration::ZERO)
        .expect_err("a root this process does not pin is not swept");

    fake.assert_peeks_exhausted();
    // The cooperative signal's forced failure is the sweep refusal's source.
    assert_tree_refused_caused_by(&err, "graceful_shutdown_tree", Untrusted::Unpinned, Cause::ForcedTerm);
    assert!(
        crate::test_child::is_unreaped_child(pid),
        "the zombie launchd holds was waited on"
    );
    assert_eq!(warns_since(mark, ""), Vec::<String>::new());
    drop(writer);
}

/// A root orphaned after the sweep is not waited on: the reap answers that launchd holds it, its
/// status cannot be collected, and the error says so instead of the wait warning. The zombie is left
/// as it was.
///
/// Mutant: the reap waits on an `Unpinned` root.
#[skuld::test]
fn graceful_shutdown_tree_does_not_wait_for_a_root_orphaned_before_its_reap() {
    crate::log_capture::install();
    let (mut child, writer) = walked_blocker();
    let pid = child.pid();
    let mark = crate::log_capture::mark();
    let fake = child.proc.script_over(|f| f);
    let _hook = crate::graceful_hooks::at(crate::graceful_hooks::HookPoint::BeforeReap, orphan_next_reap(&fake));

    let err = child
        .graceful_shutdown_tree(Duration::ZERO)
        .expect_err("the status of a zombie launchd holds cannot be collected");

    fake.assert_peeks_exhausted();
    assert!(
        matches!(&err, Error::Unassessable { detail, source: None } if detail.contains("exit status cannot be collected")),
        "{err:?}"
    );
    assert!(
        crate::test_child::is_unreaped_child(pid),
        "the zombie launchd holds was waited on"
    );
    assert_eq!(warns_since(mark, ""), Vec::<String>::new());
    drop(writer);
}