#[cfg(target_os = "linux")]
use std::os::fd::AsFd as _;
use crate::containment::cgroup::test_support::{entered_leaf_at, handle_of, pidfd_of};
use crate::containment::cgroup::{DrainStep, LeafError, NotEntered, NotPlaced, PlacementReport};
#[cfg(target_os = "linux")]
use crate::test_child::{blocker, blocker_with, StdChild};
#[cfg(target_os = "linux")]
use crate::test_groups::{cgroup, Group};
#[cfg(target_os = "linux")]
use crate::wait::block_probe::{on_drain_block, on_each_drain_block};
fn sent(outcome: crate::containment::SendOutcome) -> Result<(), crate::error::Error> {
match outcome {
crate::containment::SendOutcome::Sent(found) => found,
other => panic!("cgroup.procs is readable: {other:?}"),
}
}
#[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, WaitDeadlineArgGuard, WaitObserver};
use crate::containment::TreeDrain;
use std::os::unix::process::CommandExt;
use std::process::Stdio;
use std::sync::mpsc;
use std::time::{Duration, Instant};
let leaf =
crate::containment::cgroup::try_create_leaf(&crate::identity::spawn_kernel(crate::identity::HostKernel), 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| -> StdChild {
let procs_fd = leaf.procs_fd();
blocker_with(|cmd| {
cmd.stdout(Stdio::null()).stderr(Stdio::null());
unsafe {
cmd.pre_exec(move || crate::containment::cgroup::test_support::place_in_pre_exec(procs_fd));
}
})
};
let mut a = spawn_member(&leaf);
let mut b = spawn_member(&leaf);
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.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.kill().expect("kill member a");
a.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.kill().expect("kill member b");
b.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();
drop(leaf);
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} changed batches — a woken park with no matching changed batch behind \
it is not a real park"
);
}
#[cfg(target_os = "linux")]
fn lane_leaf() -> crate::containment::cgroup::CgroupLeaf {
crate::containment::cgroup::try_create_leaf(&crate::identity::spawn_kernel(crate::identity::HostKernel), 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() -> (StdChild, crate::identity::ProcessId) {
cat_member_as(None)
}
#[cfg(target_os = "linux")]
fn cat_member_as(uid: Option<u32>) -> (StdChild, crate::identity::ProcessId) {
use std::os::unix::process::CommandExt as _;
use std::process::Stdio;
let child = blocker_with(|cat| {
cat.stdout(Stdio::null()).stderr(Stdio::null());
if let Some(uid) = uid {
cat.uid(uid);
}
});
let id = crate::identity::ProcessId::of(child.id())
.found()
.expect("the member's identity");
(child, id)
}
#[cfg(target_os = "linux")]
fn place(member: &StdChild, dir: &std::path::Path) {
std::fs::write(dir.join("cgroup.procs"), member.id().to_string())
.unwrap_or_else(|e| panic!("move {} into {}: {e}", member.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")]
fn id_of(dir: &std::path::Path) -> u64 {
crate::containment::cgroup::cgroup_id(
rustix::fs::open(
dir,
rustix::fs::OFlags::PATH | rustix::fs::OFlags::DIRECTORY | rustix::fs::OFlags::CLOEXEC,
rustix::fs::Mode::empty(),
)
.expect("open the cgroup")
.as_fd(),
)
.expect("its id")
}
#[cfg(target_os = "linux")]
fn count_walks() -> (
std::rc::Rc<std::cell::Cell<usize>>,
crate::containment::cgroup::fault::BeforeWalkOpen,
) {
count_walks_and(|_| {})
}
#[cfg(target_os = "linux")]
fn count_walks_and(
mut then: impl FnMut(&std::path::Path) + 'static,
) -> (
std::rc::Rc<std::cell::Cell<usize>>,
crate::containment::cgroup::fault::BeforeWalkOpen,
) {
let walks = std::rc::Rc::new(std::cell::Cell::new(0));
let guard = crate::containment::cgroup::fault::set_before_walk_open({
let walks = walks.clone();
move |at| {
if at == std::path::Path::new(".") {
walks.set(walks.get() + 1);
}
then(at);
}
});
(walks, guard)
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn the_listing_walks_the_leafs_descendants_once_however_many_members_are_nested(#[fixture(cgroup)] _group: &Group) {
use crate::containment::cgroup::fault;
let leaf = lane_leaf();
let nested = leaf.leaf_path.join("nested");
std::fs::create_dir(&nested).expect("make a cgroup under the leaf");
std::fs::create_dir(nested.join("deeper")).expect("make a cgroup under that");
let nested_id = id_of(&nested);
let members: Vec<_> = (0..3)
.map(|_| {
let (member, id) = cat_member();
place(&member, &nested);
(member, id)
})
.collect();
let _read = fault::force_pidfd_cgroup_id(nested_id);
let (walks, _count) = count_walks();
let (listed, unobserved) = leaf.list_members(None);
assert!(unobserved.is_empty(), "{unobserved:?}");
let mut named: Vec<_> = listed.iter().map(|m| (m.id, m.seen)).collect();
let mut expected: Vec<_> = members.iter().map(|(_, id)| (*id, Some(nested_id))).collect();
named.sort_by_key(|(id, _)| id.pid());
expected.sort_by_key(|(id, _)| id.pid());
assert_eq!(
named, expected,
"every member is named, placed by the nested cgroup's id"
);
assert_eq!(walks.get(), 1, "one walk");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_member_that_moved_into_a_cgroup_under_the_leaf_is_placed_without_a_walk(#[fixture(cgroup)] _group: &Group) {
use crate::containment::cgroup::fault;
let leaf = lane_leaf();
let nested = leaf.leaf_path.join("nested");
std::fs::create_dir(&nested).expect("make a cgroup under the leaf");
let nested_id = id_of(&nested);
let (member, id) = cat_member();
place(&member, &leaf.leaf_path);
let _read = fault::force_pidfd_cgroup_id(nested_id);
let (walks, _count) = count_walks();
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, Some(nested_id))],
"placed by the nested cgroup's id"
);
assert_eq!(walks.get(), 1, "only the listing's own walk");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_member_of_a_cgroup_whose_id_cannot_be_read_is_placed_through_proc_after_one_walk(
#[fixture(cgroup)] _group: &Group,
) {
use crate::containment::cgroup::fault;
use crate::containment::cgroup::WalkStep;
let leaf = lane_leaf();
let nested = leaf.leaf_path.join("nested");
std::fs::create_dir(&nested).expect("make a cgroup under the leaf");
let nested_id = id_of(&nested);
let (member, id) = cat_member();
place(&member, &nested);
let _read = fault::force_pidfd_cgroup_id(nested_id);
let _walk = fault::fail_walk_step("./nested", WalkStep::Id, libc::EIO);
let (walks, _count) = count_walks();
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"
);
assert_eq!(walks.get(), 2, "the listing's walk and the member's own");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_member_of_a_readable_cgroup_is_placed_without_a_walk_beside_an_unreadable_one(#[fixture(cgroup)] _group: &Group) {
use crate::containment::cgroup::fault;
use crate::containment::cgroup::WalkStep;
let leaf = lane_leaf();
let readable = leaf.leaf_path.join("readable");
std::fs::create_dir(&readable).expect("make a cgroup under the leaf");
std::fs::create_dir(readable.join("unreadable")).expect("make a cgroup under that");
let readable_id = id_of(&readable);
let (member, id) = cat_member();
place(&member, &readable);
let _read = fault::force_pidfd_cgroup_id(readable_id);
let _walk = fault::fail_walk_step("./readable/unreadable", WalkStep::Id, libc::EIO);
let (walks, _count) = count_walks();
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, Some(readable_id))],
"placed by the readable cgroup's id"
);
assert_eq!(walks.get(), 1, "only the listing's own walk");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_member_two_cgroups_down_is_placed_without_a_walk(#[fixture(cgroup)] _group: &Group) {
use crate::containment::cgroup::fault;
let leaf = lane_leaf();
let deeper = leaf.leaf_path.join("nested").join("deeper");
std::fs::create_dir_all(&deeper).expect("make two cgroups under the leaf");
let deeper_id = id_of(&deeper);
let (member, id) = cat_member();
place(&member, &deeper);
let _read = fault::force_pidfd_cgroup_id(deeper_id);
let (walks, _count) = count_walks();
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, Some(deeper_id))],
"placed by the id of the cgroup it is in"
);
assert_eq!(walks.get(), 1, "only the listing's own walk");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_member_in_a_cgroup_made_after_the_listing_is_placed_by_one_walk(#[fixture(cgroup)] _group: &Group) {
use std::cell::RefCell;
use std::rc::Rc;
use crate::containment::cgroup::fault::{self, ForcedPidfdCgroupId};
let leaf = lane_leaf();
std::fs::create_dir(leaf.leaf_path.join("first")).expect("make a cgroup under the leaf");
let (member, id) = cat_member();
place(&member, &leaf.leaf_path);
let late = leaf.leaf_path.join("late");
let made: Rc<RefCell<Option<(ForcedPidfdCgroupId, u64)>>> = Rc::new(RefCell::new(None));
let (walks, _count) = count_walks_and({
let made = made.clone();
move |at| {
if at == std::path::Path::new("./first") && made.borrow().is_none() {
std::fs::create_dir(&late).expect("make a cgroup under the leaf mid-listing");
let late_id = id_of(&late);
*made.borrow_mut() = Some((fault::force_pidfd_cgroup_id(late_id), late_id));
}
}
});
let (listed, unobserved) = leaf.list_members(None);
let late_id = made.borrow().as_ref().expect("the cgroup was made mid-listing").1;
assert!(unobserved.is_empty(), "{unobserved:?}");
assert_eq!(
listed.iter().map(|m| (m.id, m.seen)).collect::<Vec<_>>(),
[(id, Some(late_id))],
"found under the leaf by the walk"
);
assert_eq!(walks.get(), 2, "the listing's walk and the member's own, one");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_member_in_a_cgroup_outside_the_leaf_is_not_listed_after_one_walk(#[fixture(cgroup)] _group: &Group) {
use crate::containment::cgroup::fault;
let leaf = lane_leaf();
std::fs::create_dir(leaf.leaf_path.join("first")).expect("make a cgroup under the leaf");
let (member, _id) = cat_member();
place(&member, &leaf.leaf_path);
let outside = id_of(leaf.leaf_path.parent().expect("a leaf has a parent cgroup"));
let _read = fault::force_pidfd_cgroup_id(outside);
let (walks, _count) = count_walks();
let (listed, unobserved) = leaf.list_members(None);
assert!(unobserved.is_empty(), "{unobserved:?}");
assert!(listed.is_empty(), "outside the leaf: {listed:?}");
assert_eq!(walks.get(), 2, "the listing's walk and the member's own, one");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_member_moved_into_a_cgroup_under_the_leaf_before_it_is_pinned_is_listed(#[fixture(cgroup)] _group: &Group) {
let leaf = lane_leaf();
let nested = leaf.leaf_path.join("nested");
std::fs::create_dir_all(nested.join("deeper")).expect("make two cgroups under the leaf");
let (member, id) = cat_member();
place(&member, &leaf.leaf_path);
let (walks, _count) = count_walks_and({
let pid = member.id().to_string();
move |at| {
if at == std::path::Path::new("./nested/deeper") {
std::fs::write(nested.join("cgroup.procs"), &pid).expect("move the member into nested");
}
}
});
let (listed, unobserved) = leaf.list_members(None);
assert!(unobserved.is_empty(), "{unobserved:?}");
assert_eq!(listed.iter().map(|m| m.id).collect::<Vec<_>>(), [id]);
assert_eq!(walks.get(), 1, "only the listing's own walk");
}
#[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.kill().expect("end the member");
member.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.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.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.try_wait().expect("look at the member"),
None,
"the member outside the leaf was not killed"
);
member.kill().expect("end the member");
_ = member.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) {
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.kill().expect("end the member");
gone.wait().expect("reap the member");
leaf.kill.record(Ok(()));
let (reached, unobserved) = leaf.reached_by_kill([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.try_wait().expect("look at the member"),
None,
"{who} was not signalled by the check"
);
member.kill().expect("end the member");
_ = member.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) {
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(listed);
assert_eq!(reached, [other_id]);
assert!(
unobserved.is_empty() && unplaced.is_empty(),
"{unobserved:?} {unplaced:?}"
);
assert_eq!(
other.try_wait().expect("look at the member"),
None,
"the check signalled nothing"
);
other.kill().expect("end the member");
_ = other.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::{spawn_kernel, 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));
let leaf = leaf.asking_for_test(spawn_kernel(kernel));
leaf.kill.record(Ok(()));
let (reached, unobserved) = leaf.reached_by_kill(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].why());
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}"
);
assert_eq!(
unobserved[0].pid,
Some(unplaced_id.pid()),
"the member's pid is carried with the error: {unobserved:?}"
);
unplaced.kill().expect("end the member");
_ = unplaced.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.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.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(&crate::identity::spawn_kernel(crate::identity::HostKernel), 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")]
fn own_cgroup_dir() -> tempfile::TempDir {
let dir = tempfile::tempdir().expect("tempdir");
std::fs::write(dir.path().join("cgroup.procs"), "").expect("create cgroup.procs");
dir
}
#[cfg(target_os = "linux")]
fn strays_in(own: &std::path::Path) -> Vec<std::ffi::OsString> {
std::fs::read_dir(own)
.expect("read the own cgroup")
.map(|e| e.expect("entry").file_name())
.filter(|name| name != "cgroup.procs")
.collect()
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn create_leaf_under_reports_an_own_cgroup_it_cannot_open() {
let dir = tempfile::tempdir().expect("tempdir");
let parent = dir.path().join("no-such-slice");
let err = match crate::containment::cgroup::create_leaf_under(
&parent,
&crate::identity::spawn_kernel(crate::identity::HostKernel),
None,
) {
Err(e) => e,
Ok(_) => panic!("creating a leaf under a nonexistent directory must fail"),
};
assert!(
matches!(err, LeafError::OpenOwnCgroup { .. }),
"expected OpenOwnCgroup, 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")]
#[skuld::test]
fn create_leaf_under_reports_an_own_cgroup_procs_it_cannot_open() {
let dir = tempfile::tempdir().expect("tempdir");
let err = match crate::containment::cgroup::create_leaf_under(
dir.path(),
&crate::identity::spawn_kernel(crate::identity::HostKernel),
None,
) {
Err(e) => e,
Ok(_) => panic!("an own cgroup with no cgroup.procs must fail"),
};
assert!(matches!(err, LeafError::OpenOwnCgroup { .. }), "got {err:?}");
assert!(err.to_string().contains("cgroup.procs"), "got {err}");
assert_eq!(first_source_code(&err), Some(libc::ENOENT), "{err:?}");
assert!(
strays_in(dir.path()).is_empty(),
"nothing is made before the own cgroup opens"
);
}
#[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 = own_cgroup_dir();
let err = match crate::containment::cgroup::create_leaf_under(
dir.path(),
&crate::identity::spawn_kernel(crate::identity::HostKernel),
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 = strays_in(dir.path());
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 = own_cgroup_dir();
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(),
&crate::identity::spawn_kernel(crate::identity::HostKernel),
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 = own_cgroup_dir();
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,
&crate::identity::spawn_kernel(crate::identity::HostKernel),
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 = strays_in(&parent);
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",
));
sent(leaf.terminate(crate::signal::Signal::Term)).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, None, crate::containment::TreeStop::default()),
(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,
PlacementReport::Unknown(libc::EIO),
];
for (report, verdict_taken) in reports.into_iter().flat_map(|report| [(report, false), (report, true)]) {
let kills = matches!(report, PlacementReport::Placed | PlacementReport::Unknown(_));
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());
leaf.record_placement(report);
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 sh = std::process::Command::new("sh");
sh.args(["-c", "trap '' TERM; echo r; exec cat"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped());
let (leaf, mut member) = entered_real_leaf_of(Some(sh));
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();
sent(leaf.terminate(crate::signal::Signal::Term)).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);
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());
leaf.record_placement(PlacementReport::WriteFailed(libc::EBADF));
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")]
#[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 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 waited = std::rc::Rc::new(std::cell::Cell::new(false));
let events = fake.events.clone();
let _release = crate::wait::block_probe::on_drain_block({
let waited = std::rc::Rc::clone(&waited);
move || {
waited.set(true);
FakeLeaf::set_populated(&events, false);
}
});
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!(
!waited.get(),
"the drop waited for a drain, so it wrote cgroup.kill again"
);
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_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_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, StdChild) {
entered_real_leaf_of(None)
}
#[cfg(target_os = "linux")]
fn entered_real_leaf_of(command: Option<std::process::Command>) -> (crate::containment::cgroup::CgroupLeaf, StdChild) {
use std::os::unix::process::CommandExt;
let mut leaf =
crate::containment::cgroup::try_create_leaf(&crate::identity::spawn_kernel(crate::identity::HostKernel), None)
.expect("create a real leaf");
let procs_fd = leaf.procs_fd();
let place = move |cmd: &mut std::process::Command| {
unsafe {
cmd.pre_exec(move || crate::containment::cgroup::test_support::place_in_pre_exec(procs_fd));
}
};
let member = match command {
None => blocker_with(place),
Some(mut cmd) => {
place(&mut cmd);
StdChild::spawn(&mut cmd)
}
};
leaf.record_placement(PlacementReport::Placed);
leaf.take_placement(handle_of(member.id(), &pidfd_of(member.id())))
.expect("the member entered the leaf");
(leaf, member)
}
#[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) = entered_real_leaf();
let stdin = member.stdin.take().expect("piped stdin");
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, mut member) = entered_real_leaf();
let stdin = member.stdin.take().expect("piped stdin");
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) = entered_real_leaf();
let stdin = member.stdin.take().expect("piped stdin");
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(&crate::identity::spawn_kernel(crate::identity::HostKernel), 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"))]
#[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 || {
let _signal = crate::containment::cgroup::test_support::signal_when_drain_blocks(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 || {
let _signal = crate::containment::cgroup::test_support::signal_when_drain_blocks(sync_blocking);
sync_leaf.wait_drained(None)
});
let (async_leaf, async_blocking) = (leaf.clone(), blocking.clone());
let async_waiter = std::thread::spawn(move || {
let _signal = crate::containment::cgroup::test_support::signal_when_drain_blocks(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 || {
let _signal = crate::containment::cgroup::test_support::signal_when_drain_blocks(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 || {
let _signal = crate::containment::cgroup::test_support::signal_when_drain_blocks(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_changed_batch_notifies_a_listener_that_was_there_before_it() {
use std::future::Future as _;
use crate::containment::cgroup::fault;
use crate::containment::cgroup::test_support::FakeLeaf;
let fake = FakeLeaf::new("cosca-broadcast", true);
let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone());
let (batches, batches_rx) = std::sync::mpsc::channel();
fault::set_pump_batch_notifier("cosca-broadcast", batches);
let mut first = leaf.watch.listen().expect("start the pump");
let mut second = leaf.watch.listen().expect("a second listener");
FakeLeaf::set_populated(&fake.events, false);
assert!(
batches_rx.recv().expect("a batch"),
"a write to cgroup.events is a change"
);
leaf.watch.stop_pump();
let mut context = std::task::Context::from_waker(std::task::Waker::noop());
for (which, listener) in [("first", &mut first), ("second", &mut second)] {
assert!(
std::pin::Pin::new(listener).poll(&mut context).is_ready(),
"the pump took the change in, and did not notify the {which} listener"
);
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_change_before_the_listener_exists_is_seen_by_the_read_after_it() {
use rustix::fs::inotify;
use crate::containment::cgroup::fault;
use crate::containment::cgroup::test_support::FakeLeaf;
use crate::containment::TreeDrain;
let fake = FakeLeaf::new("cosca-change-before-listen", true);
let leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(fake.leaf.clone());
let (batches, batches_rx) = std::sync::mpsc::channel();
fault::set_pump_batch_notifier("cosca-change-before-listen", batches);
let _running = leaf.watch.listen().expect("start the pump");
let opens = inotify::init(inotify::CreateFlags::CLOEXEC | inotify::CreateFlags::NONBLOCK).expect("inotify_init");
inotify::add_watch(&opens, &fake.events, inotify::WatchFlags::OPEN).expect("watch opens of cgroup.events");
let mut ran = false;
let step = leaf.drain_step_on(None, || {
ran = true;
let mut buf = [std::mem::MaybeUninit::<u8>::uninit(); 4096];
assert!(
inotify::Reader::new(&opens, &mut buf).next().is_ok(),
"the step read the clock before its first read of cgroup.events"
);
assert!(
FakeLeaf::is_populated(&fake.events),
"the leaf was populated at the step's first read"
);
FakeLeaf::set_populated(&fake.events, false);
assert!(
batches_rx.recv().expect("a batch"),
"a write to cgroup.events is a change"
);
std::time::Instant::now()
});
assert!(ran, "the step answered without reading the clock");
match step.expect("drain_step_on") {
DrainStep::Done(drain) => assert_eq!(drain, TreeDrain::AllMembersExited),
DrainStep::Block { .. } => panic!("the step returned Block: its read after the listener missed the drain"),
}
}
#[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 = own_cgroup_dir();
crate::containment::cgroup::fault::set_force_kill_supported(true);
let err = match crate::containment::cgroup::create_leaf_under(
dir.path(),
&crate::identity::spawn_kernel(crate::identity::HostKernel),
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}");
assert_eq!(first_source_code(&err), Some(libc::ENOENT), "{err:?}");
let strays = strays_in(dir.path());
assert!(
strays.is_empty(),
"the degrade left {strays:?} behind — a cosca-* cgroup this host then keeps forever"
);
}
#[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());
leaf.record_placement(PlacementReport::WriteFailed(libc::EBADF));
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 = blocker();
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")]
fn run_placement_step(procs_fd: std::os::fd::RawFd, refusing: bool) -> crate::child::spawn::fork_exec::Spawned {
use crate::child::spawn::fork_exec::{spawn, Program, StepFailure};
use crate::os_process::linux::fork::{fork_with_pidfd, CloneKind};
use std::ffi::OsStr;
let program = Program::new(&[OsStr::new("/bin/true")], &[OsStr::new("true")], std::iter::empty()).expect("no NUL");
let _lock = crate::child::spawn::spawn_lock();
unsafe {
spawn(
CloneKind::Vfork,
fork_with_pidfd,
&program,
&[],
&mut |reporter| {
crate::containment::cgroup::placement_step(procs_fd, refusing, reporter).map_err(|e| StepFailure {
kind: 1,
value: e.raw_os_error().expect("an errno") as u16,
})
},
PLACEMENT_STEP_EXIT,
)
}
.unwrap_or_else(|e| panic!("the core made no child: {e:?}"))
}
#[cfg(target_os = "linux")]
const PLACEMENT_STEP_EXIT: i32 = 126;
#[cfg(target_os = "linux")]
fn settled_status(
spawned: &mut crate::child::spawn::fork_exec::Spawned,
) -> (crate::child::spawn::fork_exec::Progress, Option<u16>) {
let progress = crate::test_support::settled(&mut spawned.status);
(progress, spawned.status.reported())
}
#[cfg(target_os = "linux")]
fn exit_code_of(spawned: &crate::child::spawn::fork_exec::Spawned) -> i32 {
crate::test_support::exit_status(&spawned.child)
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_failed_placement_is_reported_and_the_child_goes_on() {
use crate::child::spawn::fork_exec::Progress;
let mut spawned = run_placement_step(-1, false);
assert_eq!(
settled_status(&mut spawned),
(Progress::Ended { ready: true }, Some(libc::EBADF as u16))
);
assert_eq!(exit_code_of(&spawned), 0, "the program ran");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_refusing_placement_that_fails_is_reported_and_ends_the_child() {
use crate::child::spawn::fork_exec::{Failure, Progress, StepFailure};
let mut spawned = run_placement_step(-1, true);
let failure = StepFailure {
kind: 1,
value: libc::EBADF as u16,
};
assert_eq!(
settled_status(&mut spawned),
(Progress::Failed(Failure::Step(failure)), Some(libc::EBADF as u16))
);
assert_eq!(exit_code_of(&spawned), PLACEMENT_STEP_EXIT, "the program never ran");
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_successful_placement_is_reported_and_the_child_goes_on() {
use crate::child::spawn::fork_exec::Progress;
for refusing in [false, true] {
let sink = std::fs::OpenOptions::new()
.write(true)
.open("/dev/null")
.expect("open /dev/null");
let mut spawned = run_placement_step(std::os::fd::AsRawFd::as_raw_fd(&sink), refusing);
assert_eq!(
settled_status(&mut spawned),
(Progress::Ended { ready: true }, Some(0)),
"refusing: {refusing}"
);
assert_eq!(exit_code_of(&spawned), 0, "refusing: {refusing}");
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_write_that_wrote_nothing_is_reported_as_failed() {
use crate::child::spawn::fork_exec::Progress;
let sink = std::fs::OpenOptions::new()
.write(true)
.open("/dev/null")
.expect("open /dev/null");
crate::containment::cgroup::fault::set_force_placement_write_result(
crate::containment::cgroup::fault::ForcedWrite::Returns0,
);
let mut spawned = run_placement_step(std::os::fd::AsRawFd::as_raw_fd(&sink), false);
assert_eq!(
settled_status(&mut spawned),
(Progress::Ended { ready: true }, Some(libc::EIO as u16))
);
assert_eq!(exit_code_of(&spawned), 0);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_placement_whose_report_cannot_be_written_ends_the_child() {
use crate::child::spawn::fork_exec::{spawn, Program, Progress};
use crate::os_process::linux::fork::{fork_with_pidfd, CloneKind};
use std::ffi::OsStr;
use std::os::fd::AsRawFd;
let dir = tempfile::tempdir().expect("tempdir");
let spare = std::io::pipe().expect("spare pipe");
let spare_write = spare.1.as_raw_fd();
let procs = std::fs::OpenOptions::new()
.write(true)
.open("/dev/null")
.expect("open /dev/null");
let procs_fd = procs.as_raw_fd();
let marker = dir.path().join("ran");
let ran = Program::new(
&[OsStr::new("/bin/sh")],
&[
OsStr::new("sh"),
OsStr::new("-c"),
OsStr::new("echo > \"$1\""),
OsStr::new("sh"),
marker.as_os_str(),
],
std::iter::empty(),
)
.expect("no NUL");
for refusing in [false, true] {
let _lock = crate::child::spawn::spawn_lock();
let channel_fd = unsafe {
let first = libc::fcntl(0, libc::F_DUPFD_CLOEXEC, 3);
let second = libc::fcntl(0, libc::F_DUPFD_CLOEXEC, 3);
libc::close(first);
libc::close(second);
second
};
let mut spawned = unsafe {
spawn(
CloneKind::Plain,
fork_with_pidfd,
&ran,
&[],
&mut |reporter| {
if libc::fcntl(channel_fd, libc::F_GETPIPE_SZ) < 0
|| libc::fcntl(channel_fd, libc::F_GETFL) & libc::O_ACCMODE != libc::O_WRONLY
{
libc::_exit(99);
}
libc::close(channel_fd);
let placed = crate::containment::cgroup::placement_step(procs_fd, refusing, reporter);
if placed.is_ok() {
libc::dup2(spare_write, channel_fd);
}
placed.map_err(|_| crate::child::spawn::fork_exec::StepFailure { kind: 1, value: 0 })
},
PLACEMENT_STEP_EXIT,
)
}
.expect("the core made a child");
drop(_lock);
assert_eq!(exit_code_of(&spawned), PLACEMENT_STEP_EXIT, "refusing: {refusing}");
assert_eq!(
settled_status(&mut spawned),
(Progress::Ended { ready: false }, None),
"refusing: {refusing}"
);
assert!(!marker.exists(), "refusing: {refusing}: the program ran");
}
}
#[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(&crate::identity::spawn_kernel(crate::identity::HostKernel), None)
.expect("a delegated cgroup v2 leaf");
let leaf_path = leaf.leaf_path.clone();
let procs_fd = leaf.procs_fd();
let mut occupant = blocker_with(|cmd| {
cmd.stdout(std::process::Stdio::piped());
unsafe { cmd.pre_exec(move || crate::containment::cgroup::test_support::place_in_pre_exec(procs_fd)) };
});
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());
leaf.record_placement(PlacementReport::Placed);
let _first_write_fails = crate::containment::cgroup::fault::fail_next_kill_write();
let mark = crate::log_capture::mark();
leaf.abandon_without_child(&mut crate::containment::cgroup::NoWarn);
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_spawn_with_no_report_removes_its_leaf() {
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());
leaf.abandon_without_child(&mut crate::containment::cgroup::NoWarn);
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);
leaf.abandon_without_child(&mut crate::containment::cgroup::NoWarn);
leaf.abandon_without_child(&mut crate::containment::cgroup::NoWarn);
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn the_first_recorded_placement_report_stands() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-first-report");
std::fs::create_dir(&leaf_path).expect("create the leaf");
std::fs::write(leaf_path.join("cgroup.procs"), "").expect("write cgroup.procs");
let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
leaf.record_placement(PlacementReport::WriteFailed(libc::EBUSY));
leaf.record_placement(PlacementReport::Placed);
match leaf.take_placement(handle_of(std::process::id(), &pidfd_of(std::process::id()))) {
Err(NotPlaced::Absent { report, .. }) => assert_eq!(report, NotEntered::WriteFailed(libc::EBUSY)),
other => panic!("the first report was a failed write: {other:?}"),
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
#[cfg_attr(debug_assertions, should_panic(expected = "after its verdict was taken"))]
fn a_report_recorded_after_the_verdict_is_ignored() {
let dir = tempfile::tempdir().expect("tempdir");
let leaf_path = dir.path().join("cosca-late-report");
std::fs::create_dir(&leaf_path).expect("create the leaf");
let mut leaf = crate::containment::cgroup::CgroupLeaf::for_test_at(leaf_path);
leaf.record_placement(PlacementReport::Placed);
leaf.take_placement(handle_of(std::process::id(), &pidfd_of(std::process::id())))
.expect("a placed child");
leaf.record_placement(PlacementReport::WriteFailed(libc::EBUSY));
assert!(leaf.child_entered(), "the taken verdict stands");
}
#[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 mut leaf = crate::containment::cgroup::try_create_leaf(
&crate::identity::spawn_kernel(crate::identity::HostKernel),
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 {
leaf.record_placement(PlacementReport::Placed);
}
let attempts = std::rc::Rc::new(std::cell::Cell::new(0));
let observer = crate::containment::cgroup::fault::observe_rmdirs({
let attempts = attempts.clone();
move |_| {
attempts.set(attempts.get() + 1);
assert!(
attempts.get() <= 2,
"placed: {placed}: the drop made a third rmdir of a leaf it had swept"
);
}
});
drop(leaf);
drop(observer);
assert_eq!(
attempts.get(),
2,
"placed: {placed}: the drop makes one rmdir, sweeps the child cgroups, and makes one more"
);
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) = entered_real_leaf();
let kernel = std::sync::Arc::new(crate::identity::FakeKernel::over(&crate::identity::HostKernel));
let leaf = match how {
Unsignalled::Unplaced => leaf.asking_for_test(crate::identity::spawn_kernel(std::sync::Arc::clone(&kernel))),
Unsignalled::Unpinned | Unsignalled::SendFailed => 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()),
Unsignalled::SendFailed => Box::new(fail_terminate(TerminateStep::Send, libc::EIO)),
};
let hidden = matches!(how, Unsignalled::Unplaced).then(|| kernel.hide_every_pid_cgroup());
let result = sent(leaf.terminate(crate::signal::Signal::Term));
drop(hidden);
drop(guard);
assert_eq!(take_member_terms(), []);
let warns = crate::log_capture::warns_since(mark, &leaf_name);
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 => libc::EMFILE,
Unsignalled::SendFailed => libc::EIO,
Unsignalled::Unplaced => libc::ENOENT,
};
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}");
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) = 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();
sent(leaf.terminate(crate::signal::Signal::Term)).expect("terminate");
assert_eq!(crate::containment::cgroup::fault::take_member_terms(), []);
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) = entered_real_leaf();
let pid = member.id();
crate::containment::cgroup::fault::take_member_terms();
let result = sent(leaf.terminate(crate::signal::Signal::Term));
let noted = crate::containment::cgroup::fault::take_member_terms();
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) = entered_real_leaf();
#[allow(clippy::zombie_processes, reason = "reaped behind std, by pid, in the pin's seam")]
let member = member.into_inner();
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 = sent(leaf.terminate(crate::signal::Signal::Term));
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) = 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 = sent(leaf.terminate(crate::signal::Signal::Term));
let noted = crate::containment::cgroup::fault::take_member_terms();
let records = crate::log_capture::records_since_on_current_thread(mark, &leaf_name);
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(&crate::identity::spawn_kernel(crate::identity::HostKernel), 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", crate::signal::Signal::Term);
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<StdChild>) {
use std::os::unix::process::CommandExt;
let leaf =
crate::containment::cgroup::try_create_leaf(&crate::identity::spawn_kernel(crate::identity::HostKernel), None)
.expect("create a real leaf");
let members = (0..n)
.map(|_| {
let procs_fd = leaf.procs_fd();
blocker_with(|cmd| {
unsafe {
cmd.pre_exec(move || crate::containment::cgroup::test_support::place_in_pre_exec(procs_fd));
}
})
})
.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) = 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}
"
),
crate::signal::Signal::Term,
);
let warns = crate::log_capture::warns_since(mark, &leaf_name);
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(&crate::identity::spawn_kernel(crate::identity::HostKernel), None)
.expect("create a real leaf");
let result = leaf.terminate_listed("0\n", crate::signal::Signal::Term);
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", crate::signal::Signal::Term);
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) = 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 = sent(leaf.terminate(crate::signal::Signal::Term));
drop(guard);
let noted = take_member_terms();
let warns = crate::log_capture::warns_since(mark, &leaf_name);
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) = entered_real_leaf();
let kernel = std::sync::Arc::new(crate::identity::FakeKernel::over(&crate::identity::HostKernel));
let leaf = leaf.asking_for_test(crate::identity::spawn_kernel(std::sync::Arc::clone(&kernel)));
take_member_terms();
let guard = (
crate::containment::cgroup::fault::miss_pidfd_info(),
fail_terminate(TerminateStep::Exited, libc::EIO),
);
let hidden = kernel.hide_every_pid_cgroup();
let result = sent(leaf.terminate(crate::signal::Signal::Term));
drop(hidden);
drop(guard);
let noted = take_member_terms();
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(&crate::identity::HostKernel, 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_refused_placement_of_a_live_member_is_returned_as_unsupported() {
use crate::containment::cgroup::test_support::kill_record;
use crate::identity::{FakeKernel, HostKernel};
let subtree = crate::containment::cgroup::Subtree::new(
None,
None,
Some("/leaf".to_owned()),
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 refusing = FakeKernel::over(&HostKernel).on_every_pid_read("cgroup", Err(libc::ENOSYS));
let result = super::placed_or_exited(
pidfd.as_fd(),
subtree.holds(&refusing, std::process::id(), Some(pidfd.as_fd())),
);
let err = match result {
Err(err) => err,
Ok(_) => panic!("a refused placement of a live member is no answer"),
};
assert!(matches!(err, crate::error::Error::Unsupported { .. }), "{err:?}");
assert_eq!(crate::error::first_os_code(&err), Some(libc::ENOSYS), "{err:?}");
}
#[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 = blocker();
let result = crate::containment::cgroup::CgroupLeaf::placeholder_for_test().terminate_member(
child.id(),
&subtree,
crate::signal::Signal::Term,
);
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) = 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"), crate::signal::Signal::Term);
let noted = take_member_terms();
let warns = crate::log_capture::warns_since(mark, &leaf_name);
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) = entered_real_leaf();
let pid = member.id();
let leaf_name = leaf_name_of(&leaf);
member.wait().expect("reap the member");
take_member_terms();
let mark = crate::log_capture::mark();
let result = leaf.terminate_listed(&format!("{pid}\n"), crate::signal::Signal::Term);
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) = 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 = sent(leaf.terminate(crate::signal::Signal::Term));
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);
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) = entered_real_leaf();
#[allow(clippy::zombie_processes, reason = "reaped behind std, by pid, in the pin's seam")]
let member = member.into_inner();
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 = sent(leaf.terminate(crate::signal::Signal::Term));
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]), crate::signal::Signal::Term);
drop(guard);
let noted = take_member_terms();
let statuses: Vec<_> = members
.drain(..)
.map(|mut member| 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]), crate::signal::Signal::Term);
drop(guard);
let noted = take_member_terms();
let warns = crate::log_capture::warns_since(mark, &leaf_name);
for mut member in members.drain(..) {
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(&crate::identity::spawn_kernel(crate::identity::HostKernel), 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", crate::signal::Signal::Term);
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:?}");
}