use std::os::fd::{AsFd as _, OwnedFd};
use std::path::{Path, PathBuf};
use super::{cgroup_id, find_descendant, Walked};
use crate::containment::cgroup::fault::fail_walk_step;
use crate::containment::cgroup::WalkStep;
use crate::test_groups::{cgroup, Group};
pub(crate) struct Scratch(PathBuf);
impl Scratch {
pub(crate) fn new(tag: &str) -> Scratch {
let own = std::fs::read_to_string("/proc/self/cgroup").expect("read /proc/self/cgroup");
let own = own
.lines()
.find_map(|l| l.strip_prefix("0::/"))
.expect("a unified line");
let path = Path::new("/sys/fs/cgroup")
.join(own)
.join(format!("cosca-{}-{tag}", std::process::id()));
std::fs::create_dir(&path).unwrap_or_else(|e| panic!("make {}: {e}", path.display()));
Scratch(path)
}
pub(crate) fn path(&self) -> &Path {
&self.0
}
pub(crate) fn make(&self, rel: &str) -> PathBuf {
let path = self.0.join(rel);
std::fs::create_dir_all(&path).unwrap_or_else(|e| panic!("make {}: {e}", path.display()));
path
}
pub(crate) fn fd(&self) -> OwnedFd {
open_path(&self.0)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let mut dirs = Vec::new();
let mut pending = vec![self.0.clone()];
while let Some(dir) = pending.pop() {
if let Ok(entries) = std::fs::read_dir(&dir) {
pending.extend(
entries
.flatten()
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
.map(|e| e.path()),
);
}
dirs.push(dir);
}
for dir in dirs.iter().rev() {
if let Err(e) = std::fs::remove_dir(dir) {
if e.kind() != std::io::ErrorKind::NotFound && !std::thread::panicking() {
panic!("remove the scratch cgroup {}: {e}", dir.display());
}
}
}
}
}
pub(crate) fn open_path(path: &Path) -> OwnedFd {
rustix::fs::open(
path,
rustix::fs::OFlags::PATH | rustix::fs::OFlags::DIRECTORY | rustix::fs::OFlags::CLOEXEC,
rustix::fs::Mode::empty(),
)
.unwrap_or_else(|e| panic!("open {}: {e}", path.display()))
}
pub(crate) fn id_at(path: &Path) -> u64 {
cgroup_id(open_path(path).as_fd()).unwrap_or_else(|e| panic!("the cgroup id of {}: {e}", path.display()))
}
#[skuld::test]
fn cgroup_a_leaf_id_is_the_cgroup_id_its_members_read(#[fixture(cgroup)] _group: &Group) {
let own = std::fs::read_to_string("/proc/self/cgroup").expect("read /proc/self/cgroup");
let own = own
.lines()
.find_map(|l| l.strip_prefix("0::/"))
.expect("a unified line");
let pidfd = rustix::process::pidfd_open(rustix::process::getpid(), rustix::process::PidfdFlags::empty())
.expect("pidfd_open");
let read = crate::containment::cgroup::pidfd_cgroup_id(pidfd.as_fd())
.expect("PIDFD_GET_INFO")
.expect("the lane's kernel has PIDFD_GET_INFO");
assert_eq!(id_at(&Path::new("/sys/fs/cgroup").join(own)), read);
}
#[skuld::test]
fn cgroup_the_walk_finds_a_cgroup_at_any_depth_and_only_under_its_root(#[fixture(cgroup)] _group: &Group) {
let scratch = Scratch::new("walk-depth");
let deep: String = ["d"; 200].join("/");
let found = [scratch.make(&deep), scratch.make("wide/x"), scratch.path().join("wide")];
let root = scratch.fd();
for path in &found {
assert!(
matches!(find_descendant(root.as_fd(), id_at(path)), Walked::Found),
"{}",
path.display()
);
}
let elsewhere = scratch.path().parent().expect("the lane's cgroup");
for path in [scratch.path(), elsewhere] {
let walked = find_descendant(root.as_fd(), id_at(path));
assert!(matches!(walked, Walked::Absent), "{}: {walked:?}", path.display());
}
}
#[skuld::test]
fn cgroup_the_walk_skips_a_cgroup_removed_mid_walk(#[fixture(cgroup)] _group: &Group) {
let scratch = Scratch::new("walk-removed");
let target = id_at(&scratch.make("kept/target"));
let root = scratch.fd();
let removing = || {
let under = scratch.make("gone/under");
let id = id_at(&under);
let gone = scratch.path().join("gone");
let removed = std::rc::Rc::new(std::cell::Cell::new(false));
let hook = crate::containment::cgroup::fault::set_before_walk_open({
let removed = std::rc::Rc::clone(&removed);
move |path| {
if path == Path::new("./gone") {
std::fs::remove_dir(gone.join("under")).expect("remove `gone/under` mid-walk");
std::fs::remove_dir(&gone).expect("remove `gone` mid-walk");
removed.set(true);
}
}
});
(hook, removed, id)
};
let (hook, removed, _) = removing();
assert!(matches!(find_descendant(root.as_fd(), target), Walked::Found));
assert!(
removed.get(),
"the walk reached `gone` before it found the target, and skipped it once removed"
);
drop(hook);
let (_hook, removed, under) = removing();
let walked = find_descendant(root.as_fd(), under);
assert!(matches!(walked, Walked::Absent), "{walked:?}");
assert!(removed.get(), "the walk reached `gone`, and skipped it once removed");
}
#[skuld::test]
fn cgroup_a_walk_of_a_removed_root_cannot_tell(#[fixture(cgroup)] _group: &Group) {
let scratch = Scratch::new("walk-gone-root");
let root = scratch.fd();
std::fs::remove_dir(scratch.path()).expect("remove the root");
let walked = find_descendant(root.as_fd(), 1);
assert!(matches!(walked, Walked::Unknown(_)), "{walked:?}");
}
#[skuld::test]
fn cgroup_a_walk_of_a_root_gone_at_any_step_cannot_tell(#[fixture(cgroup)] _group: &Group) {
let scratch = Scratch::new("walk-gone-root-steps");
scratch.make("under");
let root = scratch.fd();
for step in [WalkStep::Open, WalkStep::List, WalkStep::Entries, WalkStep::Alive] {
for errno in [libc::ENOENT, libc::ENODEV] {
let _failing = fail_walk_step(".", step, errno);
let walked = find_descendant(root.as_fd(), 1);
assert!(matches!(walked, Walked::Unknown(_)), "{step:?} {errno}: {walked:?}");
}
}
}
#[skuld::test]
fn cgroup_a_walk_that_is_refused_cannot_tell(#[fixture(cgroup)] _group: &Group) {
let scratch = Scratch::new("walk-refused");
scratch.make("a/b");
let root = scratch.fd();
for step in [WalkStep::Open, WalkStep::Id, WalkStep::List, WalkStep::Entries] {
for errno in [libc::ENAMETOOLONG, libc::EACCES] {
let _failing = fail_walk_step("./a", step, errno);
let walked = find_descendant(root.as_fd(), 1);
assert!(matches!(walked, Walked::Unknown(_)), "{step:?} {errno}: {walked:?}");
}
}
}
#[skuld::test]
fn cgroup_a_walk_skips_a_cgroup_gone_after_its_open(#[fixture(cgroup)] _group: &Group) {
let scratch = Scratch::new("walk-gone-late");
scratch.make("a");
let target = id_at(&scratch.make("z/target"));
let root = scratch.fd();
for step in [WalkStep::Id, WalkStep::List, WalkStep::Entries] {
for errno in [libc::ENODEV, libc::ENOENT] {
let _failing = fail_walk_step("./a", step, errno);
let walked = find_descendant(root.as_fd(), target);
assert!(matches!(walked, Walked::Found), "{step:?} {errno}: {walked:?}");
let walked = find_descendant(root.as_fd(), 1);
assert!(matches!(walked, Walked::Absent), "{step:?} {errno}: {walked:?}");
}
}
}
#[skuld::test]
fn cgroup_the_walk_holds_no_descriptor_between_cgroups(#[fixture(cgroup)] _group: &Group) {
let scratch = Scratch::new("walk-fds");
for i in 0..20 {
scratch.make(&format!("w{i}/{}", ["d"; 10].join("/")));
}
let root = scratch.fd();
let open_fds = || std::fs::read_dir("/proc/self/fd").expect("list fds").count();
let before = open_fds();
let counts = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
let _hook = crate::containment::cgroup::fault::set_before_walk_open({
let counts = std::rc::Rc::clone(&counts);
move |_| counts.borrow_mut().push(open_fds())
});
let walked = find_descendant(root.as_fd(), 0);
assert!(matches!(walked, Walked::Absent), "{walked:?}");
let counts = counts.borrow();
assert_eq!(counts.len(), 1 + 20 * 11, "the walk visits every cgroup once");
assert!(
counts.iter().all(|&n| n == before),
"{before} before the walk, then {counts:?}"
);
}
#[skuld::test]
fn cgroup_the_walk_cannot_tell_behind_a_mount(#[fixture(cgroup)] _group: &Group) {
let scratch = Scratch::new("walk-mount");
let hidden = id_at(&scratch.make("sub/x"));
let elsewhere = id_at(scratch.path().parent().expect("the lane's cgroup"));
let sub = scratch.path().join("sub");
let walked = std::thread::scope(|scope| {
scope
.spawn(|| {
enter_private_mount_ns();
let root = scratch.fd();
let _mounted = TmpfsOver::new(&sub);
[hidden, elsewhere].map(|id| find_descendant(root.as_fd(), id))
})
.join()
.expect("the walking thread")
});
for walked in walked {
assert!(matches!(walked, Walked::Unknown(_)), "{walked:?}");
}
let root = scratch.fd();
assert!(matches!(find_descendant(root.as_fd(), hidden), Walked::Found));
}
pub(crate) fn enter_private_mount_ns() {
let root = std::ffi::CString::new("/").expect("no NUL");
unsafe {
assert_eq!(
libc::unshare(libc::CLONE_NEWNS),
0,
"unshare: {}",
std::io::Error::last_os_error()
);
assert_eq!(
libc::mount(
std::ptr::null(),
root.as_ptr(),
std::ptr::null(),
libc::MS_REC | libc::MS_PRIVATE,
std::ptr::null()
),
0,
"make / private: {}",
std::io::Error::last_os_error()
);
}
}
pub(crate) struct TmpfsOver(std::ffi::CString);
impl TmpfsOver {
pub(crate) fn new(target: &Path) -> TmpfsOver {
let target = std::ffi::CString::new(target.as_os_str().as_encoded_bytes()).expect("no NUL");
let rc = unsafe {
libc::mount(
c"none".as_ptr(),
target.as_ptr(),
c"tmpfs".as_ptr(),
0,
std::ptr::null(),
)
};
assert_eq!(
rc,
0,
"mount a tmpfs over the cgroup: {}",
std::io::Error::last_os_error()
);
TmpfsOver(target)
}
}
impl Drop for TmpfsOver {
fn drop(&mut self) {
let rc = unsafe { libc::umount2(self.0.as_ptr(), 0) };
assert_eq!(rc, 0, "unmount the tmpfs: {}", std::io::Error::last_os_error());
}
}