#[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,
};
use crate::containment::cgroup::{DrainStep, LeafError, NotEntered, NotPlaced, PlacementReport, WithoutChild};
#[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(at), Some(at)), (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(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(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(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(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(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(None).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(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")]
fn lane_leaf() -> crate::containment::cgroup::CgroupLeaf {
crate::containment::cgroup::try_create_leaf(None).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)?"
)
})
}
#[cfg(target_os = "linux")]
fn cat_member() -> (
crate::containment::cgroup::test_support::Member,
crate::identity::ProcessId,
) {
cat_member_as(None)
}
#[cfg(target_os = "linux")]
fn cat_member_as(
uid: Option<u32>,
) -> (
crate::containment::cgroup::test_support::Member,
crate::identity::ProcessId,
) {
use std::os::unix::process::CommandExt as _;
use std::process::{Command, Stdio};
let mut cat = Command::new("cat");
cat.stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null());
if let Some(uid) = uid {
cat.uid(uid);
}
let mut child = crate::test_spawn::spawn(&mut cat).expect("spawn a member");
let stdin = child.stdin.take().expect("cat's stdin is piped");
let id = crate::identity::ProcessId::of(child.id())
.found()
.expect("the member's identity");
(crate::containment::cgroup::test_support::Member(child, stdin), id)
}
#[cfg(target_os = "linux")]
fn place(member: &crate::containment::cgroup::test_support::Member, dir: &std::path::Path) {
std::fs::write(dir.join("cgroup.procs"), member.0.id().to_string())
.unwrap_or_else(|e| panic!("move {} into {}: {e}", member.0.id(), dir.display()));
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_cgroup_listing_names_the_members_of_the_cgroups_under_the_leaf(#[fixture(cgroup)] _group: &Group) {
let leaf = lane_leaf();
let (in_leaf, in_leaf_id) = cat_member();
let (under, under_id) = cat_member();
let (deeper, deeper_id) = cat_member();
let nested = leaf.leaf_path.join("nested");
let deepest = nested.join("deeper");
std::fs::create_dir(&nested).expect("make a cgroup under the leaf");
std::fs::create_dir(&deepest).expect("make a cgroup under that");
place(&in_leaf, &leaf.leaf_path);
place(&under, &nested);
place(&deeper, &deepest);
let (members, unobserved) = leaf.list_members(None);
assert!(unobserved.is_empty(), "every member can be named: {unobserved:?}");
for (id, who) in [
(in_leaf_id, "the member in the leaf"),
(under_id, "the member in a cgroup under the leaf"),
(deeper_id, "the member two cgroups down"),
] {
assert!(members.iter().any(|m| m.id == id), "{who} is named: {members:?}");
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_member_placed_through_proc_is_listed_with_no_cgroup_id(#[fixture(cgroup)] _group: &Group) {
use crate::containment::cgroup::fault;
use crate::containment::cgroup::WalkStep;
let leaf = lane_leaf();
let (member, id) = cat_member();
place(&member, &leaf.leaf_path);
std::fs::create_dir(leaf.leaf_path.join("nested")).expect("make a cgroup under the leaf");
let _read = fault::force_pidfd_cgroup_id(u64::MAX);
let _walk = fault::fail_walk_step("./nested", WalkStep::Id, libc::EIO);
let (listed, unobserved) = leaf.list_members(None);
assert!(unobserved.is_empty(), "{unobserved:?}");
assert_eq!(
listed.iter().map(|m| (m.id, m.seen)).collect::<Vec<_>>(),
[(id, None)],
"placed through /proc, so no cgroup id placed it"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_cgroup_lists_its_members_before_it_kills_them(#[fixture(cgroup)] _group: &Group) {
use crate::containment::cgroup::fault;
use crate::containment::Contains as _;
let leaf = lane_leaf();
let (member, id) = cat_member();
place(&member, &leaf.leaf_path);
let member = std::rc::Rc::new(std::cell::RefCell::new(member));
let _ending = fault::set_before_kill_write({
let member = member.clone();
move || {
let mut member = member.borrow_mut();
member.0.kill().expect("end the member");
member.0.wait().expect("reap the member");
}
});
let (sent, wait) = leaf.kill(None).split();
sent.into_result().expect("the leaf's kill");
assert_eq!(
wait.members_for_test(),
[id],
"the member was named before the kill ended it"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_cgroup_kill_the_kernel_refused_waits_for_no_member(#[fixture(cgroup)] _group: &Group) {
use std::cell::Cell;
use std::rc::Rc;
use crate::containment::cgroup::fault;
use crate::containment::Contains as _;
let leaf = lane_leaf();
let (member, _) = cat_member();
place(&member, &leaf.leaf_path);
let pid = member.0.id();
let _refused = fault::fail_next_kill_write();
let (sent, wait) = leaf.kill(None).split();
assert!(sent.into_result().is_err(), "the kill was refused");
let blocked = Rc::new(Cell::new(false));
let _blocking = crate::wait::block_probe::on_blocking({
let blocked = blocked.clone();
move || {
blocked.set(true);
nix::sys::signal::kill(
nix::unistd::Pid::from_raw(pid as i32),
nix::sys::signal::Signal::SIGKILL,
)
.expect("end the member");
}
});
wait.wait().expect("a kill that failed waits for nothing");
assert!(!blocked.get(), "the wait blocked on a member the kill did not reach");
drop(member);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_member_that_left_the_leaf_before_the_kill_is_neither_killed_nor_waited_for(#[fixture(cgroup)] _group: &Group) {
use std::cell::Cell;
use std::rc::Rc;
use crate::containment::cgroup::fault;
use crate::containment::Contains as _;
let leaf = lane_leaf();
let (member, _) = cat_member();
place(&member, &leaf.leaf_path);
let pid = member.0.id();
let outside = leaf
.leaf_path
.parent()
.expect("the leaf has a parent cgroup")
.to_owned();
let member = Rc::new(std::cell::RefCell::new(member));
let _leaving = fault::set_before_kill_write({
let member = member.clone();
move || place(&member.borrow(), &outside)
});
let blocked = Rc::new(Cell::new(false));
let _blocking = crate::wait::block_probe::on_blocking({
let blocked = blocked.clone();
move || {
blocked.set(true);
_ = nix::sys::signal::kill(
nix::unistd::Pid::from_raw(pid as i32),
nix::sys::signal::Signal::SIGKILL,
);
}
});
let (sent, wait) = leaf.kill(None).split();
sent.into_result().expect("the leaf's kill");
wait.wait().expect("the leaf drained");
assert!(!blocked.get(), "the wait blocked on a member that left the leaf");
let mut member = member.borrow_mut();
assert_eq!(
member.0.try_wait().expect("look at the member"),
None,
"the member outside the leaf was not killed"
);
member.0.kill().expect("end the member");
_ = member.0.wait();
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_member_still_in_the_leaf_is_reached_by_the_kill_and_one_that_left_is_not(#[fixture(cgroup)] _group: &Group) {
use crate::identity::HostKernel;
let leaf = lane_leaf();
let (mut inside, inside_id) = cat_member();
let (mut outside, outside_id) = cat_member();
let (mut gone, gone_id) = cat_member();
place(&inside, &leaf.leaf_path);
place(&outside, leaf.leaf_path.parent().expect("the leaf has a parent cgroup"));
gone.0.kill().expect("end the member");
gone.0.wait().expect("reap the member");
leaf.kill.record(Ok(()));
let (reached, unobserved) = leaf.reached_by_kill(
&HostKernel,
[inside_id, outside_id, gone_id].map(listed_before).to_vec(),
);
assert_eq!(reached, [inside_id, gone_id]);
assert!(unobserved.is_empty(), "every member could be placed: {unobserved:?}");
for (member, who) in [
(&mut inside, "the member in the leaf"),
(&mut outside, "the member outside"),
] {
assert_eq!(
member.0.try_wait().expect("look at the member"),
None,
"{who} was not signalled by the check"
);
member.0.kill().expect("end the member");
_ = member.0.wait();
}
}
#[cfg(target_os = "linux")]
fn listed_before(id: crate::identity::ProcessId) -> super::Listed {
super::Listed { id, seen: None }
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_member_of_another_uid_still_in_the_leaf_is_reached_by_the_kill(#[fixture(cgroup)] _group: &Group) {
use crate::identity::HostKernel;
let leaf = lane_leaf();
let (mut other, other_id) = cat_member_as(Some(65534));
place(&other, &leaf.leaf_path);
let (listed, unobserved) = leaf.list_members(None);
assert_eq!(
listed.iter().map(|m| m.id).collect::<Vec<_>>(),
[other_id],
"the member is listed"
);
leaf.kill.record(Ok(()));
let (reached, unplaced) = leaf.reached_by_kill(&HostKernel, listed);
assert_eq!(reached, [other_id]);
assert!(
unobserved.is_empty() && unplaced.is_empty(),
"{unobserved:?} {unplaced:?}"
);
assert_eq!(
other.0.try_wait().expect("look at the member"),
None,
"the check signalled nothing"
);
other.0.kill().expect("end the member");
_ = other.0.wait();
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_member_whose_place_cannot_be_checked_after_the_kill_is_an_unobserved_error(#[fixture(cgroup)] _group: &Group) {
use crate::identity::{FakeKernel, HostKernel};
let leaf = lane_leaf();
let (mut unplaced, unplaced_id) = cat_member();
place(&unplaced, &leaf.leaf_path);
let kernel = FakeKernel::over(&HostKernel).on_pidfd_open(unplaced_id.pid(), Err(rustix::io::Errno::MFILE));
leaf.kill.record(Ok(()));
let (reached, unobserved) = leaf.reached_by_kill(&kernel, vec![listed_before(unplaced_id)]);
assert!(
reached.is_empty(),
"a member that cannot be placed is not claimed reached"
);
assert_eq!(unobserved.len(), 1, "it is reported: {unobserved:?}");
let report = crate::error::said(&unobserved[0]);
assert!(
report.contains(&unplaced_id.pid().to_string()) && report.contains("exit cannot be observed"),
"the error names the member and what is left undone: {report}"
);
unplaced.0.kill().expect("end the member");
_ = unplaced.0.wait();
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn the_wait_over_a_leafs_listed_members_blocks_on_a_running_member(#[fixture(cgroup)] _group: &Group) {
use std::cell::Cell;
use std::rc::Rc;
use crate::containment::dispatch::TreeKillOutcome;
use crate::containment::drain_edge::DrainEdge;
use crate::containment::TreeKill;
let leaf = lane_leaf();
let (mut member, id) = cat_member();
place(&member, &leaf.leaf_path);
let pid = member.0.id();
let (members, unobserved) = leaf.list_members(None);
assert_eq!(
members.iter().map(|m| m.id).collect::<Vec<_>>(),
[id],
"the member is listed"
);
let members = members.into_iter().map(|m| m.id).collect();
let blocked = Rc::new(Cell::new(false));
let _blocking = crate::wait::block_probe::on_blocking({
let blocked = blocked.clone();
move || {
blocked.set(true);
nix::sys::signal::kill(
nix::unistd::Pid::from_raw(pid as i32),
nix::sys::signal::Signal::SIGKILL,
)
.expect("end the member");
}
});
let (_, wait) = TreeKill::listed(
TreeKillOutcome::Ran(Ok(())),
members,
unobserved,
DrainEdge::Cgroup(&leaf),
)
.split();
wait.wait().expect("the member exited and the leaf drained");
assert!(blocked.get(), "the wait did not block on a member that was running");
_ = member.0.wait();
}
#[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(None).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, None) {
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:?}");
assert_eq!(first_source_code(&err), Some(libc::ENOENT), "{err:?}");
}
#[cfg(target_os = "linux")]
fn first_source_code(err: &LeafError) -> Option<i32> {
std::error::Error::source(err)
.and_then(|source| source.downcast_ref::<std::io::Error>())
.and_then(std::io::Error::raw_os_error)
}
#[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(), None) {
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(), None) {
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, None) {
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:?}"
);
assert_eq!(
first_source_code(&err),
Some(libc::EACCES),
"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");
assert!(
matches!(&err, crate::error::Error::Containment { source: Some(_), .. }),
"a refused cgroup.kill write must surface as Error::Containment over the OS error, got {err:?}"
);
assert_eq!(
crate::error::first_os_code(&err),
Some(libc::EISDIR),
"the kernel's errno must reach the caller, got {err}"
);
let tree = crate::containment::Tree::contained(crate::containment::Mechanism::Cgroup(leaf));
assert!(
tree.kill(None).outcome().into_result().is_err(),
"a cgroup tree must propagate like every sibling mechanism; 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 lists no member")
.expect("an already-removed leaf has no member left to signal");
let tree = crate::containment::Tree::contained(crate::containment::Mechanism::Cgroup(leaf));
assert!(
matches!(
tree.terminate(0, None),
crate::containment::TerminateOutcome::Sent { result: Ok(()), .. }
),
"terminate and hard_kill must agree about an already-gone leaf"
);
assert!(tree.kill(None).outcome().into_result().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 tree = crate::containment::Tree::contained(crate::containment::Mechanism::Cgroup(entered_leaf_at(
leaf_path.clone(),
)));
let mark = crate::log_capture::mark();
tree.disarm().expect("disarm");
drop(tree);
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 tree = crate::containment::Tree::contained(crate::containment::Mechanism::Cgroup(entered_leaf_at(
leaf_path.clone(),
)));
tree.disarm().expect("disarm");
drop(tree);
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(#[fixture(cgroup)] _group: &Group) {
use std::io::Read as _;
crate::log_capture::install();
let mut cmd = std::process::Command::new("sh");
cmd.args(["-c", "trap '' TERM; echo r; exec cat"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped());
let (leaf, mut member, stdin) = entered_real_leaf_of(cmd);
let pid = member.id();
let leaf_path = leaf.path().to_owned();
let leaf_name = leaf_path
.file_name()
.expect("a leaf name")
.to_string_lossy()
.into_owned();
let mut ready = [0u8; 2];
member
.stdout
.as_mut()
.expect("piped stdout")
.read_exact(&mut ready)
.expect("the member reports that it ignores SIGTERM");
leaf.disarm();
crate::containment::cgroup::fault::take_member_terms();
leaf.terminate()
.expect("cgroup.procs is readable")
.expect("terminate the leaf");
assert_eq!(
crate::containment::cgroup::fault::take_member_terms(),
[(Some(pid), crate::send_log::Via::Pidfd, libc::SIGTERM)],
"the SIGTERM the member survives was sent"
);
let mark = crate::log_capture::mark();
drop(leaf);
let levels = crate::log_capture::levels_since(mark, &leaf_name);
let records = crate::log_capture::records_since(mark, &leaf_name);
drop(stdin);
member.wait().expect("reap the member");
std::fs::remove_dir(&leaf_path).expect("remove the emptied leaf");
assert_eq!(
levels,
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:?}"
);
assert_eq!(
fake.kill_written(),
crate::containment::cgroup::KILL_PAYLOAD,
"the drop must write cgroup.kill, not only record the step, 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");
fake.clear_kill();
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!(fake.kill_written(), b"", "the landed kill is not written again");
assert_eq!(
steps,
vec!["rmdir populated 1", "rmdir populated 0"],
"a disarmed leaf's landed kill is not written again, and the rmdir retries only once it drains, got {steps:?}"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn death_watch_an_armed_drop_after_a_failed_kill_does_not_write_it_again() {
use crate::containment::cgroup::fault;
use crate::containment::cgroup::test_support::FakeLeaf;
crate::log_capture::install();
let name = "cosca-armed-drop-earlier-kill-failed";
let fake = FakeLeaf::new(name, true);
let (leaf_dir, events) = (fake.leaf.clone(), fake.events.clone());
fault::set_rmdir_hook(move |_| FakeLeaf::rmdir(&leaf_dir, &events));
let leaf = entered_leaf_at(fake.leaf.clone());
{
let _first_write_fails = fault::fail_next_kill_write();
leaf.hard_kill().expect_err("the forced failure");
}
let mark = crate::log_capture::mark();
fault::record_leaf_steps();
drop(leaf);
let steps = fault::take_leaf_steps();
fault::take_rmdir_hook();
assert_eq!(steps, ["rmdir populated 1"], "no second write, and no wait for a drain");
assert_eq!(fake.kill_written(), b"", "nothing wrote cgroup.kill");
assert!(fake.leaf.exists(), "the leaf is left behind");
let warns = crate::log_capture::records_since(mark, "cgroup.kill failed");
assert_eq!(warns.len(), 1, "the failed kill is warned once: {warns:?}");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_armed_drop_after_a_landed_kill_waits_for_its_drain_and_does_not_write_it_again() {
use crate::containment::cgroup::fault;
use crate::containment::cgroup::test_support::FakeLeaf;
let fake = FakeLeaf::new("cosca-armed-drop-landed-kill", true);
let (leaf_dir, events) = (fake.leaf.clone(), fake.events.clone());
fault::set_rmdir_hook(move |_| FakeLeaf::rmdir(&leaf_dir, &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.hard_kill().expect("kill the tree");
fake.clear_kill();
fault::record_leaf_steps();
drop(leaf);
let steps = fault::take_leaf_steps();
drop(actor);
fault::take_rmdir_hook();
assert_eq!(fake.kill_written(), b"", "the landed kill is not written again");
assert_eq!(
steps,
["rmdir populated 1", "rmdir populated 0"],
"the drop waits for the drain of the kill that landed, then removes the leaf"
);
assert!(!fake.leaf.exists());
}
#[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();
let killed = leaf.hard_kill();
if killed.is_ok() {
FakeLeaf::set_populated(&fake.events, false);
}
killed.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,
) {
entered_real_leaf_of(crate::test_child::held_std_blocker(std::process::Stdio::null()))
}
#[cfg(target_os = "linux")]
fn entered_real_leaf_of(
mut cmd: std::process::Command,
) -> (
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(None).expect("create a real leaf");
let (procs_fd, slot) = (leaf.procs_fd(), leaf.placement_slot());
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(None);
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::containment::drain_edge::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::containment::drain_edge::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::containment::drain_edge::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::containment::drain_edge::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(std::time::Instant::now())).expect("wait"),
TreeDrain::MembersRemain
);
FakeLeaf::set_populated(&fake.events, false);
assert_eq!(
leaf.wait_drained(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(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(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::containment::drain_edge::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");
let said = crate::error::said(&e);
assert!(said.contains("can no longer be watched"), "{said}");
assert_eq!(crate::error::first_os_code(&e), Some(libc::EIO), "{e:?}");
assert!(!said.contains("forced"), "{said}");
}
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.words.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(), None) {
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(), None) {
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:?}"
);
assert_eq!(first_source_code(&err), Some(libc::EMFILE), "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_TESTCFG_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(&[gate, procs_fd, slot.fd, slot.parent_fd], 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(None).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 a_gone_leafs_kill_is_the_teardowns_one_write() {
use crate::containment::cgroup::fault;
crate::log_capture::install();
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-gone-leaf-kill");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path.clone());
std::fs::remove_dir(&leaf_path).expect("remove the leaf behind the handle's back");
leaf.hard_kill().expect("a gone leaf is a completed teardown");
let _next_write_fails = fault::fail_next_kill_write();
let mark = crate::log_capture::mark();
leaf.drain_and_remove("in a test", &mut crate::containment::cgroup::NoWarn, false);
let warns = crate::log_capture::records_since_on_current_thread(mark, "cgroup.kill failed");
assert!(warns.is_empty(), "the removal wrote again: {warns:?}");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_leaf_kill_is_worded_the_same_by_the_writer_and_by_a_later_teardown() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-kill-wording");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
let _write_fails = crate::containment::cgroup::fault::fail_next_kill_write();
let written = leaf.kill_unless_written();
let found = leaf.kill_unless_written();
assert_eq!(written, Err(std::io::Error::from_raw_os_error(libc::EIO).to_string()));
assert_eq!(found, written);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_spawns_failed_leaf_kill_is_warned_when_the_removal_succeeds() {
crate::log_capture::install();
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-abandoned-kill-failed-removed");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path.clone());
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);
unsafe { crate::containment::cgroup::place_self_in_cgroup_pre_exec(procs_fd, leaf.placement_slot()) }
.expect("report a placement");
let _first_write_fails = crate::containment::cgroup::fault::fail_next_kill_write();
let mark = crate::log_capture::mark();
assert_eq!(
leaf.abandon_without_child(&mut crate::containment::cgroup::NoWarn),
WithoutChild::Named
);
assert!(!leaf_path.exists(), "the leaf is removed");
let warns = crate::log_capture::records_since_on_current_thread(mark, "cgroup.kill failed");
assert_eq!(warns.len(), 1, "the failed kill is warned once: {warns:?}");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_abandoned_intent_given_no_pidfd_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)
.expect("send a forged intent");
}
assert_eq!(
leaf.abandon_without_child(&mut crate::containment::cgroup::NoWarn),
WithoutChild::Named,
"the intent named a pid"
);
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_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_without_child(&mut crate::containment::cgroup::NoWarn),
WithoutChild::Unnamed,
"nothing named a pid"
);
assert!(!leaf_path.exists(), "the empty leaf is removed");
}
#[cfg(all(target_os = "linux", debug_assertions))]
#[skuld::test]
#[should_panic(expected = "the leaf answers for a child once")]
fn an_abandonment_without_a_child_repeated_is_a_breach() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-abandoned-twice");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
assert_eq!(
leaf.abandon_without_child(&mut crate::containment::cgroup::NoWarn),
WithoutChild::Unnamed
);
assert_eq!(
leaf.abandon_without_child(&mut crate::containment::cgroup::NoWarn),
WithoutChild::AlreadyAbandoned
);
}
#[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(None).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", 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}");
}
#[cfg(target_os = "linux")]
#[derive(Debug, Clone, Copy)]
enum Unsignalled {
Unpinned,
Unplaced,
SendFailed,
}
#[cfg(target_os = "linux")]
fn terminate_reports_a_member_it_could_not_signal(how: Unsignalled) {
use std::os::unix::process::ExitStatusExt as _;
use crate::containment::cgroup::fault::{fail_terminate, take_member_terms, TerminateStep};
crate::log_capture::install();
let (leaf, mut member, stdin) = entered_real_leaf();
let pid = member.id();
let leaf_name = leaf
.path()
.file_name()
.expect("a leaf name")
.to_string_lossy()
.into_owned();
take_member_terms();
let mark = crate::log_capture::mark();
let guard: Box<dyn std::any::Any> = match how {
Unsignalled::Unpinned => Box::new(fail_terminate(TerminateStep::Pin, libc::EMFILE)),
Unsignalled::Unplaced => Box::new((
crate::containment::cgroup::fault::miss_pidfd_info(),
crate::containment::cgroup::fault::hide_proc(),
)),
Unsignalled::SendFailed => Box::new(fail_terminate(TerminateStep::Send, libc::EIO)),
};
let result = leaf.terminate().expect("cgroup.procs is readable");
drop(guard);
assert_eq!(take_member_terms(), []);
let warns = crate::log_capture::warns_since(mark, &leaf_name);
drop(stdin);
let status = member.wait().expect("reap the member");
drop(leaf);
assert_eq!(status.signal(), None, "the member got no SIGTERM: {status:?}");
let err = result.expect_err("a member got no SIGTERM");
let detail = err.to_string();
assert!(detail.contains(&leaf_name), "{detail}");
let reported = crate::error::said(&err);
assert!(reported.contains(&format!("pid {pid}")), "{reported}");
match how {
Unsignalled::SendFailed => assert!(matches!(err, crate::error::Error::Containment { .. }), "{err:?}"),
_ => assert!(matches!(err, crate::error::Error::Unassessable { .. }), "{err:?}"),
}
let code = match how {
Unsignalled::Unpinned => Some(libc::EMFILE),
Unsignalled::SendFailed => Some(libc::EIO),
Unsignalled::Unplaced => None,
};
match code {
Some(code) => {
assert_eq!(crate::error::first_os_code(&err), Some(code), "{err:?}");
let os_error = std::io::Error::from_raw_os_error(code).to_string();
assert!(!detail.contains(&os_error), "{detail}");
}
None => assert!(crate::error::first_os_code(&err).is_some(), "{err:?}"),
}
assert_eq!(warns.len(), 1, "{warns:?}");
assert!(warns[0].contains(&format!("pid {pid}")), "{warns:?}");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_reports_a_member_it_could_not_pin(#[fixture(cgroup)] _group: &Group) {
terminate_reports_a_member_it_could_not_signal(Unsignalled::Unpinned);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_reports_a_member_it_could_not_place(#[fixture(cgroup)] _group: &Group) {
terminate_reports_a_member_it_could_not_signal(Unsignalled::Unplaced);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_reports_a_member_whose_sigterm_failed(#[fixture(cgroup)] _group: &Group) {
terminate_reports_a_member_it_could_not_signal(Unsignalled::SendFailed);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_leaves_alone_a_member_that_left_after_the_listing(#[fixture(cgroup)] _group: &Group) {
use std::os::unix::process::ExitStatusExt as _;
let (leaf, mut member, stdin) = entered_real_leaf();
let pid = member.id();
let _armed = crate::containment::cgroup::fault::set_after_procs_read(move || {
crate::child::front_cgroup_tests::move_out_of_its_leaf(pid);
});
crate::containment::cgroup::fault::take_member_terms();
leaf.terminate().expect("cgroup.procs is readable").expect("terminate");
assert_eq!(crate::containment::cgroup::fault::take_member_terms(), []);
drop(stdin);
let status = member.wait().expect("reap the member");
assert_eq!(status.signal(), None, "the member exited on its own EOF: {status:?}");
drop(leaf);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_sends_a_member_its_sigterm(#[fixture(cgroup)] _group: &Group) {
use std::os::unix::process::ExitStatusExt as _;
let (leaf, mut member, stdin) = entered_real_leaf();
let pid = member.id();
crate::containment::cgroup::fault::take_member_terms();
let result = leaf.terminate().expect("cgroup.procs is readable");
let noted = crate::containment::cgroup::fault::take_member_terms();
drop(stdin);
let status = member.wait().expect("reap the member");
drop(leaf);
assert_eq!(status.signal(), Some(libc::SIGTERM), "got {status:?}");
assert_eq!(noted, [(Some(pid), crate::send_log::Via::Pidfd, libc::SIGTERM)]);
result.expect("terminate");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_counts_a_member_reaped_after_its_pin_as_gone(#[fixture(cgroup)] _group: &Group) {
crate::log_capture::install();
let (leaf, member, _stdin) = entered_real_leaf();
let pid = member.id();
let leaf_name = leaf
.path()
.file_name()
.expect("a leaf name")
.to_string_lossy()
.into_owned();
let _armed = crate::containment::cgroup::fault::set_after_terminate_pin(move || {
assert_eq!(
unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) },
0,
"kill the member"
);
crate::test_child::reaped_elsewhere::reap_behind(pid);
});
crate::containment::cgroup::fault::take_member_terms();
let mark = crate::log_capture::mark();
let result = leaf.terminate().expect("cgroup.procs is readable");
let warns = crate::log_capture::warns_since(mark, &leaf_name);
let gone = crate::log_capture::records_since_on_current_thread(mark, "exited before it was placed");
assert_eq!(crate::containment::cgroup::fault::take_member_terms(), []);
result.expect("a member reaped after its pin is gone");
assert_eq!(warns, Vec::<String>::new(), "nothing warns of a member that is gone");
let [(level, text)] = gone.as_slice() else {
panic!("the member's debug record is the one that says it exited before it was placed: {gone:?}");
};
assert_eq!(*level, log::Level::Debug, "{text}");
assert!(
text.contains("os error"),
"the record carries the placement error it was told by: {text}"
);
drop(leaf);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_signals_a_member_when_the_leafs_id_cannot_be_read(#[fixture(cgroup)] _group: &Group) {
use std::os::unix::process::ExitStatusExt as _;
crate::log_capture::install();
let (leaf, mut member, stdin) = entered_real_leaf();
let pid = member.id();
let leaf_name = leaf_name_of(&leaf);
let _no_id = crate::containment::cgroup::fault::fail_cgroup_id(libc::EPERM);
crate::containment::cgroup::fault::take_member_terms();
let mark = crate::log_capture::mark();
let result = leaf.terminate().expect("cgroup.procs is readable");
let noted = crate::containment::cgroup::fault::take_member_terms();
let records = crate::log_capture::records_since_on_current_thread(mark, &leaf_name);
drop(stdin);
let status = member.wait().expect("reap the member");
drop(_no_id);
drop(leaf);
assert_eq!(status.signal(), Some(libc::SIGTERM), "got {status:?}");
assert_eq!(noted, [(Some(pid), crate::send_log::Via::Pidfd, libc::SIGTERM)]);
result.expect("terminate");
let [(level, text)] = records.as_slice() else {
panic!("the fallback is the one record naming the leaf: {records:?}");
};
assert_eq!(*level, log::Level::Debug, "{text}");
assert!(text.contains("/proc"), "{text}");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_warns_once_when_the_id_cannot_be_read_and_a_member_is_unsignalled(
#[fixture(cgroup)] _group: &Group,
) {
crate::log_capture::install();
let leaf = crate::containment::cgroup::try_create_leaf(None).expect("create a real leaf");
let leaf_name = leaf_name_of(&leaf);
let _no_id = crate::containment::cgroup::fault::fail_cgroup_id(libc::EPERM);
let mark = crate::log_capture::mark();
let result = leaf.terminate_listed("0\n");
let warns = crate::log_capture::warns_since(mark, &leaf_name);
drop(_no_id);
drop(leaf);
assert!(
matches!(result, Err(crate::error::Error::Unassessable { .. })),
"got {result:?}"
);
assert_eq!(warns.len(), 1, "{warns:?}");
assert!(warns[0].contains("pid 0"), "{warns:?}");
}
#[cfg(target_os = "linux")]
fn leaf_name_of(leaf: &crate::containment::cgroup::CgroupLeaf) -> String {
leaf.path()
.file_name()
.expect("a leaf name")
.to_string_lossy()
.into_owned()
}
#[cfg(target_os = "linux")]
fn real_leaf_with_members(
n: usize,
) -> (
crate::containment::cgroup::CgroupLeaf,
Vec<(std::process::Child, std::process::ChildStdin)>,
) {
use std::os::unix::process::CommandExt;
let leaf = crate::containment::cgroup::try_create_leaf(None).expect("create a real leaf");
let members = (0..n)
.map(|_| {
let mut channel = crate::containment::cgroup::ReportChannel::new().expect("open a report channel");
let mut cmd = crate::test_child::held_std_blocker(std::process::Stdio::null());
let (procs_fd, slot) = (leaf.procs_fd(), channel.slot());
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");
assert_eq!(
channel.wait(pidfd_of(member.id()).as_fd()),
PlacementReport::Placed,
"the member entered the leaf"
);
(member, stdin)
})
.collect();
(leaf, members)
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_reports_a_listed_pid_zero_as_unassessable(#[fixture(cgroup)] _group: &Group) {
use std::os::unix::process::ExitStatusExt as _;
crate::log_capture::install();
let (leaf, mut member, stdin) = entered_real_leaf();
let pid = member.id();
let leaf_name = leaf
.path()
.file_name()
.expect("a leaf name")
.to_string_lossy()
.into_owned();
crate::containment::cgroup::fault::take_member_terms();
let mark = crate::log_capture::mark();
let result = leaf.terminate_listed(&format!(
"0
{pid}
"
));
let warns = crate::log_capture::warns_since(mark, &leaf_name);
drop(stdin);
let status = member.wait().expect("reap the member");
drop(leaf);
assert_eq!(
status.signal(),
Some(libc::SIGTERM),
"the member after the 0 is signalled: {status:?}"
);
match result {
Err(error @ crate::error::Error::Unassessable { .. }) => {
let said = crate::error::said(&error);
assert!(said.contains("pid 0: "), "{said}");
assert!(said.contains("pid namespace"), "{said}");
assert!(
!said.contains(&format!("pid {pid}:")),
"the signalled member is not reported: {said}"
);
}
other => panic!("a listed pid 0 was not signalled: expected Unassessable, got {other:?}"),
}
assert_eq!(warns.len(), 1, "{warns:?}");
assert!(warns[0].contains("pid 0"), "{warns:?}");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_reports_a_leaf_listing_only_pid_zero(#[fixture(cgroup)] _group: &Group) {
let leaf = crate::containment::cgroup::try_create_leaf(None).expect("create a real leaf");
let result = leaf.terminate_listed("0\n");
drop(leaf);
assert!(
matches!(result, Err(crate::error::Error::Unassessable { .. })),
"got {result:?}"
);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn terminate_of_several_members_it_could_not_signal_keeps_every_cause_below_the_error() {
use crate::containment::cgroup::fault::{fail_terminate, TerminateStep};
use crate::error::Error;
let _pin = fail_terminate(TerminateStep::Pin, libc::EMFILE);
let result = crate::containment::cgroup::CgroupLeaf::placeholder_for_test()
.terminate_listed("0\nnot-a-pid\n4000001\n4000002\n");
let err = result.expect_err("no member got a SIGTERM");
let Error::Unassessable {
detail,
source: Some(source),
} = &err
else {
panic!("{err:?}");
};
assert!(detail.contains("4 could not be shown to be members"), "{detail}");
assert!(
!detail.contains("pid 4000001") && !detail.contains("os error"),
"{detail}"
);
let Error::Several(members) = &**source else {
panic!("expected Several, got {source:?}");
};
let said: Vec<_> = members.iter().map(|m| m.to_string()).collect();
assert!(said[0].contains("pid 0"), "{said:?}");
assert!(said[1].contains("not-a-pid"), "{said:?}");
assert!(
said[2].contains("pid 4000001") && said[3].contains("pid 4000002"),
"{said:?}"
);
let codes: Vec<_> = members.iter().map(|m| crate::error::first_os_code(&**m)).collect();
assert_eq!(codes, [None, None, Some(libc::EMFILE), Some(libc::EMFILE)]);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_reports_a_member_whose_exit_could_not_be_read(#[fixture(cgroup)] _group: &Group) {
use std::os::unix::process::ExitStatusExt as _;
use crate::containment::cgroup::fault::{fail_terminate, take_member_terms, TerminateStep};
crate::log_capture::install();
let (leaf, mut member, stdin) = entered_real_leaf();
let pid = member.id();
let leaf_name = leaf_name_of(&leaf);
take_member_terms();
let mark = crate::log_capture::mark();
let guard = fail_terminate(TerminateStep::Exited, libc::EIO);
let result = leaf.terminate().expect("cgroup.procs is readable");
drop(guard);
let noted = take_member_terms();
let warns = crate::log_capture::warns_since(mark, &leaf_name);
drop(stdin);
let status = member.wait().expect("reap the member");
drop(leaf);
assert_eq!(status.signal(), None, "the member got no SIGTERM: {status:?}");
assert_eq!(noted, []);
let err = result.expect_err("a member got no SIGTERM");
let crate::error::Error::Unassessable { .. } = &err else {
panic!("expected Unassessable, got {err:?}");
};
let reported = crate::error::said(&err);
assert!(
reported.contains(&format!("pid {pid}: its exit could not be read")),
"{reported}"
);
assert!(!reported.contains("could not be placed"), "{reported}");
assert_eq!(crate::error::first_os_code(&err), Some(libc::EIO), "{err:?}");
assert_eq!(warns.len(), 1, "{warns:?}");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_reports_a_member_whose_place_and_exit_cannot_be_read(#[fixture(cgroup)] _group: &Group) {
use std::os::unix::process::ExitStatusExt as _;
use crate::containment::cgroup::fault::{fail_terminate, take_member_terms, TerminateStep};
let (leaf, mut member, stdin) = entered_real_leaf();
take_member_terms();
let guard = (
crate::containment::cgroup::fault::miss_pidfd_info(),
crate::containment::cgroup::fault::hide_proc(),
fail_terminate(TerminateStep::Exited, libc::EIO),
);
let result = leaf.terminate().expect("cgroup.procs is readable");
drop(guard);
let noted = take_member_terms();
drop(stdin);
let status = member.wait().expect("reap the member");
drop(leaf);
assert_eq!(status.signal(), None, "the member got no SIGTERM: {status:?}");
assert_eq!(noted, []);
let err = result.expect_err("a member got no SIGTERM");
let crate::error::Error::Unassessable { .. } = &err else {
panic!("expected Unassessable, got {err:?}");
};
let rendered = crate::error::said(&err);
assert!(rendered.contains("could not be placed"), "{rendered}");
assert!(
rendered.contains("its placement and its exit could not be read"),
"{rendered}"
);
assert!(
rendered.contains("its exit could not be read") && rendered.contains("(os error 5)"),
"the failed exit read is in the report too: {rendered}"
);
assert_eq!(crate::error::first_os_code(&err), Some(libc::ENOENT), "{err:?}");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_placement_whose_exit_read_fails_too_keeps_its_os_code_as_the_source() {
use crate::containment::cgroup::fault::{fail_pidfd_info, fail_terminate, TerminateStep};
use crate::containment::cgroup::test_support::kill_record;
let subtree = crate::containment::cgroup::Subtree::new(
Some(7),
None,
None,
crate::containment::cgroup::Swept::default(),
crate::containment::cgroup::PlacedAtRemoval::default(),
kill_record(true),
);
let pidfd = rustix::process::pidfd_open(rustix::process::getpid(), rustix::process::PidfdFlags::empty())
.expect("pidfd_open");
let _placement = fail_pidfd_info();
let _exit = fail_terminate(TerminateStep::Exited, libc::EBADF);
let result = super::placed_or_exited(pidfd.as_fd(), subtree.holds(std::process::id(), Some(pidfd.as_fd())));
let err = match result {
Err(err) => err,
Ok(_) => panic!("neither the place nor the exit could be read"),
};
assert_eq!(crate::error::first_os_code(&err), Some(libc::EIO), "{err:?}");
let own = err.to_string();
assert!(own.contains("its placement and its exit could not be read"), "{own}");
assert!(!own.contains("process containment failed"), "{own}");
assert!(
!own.contains("(os error"),
"both errors are below the error, not in its own text: {own}"
);
let crate::error::Error::Unassessable {
source: Some(source), ..
} = &err
else {
panic!("{err:?}");
};
let crate::error::Error::Several(both) = &**source else {
panic!("expected Several, got {source:?}");
};
let codes: Vec<_> = both.iter().map(|e| crate::error::first_os_code(&**e)).collect();
assert_eq!(codes, [Some(libc::EIO), Some(libc::EBADF)]);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_member_whose_placement_fails_is_named_with_the_os_text_once() {
use crate::containment::cgroup::fault::fail_pidfd_info;
use crate::containment::cgroup::test_support::kill_record;
let subtree = crate::containment::cgroup::Subtree::new(
Some(7),
None,
None,
crate::containment::cgroup::Swept::default(),
crate::containment::cgroup::PlacedAtRemoval::default(),
kill_record(true),
);
let _placement = fail_pidfd_info();
let mut child =
crate::test_spawn::spawn(std::process::Command::new("/bin/cat").stdin(std::process::Stdio::piped()))
.expect("spawn a member");
let result = crate::containment::cgroup::CgroupLeaf::placeholder_for_test().terminate_member(child.id(), &subtree);
drop(child.stdin.take());
let status = child.wait().expect("reap the member");
assert!(status.success(), "the member was signalled: {status:?}");
let Err(super::Unsignalled::Unproven(unsent)) = result else {
panic!("a placement that failed on a live member is unproven");
};
let crate::error::Error::Unassessable {
detail,
source: Some(cause),
} = &unsent
else {
panic!("a member that could not be placed is an Unassessable with its cause: {unsent:?}");
};
assert_eq!(detail.matches("(os error 5)").count(), 0, "{detail}");
assert!(detail.contains(&format!("pid {}", child.id())), "{detail}");
let message = crate::error::said(&**cause);
assert_eq!(message.matches("(os error 5)").count(), 1, "{message}");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_does_not_signal_a_member_that_exited_unreaped(#[fixture(cgroup)] _group: &Group) {
use crate::containment::cgroup::fault::take_member_terms;
crate::log_capture::install();
let (leaf, mut member, stdin) = entered_real_leaf();
let pid = member.id();
let leaf_name = leaf_name_of(&leaf);
assert_eq!(
unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) },
0,
"kill the member"
);
crate::test_child::wait_until_zombie(pid);
take_member_terms();
let mark = crate::log_capture::mark();
let result = leaf.terminate_listed(&format!("{pid}\n"));
let noted = take_member_terms();
let warns = crate::log_capture::warns_since(mark, &leaf_name);
drop(stdin);
member.wait().expect("reap the member");
drop(leaf);
result.expect("a member that exited is not a failure");
assert_eq!(noted, [], "a member that exited was signalled");
assert_eq!(warns, Vec::<String>::new());
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_counts_a_member_gone_before_its_pin_as_gone(#[fixture(cgroup)] _group: &Group) {
use crate::containment::cgroup::fault::take_member_terms;
crate::log_capture::install();
let (leaf, mut member, stdin) = entered_real_leaf();
let pid = member.id();
let leaf_name = leaf_name_of(&leaf);
drop(stdin);
member.wait().expect("reap the member");
take_member_terms();
let mark = crate::log_capture::mark();
let result = leaf.terminate_listed(&format!("{pid}\n"));
let noted = take_member_terms();
let gone = crate::log_capture::records_since_on_current_thread(mark, &format!("pid {pid} is gone"));
let warns = crate::log_capture::warns_since(mark, &leaf_name);
drop(leaf);
result.expect("a member gone before its pin is not a failure");
assert_eq!(noted, []);
assert_eq!(gone.len(), 1, "the pin answered ESRCH: {gone:?}");
assert_eq!(warns, Vec::<String>::new());
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_counts_a_member_gone_at_its_send_as_gone(#[fixture(cgroup)] _group: &Group) {
use std::os::unix::process::ExitStatusExt as _;
use crate::containment::cgroup::fault::{fail_terminate, take_member_terms, TerminateStep};
crate::log_capture::install();
let (leaf, mut member, stdin) = entered_real_leaf();
let pid = member.id();
let leaf_name = leaf_name_of(&leaf);
take_member_terms();
let mark = crate::log_capture::mark();
let guard = fail_terminate(TerminateStep::Send, libc::ESRCH);
let result = leaf.terminate().expect("cgroup.procs is readable");
drop(guard);
let noted = take_member_terms();
let exited =
crate::log_capture::records_since_on_current_thread(mark, &format!("pid {pid} exited before its SIGTERM"));
let warns = crate::log_capture::warns_since(mark, &leaf_name);
drop(stdin);
let status = member.wait().expect("reap the member");
drop(leaf);
assert_eq!(status.signal(), None, "the seam refused the send: {status:?}");
result.expect("a member gone at its send is not a failure");
assert_eq!(noted, []);
assert_eq!(exited.len(), 1, "{exited:?}");
assert_eq!(warns, Vec::<String>::new());
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_counts_a_member_reaped_after_its_pin_as_gone_through_proc(#[fixture(cgroup)] _group: &Group) {
crate::log_capture::install();
let (leaf, member, _stdin) = entered_real_leaf();
let pid = member.id();
let leaf_name = leaf_name_of(&leaf);
let _armed = crate::containment::cgroup::fault::set_after_terminate_pin(move || {
assert_eq!(
unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) },
0,
"kill the member"
);
crate::test_child::reaped_elsewhere::reap_behind(pid);
});
crate::containment::cgroup::fault::take_member_terms();
let _no_info = crate::containment::cgroup::fault::miss_pidfd_info();
let mark = crate::log_capture::mark();
let result = leaf.terminate().expect("cgroup.procs is readable");
let warns = crate::log_capture::warns_since(mark, &leaf_name);
let gone =
crate::log_capture::records_since_on_current_thread(mark, &format!("pid {pid} exited before it was placed"));
drop(_no_info);
assert_eq!(crate::containment::cgroup::fault::take_member_terms(), []);
result.expect("a member reaped after its pin is gone");
assert_eq!(warns, Vec::<String>::new());
assert_eq!(
gone.len(),
1,
"the place was read through /proc and found gone: {gone:?}"
);
drop(leaf);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_tries_every_member_after_one_fails(#[fixture(cgroup)] _group: &Group) {
use std::os::unix::process::ExitStatusExt as _;
use crate::containment::cgroup::fault::{fail_terminate_once, take_member_terms, TerminateStep};
let (leaf, mut members) = real_leaf_with_members(2);
let pids: Vec<u32> = members.iter().map(|(m, _)| m.id()).collect();
take_member_terms();
let guard = fail_terminate_once(TerminateStep::Pin, libc::EMFILE);
let result = leaf.terminate_listed(&format!("{}\n{}\n", pids[0], pids[1]));
drop(guard);
let noted = take_member_terms();
let statuses: Vec<_> = members
.drain(..)
.map(|(mut member, stdin)| {
drop(stdin);
member.wait().expect("reap the member")
})
.collect();
drop(leaf);
assert_eq!(statuses[0].signal(), None, "the unpinned member got no SIGTERM");
assert_eq!(
statuses[1].signal(),
Some(libc::SIGTERM),
"the member after the failed one is signalled: {:?}",
statuses[1]
);
assert_eq!(noted, [(Some(pids[1]), crate::send_log::Via::Pidfd, libc::SIGTERM)]);
let said = match result {
Err(error @ crate::error::Error::Unassessable { .. }) => crate::error::said(&error),
other => panic!("expected Unassessable, got {other:?}"),
};
assert!(said.contains(&format!("pid {}:", pids[0])), "{said}");
assert!(!said.contains(&format!("pid {}:", pids[1])), "{said}");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_reports_every_member_that_got_no_sigterm_in_one_error_and_warn(#[fixture(cgroup)] _group: &Group) {
use crate::containment::cgroup::fault::{fail_terminate, take_member_terms, TerminateStep};
crate::log_capture::install();
let (leaf, mut members) = real_leaf_with_members(2);
let pids: Vec<u32> = members.iter().map(|(m, _)| m.id()).collect();
let leaf_name = leaf_name_of(&leaf);
take_member_terms();
let mark = crate::log_capture::mark();
let guard = fail_terminate(TerminateStep::Send, libc::EIO);
let result = leaf.terminate_listed(&format!("0\n{}\n{}\n", pids[0], pids[1]));
drop(guard);
let noted = take_member_terms();
let warns = crate::log_capture::warns_since(mark, &leaf_name);
for (mut member, stdin) in members.drain(..) {
drop(stdin);
member.wait().expect("reap the member");
}
drop(leaf);
assert_eq!(noted, []);
let (detail, source) = match result {
Err(crate::error::Error::Containment { detail, source }) => (detail, source),
other => panic!("a failed send makes the call Containment, got {other:?}"),
};
assert!(
!detail.contains("pid 0:") && !detail.contains("os error"),
"no member's words are in the detail: {detail}"
);
assert!(detail.contains("failed for 2"), "{detail}");
let Some(source) = source else {
panic!("the members are the call's source");
};
let crate::error::Error::Several(members) = &*source else {
panic!("expected Several, got {source:?}");
};
let said: Vec<_> = members.iter().map(|m| m.to_string()).collect();
assert_eq!(said.len(), 3, "{said:?}");
for (member, pid) in said
.iter()
.zip([pids[0].to_string(), pids[1].to_string(), "0".to_owned()])
{
assert!(member.contains(&format!("pid {pid}:")), "{pid}: {said:?}");
}
let codes: Vec<_> = members.iter().map(|m| crate::error::first_os_code(&**m)).collect();
assert_eq!(codes, [Some(libc::EIO), Some(libc::EIO), None]);
assert_eq!(warns.len(), 1, "{warns:?}");
for needle in [format!("pid {}:", pids[0]), format!("pid {}:", pids[1])] {
assert!(warns[0].contains(&needle), "{needle} is not named: {warns:?}");
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_terminate_reports_a_listed_line_that_is_no_pid(#[fixture(cgroup)] _group: &Group) {
crate::log_capture::install();
let leaf = crate::containment::cgroup::try_create_leaf(None).expect("create a real leaf");
let leaf_name = leaf_name_of(&leaf);
let mark = crate::log_capture::mark();
let result = leaf.terminate_listed("abc\n");
let warns = crate::log_capture::warns_since(mark, &leaf_name);
drop(leaf);
let said = match result {
Err(error @ crate::error::Error::Unassessable { .. }) => crate::error::said(&error),
other => panic!("expected Unassessable, got {other:?}"),
};
assert!(said.contains("\"abc\""), "{said}");
assert_eq!(warns.len(), 1, "{warns:?}");
}