subc-daemon 0.54.12

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
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
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
use super::*;
use cortexkit_test_support::ScratchDir;
use std::{fs, path::Path};

async fn cleanup_reaped_cgroup(
    placement: &subc_cgroup::Placement,
    name: &str,
) -> Option<ordinary_cgroup::Unresolved> {
    ordinary_cgroup::cleanup(placement, &placement.module_path(name).unwrap()).await
}

struct KernelCgroup {
    root: PathBuf,
    placement: subc_cgroup::Placement,
    modules: PathBuf,
}

impl KernelCgroup {
    fn new(test_name: &str) -> Option<Self> {
        let required = std::env::var_os("SUBC_REQUIRE_CGROUP_TEST").is_some()
            || std::env::var_os("SUBC_TEST_CGROUP_REQUIRED").is_some();
        let base = std::env::var_os("SUBC_TEST_CGROUP_ROOT")
            .map(PathBuf::from)
            .or_else(|| {
                std::env::var_os("SUBC_REQUIRE_CGROUP_TEST")
                    .map(|_| PathBuf::from("/sys/fs/cgroup"))
            });
        let Some(base) = base else {
            assert!(
                !required,
                "required cgroup test needs SUBC_TEST_CGROUP_ROOT"
            );
            eprintln!("SKIP {test_name}: set SUBC_TEST_CGROUP_ROOT to an owned delegated cgroup");
            return None;
        };
        let root = base.join(format!(
            "subc-reap-test-{test_name}-{}-{}",
            std::process::id(),
            unix_ms_now()
        ));
        if let Err(error) = fs::create_dir(&root) {
            assert!(!required, "required cgroup test cannot execute: {error}");
            eprintln!("SKIP {test_name}: no writable delegated cgroup: {error}");
            return None;
        }
        let placement = subc_cgroup::prepare_at(&root).unwrap().unwrap();
        // Each spawn gets its own uniquely named cgroup under `subc-modules`, so
        // the fixture watches that directory instead of guessing the name.
        let modules = root.join("subc-modules");
        let fixture = Self {
            root,
            placement,
            modules,
        };
        // The test root is itself a non-root cgroup, so it has the same
        // interface files a module cgroup gets.
        if !fixture.root.join("cgroup.kill").exists()
            || !fixture.root.join("cgroup.freeze").exists()
        {
            assert!(
                !required,
                "required cgroup.kill/cgroup.freeze interface unavailable"
            );
            eprintln!("SKIP {test_name}: cgroup.kill/cgroup.freeze unavailable");
            return None;
        }
        Some(fixture)
    }

    /// The module cgroups that exist right now.
    fn module_cgroups(&self) -> Vec<PathBuf> {
        fs::read_dir(&self.modules)
            .map(|entries| {
                entries
                    .filter_map(Result::ok)
                    .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir()))
                    .map(|entry| entry.path())
                    .collect()
            })
            .unwrap_or_default()
    }
}

impl Drop for KernelCgroup {
    fn drop(&mut self) {
        for module in self.module_cgroups() {
            let _ = fs::write(module.join("cgroup.kill"), "1");
            let deadline = std::time::Instant::now() + Duration::from_secs(1);
            while !ordinary_cgroup::is_empty(&module) && std::time::Instant::now() < deadline {
                std::thread::sleep(Duration::from_millis(1));
            }
            fn remove_empty_tree(path: &Path) {
                if let Ok(entries) = fs::read_dir(path) {
                    for entry in entries.flatten() {
                        if entry.file_type().is_ok_and(|kind| kind.is_dir()) {
                            remove_empty_tree(&entry.path());
                        }
                    }
                }
                let _ = fs::remove_dir(path);
            }
            remove_empty_tree(&module);
        }
        let _ = fs::remove_dir(&self.modules);
        let _ = fs::remove_dir(&self.root);
    }
}

fn spawn_module(
    placement: subc_cgroup::Placement,
    dir: &Path,
    args: Vec<String>,
) -> SupervisedChild {
    let supervisor = Supervisor::new_for_test(
        Arc::new(Registry::default()),
        RestartPolicy::new(3, Duration::ZERO),
    )
    .with_cgroup_placement(Some(placement));
    let spec = ModuleSpec {
        script: None,
        carry_containment: false,
        module_id: "reaped-module".to_string(),
        program: PathBuf::from("/bin/sh"),
        args,
        env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
            .into_iter()
            .map(|key| (key.to_string(), dir.display().to_string()))
            .collect(),
        reserved: false,
        reserved_prefixes: Vec::new(),
        protocol: ModuleProtocol::None,
        overlap: Default::default(),
    };
    spawn_and_mark_running(
        &spec,
        &supervisor.runtime_config(),
        &Arc::new(Mutex::new(SupervisorSnapshot::starting())),
    )
    .expect("spawn module that exits without waiting for its child")
}

async fn reap_leftover(test_name: &str, ignore_term: bool) {
    let Some(kernel) = KernelCgroup::new(test_name) else {
        return;
    };
    let dir = ScratchDir::new(test_name);
    let marker = dir.join("terminated");
    let pid_file = dir.join("leftover.pid");
    let script = dir.join("leftover.sh");
    let body = if ignore_term {
        "trap '' TERM\necho $$ > \"$2\"\nexec sleep 600\n"
    } else {
        "trap 'printf terminated > \"$1\"; exit 0' TERM\necho $$ > \"$2\"\nwhile :; do :; done\n"
    };
    fs::write(&script, body).unwrap();
    let mut child = spawn_module(
        kernel.placement.clone(),
        &dir,
        vec![
            "-c".into(),
            "/bin/sh \"$1\" \"$2\" \"$3\" & while [ ! -s \"$3\" ]; do sleep 0.01; done".into(),
            "fixture".into(),
            script.display().to_string(),
            marker.display().to_string(),
            pid_file.display().to_string(),
        ],
    );
    // The spawn creates its cgroup before exec; without this, a cleanup that
    // never placed the module would pass the removal check below.
    assert_eq!(
        kernel.module_cgroups().len(),
        1,
        "the spawn must create exactly one module cgroup"
    );
    let started = Instant::now();
    timeout(Duration::from_secs(10), async {
        child.wait().await?;
        child.finish_exit(false).await
    })
    .await
    .expect("leftover cleanup must finish")
    .expect("reap module");
    let elapsed = started.elapsed();
    let pid: i32 = fs::read_to_string(&pid_file)
        .unwrap()
        .trim()
        .parse()
        .unwrap();
    let running = fs::read_to_string(format!("/proc/{pid}/stat"))
        .ok()
        .and_then(|stat| {
            stat.rsplit_once(") ")
                .map(|(_, rest)| !rest.starts_with('Z'))
        })
        .unwrap_or(false);
    assert!(!running, "leftover {pid} must not outlive cleanup");
    assert_eq!(
        kernel.module_cgroups(),
        Vec::<PathBuf>::new(),
        "module cgroup must be removed"
    );
    if ignore_term {
        assert!(
            elapsed >= Duration::from_millis(1900),
            "SIGTERM grace was skipped: {elapsed:?}"
        );
        assert!(
            elapsed < Duration::from_secs(5),
            "SIGKILL escalation was late: {elapsed:?}"
        );
    } else {
        assert!(
            marker.exists(),
            "leftover must receive SIGTERM before cgroup.kill"
        );
        assert!(
            elapsed < Duration::from_secs(1),
            "a cooperative child should not use the full grace: {elapsed:?}"
        );
    }
    eprintln!("EXECUTED {test_name}: leftover {pid} stopped in {elapsed:?}");
}

#[tokio::test]
async fn linux_reaped_cgroup_sigterm_then_exit() {
    reap_leftover("linux_reaped_cgroup_sigterm_then_exit", false).await;
}

#[tokio::test]
async fn linux_reaped_cgroup_ignored_sigterm_escalates_after_two_seconds() {
    reap_leftover("linux_reaped_cgroup_ignored_sigterm", true).await;
}

#[tokio::test]
async fn linux_reaped_cgroup_empty_has_no_grace_wait() {
    let Some(kernel) = KernelCgroup::new("linux_reaped_cgroup_empty") else {
        return;
    };
    let dir = ScratchDir::new("linux-reaped-cgroup-empty");
    let mut child = spawn_module(
        kernel.placement.clone(),
        &dir,
        vec!["-c".into(), "exit 0".into()],
    );
    assert_eq!(
        kernel.module_cgroups().len(),
        1,
        "the spawn must create exactly one module cgroup"
    );
    let started = Instant::now();
    child.wait().await.unwrap();
    child.finish_exit(false).await.unwrap();
    assert!(started.elapsed() < Duration::from_secs(1));
    assert_eq!(
        kernel.module_cgroups(),
        Vec::<PathBuf>::new(),
        "empty module cgroup must be removed"
    );
    eprintln!("EXECUTED linux_reaped_cgroup_empty: no grace wait");
}

#[path = "carried_cgroup_tests.rs"]
mod carried;

// Ordinary files let the policy tests run without cgroup delegation. The child
// remains owned and unreaped until signalling ends, so its PID cannot be reused
// even though these stand-ins do not implement the kernel's freezer.
async fn scratch_leftover(test_name: &str, ignore_term: bool, freezer: &str) -> (bool, Duration) {
    let dir = ScratchDir::new(test_name);
    fs::write(dir.join("cgroup.procs"), "").unwrap();
    let placement = subc_cgroup::prepare_at(&dir).unwrap().unwrap();
    let module = placement.module_path("reaped-module").unwrap();
    fs::write(module.join("cgroup.kill"), "0").unwrap();
    let frozen = if freezer == "confirmed" { 1 } else { 0 };
    fs::write(
        module.join("cgroup.events"),
        format!("populated 1\nfrozen {frozen}\n"),
    )
    .unwrap();
    match freezer {
        "unavailable" => {}
        "io-error" => fs::create_dir(module.join("cgroup.freeze")).unwrap(),
        _ => fs::write(module.join("cgroup.freeze"), "0").unwrap(),
    }
    let marker = dir.join("terminated");
    let ready = dir.join("ready");
    let body = if ignore_term {
        "trap '' TERM; echo ready > \"$2\"; exec sleep 600"
    } else {
        "trap 'printf terminated > \"$1\"; exit 0' TERM; echo ready > \"$2\"; while :; do :; done"
    };
    let mut child = Command::new("/bin/sh")
        .args(["-c", body, "fixture"])
        .arg(&marker)
        .arg(&ready)
        .kill_on_drop(true)
        .spawn()
        .unwrap();
    let pid = child.id().unwrap();
    timeout(Duration::from_secs(5), async {
        while !ready.exists() {
            sleep(Duration::from_millis(1)).await;
        }
    })
    .await
    .unwrap();
    fs::write(module.join("cgroup.procs"), format!("{pid}\n")).unwrap();
    let kernel = async {
        loop {
            tokio::select! {
                status = child.wait() => { status.unwrap(); break; }
                _ = sleep(Duration::from_millis(1)) => {
                    if fs::read(module.join("cgroup.kill")).unwrap() == b"1" {
                        let pid = rustix::process::Pid::from_raw(pid as i32).unwrap();
                        rustix::process::kill_process(pid, rustix::process::Signal::KILL).unwrap();
                        child.wait().await.unwrap();
                        break;
                    }
                }
            }
        }
        fs::write(module.join("cgroup.events"), "populated 0\nfrozen 0\n").unwrap();
        // Kernel interface files disappear with rmdir; ordinary files must be
        // removed here so the same production removal call can succeed.
        for entry in fs::read_dir(&module).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                fs::remove_dir(path).unwrap();
            } else {
                fs::remove_file(path).unwrap();
            }
        }
        fs::remove_dir(&module).unwrap();
    };
    let started = Instant::now();
    timeout(Duration::from_secs(5), async {
        tokio::join!(cleanup_reaped_cgroup(&placement, "reaped-module"), kernel);
    })
    .await
    .expect("scratch cleanup must finish");
    assert!(!module.exists(), "scratch module directory must be removed");
    (marker.exists(), started.elapsed())
}

#[tokio::test]
async fn scratch_reaped_cgroup_sigterm_then_exit() {
    let (marker, elapsed) = scratch_leftover("scratch-reap-term", false, "confirmed").await;
    assert!(marker, "leftover must receive SIGTERM before cgroup.kill");
    assert!(elapsed < Duration::from_secs(1));
}

#[tokio::test]
async fn scratch_reaped_cgroup_ignored_sigterm_escalates_after_two_seconds() {
    let (_, elapsed) = scratch_leftover("scratch-reap-ignore", true, "confirmed").await;
    assert!(
        elapsed >= Duration::from_millis(1900),
        "grace was skipped: {elapsed:?}"
    );
    assert!(elapsed < Duration::from_secs(5));
}

#[tokio::test]
async fn scratch_reaped_cgroup_freeze_failures_never_send_sigterm() {
    for freezer in ["unavailable", "timeout", "io-error"] {
        let (marker, elapsed) =
            scratch_leftover(&format!("scratch-reap-{freezer}"), false, freezer).await;
        assert!(!marker, "unfrozen PIDs must not be signalled: {freezer}");
        assert!(
            elapsed < Duration::from_secs(1),
            "fallback must skip grace: {elapsed:?}"
        );
    }
}

#[tokio::test(start_paused = true)]
async fn scratch_reaped_cgroup_empty_skips_freeze_and_kill() {
    let dir = ScratchDir::new("scratch-reap-empty");
    fs::write(dir.join("cgroup.procs"), "").unwrap();
    let placement = subc_cgroup::prepare_at(&dir).unwrap().unwrap();
    let module = placement.module_path("reaped-module").unwrap();
    fs::write(module.join("cgroup.events"), "populated 0\nfrozen 0\n").unwrap();
    fs::write(module.join("cgroup.freeze"), "unchanged").unwrap();
    fs::write(module.join("cgroup.kill"), "unchanged").unwrap();
    let started = Instant::now();
    assert!(cleanup_reaped_cgroup(&placement, "reaped-module")
        .await
        .is_none());
    assert_eq!(started.elapsed(), Duration::ZERO);
    assert_eq!(
        fs::read(module.join("cgroup.freeze")).unwrap(),
        b"unchanged"
    );
    assert_eq!(fs::read(module.join("cgroup.kill")).unwrap(), b"unchanged");
}

#[tokio::test(start_paused = true)]
async fn scratch_reaped_cgroup_stays_populated_after_kill() {
    let dir = ScratchDir::new("scratch-reap-stuck");
    fs::write(dir.join("cgroup.procs"), "").unwrap();
    let placement = subc_cgroup::prepare_at(&dir).unwrap().unwrap();
    let module = placement.module_path("reaped-module").unwrap();
    fs::write(module.join("cgroup.events"), "populated 1\n").unwrap();
    fs::write(module.join("cgroup.kill"), "0").unwrap();
    let started = Instant::now();
    let unresolved = timeout(
        Duration::from_secs(11),
        cleanup_reaped_cgroup(&placement, "reaped-module"),
    )
    .await
    .expect("leader cleanup must return even when cgroup.kill leaves survivors")
    .expect("surviving cgroup must be retained");
    assert_eq!(started.elapsed(), Duration::from_secs(10));
    assert_eq!(fs::read(module.join("cgroup.kill")).unwrap(), b"1");
    assert!(module.is_dir(), "the unresolved subtree must be retained");
    assert!(unresolved.detail().contains(&module.display().to_string()));
}

#[tokio::test]
async fn ordinary_cgroup_is_recovered_when_its_recorded_leader_is_gone() {
    use crate::{live_children, run_dir_lock::RunDirLock};

    let dir = ScratchDir::new("ordinary-cgroup-recovery");
    fs::write(dir.join("cgroup.procs"), "").unwrap();
    let placement = subc_cgroup::prepare_at(&dir).unwrap().unwrap();
    let record = dir.join("live-children.json");
    let roster = ChildRoster::default();
    roster.record_to(record.clone());
    let spec = ModuleSpec {
        script: None,
        carry_containment: false,
        module_id: "ordinary-boot-recovery".into(),
        program: PathBuf::from("/bin/true"),
        args: vec![],
        env: vec![],
        reserved: false,
        reserved_prefixes: vec![],
        protocol: ModuleProtocol::None,
        overlap: Default::default(),
    };
    let mut prepared = prepare_child_in_slot(
        &spec,
        None,
        None,
        None,
        &roster,
        None,
        None,
        SpawnRole::Plain,
        false,
        false,
    )
    .unwrap();
    // Install scratch control files before placing the real leader; they model
    // a subtree with a survivor but cannot send a signal to a real process.
    let module = placement.module_path(&prepared.cgroup_name).unwrap();
    fs::write(module.join("cgroup.procs"), "").unwrap();
    fs::write(module.join("cgroup.kill"), "0").unwrap();
    fs::write(module.join("cgroup.events"), "populated 1\n").unwrap();
    apply_cgroup_placement(&mut prepared.command, &spec, &module).unwrap();
    prepared.cgroup_placement = Some(placement.clone());
    prepared.cgroup_path = Some(module.clone());
    let mut child = launch_child_in_slot(
        &spec,
        &Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default()))),
        &roster,
        prepared,
        Duration::from_secs(1),
    )
    .unwrap();
    let pid = child.pid;
    child.wait().await.unwrap();
    fs::write(module.join("cgroup.procs"), "42\n").unwrap();

    let owner = RunDirLock::acquire(&record).unwrap();
    let decisions = live_children::sweep_orphans_with_placement(
        &owner,
        &live_children::AdoptedPids::default(),
        live_children::SweepBounds {
            term_grace: Duration::ZERO,
            kill_bound: Duration::ZERO,
        },
        Some(&placement),
    )
    .await;
    assert!(
        matches!(decisions.as_slice(), [(entry, live_children::SweepDecision::ContainerSurvivors(pids))] if entry.pid == pid && pids == &[42]),
        "recovery lost the ordinary cgroup: {decisions:?}"
    );
    let restarted = ChildRoster::default();
    restarted.set_cgroup_placement(Some(placement));
    restarted.record_to(record);
    assert_eq!(fs::read(module.join("cgroup.kill")).unwrap(), b"1");
    assert!(restarted
        .retained_view()
        .waiting_detail(&spec.module_id)
        .is_some());
    assert_eq!(restarted.previous_instance_pid(&spec.module_id), Some(pid));
    fs::write(module.join("cgroup.events"), "populated 0\n").unwrap();
    assert_eq!(restarted.previous_instance_pid(&spec.module_id), None);
}

#[tokio::test]
async fn linux_cgroup_cpu_survives_child_reap() {
    let Some(kernel) = KernelCgroup::new("cpu-reap") else {
        return;
    };
    let dir = ScratchDir::new("cgroup-cpu-reap");
    let script = r#"
        (while [ ! -f "$1/reap" ]; do sleep 0.01; done; echo exit) |
          SUBC_RESOURCE_COMMAND_FIXTURE=1 "$2" --exact resource_totals::tests::resource_command_fixture --nocapture > "$1/child.out" &
        command=$!
        echo "$command" > "$1/child.pid"
        wait "$command"
        touch "$1/reaped"
        while [ ! -f "$1/finish" ]; do sleep 0.01; done
    "#;
    let mut child = spawn_module(
        kernel.placement.clone(),
        &dir,
        vec![
            "-c".into(),
            script.into(),
            "fixture".into(),
            dir.display().to_string(),
            std::env::current_exe().unwrap().display().to_string(),
        ],
    );
    let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
    while !fs::read_to_string(dir.join("child.out")).is_ok_and(|s| s.contains("RESOURCE_READY")) {
        assert!(
            tokio::time::Instant::now() < deadline,
            "CPU child never became ready"
        );
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    let pid: u32 = fs::read_to_string(dir.join("child.pid"))
        .unwrap()
        .trim()
        .parse()
        .unwrap();
    let usage = subc_os::resource_usage(pid).unwrap();
    let child_cpu = (usage.cpu_user + usage.cpu_system).as_millis() as u64;
    assert!(child_cpu >= 100);
    let group = kernel.module_cgroups().pop().unwrap();
    let before = subc_cgroup::read_cpu_ms(&group).unwrap();
    assert!(before >= child_cpu);
    fs::write(dir.join("reap"), "").unwrap();
    while !dir.join("reaped").exists() {
        assert!(
            tokio::time::Instant::now() < deadline,
            "CPU child was not reaped"
        );
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    let after = subc_cgroup::read_cpu_ms(&group).unwrap();
    fs::write(dir.join("finish"), "").unwrap();
    child.wait().await.unwrap();
    assert!(
        after >= before,
        "cgroup CPU dropped across reap: {before} -> {after}"
    );
    assert!(after >= child_cpu);
    eprintln!("EXECUTED linux_cgroup_cpu_survives_child_reap: {before} -> {after}");
}