#[cfg(target_os = "linux")]
use std::os::fd::AsFd as _;
use crate::containment::cgroup::test_support::{
block_on, childs_copy, entered_leaf_at, fork_running, handle_of, pidfd_of, reap,
};
use crate::containment::cgroup::{DrainStep, LeafError, NotEntered, NotPlaced, PlacementReport};
#[cfg(target_os = "linux")]
use crate::test_groups::{cgroup, Group};
#[cfg(target_os = "linux")]
#[skuld::test]
fn enodev_is_removed_after_drain() {
let e = std::io::Error::from_raw_os_error(libc::ENODEV);
assert!(crate::containment::cgroup::removed_after_drain(&e));
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn enoent_is_removed_after_drain() {
let e = std::io::Error::from_raw_os_error(libc::ENOENT);
assert!(crate::containment::cgroup::removed_after_drain(&e));
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn unrelated_errnos_are_not_removed_after_drain() {
for errno in [libc::EACCES, libc::EIO, libc::EBUSY, libc::EPERM] {
let e = std::io::Error::from_raw_os_error(errno);
assert!(
!crate::containment::cgroup::removed_after_drain(&e),
"errno {errno} must not be classified as proof of drain"
);
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn drain_step_block_carries_the_original_deadline_instant() {
use crate::containment::cgroup::test_support::{entered_leaf_at, FakeLeaf};
use std::time::{Duration, Instant};
let fake = FakeLeaf::new("cosca-drain-step-block-deadline", true);
let leaf = entered_leaf_at(fake.leaf.clone());
leaf.disarm();
let at = Instant::now() + Duration::from_secs(3600);
for (deadline, expected) in [(Some(Some(at)), Some(at)), (Some(None), None), (None, None)] {
match leaf.drain_step(deadline).expect("drain_step") {
DrainStep::Block { deadline, .. } => {
assert_eq!(
deadline, expected,
"Block must carry the caller's deadline instant unchanged"
)
}
DrainStep::Done(_) => {
panic!("expected Block for {deadline:?}: a populated fake leaf must not shortcut to Done")
}
}
}
let past = Instant::now().checked_sub(Duration::from_secs(1)).unwrap();
match leaf.drain_step(Some(Some(past))).expect("drain_step") {
DrainStep::Done(crate::containment::TreeDrain::MembersRemain) => {}
DrainStep::Done(other) => {
panic!("expected Done(MembersRemain) for an already-expired deadline, got Done({other:?})")
}
DrainStep::Block { .. } => {
panic!("expected Done(MembersRemain) for an already-expired deadline, got Block")
}
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn drain_step_pins_the_exact_zero_remaining_boundary() {
use crate::containment::cgroup::test_support::{entered_leaf_at, FakeLeaf};
use std::time::Duration;
let fake = FakeLeaf::new("cosca-drain-step-zero-boundary", true);
let leaf = entered_leaf_at(fake.leaf.clone());
leaf.disarm();
let (_guard, t0) = crate::wait::test_clock::FrozenClockGuard::install();
let at = t0 + Duration::from_secs(3600);
let deadline = Some(Some(at));
crate::wait::test_clock::advance(Duration::from_secs(3600) - Duration::from_nanos(1));
match leaf.drain_step(deadline).expect("drain_step") {
DrainStep::Block { .. } => {}
DrainStep::Done(_) => panic!("1ns before the deadline must still take Block, not the shortcut"),
}
crate::wait::test_clock::advance(Duration::from_nanos(1));
match leaf.drain_step(deadline).expect("drain_step") {
DrainStep::Done(crate::containment::TreeDrain::MembersRemain) => {}
DrainStep::Done(other) => {
panic!("at the deadline exactly, expected Done(MembersRemain), got Done({other:?})")
}
DrainStep::Block { .. } => {
panic!("at the deadline exactly, drain_step must take the zero-remaining shortcut, not Block")
}
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn wait_drained_through_wait_deadline_never_answers_early() {
use crate::containment::cgroup::test_support::{entered_leaf_at, FakeLeaf, WaitDeadlineArgGuard};
use crate::containment::TreeDrain;
use std::time::{Duration, Instant};
let fake = FakeLeaf::new("cosca-wait-drained-fakeleaf-bounded", true);
let leaf = entered_leaf_at(fake.leaf.clone());
leaf.disarm();
const BOUND: Duration = Duration::from_millis(50);
let start = Instant::now();
let deadline = start + BOUND;
let (_guard, armed_rx) = WaitDeadlineArgGuard::install();
let result = leaf.wait_drained(Some(Some(deadline))).expect("wait_drained");
let elapsed = start.elapsed();
assert_eq!(
result,
TreeDrain::MembersRemain,
"a populated leaf that never drains must report MembersRemain once its deadline passes"
);
assert!(
elapsed >= BOUND,
"wait_drained returned after {elapsed:?}, before its own {BOUND:?} deadline"
);
let armed: Vec<Instant> = armed_rx.try_iter().collect();
assert!(
!armed.is_empty(),
"a bounded wait with no deadline passed yet must arm `wait_deadline` at least once"
);
assert!(
armed.iter().all(|&at| at == deadline),
"wait_deadline must be armed with exactly the caller's own requested deadline \
({deadline:?}), got {armed:?}"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
#[should_panic(expected = "no progress")]
fn wait_drained_panics_when_its_advance_is_dropped() {
use crate::containment::cgroup::test_support::{entered_leaf_at, FakeLeaf, WaitObserver};
use crate::wait::test_clock::{FrozenClockGuard, SkipAdvanceGuard};
use std::time::Duration;
struct JoinOnDrop(Option<std::thread::JoinHandle<()>>);
impl Drop for JoinOnDrop {
fn drop(&mut self) {
if let Some(drainer) = self.0.take() {
drainer.join().expect("the drainer thread");
}
}
}
let fake = FakeLeaf::new("cosca-wait-drained-advance-dropped", true);
let leaf = entered_leaf_at(fake.leaf.clone());
leaf.disarm();
let (block_tx, block_rx) = std::sync::mpsc::channel();
let events = fake.events.clone();
let _drainer = JoinOnDrop(Some(std::thread::spawn(move || {
for _ in 0..2 {
if block_rx.recv().is_err() {
return;
}
}
FakeLeaf::set_populated(&events, false);
})));
let (_clock, at) = FrozenClockGuard::install();
let _skip = SkipAdvanceGuard::install();
WaitObserver::run_with_block_sender(block_tx, || {
leaf.wait_drained(Some(Some(at + Duration::from_millis(5)))).ok()
});
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn wait_drained_terminates_under_a_frozen_clock() {
use crate::containment::cgroup::test_support::{entered_leaf_at, FakeLeaf};
use crate::containment::TreeDrain;
use crate::wait::test_clock::FrozenClockGuard;
use std::time::Duration;
let fake = FakeLeaf::new("cosca-wait-drained-frozen-clock", true);
let leaf = entered_leaf_at(fake.leaf.clone());
leaf.disarm();
let (_clock, at) = FrozenClockGuard::install();
let verdict = leaf
.wait_drained(Some(Some(at + Duration::from_millis(5))))
.expect("wait_drained");
assert_eq!(verdict, TreeDrain::MembersRemain);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_wait_drained_tracks_two_real_members_through_exit(#[fixture(cgroup)] _group: &Group) {
use crate::containment::cgroup::fault;
use crate::containment::cgroup::test_support::{
assert_bounded_conclusion, Member, WaitDeadlineArgGuard, WaitObserver,
};
use crate::containment::TreeDrain;
use std::os::unix::process::CommandExt;
use std::process::{Command, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};
let leaf = crate::containment::cgroup::try_create_leaf().unwrap_or_else(|e| {
panic!(
"the cgroup tests are enabled but no usable delegated cgroup v2 leaf could be created \
({e}) — is this process running inside a writable, delegated cgroup v2 slice with \
cgroup.kill support (kernel >= 5.14)?"
)
});
let leaf_name = leaf
.leaf_path
.file_name()
.expect("a leaf has a name")
.to_str()
.expect("leaf names are UTF-8");
let (batches_tx, batches_rx) = mpsc::channel();
fault::set_pump_batch_notifier(leaf_name, batches_tx);
let mut total_woken = 0usize;
let spawn_member = |leaf: &crate::containment::cgroup::CgroupLeaf,
channel: &crate::containment::cgroup::ReportChannel|
-> Member {
let procs_fd = leaf.procs_fd();
let slot = channel.slot();
let mut cmd = Command::new("cat");
cmd.stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null());
unsafe {
cmd.pre_exec(move || crate::containment::cgroup::place_self_in_cgroup_pre_exec(procs_fd, slot));
}
let mut child = crate::test_spawn::spawn(&mut cmd).expect("spawn a real long-lived cgroup leaf member");
let stdin = child.stdin.take().expect("cat's stdin must be piped");
Member(child, stdin)
};
let channel_a = crate::containment::cgroup::ReportChannel::new().expect("open member a's report channel");
let channel_b = crate::containment::cgroup::ReportChannel::new().expect("open member b's report channel");
let mut a = spawn_member(&leaf, &channel_a);
let mut b = spawn_member(&leaf, &channel_b);
for (name, member, mut channel) in [("a", &a, channel_a), ("b", &b, channel_b)] {
assert_eq!(
channel.wait(pidfd_of(member.0.id()).as_fd()),
PlacementReport::Placed,
"member {name}'s own report must survive the other member's spawn"
);
}
let procs = std::fs::read_to_string(leaf.leaf_path.join("cgroup.procs")).expect("read cgroup.procs");
for (name, member) in [("a", &a), ("b", &b)] {
assert!(
procs.lines().any(|line| line.trim() == member.0.id().to_string()),
"member {name} must actually be placed in the leaf; cgroup.procs is {procs:?}"
);
}
let mut bounded_wait_drained = || {
const BOUND: Duration = Duration::from_millis(250);
let start = Instant::now();
let deadline = start + BOUND;
let (_deadline_arg_guard, armed_rx) = WaitDeadlineArgGuard::install();
let (result, parks, blocks, zero_remainings) =
WaitObserver::run(|| leaf.wait_drained(Some(Some(deadline))).expect("wait_drained"));
let elapsed = start.elapsed();
assert_bounded_conclusion(&parks, blocks, zero_remainings, deadline);
assert!(
elapsed >= BOUND,
"wait_drained returned after {elapsed:?}, before its own {BOUND:?} deadline"
);
let armed: Vec<Instant> = armed_rx.try_iter().collect();
assert!(
armed.iter().all(|&at| at == deadline),
"wait_deadline must always be armed with exactly the caller's own requested \
deadline ({deadline:?}), got {armed:?}"
);
total_woken += parks.iter().filter(|p| p.woken).count();
result
};
assert_eq!(
bounded_wait_drained(),
TreeDrain::MembersRemain,
"both members are alive; must report MembersRemain"
);
a.0.kill().expect("kill member a");
a.0.wait().expect("reap member a");
assert_eq!(
bounded_wait_drained(),
TreeDrain::MembersRemain,
"one member is still alive; must still report MembersRemain"
);
let (rendezvous_tx, rendezvous_rx) = mpsc::channel();
let (result, parks, zero_remainings) = std::thread::scope(|scope| {
let handle = scope.spawn(|| {
WaitObserver::run_with_block_sender(rendezvous_tx, || {
leaf.wait_drained(None).expect("wait_drained once both are gone")
})
});
rendezvous_rx
.recv()
.expect("drain_step must announce blocking before wait_drained returns");
b.0.kill().expect("kill member b");
b.0.wait().expect("reap member b");
handle.join().expect("wait_drained thread must not panic")
});
let blocks = 1 + rendezvous_rx.try_iter().count();
assert_eq!(
result,
TreeDrain::AllMembersExited,
"both members exited; must report AllMembersExited"
);
assert_eq!(
zero_remainings, 0,
"an unbounded call has no deadline to shortcut on, so the zero-remaining seam must never \
fire, got {zero_remainings}"
);
assert_eq!(
blocks,
parks.len(),
"drain_step announced blocking {blocks} times, but the wait site's own wait call \
returned {} times — every announced block must show up as a wait-site return",
parks.len()
);
assert!(
!parks.is_empty(),
"the rendezvous above guarantees the wait call reached the wait site at least once \
before the kill; got none"
);
assert!(
parks.iter().all(|p| p.deadline.is_none() && p.woken),
"every park in an unbounded call is armed with no deadline and can only conclude by \
being woken — it has no timeout to elapse, got {parks:?}"
);
total_woken += parks.iter().filter(|p| p.woken).count();
let changed_batches = batches_rx.try_iter().filter(|¬ified| notified).count();
assert!(
total_woken <= changed_batches,
"{total_woken} parks woke across this test, but the pump reported only \
{changed_batches} batches that actually broadcast — a woken park with no matching real \
broadcast behind it is not a real park"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_leaf_procs_fd_is_not_inherited_across_exec(#[fixture(cgroup)] _group: &Group) {
let leaf = crate::containment::cgroup::try_create_leaf().unwrap_or_else(|e| {
panic!("the cgroup tests are enabled but no usable delegated cgroup v2 leaf could be created ({e})")
});
let flags = unsafe { libc::fcntl(leaf.procs_fd(), libc::F_GETFD) };
assert_ne!(flags, -1, "F_GETFD: {}", std::io::Error::last_os_error());
assert_ne!(
flags & libc::FD_CLOEXEC,
0,
"the parent-held cgroup.procs fd must be CLOEXEC"
);
let out =
crate::test_spawn::output_captured(std::process::Command::new("/bin/sh").args(["-c", "ls -l /proc/$$/fd"]))
.expect("run sh");
assert!(out.status.success(), "ls failed: {out:?}");
let fds = String::from_utf8_lossy(&out.stdout);
let procs = leaf.leaf_path.join("cgroup.procs");
assert!(
!fds.contains(&*procs.to_string_lossy()),
"an unrelated program inherited {}:\n{fds}",
procs.display()
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn create_leaf_under_reports_a_refused_mkdir() {
let dir = tempfile::tempdir().expect("tempdir");
let parent = dir.path().join("no-such-slice");
let err = match crate::containment::cgroup::create_leaf_under(&parent) {
Err(e) => e,
Ok(_) => panic!("creating a leaf under a nonexistent directory must fail"),
};
assert!(
matches!(err, LeafError::CreateLeafDir { .. }),
"expected CreateLeafDir, got {err:?}"
);
let rendered = err.to_string();
assert!(rendered.contains("no-such-slice"), "path missing from {rendered:?}");
let reason = std::io::Error::from_raw_os_error(libc::ENOENT).to_string();
assert!(rendered.contains(&reason), "errno missing from {rendered:?}");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn create_leaf_under_reports_a_missing_cgroup_kill() {
let dir = tempfile::tempdir().expect("tempdir");
let err = match crate::containment::cgroup::create_leaf_under(dir.path()) {
Err(e) => e,
Ok(_) => panic!("a plain directory has no cgroup.kill; leaf creation must fail"),
};
assert!(
matches!(err, LeafError::KillUnsupported { .. }),
"expected KillUnsupported, got {err:?}"
);
assert!(err.to_string().contains("cgroup.kill"), "got {err}");
let strays: Vec<_> = std::fs::read_dir(dir.path())
.expect("read tempdir")
.map(|e| e.expect("entry").file_name())
.collect();
assert!(strays.is_empty(), "a failed leaf creation left {strays:?} behind");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn create_leaf_under_reports_a_leaf_its_unwind_could_not_remove() {
crate::log_capture::install();
let dir = tempfile::tempdir().expect("tempdir");
let marker = dir.path().to_string_lossy().into_owned();
crate::containment::cgroup::fault::set_force_occupy_before_unwind(true);
let mark = crate::log_capture::mark();
let err = match crate::containment::cgroup::create_leaf_under(dir.path()) {
Err(e) => e,
Ok(_) => panic!("a plain directory has no cgroup.kill; leaf creation must fail"),
};
assert!(
!crate::containment::cgroup::fault::occupy_before_unwind_armed(),
"the seam must be consumed by the unwind it stands in for"
);
assert!(matches!(err, LeafError::KillUnsupported { .. }), "got {err:?}");
assert_eq!(
crate::log_capture::levels_since(mark, &marker),
vec![log::Level::Warn],
"the unwind left a leaf behind and must say so"
);
let enotempty = std::io::Error::from_raw_os_error(libc::ENOTEMPTY).to_string();
assert!(
crate::log_capture::records_since(mark, &marker)
.iter()
.any(|record| record.contains(&enotempty)),
"the record must carry the kernel's reason"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn create_leaf_under_reports_a_cgroup_kill_it_could_not_check() {
let dir = tempfile::tempdir().expect("tempdir");
let parent = dir.path().to_path_buf();
crate::containment::cgroup::fault::set_force_kill_check_errno(libc::EACCES);
let err = match crate::containment::cgroup::create_leaf_under(&parent) {
Err(e) => e,
Ok(_) => panic!("a plain directory has no cgroup.kill; leaf creation must fail"),
};
assert!(
matches!(err, LeafError::CheckKill { .. }),
"expected CheckKill, got {err:?}"
);
let reason = std::io::Error::from_raw_os_error(libc::EACCES).to_string();
assert!(err.to_string().contains(&reason), "the errno is the diagnosis: {err}");
let strays: Vec<_> = std::fs::read_dir(&parent)
.expect("read the parent")
.map(|e| e.expect("entry").file_name())
.collect();
assert!(strays.is_empty(), "a failed leaf creation left {strays:?} behind");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn hard_kill_propagates_a_kill_the_kernel_refused() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-refused-kill");
std::fs::create_dir(&leaf_path).expect("create the leaf");
std::fs::create_dir(leaf_path.join("cgroup.kill")).expect("create cgroup.kill as a directory");
let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
let err = leaf
.hard_kill()
.expect_err("a refused cgroup.kill write must not read as success");
let crate::error::Error::Io(io) = &err else {
panic!("a refused cgroup.kill write must surface as Error::Io, got {err:?}");
};
assert_eq!(
io.raw_os_error(),
Some(libc::EISDIR),
"the kernel's errno must reach the caller, got {err}"
);
let attached = crate::containment::Attached::Cgroup(leaf);
assert!(
attached.hard_kill().is_err(),
"Attached::Cgroup must propagate like every sibling arm; swallowing it makes \
kill_tree() report a completed teardown over a live tree"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn hard_kill_reads_an_already_removed_leaf_as_a_completed_teardown() {
crate::log_capture::install();
let mark = crate::log_capture::mark();
let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(std::path::PathBuf::from(
"/nonexistent/cosca-hard-kill-already-gone",
));
leaf.hard_kill()
.expect("an already-removed leaf is a completed teardown, not a failure");
assert_eq!(
crate::log_capture::levels_since(mark, "cosca-hard-kill-already-gone"),
vec![log::Level::Debug],
"an already-gone leaf is routine: exactly one record, and not at warn"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn terminate_reads_an_already_removed_leaf_as_a_completed_teardown() {
let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(std::path::PathBuf::from(
"/nonexistent/cosca-terminate-already-gone",
));
leaf.terminate()
.expect("an already-removed leaf has no member left to signal");
let attached = crate::containment::Attached::Cgroup(leaf);
assert!(
attached.terminate(0).is_ok(),
"terminate and hard_kill must agree about an already-gone leaf"
);
assert!(attached.hard_kill().is_ok());
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn drop_reports_a_leaf_it_could_not_remove() {
crate::log_capture::install();
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-undeletable-leaf");
std::fs::create_dir(&leaf_path).expect("create the leaf");
std::fs::write(leaf_path.join("occupant"), "").expect("make the leaf unremovable");
let mark = crate::log_capture::mark();
drop(crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path));
assert_eq!(
crate::log_capture::levels_since(mark, "cosca-undeletable-leaf"),
vec![log::Level::Warn],
"a leaf that outlived its Drop is reported, or never known about"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn drop_kills_through_a_leaf_unless_the_child_provably_never_entered() {
crate::log_capture::install();
let reports = [
PlacementReport::NotReported,
PlacementReport::WriteFailed(libc::EBADF),
PlacementReport::Placed,
];
for (report, verdict_taken) in reports.into_iter().flat_map(|report| [(report, false), (report, true)]) {
let kills = report == PlacementReport::Placed;
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-drop-kill-leaf");
std::fs::create_dir(&leaf_path).expect("create the leaf");
std::fs::write(leaf_path.join("occupant"), "").expect("make the leaf unremovable");
let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path.clone());
match report {
PlacementReport::NotReported => {}
PlacementReport::WriteFailed(_) => {
_ = unsafe { crate::containment::cgroup::place_self_in_cgroup_pre_exec(-1, leaf.placement_slot()) };
}
PlacementReport::Placed => unsafe { leaf.placement_slot().report_placed_for_test() },
}
if verdict_taken {
assert_eq!(
leaf.take_placement(handle_of(std::process::id(), &pidfd_of(std::process::id())))
.is_ok(),
report == PlacementReport::Placed
);
assert!(!leaf.holds_spawn_resources());
}
let mark = crate::log_capture::mark();
drop(leaf);
assert_eq!(
leaf_path.join("cgroup.kill").exists(),
kills,
"a child that reported {report:?} (verdict taken: {verdict_taken}): cgroup.kill \
written must be {kills}"
);
assert_eq!(
crate::log_capture::levels_since(mark, &leaf_path.to_string_lossy()),
vec![log::Level::Warn],
"the unremoved leaf is reported either way"
);
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_leaf_does_not_kill_the_tree_it_was_detached_from() {
crate::log_capture::install();
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-detached-leaf");
std::fs::create_dir(&leaf_path).expect("create the leaf");
std::fs::write(leaf_path.join("occupant"), "").expect("stand in for the detached tree");
std::fs::write(leaf_path.join("cgroup.kill"), b"").expect("create cgroup.kill");
std::fs::write(leaf_path.join("cgroup.events"), b"populated 1\nfrozen 0\n").expect("create cgroup.events");
let attached = crate::containment::Attached::Cgroup(entered_leaf_at(leaf_path.clone()));
let mark = crate::log_capture::mark();
attached.disarm();
drop(attached);
assert_eq!(
std::fs::read(leaf_path.join("cgroup.kill")).expect("read cgroup.kill"),
b"",
"a detached tree must not be killed: cgroup.kill must never be written"
);
assert!(leaf_path.is_dir(), "the detached tree's leaf must survive with it");
assert_eq!(
crate::log_capture::levels_since(mark, "cosca-detached-leaf"),
vec![log::Level::Debug],
"a leaf left behind for a detached tree is what the caller asked for, not a leak"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_armed_leaf_still_kills_the_tree_on_drop() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-armed-leaf");
std::fs::create_dir(&leaf_path).expect("create the leaf");
std::fs::write(leaf_path.join("occupant"), "").expect("keep the leaf unremovable");
std::fs::write(leaf_path.join("cgroup.kill"), b"").expect("create cgroup.kill");
drop(entered_leaf_at(leaf_path.clone()));
assert_eq!(
std::fs::read(leaf_path.join("cgroup.kill")).expect("read cgroup.kill"),
b"1",
"an occupied leaf that was NOT detached must still be killed on Drop"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_leaf_still_removes_itself_once_it_is_empty() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-detached-empty-leaf");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let attached = crate::containment::Attached::Cgroup(entered_leaf_at(leaf_path.clone()));
attached.disarm();
drop(attached);
assert!(
!leaf_path.exists(),
"an empty leaf is removable, and cosca does not come back for one it left"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_leaf_whose_tree_was_killed_but_still_refuses_rmdir_is_reported_once() {
crate::log_capture::install();
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-killed-opted-out-leaf");
std::fs::create_dir(&leaf_path).expect("create the leaf");
std::fs::write(leaf_path.join("occupant"), "").expect("leftover file that makes rmdir fail with ENOTEMPTY");
std::fs::write(leaf_path.join("cgroup.kill"), b"").expect("create cgroup.kill");
let leaf = entered_leaf_at(leaf_path);
leaf.disarm();
leaf.hard_kill().expect("kill the tree");
let mark = crate::log_capture::mark();
drop(leaf);
let records = crate::log_capture::records_since(mark, "cosca-killed-opted-out-leaf");
assert_eq!(
crate::log_capture::levels_since(mark, "cosca-killed-opted-out-leaf"),
vec![log::Level::Warn],
"a killed tree's leaf that outlived its Drop is a leak, got {records:?}"
);
assert!(
records.iter().all(|r| !r.contains("detached")),
"the caller killed this tree; it was not left running, got {records:?}"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_leaf_whose_tree_survived_terminate_is_not_reported_as_a_leak() {
use std::os::fd::AsRawFd;
crate::log_capture::install();
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-terminate-survivor-leaf");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let (ready_read, ready_write) = std::io::pipe().expect("pipe");
let ready_write_fd = ready_write.as_raw_fd();
let guard = fork_running(move || {
unsafe {
libc::signal(libc::SIGTERM, libc::SIG_IGN);
if libc::write(ready_write_fd, b"r".as_ptr().cast(), 1) != 1 {
libc::_exit(1);
}
libc::pause();
}
});
drop(ready_write);
block_on(ready_read.as_raw_fd()); drop(ready_read);
std::fs::write(leaf_path.join("cgroup.procs"), format!("{}\n", guard.pid())).expect("list the member");
std::fs::write(leaf_path.join("cgroup.events"), b"populated 1\nfrozen 0\n").expect("create cgroup.events");
let leaf = entered_leaf_at(leaf_path);
leaf.disarm();
leaf.terminate().expect("signal the tree");
let mark = crate::log_capture::mark();
drop(leaf);
drop(guard);
let records = crate::log_capture::records_since(mark, "cosca-terminate-survivor-leaf");
assert_eq!(
crate::log_capture::levels_since(mark, "cosca-terminate-survivor-leaf"),
vec![log::Level::Debug],
"a tree that survived SIGTERM is left running, not leaked, got {records:?}"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_leaf_that_is_already_gone_reports_nothing() {
crate::log_capture::install();
let leaf = entered_leaf_at(std::path::PathBuf::from("/nonexistent/cosca-detached-gone-leaf"));
leaf.disarm();
let mark = crate::log_capture::mark();
drop(leaf);
assert_eq!(
crate::log_capture::levels_since(mark, "cosca-detached-gone-leaf"),
Vec::<log::Level>::new(),
"nothing is left behind for the detached tree, so there is nothing to report"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn drop_kills_only_a_leaf_its_child_entered_and_that_is_armed() {
for (entered, armed) in [(true, true), (true, false), (false, true), (false, false)] {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-two-flags-leaf");
std::fs::create_dir(&leaf_path).expect("create the leaf");
std::fs::write(leaf_path.join("occupant"), "").expect("keep the leaf unremovable");
std::fs::write(leaf_path.join("cgroup.kill"), b"").expect("create cgroup.kill");
let leaf = if entered {
entered_leaf_at(leaf_path.clone())
} else {
let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path.clone());
_ = unsafe { crate::containment::cgroup::place_self_in_cgroup_pre_exec(-1, leaf.placement_slot()) };
assert!(
leaf.take_placement(handle_of(std::process::id(), &pidfd_of(std::process::id())))
.is_err(),
"a failed write is not a placement"
);
leaf
};
if !armed {
leaf.disarm();
}
drop(leaf);
let expected: &[u8] = if entered && armed { b"1" } else { b"" };
assert_eq!(
std::fs::read(leaf_path.join("cgroup.kill")).expect("read cgroup.kill"),
expected,
"entered={entered}, armed={armed}"
);
}
}
#[cfg(target_os = "linux")]
fn on_each_drain_block(mut act: impl FnMut(usize) + Send + 'static) -> impl Drop {
struct Stop(Option<std::thread::JoinHandle<()>>);
impl Drop for Stop {
fn drop(&mut self) {
crate::containment::cgroup::fault::take_drain_blocking_notifier();
self.0.take().expect("actor").join().expect("actor thread");
}
}
let (blocking_tx, blocking_rx) = std::sync::mpsc::channel();
let actor = std::thread::spawn(move || {
let mut n = 0;
while blocking_rx.recv().is_ok() {
act(n);
n += 1;
}
});
crate::containment::cgroup::fault::set_drain_blocking_notifier(blocking_tx);
Stop(Some(actor))
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_armed_drop_removes_its_leaf_only_after_it_drains() {
use crate::containment::cgroup::fault;
use crate::containment::cgroup::test_support::FakeLeaf;
let fake = FakeLeaf::new("cosca-draining-leaf", true);
let (leaf, events) = (fake.leaf.clone(), fake.events.clone());
fault::set_rmdir_hook(move |_| FakeLeaf::rmdir(&leaf, &events));
let events = fake.events.clone();
let actor = on_each_drain_block(move |_| FakeLeaf::set_populated(&events, false));
fault::record_leaf_steps();
drop(entered_leaf_at(fake.leaf.clone()));
let steps = fault::take_leaf_steps();
drop(actor);
fault::take_rmdir_hook();
assert!(
!fake.leaf.exists(),
"the drop must remove the drained leaf, got {steps:?}"
);
let killed_at = steps
.iter()
.position(|s| s == "kill")
.unwrap_or_else(|| panic!("an occupied armed leaf must be killed through, got {steps:?}"));
let after_kill = &steps[killed_at + 1..];
assert!(!after_kill.is_empty(), "the drop must retry the rmdir, got {steps:?}");
assert!(
after_kill.iter().all(|s| s.starts_with("rmdir populated 0")),
"every rmdir after the kill must wait for the drain, got {steps:?}"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_leaf_whose_tree_was_killed_removes_itself_only_after_it_drains() {
use crate::containment::cgroup::fault;
use crate::containment::cgroup::test_support::FakeLeaf;
let fake = FakeLeaf::new("cosca-disarmed-draining-leaf", true);
let (leaf, events) = (fake.leaf.clone(), fake.events.clone());
fault::set_rmdir_hook(move |_| FakeLeaf::rmdir(&leaf, &events));
let events = fake.events.clone();
let actor = on_each_drain_block(move |_| FakeLeaf::set_populated(&events, false));
let leaf = entered_leaf_at(fake.leaf.clone());
leaf.disarm();
leaf.hard_kill().expect("kill the tree");
fault::record_leaf_steps();
drop(leaf);
let steps = fault::take_leaf_steps();
drop(actor);
fault::take_rmdir_hook();
assert!(
!fake.leaf.exists(),
"a disarmed Drop must still remove a leaf its caller already killed, once it drains, got {steps:?}"
);
assert_eq!(
steps,
vec!["rmdir populated 1", "kill", "rmdir populated 0"],
"a disarmed leaf's kill must be re-fired and then retried only once it drains, got {steps:?}"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_drop_re_fires_the_kill_before_waiting_on_a_repopulated_leaf() {
use crate::containment::cgroup::fault;
use crate::containment::cgroup::test_support::FakeLeaf;
let fake = FakeLeaf::new("cosca-disarmed-repopulated-leaf", true);
let (leaf, events) = (fake.leaf.clone(), fake.events.clone());
fault::set_rmdir_hook(move |_| FakeLeaf::rmdir(&leaf, &events));
let events = fake.events.clone();
let actor = on_each_drain_block(move |_| FakeLeaf::set_populated(&events, false));
let leaf = entered_leaf_at(fake.leaf.clone());
leaf.disarm();
leaf.hard_kill().expect("kill the tree");
FakeLeaf::set_populated(&fake.events, false);
FakeLeaf::set_populated(&fake.events, true);
fault::record_leaf_steps();
drop(leaf);
let steps = fault::take_leaf_steps();
drop(actor);
fault::take_rmdir_hook();
assert!(
!fake.leaf.exists(),
"Drop must still remove the leaf once its re-fired kill drains, got {steps:?}"
);
let killed_at = steps
.iter()
.position(|s| s == "kill")
.unwrap_or_else(|| panic!("a re-populated leaf must be killed again before Drop waits, got {steps:?}"));
let after_kill = &steps[killed_at + 1..];
assert!(
!after_kill.is_empty(),
"the drop must retry the rmdir after re-firing the kill, got {steps:?}"
);
assert!(
after_kill.iter().all(|s| s.starts_with("rmdir populated 0")),
"every rmdir after the re-fired kill must wait for the drain, got {steps:?}"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_never_killed_leaf_sweeps_and_retries_once_it_has_already_drained() {
use crate::containment::cgroup::fault;
use crate::containment::cgroup::test_support::FakeLeaf;
let fake = FakeLeaf::new("cosca-disarmed-self-drained-leaf", false);
std::fs::create_dir(fake.leaf.join("leftover-child")).expect("leave an empty child cgroup behind");
let (leaf, events) = (fake.leaf.clone(), fake.events.clone());
fault::set_rmdir_hook(move |path| {
if !path.exists() {
return Err(std::io::Error::from_raw_os_error(libc::ENOENT));
}
if path.join("leftover-child").exists() {
return Err(std::io::Error::from_raw_os_error(libc::EBUSY));
}
FakeLeaf::rmdir(&leaf, &events)
});
let leaf = entered_leaf_at(fake.leaf.clone());
leaf.disarm();
crate::log_capture::install();
let mark = crate::log_capture::mark();
drop(leaf);
fault::take_rmdir_hook();
assert!(
!fake.leaf.exists(),
"a leaf that already drained on its own must be removed once its leftover child cgroup is swept"
);
assert!(
!crate::log_capture::levels_since(mark, "cosca-disarmed-self-drained-leaf").contains(&log::Level::Warn),
"a clean sweep-and-retry is success, not a leak"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_never_killed_leaf_still_populated_does_not_sweep() {
use crate::containment::cgroup::fault;
use crate::containment::cgroup::test_support::FakeLeaf;
let fake = FakeLeaf::new("cosca-disarmed-still-populated-leaf", true);
std::fs::create_dir(fake.leaf.join("live-child")).expect("a live tree's own child cgroup");
let (leaf, events) = (fake.leaf.clone(), fake.events.clone());
let sweeps = std::rc::Rc::new(std::cell::Cell::new(0));
let counted = sweeps.clone();
fault::set_rmdir_hook(move |path| {
if !path.exists() {
return Err(std::io::Error::from_raw_os_error(libc::ENOENT));
}
if path.join("live-child").exists() {
counted.set(counted.get() + 1);
return Err(std::io::Error::from_raw_os_error(libc::EBUSY));
}
FakeLeaf::rmdir(&leaf, &events)
});
let leaf = entered_leaf_at(fake.leaf.clone());
leaf.disarm();
crate::log_capture::install();
let mark = crate::log_capture::mark();
drop(leaf);
fault::take_rmdir_hook();
assert_eq!(
sweeps.get(),
1,
"a still-populated leaf gets exactly the one, doomed rmdir, no retry"
);
assert!(
fake.leaf.join("live-child").exists(),
"a live tree's child cgroup must not be swept away"
);
assert_eq!(
crate::log_capture::levels_since(mark, "cosca-disarmed-still-populated-leaf"),
vec![log::Level::Debug],
"a tree the caller left running is not a leak"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_disarmed_leaf_whose_kill_attempt_failed_is_reported_at_warn() {
use crate::containment::cgroup::fault;
use crate::containment::cgroup::test_support::FakeLeaf;
crate::log_capture::install();
let fake = FakeLeaf::new("cosca-disarmed-kill-failed-leaf", true);
std::fs::remove_file(fake.leaf.join("cgroup.kill")).expect("remove the real cgroup.kill");
std::fs::create_dir(fake.leaf.join("cgroup.kill")).expect("make cgroup.kill unwritable");
let (leaf, events) = (fake.leaf.clone(), fake.events.clone());
fault::set_rmdir_hook(move |_| FakeLeaf::rmdir(&leaf, &events));
let leaf = entered_leaf_at(fake.leaf.clone());
leaf.disarm();
leaf.hard_kill()
.expect_err("a directory cannot be written as cgroup.kill");
let mark = crate::log_capture::mark();
drop(leaf);
fault::take_rmdir_hook();
assert_eq!(
crate::log_capture::levels_since(mark, "cosca-disarmed-kill-failed-leaf"),
vec![log::Level::Warn],
"a kill_tree() that actually failed is a mechanism failure, not an opt-out"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_drain_wait_wakes_when_the_leaf_is_removed_without_a_populated_event() {
use crate::containment::cgroup::test_support::FakeLeaf;
use crate::containment::TreeDrain;
let fake = FakeLeaf::new("cosca-removed-while-waited", true);
let waited = fake.leaf.clone();
let removed = fake.leaf.clone();
let waiter = std::thread::spawn(move || {
let _actor = on_each_drain_block(move |_| FakeLeaf::remove(&removed));
crate::containment::cgroup::CgroupLeaf::for_test_at(waited).wait_drained(None)
});
assert_eq!(
waiter.join().expect("waiter").expect("wait_drained"),
TreeDrain::AllMembersExited,
"a removed leaf holds no member"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_armed_drop_whose_leaf_a_third_party_removes_reports_nothing() {
use crate::containment::cgroup::fault;
use crate::containment::cgroup::test_support::FakeLeaf;
crate::log_capture::install();
let fake = FakeLeaf::new("cosca-removed-under-drop", true);
let (leaf, events) = (fake.leaf.clone(), fake.events.clone());
fault::set_rmdir_hook(move |_| FakeLeaf::rmdir(&leaf, &events));
let removed = fake.leaf.clone();
let actor = on_each_drain_block(move |_| FakeLeaf::remove(&removed));
let mark = crate::log_capture::mark();
drop(entered_leaf_at(fake.leaf.clone()));
drop(actor);
fault::take_rmdir_hook();
let records = crate::log_capture::records_since(mark, "cosca-removed-under-drop");
assert!(
!crate::log_capture::levels_since(mark, "cosca-removed-under-drop").contains(&log::Level::Warn),
"a leaf a third party removed was not left behind, got {records:?}"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_armed_drop_reports_an_rmdir_refused_after_its_drain_once_without_retrying() {
use crate::containment::cgroup::fault;
use crate::containment::cgroup::test_support::FakeLeaf;
crate::log_capture::install();
let fake = FakeLeaf::new("cosca-refused-after-drain", true);
let (leaf, events) = (fake.leaf.clone(), fake.events.clone());
let drained_rmdirs = std::rc::Rc::new(std::cell::Cell::new(0));
let counted = drained_rmdirs.clone();
fault::set_rmdir_hook(move |_| {
if !FakeLeaf::is_populated(&events) {
counted.set(counted.get() + 1);
return Err(std::io::Error::from_raw_os_error(libc::EBUSY));
}
FakeLeaf::rmdir(&leaf, &events)
});
let events = fake.events.clone();
let actor = on_each_drain_block(move |_| FakeLeaf::set_populated(&events, false));
let mark = crate::log_capture::mark();
drop(entered_leaf_at(fake.leaf.clone()));
drop(actor);
fault::take_rmdir_hook();
let records = crate::log_capture::records_since(mark, "cosca-refused-after-drain");
assert_eq!(drained_rmdirs.get(), 1, "one rmdir after the drain, no retry");
assert_eq!(
crate::log_capture::levels_since(mark, "cosca-refused-after-drain"),
vec![log::Level::Warn],
"reported once, got {records:?}"
);
for cause in ["moved into it after the kill", "child cgroup", "mount"] {
assert!(
records[0].contains(cause),
"the report must name {cause:?}: {}",
records[0]
);
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn sweeping_a_leaf_that_is_already_gone_removes_nothing() {
let dir = tempfile::tempdir().expect("tempdir");
assert_eq!(
crate::containment::cgroup::LeafDir::open_for_test(&dir.path().join("cosca-gone"))
.remove_children()
.expect("sweep"),
0
);
}
#[cfg(target_os = "linux")]
fn entered_real_leaf() -> (
crate::containment::cgroup::CgroupLeaf,
std::process::Child,
std::process::ChildStdin,
) {
use std::os::unix::process::CommandExt;
let mut leaf = crate::containment::cgroup::try_create_leaf().expect("create a real leaf");
let (procs_fd, slot) = (leaf.procs_fd(), leaf.placement_slot());
let mut cmd = crate::test_child::held_std_blocker(std::process::Stdio::null());
unsafe {
cmd.pre_exec(move || crate::containment::cgroup::place_self_in_cgroup_pre_exec(procs_fd, slot));
}
let mut member = crate::test_spawn::spawn(&mut cmd).expect("spawn a member");
let stdin = member.stdin.take().expect("piped stdin");
leaf.take_placement(handle_of(member.id(), &pidfd_of(member.id())))
.expect("the member entered the leaf");
(leaf, member, stdin)
}
#[cfg(target_os = "linux")]
fn enter_a_private_mount_namespace() {
unsafe {
assert_eq!(
libc::unshare(libc::CLONE_NEWNS),
0,
"unshare: {}",
std::io::Error::last_os_error()
);
assert_eq!(
libc::mount(
std::ptr::null(),
c"/".as_ptr(),
std::ptr::null(),
libc::MS_REC | libc::MS_PRIVATE,
std::ptr::null()
),
0,
"make / private: {}",
std::io::Error::last_os_error()
);
}
}
#[cfg(target_os = "linux")]
fn mount_a_tmpfs_over(over: &std::path::Path) {
let over = std::ffi::CString::new(over.as_os_str().as_encoded_bytes()).expect("no NUL");
let mounted = unsafe { libc::mount(c"tmpfs".as_ptr(), over.as_ptr(), c"tmpfs".as_ptr(), 0, std::ptr::null()) };
assert_eq!(mounted, 0, "mount a tmpfs: {}", std::io::Error::last_os_error());
}
#[cfg(target_os = "linux")]
fn drop_under_a_mount(
leaf: crate::containment::cgroup::CgroupLeaf,
over: std::path::PathBuf,
marker: String,
member_stdin: std::process::ChildStdin,
) -> (Vec<log::Level>, Vec<String>) {
crate::log_capture::install();
std::thread::spawn(move || {
enter_a_private_mount_namespace();
mount_a_tmpfs_over(&over);
let mut stdin = Some(member_stdin);
let _guard = on_each_drain_block(move |_| {
if let Some(mut s) = stdin.take() {
crate::test_child::write_to_possibly_dead_stdin(&mut s, b"x");
}
});
let mark = crate::log_capture::mark();
drop(leaf);
(
crate::log_capture::levels_since(mark, &marker),
crate::log_capture::records_since(mark, &marker),
)
})
.join()
.expect("the dropping thread")
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_an_armed_drop_under_a_mount_over_its_leaf_kills_the_tree_and_reports_the_leaf(
#[fixture(cgroup)] _group: &Group,
) {
use std::os::unix::process::ExitStatusExt as _;
let (leaf, mut member, stdin) = entered_real_leaf();
let leaf_path = leaf.leaf_path.clone();
let name = leaf_path.file_name().expect("a name").to_string_lossy().into_owned();
let (levels, records) = drop_under_a_mount(leaf, leaf_path.clone(), name, stdin);
let status = member.wait().expect("reap the member");
std::fs::remove_dir(&leaf_path).expect("remove the drained leaf");
assert_eq!(status.signal(), Some(libc::SIGKILL), "the real tree must be killed");
assert_eq!(levels, vec![log::Level::Warn], "the leaf left behind is reported, once");
assert!(
records[0].contains("mount"),
"the report must name a mount as a cause: {}",
records[0]
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_an_armed_drop_under_a_mount_over_its_name_in_its_own_namespace_kills_the_tree_and_reports_the_leaf(
#[fixture(cgroup)] _group: &Group,
) {
use std::os::unix::process::ExitStatusExt as _;
crate::log_capture::install();
let (leaf_path, mut member, levels, records) = std::thread::spawn(|| {
enter_a_private_mount_namespace();
let (leaf, member, stdin) = entered_real_leaf();
let leaf_path = leaf.leaf_path.clone();
let name = leaf_path.file_name().expect("a name").to_string_lossy().into_owned();
mount_a_tmpfs_over(&leaf_path);
let mut stdin = Some(stdin);
let _guard = on_each_drain_block(move |_| {
if let Some(mut s) = stdin.take() {
crate::test_child::write_to_possibly_dead_stdin(&mut s, b"x");
}
});
let mark = crate::log_capture::mark();
drop(leaf);
(
leaf_path,
member,
crate::log_capture::levels_since(mark, &name),
crate::log_capture::records_since(mark, &name),
)
})
.join()
.expect("the dropping thread");
let status = member.wait().expect("reap the member");
std::fs::remove_dir(&leaf_path).expect("remove the drained leaf");
assert_eq!(status.signal(), Some(libc::SIGKILL), "the real tree must be killed");
assert_eq!(levels, vec![log::Level::Warn], "the leaf left behind is reported, once");
assert!(
records[0].contains("mount"),
"the report must name a mount as a cause: {}",
records[0]
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_an_armed_drop_under_a_mount_over_its_parent_still_removes_the_leaf(#[fixture(cgroup)] _group: &Group) {
use std::os::unix::process::ExitStatusExt as _;
let (leaf, mut member, stdin) = entered_real_leaf();
let leaf_path = leaf.leaf_path.clone();
let parent = leaf_path.parent().expect("a parent").to_path_buf();
let name = leaf_path.file_name().expect("a name").to_string_lossy().into_owned();
let (levels, _) = drop_under_a_mount(leaf, parent, name, stdin);
let removed = !leaf_path.exists();
let status = member.wait().expect("reap the member");
if !removed {
crate::containment::cgroup::test_support::remove_drained_leaf(&leaf_path);
}
assert!(removed, "the real leaf must be killed through and removed");
assert_eq!(status.signal(), Some(libc::SIGKILL), "the real tree must be killed");
assert!(
!levels.contains(&log::Level::Warn),
"nothing was left behind, got {levels:?}"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_a_leaf_whose_drain_cannot_be_watched_is_not_created(#[fixture(cgroup)] _group: &Group) {
crate::containment::cgroup::fault::set_force_inotify_failure(true);
let result = crate::containment::cgroup::try_create_leaf();
let consumed = !crate::containment::cgroup::fault::take_force_inotify_failure();
assert!(consumed, "the creation must have tried, and failed, to watch");
let leaf = match result {
Err(LeafError::WatchDrain { source, path }) => {
assert_eq!(source.raw_os_error(), Some(libc::EMFILE));
path.parent().expect("cgroup.events is in the leaf").to_path_buf()
}
Err(e) => panic!("expected WatchDrain, got {e:?}"),
Ok(_) => panic!("a leaf whose drain cannot be watched must not be created"),
};
assert!(!leaf.exists(), "the half-made leaf must be removed: {}", leaf.display());
}
#[cfg(all(target_os = "linux", feature = "tokio"))]
fn signal_when_blocking(tx: std::sync::mpsc::Sender<()>) {
crate::containment::cgroup::fault::set_drain_blocking_notifier(tx);
}
#[cfg(all(target_os = "linux", feature = "tokio"))]
#[skuld::test]
fn a_parked_async_wait_does_not_hold_up_another() {
use std::future::Future as _;
use crate::containment::cgroup::test_support::FakeLeaf;
use crate::containment::TreeDrain;
let fake = FakeLeaf::new("cosca-parked-waiter", true);
let leaf = std::sync::Arc::new(crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone()));
let runtime = ::tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("a runtime");
runtime.block_on(async {
let mut parked = std::pin::pin!(crate::tokio::wait::cgroup_wait_tree_drained(&leaf, None));
let mut context = std::task::Context::from_waker(std::task::Waker::noop());
assert!(parked.as_mut().poll(&mut context).is_pending(), "the leaf is populated");
let (blocking, blocking_rx) = std::sync::mpsc::channel();
let other_leaf = leaf.clone();
let other = std::thread::spawn(move || {
signal_when_blocking(blocking);
let runtime = ::tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("a runtime");
runtime.block_on(crate::tokio::wait::cgroup_wait_tree_drained(&other_leaf, None))
});
blocking_rx.recv().expect("the second wait blocks");
FakeLeaf::set_populated(&fake.events, false);
assert_eq!(
other.join().expect("the second waiter").expect("wait"),
TreeDrain::AllMembersExited
);
let _ = &parked;
});
}
#[cfg(all(target_os = "linux", feature = "tokio"))]
#[skuld::test]
fn a_sync_and_an_async_wait_share_the_leafs_one_watch() {
use crate::containment::cgroup::test_support::FakeLeaf;
use crate::containment::TreeDrain;
let fake = FakeLeaf::new("cosca-two-waiters", true);
let leaf = std::sync::Arc::new(crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone()));
let (blocking, blocking_rx) = std::sync::mpsc::channel();
let (sync_leaf, sync_blocking) = (leaf.clone(), blocking.clone());
let sync_waiter = std::thread::spawn(move || {
signal_when_blocking(sync_blocking);
sync_leaf.wait_drained(None)
});
let (async_leaf, async_blocking) = (leaf.clone(), blocking.clone());
let async_waiter = std::thread::spawn(move || {
signal_when_blocking(async_blocking);
let runtime = ::tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("a runtime");
runtime.block_on(crate::tokio::wait::cgroup_wait_tree_drained(&async_leaf, None))
});
blocking_rx.recv().expect("a waiter blocks");
blocking_rx.recv().expect("the other waiter blocks");
FakeLeaf::set_populated(&fake.events, false);
assert_eq!(
sync_waiter.join().expect("sync waiter").expect("sync wait"),
TreeDrain::AllMembersExited
);
assert_eq!(
async_waiter.join().expect("async waiter").expect("async wait"),
TreeDrain::AllMembersExited
);
assert_eq!(
crate::containment::cgroup::fault::arms_of("cosca-two-waiters"),
1,
"only the leaf's own watch is armed, at creation"
);
}
#[cfg(all(target_os = "linux", feature = "tokio"))]
#[skuld::test]
fn a_cancelled_async_wait_leaves_the_others_waiting() {
use crate::containment::cgroup::test_support::FakeLeaf;
use crate::containment::TreeDrain;
let fake = FakeLeaf::new("cosca-cancelled-waiter", true);
let leaf = std::sync::Arc::new(crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone()));
let (blocking, blocking_rx) = std::sync::mpsc::channel();
let (cancel, cancelled) = ::tokio::sync::oneshot::channel::<()>();
let async_leaf = leaf.clone();
let async_waiter = std::thread::spawn(move || {
signal_when_blocking(blocking);
let runtime = ::tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("a runtime");
runtime.block_on(async {
::tokio::select! {
drained = crate::tokio::wait::cgroup_wait_tree_drained(&async_leaf, None) => {
panic!("the leaf was never drained, got {drained:?}")
}
_ = cancelled => {}
}
});
});
blocking_rx.recv().expect("the async wait blocks");
cancel.send(()).expect("cancel the async wait");
async_waiter.join().expect("the async waiter");
FakeLeaf::set_populated(&fake.events, false);
assert_eq!(leaf.wait_drained(None).expect("wait"), TreeDrain::AllMembersExited);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_wait_past_its_deadline_answers_from_the_leafs_state() {
use crate::containment::cgroup::test_support::FakeLeaf;
use crate::containment::TreeDrain;
let fake = FakeLeaf::new("cosca-past-deadline", true);
let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone());
assert_eq!(
leaf.wait_drained(Some(Some(std::time::Instant::now()))).expect("wait"),
TreeDrain::MembersRemain
);
FakeLeaf::set_populated(&fake.events, false);
assert_eq!(
leaf.wait_drained(Some(Some(std::time::Instant::now()))).expect("wait"),
TreeDrain::AllMembersExited
);
}
#[cfg(target_os = "linux")]
fn blocked_wait(
leaf: &std::sync::Arc<crate::containment::cgroup::CgroupLeaf>,
) -> (
std::thread::JoinHandle<Result<crate::containment::TreeDrain, crate::error::Error>>,
std::sync::mpsc::Receiver<()>,
) {
let (blocking, blocking_rx) = std::sync::mpsc::channel();
let leaf = leaf.clone();
let waiter = std::thread::spawn(move || {
crate::containment::cgroup::fault::set_drain_blocking_notifier(blocking);
leaf.wait_drained(None)
});
blocking_rx.recv().expect("the wait blocks");
(waiter, blocking_rx)
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn dropping_the_leaf_stops_and_joins_its_pump() {
use crate::containment::cgroup::fault;
use crate::containment::cgroup::test_support::FakeLeaf;
use crate::containment::TreeDrain;
let fake = FakeLeaf::new("cosca-pumped-leaf", true);
let leaf = std::sync::Arc::new(crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone()));
_ = leaf.wait_drained(Some(Some(std::time::Instant::now())));
assert_eq!(
fault::pumps_of("cosca-pumped-leaf"),
(0, 0),
"a wait that cannot block starts none"
);
let (waiter, _blocking_rx) = blocked_wait(&leaf);
assert_eq!(
fault::pumps_of("cosca-pumped-leaf"),
(1, 0),
"a blocking wait starts the pump"
);
FakeLeaf::set_populated(&fake.events, false);
assert_eq!(
waiter.join().expect("waiter").expect("wait"),
TreeDrain::AllMembersExited
);
FakeLeaf::set_populated(&fake.events, true);
let (waiter, _blocking_rx) = blocked_wait(&leaf);
FakeLeaf::set_populated(&fake.events, false);
assert_eq!(
waiter.join().expect("waiter").expect("wait"),
TreeDrain::AllMembersExited
);
assert_eq!(fault::pumps_of("cosca-pumped-leaf"), (1, 0), "one pump per leaf");
drop(std::sync::Arc::into_inner(leaf).expect("the waiters are joined"));
assert_eq!(
fault::pumps_of("cosca-pumped-leaf"),
(1, 1),
"the drop joins the pump it stopped"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_drained_leaf_is_answered_without_a_pump() {
use crate::containment::cgroup::fault;
use crate::containment::cgroup::test_support::FakeLeaf;
use crate::containment::TreeDrain;
let fake = FakeLeaf::new("cosca-drained-unpumped", false);
let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone());
assert_eq!(leaf.wait_drained(None).expect("wait"), TreeDrain::AllMembersExited);
assert_eq!(
leaf.wait_drained(Some(Some(std::time::Instant::now()))).expect("wait"),
TreeDrain::AllMembersExited
);
#[cfg(feature = "tokio")]
{
let runtime = ::tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("a runtime");
assert_eq!(
runtime
.block_on(crate::tokio::wait::cgroup_wait_tree_drained(&leaf, None))
.expect("wait"),
TreeDrain::AllMembersExited
);
}
assert_eq!(fault::pumps_of("cosca-drained-unpumped"), (0, 0));
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_pump_wakes_every_wait_with_its_error() {
use crate::containment::cgroup::fault;
use crate::containment::cgroup::test_support::FakeLeaf;
let fake = FakeLeaf::new("cosca-failed-pump", true);
let leaf = std::sync::Arc::new(crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone()));
let waiters = [blocked_wait(&leaf), blocked_wait(&leaf)];
fault::set_force_pump_failure("cosca-failed-pump");
FakeLeaf::set_populated(&fake.events, true);
for (waiter, _blocking_rx) in waiters {
let e = waiter.join().expect("waiter").expect_err("the pump failed");
assert!(e.to_string().contains("can no longer be watched"), "{e}");
}
assert!(
!fault::take_force_pump_failure("cosca-failed-pump".as_ref()),
"the pump took it"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_siblings_removal_wakes_no_wait() {
use crate::containment::cgroup::fault;
use crate::containment::cgroup::test_support::FakeLeaf;
use crate::containment::TreeDrain;
let fake = FakeLeaf::new("cosca-sibling-watcher", true);
let leaf = std::sync::Arc::new(crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone()));
let (batches, batches_rx) = std::sync::mpsc::channel();
fault::set_pump_batch_notifier("cosca-sibling-watcher", batches);
let (waiter, _blocking_rx) = blocked_wait(&leaf);
let sibling = fake.leaf.with_file_name("cosca-sibling");
std::fs::create_dir(&sibling).expect("make a sibling");
std::fs::remove_dir(&sibling).expect("remove the sibling");
assert!(
!batches_rx.recv().expect("a batch"),
"a sibling's removal notifies no one"
);
FakeLeaf::set_populated(&fake.events, false);
assert!(batches_rx.recv().expect("a batch"), "a write to cgroup.events notifies");
assert_eq!(
waiter.join().expect("waiter").expect("wait"),
TreeDrain::AllMembersExited
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_pump_without_a_watch_fails_loudly() {
use event_listener::Listener as _;
crate::log_capture::install();
let mark = crate::log_capture::mark();
let watcher = crate::containment::cgroup::Watcher::new(None, "cosca-unwatched".into());
let listener = watcher.listen().expect("start the pump");
listener.wait();
assert!(
watcher.failure().is_some_and(|why| why.contains("never armed")),
"{:?}",
watcher.failure()
);
drop(watcher);
assert_eq!(
crate::log_capture::contains_since(mark, "cosca-unwatched"),
cfg!(debug_assertions),
"the joined pump panicked on its debug assertion in exactly the builds that keep it"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn the_pump_thread_name_fits_the_kernels_limit() {
assert!(crate::containment::cgroup::PUMP_THREAD.len() <= 15);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn drop_reports_nothing_for_a_leaf_that_is_already_gone() {
crate::log_capture::install();
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-already-gone-leaf");
let mark = crate::log_capture::mark();
drop(crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path));
let levels = crate::log_capture::levels_since(mark, "cosca-already-gone-leaf");
assert!(
!levels.contains(&log::Level::Warn),
"an already-removed leaf left nothing on this host; reporting one as a leak is \
narrating a non-event, got {levels:?}"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn create_leaf_under_reports_an_unopenable_cgroup_procs_and_removes_the_leaf() {
let dir = tempfile::tempdir().expect("tempdir");
crate::containment::cgroup::fault::set_force_kill_supported(true);
let err = match crate::containment::cgroup::create_leaf_under(dir.path()) {
Err(e) => e,
Ok(_) => panic!("a plain directory has no cgroup.procs to open; leaf creation must fail"),
};
assert!(
!crate::containment::cgroup::fault::kill_supported_armed(),
"the seam must be consumed by the step it stands in for"
);
assert!(
matches!(err, LeafError::OpenProcs { .. }),
"expected OpenProcs, got {err:?}"
);
assert!(err.to_string().contains("cgroup.procs"), "got {err}");
let strays: Vec<_> = std::fs::read_dir(dir.path())
.expect("read tempdir")
.map(|e| e.expect("entry").file_name())
.collect();
assert!(
strays.is_empty(),
"the degrade left {strays:?} behind — a cosca-* cgroup this host then keeps forever"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn create_leaf_under_reports_an_unopenable_report_channel_and_removes_the_leaf() {
let dir = tempfile::tempdir().expect("tempdir");
crate::containment::cgroup::fault::set_force_kill_supported(true);
crate::containment::cgroup::fault::set_force_report_channel_failure(true);
let err = match crate::containment::cgroup::create_leaf_under(dir.path()) {
Err(e) => e,
Ok(_) => panic!("the report channel could not be opened; leaf creation must fail"),
};
assert!(
!crate::containment::cgroup::fault::report_channel_failure_armed(),
"the seam must be consumed by the channel it fails"
);
assert!(
matches!(err, LeafError::OpenReportChannel(_)),
"expected OpenReportChannel, got {err:?}"
);
let reason = std::io::Error::from_raw_os_error(libc::EMFILE).to_string();
assert!(err.to_string().contains(&reason), "got {err}");
let strays: Vec<_> = std::fs::read_dir(dir.path())
.expect("read tempdir")
.map(|e| e.expect("entry").file_name())
.collect();
assert!(strays.is_empty(), "a failed channel left {strays:?} behind");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn take_placement_reports_an_unreadable_cgroup_procs() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-unreadable-procs");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path.clone());
match leaf.take_placement(handle_of(std::process::id(), &pidfd_of(std::process::id()))) {
Err(NotPlaced::Unreadable {
pid,
path,
source,
report,
}) => {
assert_eq!(pid, std::process::id());
assert_eq!(path, leaf_path.join("cgroup.procs"));
assert_eq!(source.kind(), std::io::ErrorKind::NotFound);
assert_eq!(report, NotEntered::NotReported, "no child ever ran");
}
Err(other) => panic!("an unreadable cgroup.procs must not read as an empty one: {other}"),
Ok(()) => panic!("no child reported a placement"),
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn take_placement_reads_the_real_procs_and_state_of_a_child_that_did_not_enter() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-absent-procs");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let listed = format!("{}\n", std::process::id());
std::fs::write(leaf_path.join("cgroup.procs"), &listed).expect("write cgroup.procs");
let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path.clone());
_ = unsafe { crate::containment::cgroup::place_self_in_cgroup_pre_exec(-1, leaf.placement_slot()) };
let mut child = crate::test_spawn::spawn(&mut std::process::Command::new("/bin/true")).expect("spawn");
let pid = child.id();
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
let waited = unsafe { libc::waitid(libc::P_PID, pid, &mut info, libc::WEXITED | libc::WNOWAIT) };
assert_eq!(waited, 0, "waitid: {}", std::io::Error::last_os_error());
let verdict = leaf.take_placement(handle_of(pid, &pidfd_of(pid)));
child.wait().expect("reap the child");
match verdict {
Err(NotPlaced::Absent {
pid: reported,
path,
procs,
report,
child_state,
}) => {
assert_eq!(reported, pid);
assert_eq!(path, leaf_path.join("cgroup.procs"));
assert_eq!(procs, listed, "the file's real contents");
assert_eq!(report, NotEntered::WriteFailed(libc::EBADF));
assert_eq!(child_state, Some('Z'), "the child's real /proc state");
}
Err(other) => panic!("a readable cgroup.procs must be quoted: {other}"),
Ok(()) => panic!("the child reported a failed write"),
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn take_placement_reads_the_childs_state_before_cgroup_procs() {
use std::io::Write;
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-ordered-reads");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let procs_path = leaf_path.join("cgroup.procs");
nix::unistd::mkfifo(&procs_path, nix::sys::stat::Mode::S_IRWXU).expect("mkfifo cgroup.procs");
let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
let mut child =
crate::test_spawn::spawn(std::process::Command::new("/bin/cat").stdin(std::process::Stdio::piped()))
.expect("spawn");
let pid = child.id();
let writer = std::thread::spawn(move || {
let mut fifo = std::fs::OpenOptions::new()
.write(true)
.open(&procs_path)
.expect("open the FIFO");
child.kill().expect("kill the child");
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
let waited = unsafe { libc::waitid(libc::P_PID, pid, &mut info, libc::WEXITED | libc::WNOWAIT) };
assert_eq!(waited, 0, "waitid: {}", std::io::Error::last_os_error());
fifo.write_all(b"listed\n").expect("write the FIFO");
child
});
let verdict = leaf.take_placement(handle_of(pid, &pidfd_of(pid)));
writer.join().expect("the writer").wait().expect("reap the child");
match verdict {
Err(NotPlaced::Absent { procs, child_state, .. }) => {
assert_eq!(procs, "listed\n");
assert!(
child_state.is_some_and(|state| state != 'Z'),
"the state was read after cgroup.procs: {child_state:?}"
);
}
Err(other) => panic!("a readable cgroup.procs must be quoted: {other}"),
Ok(()) => panic!("no child reported a placement"),
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn placement_hook_proceeds_past_a_failed_placement() {
let channel = crate::containment::cgroup::ReportChannel::new().expect("open the report channel");
let result = unsafe { crate::containment::cgroup::place_self_in_cgroup_pre_exec(-1, channel.slot()) };
assert!(
result.is_ok(),
"a failed placement must not abort the spawn: {result:?}"
);
assert_eq!(channel.report_for_test(), PlacementReport::WriteFailed(libc::EBADF));
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn placement_hook_fails_when_its_report_cannot_be_sent() {
let sink = std::fs::OpenOptions::new()
.write(true)
.open("/dev/null")
.expect("open /dev/null");
let procs_fd = std::os::fd::IntoRawFd::into_raw_fd(sink);
let slot = crate::containment::cgroup::ReportSlot { fd: -1, parent_fd: -1 };
let result = unsafe { crate::containment::cgroup::place_self_in_cgroup_pre_exec(procs_fd, slot) };
assert_eq!(
result.map_err(|e| e.raw_os_error()),
Err(Some(libc::EBADF)),
"an undeliverable report must abort the spawn"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn placement_hook_proceeds_when_the_parent_decided_without_the_exchange() {
use std::io::{Read, Write};
use std::os::fd::{AsRawFd, IntoRawFd};
use std::os::unix::process::CommandExt;
const NAME: &str =
"containment::cgroup::leaf::leaf_tests::placement_hook_proceeds_when_the_parent_decided_without_the_exchange";
const INNER: &str = "COSCA_TEST_DECIDED_ALONE";
if std::env::var_os(INNER).is_none() {
let out = crate::test_spawn::output_captured(
crate::test_reexec::with_json_events(
crate::test_reexec::command(std::env::current_exe().expect("this test binary")).args([
NAME,
"--exact",
crate::test_reexec::NOCAPTURE,
"--test-threads=1",
]),
)
.env(INNER, "1"),
)
.expect("run the case alone");
let stdout = String::from_utf8_lossy(&out.stdout);
if let Err(why) = crate::test_reexec::suite_passed_exactly_one(&out) {
panic!(
"{why}\n{}\n--- stdout ---\n{stdout}\n--- stderr ---\n{}",
out.status,
String::from_utf8_lossy(&out.stderr)
);
}
return;
}
let channel = crate::containment::cgroup::ReportChannel::new().expect("open the report channel");
let slot = channel.slot();
let (procs_read, procs_write) = std::io::pipe().expect("a pipe standing in for cgroup.procs");
let procs_fd = procs_write.into_raw_fd();
let (mut forked_read, forked_write) = std::io::pipe().expect("open the forked signal");
let (gate_read, mut gate_write) = std::io::pipe().expect("open the gate");
let (forked_fd, gate_fd) = (forked_write.as_raw_fd(), gate_read.as_raw_fd());
let decider = std::thread::spawn(move || {
let mut byte = [0u8; 1];
forked_read.read_exact(&mut byte).expect("the child forked");
channel.proceed();
gate_write.write_all(b"x").expect("release the child");
});
let mut cmd = std::process::Command::new("/bin/true");
unsafe {
cmd.pre_exec(move || {
libc::write(forked_fd, b"x".as_ptr().cast(), 1);
block_on(gate_fd);
crate::containment::cgroup::placement_hook(procs_fd, slot)
})
};
let status = crate::test_spawn::spawn(&mut cmd)
.expect("a decided exchange must not abort the spawn")
.wait();
unsafe { libc::close(procs_fd) };
decider.join().expect("the deciding thread");
drop(forked_write);
assert!(status.expect("wait").success(), "the child must have exec'd");
assert_eq!(
std::io::read_to_string(procs_read).expect("read the pipe"),
"",
"no placement write"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn placement_hook_fails_a_spawn_the_parent_abandoned_before_touching_the_leaf() {
let channel = crate::containment::cgroup::ReportChannel::new().expect("open the report channel");
let (_end, slot) = childs_copy(&channel);
let (procs_read, procs_write) = std::io::pipe().expect("a pipe standing in for cgroup.procs");
let received = channel.shut();
assert!(received.pid.is_none(), "nothing was sent before the shut");
let result = unsafe {
crate::containment::cgroup::place_self_in_cgroup_pre_exec(
std::os::fd::IntoRawFd::into_raw_fd(procs_write),
slot,
)
};
assert_eq!(result.map_err(|e| e.raw_os_error()), Err(Some(libc::ECANCELED)));
assert_eq!(
std::io::read_to_string(procs_read).expect("read the pipe"),
"",
"no placement write"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_child_released_after_its_spawn_was_abandoned_never_execs() {
use std::io::Write;
use std::os::fd::{AsRawFd, IntoRawFd};
let channel = crate::containment::cgroup::ReportChannel::new().expect("open the report channel");
let slot = channel.slot();
let (procs_read, procs_write) = std::io::pipe().expect("a pipe standing in for cgroup.procs");
let procs_fd = procs_write.into_raw_fd();
let (gate_read, mut gate_write) = std::io::pipe().expect("open the gate");
let gate = gate_read.as_raw_fd();
let guard = fork_running(move || {
block_on(gate);
_ = unsafe { crate::containment::cgroup::placement_hook(procs_fd, slot) };
});
unsafe { libc::close(procs_fd) };
let received = channel.shut();
assert!(received.pid.is_none(), "the child was held before its hook");
gate_write.write_all(b"x").expect("release the child");
let pid = guard.defuse();
let mut status = 0;
assert_eq!(unsafe { libc::waitpid(pid as i32, &mut status, 0) }, pid as i32);
assert!(libc::WIFEXITED(status), "status {status:#x}");
assert_eq!(
libc::WEXITSTATUS(status),
crate::containment::cgroup::ABANDONED_EXIT,
"the abandoned child must exit from its hook, not exec"
);
assert_eq!(
std::io::read_to_string(procs_read).expect("read the pipe"),
"",
"no placement write"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn placement_hook_aborts_a_spawn_whose_report_cannot_be_sent() {
use std::os::unix::process::CommandExt;
let sink = std::fs::OpenOptions::new()
.write(true)
.open("/dev/null")
.expect("open /dev/null");
let procs_fd = std::os::fd::IntoRawFd::into_raw_fd(sink);
let slot = crate::containment::cgroup::ReportSlot { fd: -1, parent_fd: -1 };
let mut cmd = std::process::Command::new("/bin/true");
unsafe { cmd.pre_exec(move || crate::containment::cgroup::place_self_in_cgroup_pre_exec(procs_fd, slot)) };
let result = crate::test_spawn::spawn(&mut cmd);
unsafe { libc::close(procs_fd) };
assert!(result.is_err(), "the spawn must fail");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn drop_removes_an_empty_leaf_whose_report_is_in_flight_without_a_kill() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-in-flight-empty");
std::fs::create_dir(&leaf_path).expect("create the leaf");
drop(crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path.clone()));
assert!(!leaf_path.exists(), "the leaf must be removed");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_drop_of_an_abandoned_spawn_spares_an_occupant_that_is_not_its_child(#[fixture(cgroup)] _group: &Group) {
use std::io::{Read, Write};
use std::os::unix::process::CommandExt;
let leaf = crate::containment::cgroup::try_create_leaf().expect("a delegated cgroup v2 leaf");
let leaf_path = leaf.leaf_path.clone();
let own = crate::containment::cgroup::ReportChannel::new().expect("open the occupant's channel");
let (procs_fd, slot) = (leaf.procs_fd(), own.slot());
let mut cmd = std::process::Command::new("/bin/cat");
cmd.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped());
unsafe { cmd.pre_exec(move || crate::containment::cgroup::place_self_in_cgroup_pre_exec(procs_fd, slot)) };
let mut occupant = crate::test_spawn::spawn(&mut cmd).expect("spawn the occupant");
drop(leaf);
let mut echo = [0u8; 1];
occupant
.stdin
.as_mut()
.expect("stdin")
.write_all(b"x")
.expect("write to the occupant");
occupant
.stdout
.as_mut()
.expect("stdout")
.read_exact(&mut echo)
.expect("the occupant must still be alive to echo");
assert_eq!(&echo, b"x");
assert!(leaf_path.exists(), "an occupied leaf is left, and reported");
occupant.kill().expect("kill the occupant");
occupant.wait().expect("reap the occupant");
std::fs::remove_dir(&leaf_path).expect("remove the emptied leaf");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_child_is_killed_and_reaped_by_its_pidfd_when_the_leaf_kill_fails() {
use std::os::unix::process::CommandExt;
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-abandoned-kill-fails");
std::fs::create_dir(&leaf_path).expect("create the leaf");
std::fs::create_dir(leaf_path.join("cgroup.kill")).expect("make cgroup.kill unwritable");
let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
let sink = std::fs::OpenOptions::new()
.write(true)
.open("/dev/null")
.expect("open /dev/null");
let procs_fd = std::os::fd::IntoRawFd::into_raw_fd(sink);
let slot = leaf.placement_slot();
let mut cmd = std::process::Command::new("/bin/cat");
cmd.stdin(std::process::Stdio::piped()).process_group(0);
unsafe { cmd.pre_exec(move || crate::containment::cgroup::place_self_in_cgroup_pre_exec(procs_fd, slot)) };
let mut child = crate::test_spawn::spawn(&mut cmd).expect("spawn");
let stdin = child.stdin.take().expect("piped stdin");
let pid = child.id();
let pidfd = pidfd_of(pid);
unsafe { libc::close(procs_fd) };
drop(child);
let _armed = crate::containment::cgroup::fault::set_before_exit_wait(move || drop(stdin));
drop(leaf);
crate::containment::cgroup::fault::run_before_exit_wait();
assert!(
crate::containment::cgroup::fault::take_reaped_orphans().contains(&(pid, Some(libc::SIGKILL))),
"the child must be killed by its pidfd"
);
assert!(reaped(&pidfd), "and reaped");
}
#[cfg(target_os = "linux")]
fn reaped(pidfd: &std::os::fd::OwnedFd) -> bool {
use std::os::fd::AsFd;
use rustix::process::{waitid, WaitId, WaitIdOptions};
matches!(
waitid(
WaitId::PidFd(pidfd.as_fd()),
WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT,
),
Err(rustix::io::Errno::CHILD)
)
}
#[cfg(target_os = "linux")]
fn spawn_placing(
leaf: &crate::containment::cgroup::CgroupLeaf,
argv: &[&str],
fail: bool,
stdin: std::process::Stdio,
stdout: std::process::Stdio,
) -> std::process::Child {
use std::os::unix::process::CommandExt;
let procs_fd = if fail {
-1
} else {
let sink = std::fs::OpenOptions::new()
.write(true)
.open("/dev/null")
.expect("open /dev/null");
std::os::fd::IntoRawFd::into_raw_fd(sink)
};
let slot = leaf.placement_slot();
let mut cmd = std::process::Command::new(argv[0]);
cmd.args(&argv[1..]).stdin(stdin).stdout(stdout).process_group(0);
unsafe { cmd.pre_exec(move || crate::containment::cgroup::placement_hook(procs_fd, slot)) };
let child = crate::test_spawn::spawn(&mut cmd).expect("spawn");
if procs_fd >= 0 {
unsafe { libc::close(procs_fd) };
}
child
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_child_without_a_pidfd_is_killed_and_reaped_through_its_proc_directory() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-abandoned-no-pidfd");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
crate::containment::cgroup::fault::set_force_child_pidfd_failure(true);
let mut child = spawn_placing(
&leaf,
crate::test_child::BLOCKER_ARGV,
false,
std::process::Stdio::piped(),
std::process::Stdio::null(),
);
crate::containment::cgroup::fault::set_force_child_pidfd_failure(false);
let stdin = child.stdin.take().expect("piped stdin");
let _release = crate::containment::cgroup::fault::set_before_exit_wait(move || drop(stdin));
let pid = child.id();
let pidfd = pidfd_of(pid);
drop(child);
drop(leaf);
crate::containment::cgroup::fault::run_before_exit_wait();
assert!(
crate::containment::cgroup::fault::take_reaped_orphans().contains(&(pid, Some(libc::SIGKILL))),
"the child must be killed through its /proc directory"
);
assert!(reaped(&pidfd), "and reaped");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_intent_without_a_handle_is_never_signalled() {
use std::io::{Read, Write};
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-abandoned-no-handle");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
let mut other = crate::test_spawn::spawn(
std::process::Command::new("/bin/cat")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped()),
)
.expect("spawn another child");
unsafe {
leaf.placement_slot()
.send(crate::containment::cgroup::TAG_INTENT, other.id() as i32, 0, -1)
.expect("send a forged intent");
}
assert_eq!(
leaf.abandon_before_verdict(false, None),
crate::containment::cgroup::Abandoned::OutOfReach
);
assert_eq!(crate::containment::cgroup::fault::take_signalled_by_pid(), 0);
let mut echo = [0u8; 1];
other
.stdin
.as_mut()
.expect("stdin")
.write_all(b"x")
.expect("write to the other child");
other
.stdout
.as_mut()
.expect("stdout")
.read_exact(&mut echo)
.expect("the other child must be alive to echo");
other.kill().expect("kill the other child");
other.wait().expect("reap the other child");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_child_with_no_handle_on_itself_is_out_of_reach() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-abandoned-no-handle-spawn");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
crate::containment::cgroup::fault::set_force_child_pidfd_failure(true);
crate::containment::cgroup::fault::set_force_child_proc_dir_failure(true);
let mut child = spawn_placing(
&leaf,
&["cat"],
true,
std::process::Stdio::piped(),
std::process::Stdio::piped(),
);
crate::containment::cgroup::fault::set_force_child_pidfd_failure(false);
crate::containment::cgroup::fault::set_force_child_proc_dir_failure(false);
assert_eq!(
leaf.abandon_before_verdict(false, None),
crate::containment::cgroup::Abandoned::OutOfReach
);
assert_eq!(crate::containment::cgroup::fault::take_signalled_by_pid(), 0);
crate::test_child::assert_echoes(
child.stdin.as_mut().expect("stdin"),
child.stdout.as_mut().expect("stdout"),
);
child.kill().expect("kill the child");
child.wait().expect("reap the child");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_child_std_already_reaped_is_never_signalled() {
use std::io::Write;
use std::os::fd::AsRawFd;
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-abandoned-reaped");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
let slot = leaf.placement_slot();
let (gate_read, mut gate_write) = std::io::pipe().expect("open the gate");
let gate = gate_read.as_raw_fd();
crate::containment::cgroup::fault::set_force_child_pidfd_failure(true);
let guard = fork_running(move || {
_ = unsafe { slot.send_intent() };
block_on(gate);
});
crate::containment::cgroup::fault::set_force_child_pidfd_failure(false);
gate_write.write_all(b"x").expect("release the child");
reap(guard.defuse());
assert_eq!(
leaf.abandon_before_verdict(false, None),
crate::containment::cgroup::Abandoned::Ended
);
assert_eq!(crate::containment::cgroup::fault::take_signalled_by_pid(), 0);
assert_eq!(crate::containment::cgroup::fault::take_reaped_orphans(), Vec::new());
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_spawn_whose_child_sent_nothing_may_leave_it_unreaped() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-abandoned-silent");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path.clone());
assert_eq!(
leaf.abandon_before_verdict(false, None),
crate::containment::cgroup::Abandoned::MaybeUnreaped
);
assert!(!leaf_path.exists(), "the empty leaf is removed");
assert_eq!(crate::containment::cgroup::fault::take_signalled_by_pid(), 0);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_child_reaped_between_the_check_and_the_kill_is_not_signalled_by_number() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-abandoned-window");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
let child = spawn_placing(
&leaf,
&["/bin/true"],
false,
std::process::Stdio::inherit(),
std::process::Stdio::null(),
);
let pid = child.id();
drop(child);
crate::containment::cgroup::fault::set_between_check_and_kill(move || reap(pid));
assert_eq!(
leaf.abandon_before_verdict(false, None),
crate::containment::cgroup::Abandoned::Ended
);
assert_eq!(crate::containment::cgroup::fault::take_signalled_by_pid(), 0);
assert_eq!(crate::containment::cgroup::fault::take_reaped_orphans(), Vec::new());
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_child_that_refuses_the_kill_is_reaped_once_it_exits() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-abandoned-refuses");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
let mut child = spawn_placing(
&leaf,
&["cat"],
true,
std::process::Stdio::piped(),
std::process::Stdio::piped(),
);
let pid = child.id();
let pidfd = pidfd_of(pid);
let mut stdin = child.stdin.take().expect("piped stdin");
let mut stdout = child.stdout.take().expect("piped stdout");
drop(child);
let (reaped_tx, reaped_rx) = std::sync::mpsc::channel();
crate::containment::cgroup::fault::set_force_child_kill_denied(true);
crate::containment::cgroup::fault::set_background_reap_notifier(reaped_tx);
assert_eq!(
leaf.abandon_before_verdict(false, None),
crate::containment::cgroup::Abandoned::OutOfReach
);
crate::test_child::assert_echoes(&mut stdin, &mut stdout);
assert!(!reaped(&pidfd), "the child refused the kill and is still running");
rustix::process::pidfd_send_signal(&pidfd, rustix::process::Signal::KILL).expect("kill the child");
reaped_rx.recv().expect("the background reaper must reap it");
assert!(reaped(&pidfd), "the child must be reaped once it exits");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_child_is_killed_with_the_group_it_leads() {
use std::io::{BufRead, Read};
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-abandoned-group");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
let mut child = spawn_placing(
&leaf,
&["/bin/sh", "-c", "exec 3<&0; cat <&3 3<&- & echo forked; wait"],
false,
std::process::Stdio::piped(),
std::process::Stdio::piped(),
);
let mut stdin = child.stdin.take().expect("piped stdin");
let mut stdout = std::io::BufReader::new(child.stdout.take().expect("stdout"));
let mut line = String::new();
stdout.read_line(&mut line).expect("read the child's line");
assert_eq!(
line, "forked\n",
"the descendant must exist before the spawn is abandoned"
);
drop(child);
let _release = crate::containment::cgroup::fault::set_before_exit_wait(move || {
crate::test_child::write_to_possibly_dead_stdin(&mut stdin, b"x");
drop(stdin);
});
drop(leaf);
crate::containment::cgroup::fault::run_before_exit_wait();
let mut rest = Vec::new();
stdout
.read_to_end(&mut rest)
.expect("read to EOF: every process holding stdout is dead");
assert!(
rest.is_empty(),
"the descendant echoed a byte written after drop(leaf) — the group kill failed to reach \
it in time, got {rest:?}"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn placement_hook_reports_a_write_that_wrote_nothing_as_failed() {
let channel = crate::containment::cgroup::ReportChannel::new().expect("open the report channel");
let sink = std::fs::OpenOptions::new()
.write(true)
.open("/dev/null")
.expect("open /dev/null");
let procs_fd = std::os::fd::IntoRawFd::into_raw_fd(sink);
crate::containment::cgroup::fault::set_force_placement_write_result(0);
let result = unsafe { crate::containment::cgroup::place_self_in_cgroup_pre_exec(procs_fd, channel.slot()) };
assert!(
result.is_ok(),
"a failed placement must not abort the spawn: {result:?}"
);
assert_eq!(channel.report_for_test(), PlacementReport::WriteFailed(libc::EIO));
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_drop_removes_a_leaf_holding_child_cgroups(#[fixture(cgroup)] _group: &Group) {
for placed in [true, false] {
let leaf = crate::containment::cgroup::try_create_leaf().expect("a delegated cgroup v2 leaf");
let leaf_path = leaf.leaf_path.clone();
std::fs::create_dir_all(leaf_path.join("nested").join("deeper")).expect("create child cgroups");
if placed {
unsafe { leaf.placement_slot().report_placed_for_test() };
}
drop(leaf);
assert!(
!leaf_path.exists(),
"placed: {placed}: the leaf and its child cgroups must be removed"
);
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn leaf_names_carry_random_bits_past_the_pid_and_sequence() {
let suffix = |name: String| {
let parts = name.split('-').collect::<Vec<_>>();
assert_eq!(parts.len(), 4, "cosca-<pid>-<seq>-<random>: {name}");
assert_eq!((parts[0], parts[1]), ("cosca", std::process::id().to_string().as_str()));
assert!(
parts[3].len() == 16 && parts[3].bytes().all(|b| b.is_ascii_hexdigit()),
"{name}"
);
parts[3].to_owned()
};
let a = suffix(crate::containment::cgroup::leaf_name().expect("a name"));
let b = suffix(crate::containment::cgroup::leaf_name().expect("a name"));
assert_ne!(a, b);
}
#[cfg(all(target_os = "linux", feature = "tokio"))]
#[skuld::test]
fn end_child_refuses_inside_a_section() {
let received = crate::containment::cgroup::Received {
report: None,
pid: None,
pidfd: None,
proc_dir: None,
};
let _section = crate::bounded::Section::enter();
let refused = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| super::end_child(&received)));
assert!(refused.is_err(), "end_child must refuse inside a bounded section");
}
#[cfg(all(target_os = "linux", debug_assertions))]
#[skuld::test]
fn a_leaf_watches_one_front() {
let mut leaf = crate::containment::cgroup::CgroupLeaf::placeholder_for_test();
leaf.watch_front(7);
leaf.watch_front(7);
let second = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| leaf.watch_front(8)));
let message = second.expect_err("a second front was watched");
let message = message
.downcast_ref::<String>()
.map(String::as_str)
.or_else(|| message.downcast_ref::<&str>().copied())
.unwrap_or_default();
assert!(message.contains("a leaf watches one front"), "{message}");
}