use std::ffi::{OsStr, OsString};
use std::io;
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd};
use std::path::Path;
use rustix::fs::{AtFlags, Mode, OFlags};
const FILEID_KERNFS: libc::c_int = 0xfe;
pub(crate) fn cgroup_id(dir: BorrowedFd<'_>) -> io::Result<u64> {
#[repr(C)]
struct KernfsHandle {
handle_bytes: libc::c_uint,
handle_type: libc::c_int,
f_handle: [u8; 8],
}
let mut handle = KernfsHandle {
handle_bytes: 8,
handle_type: 0,
f_handle: [0; 8],
};
let mut mount_id: libc::c_int = 0;
let rc = unsafe {
libc::name_to_handle_at(
dir.as_raw_fd(),
c"".as_ptr(),
(&raw mut handle).cast::<libc::file_handle>(),
&mut mount_id,
libc::AT_EMPTY_PATH,
)
};
if rc != 0 {
return Err(io::Error::last_os_error());
}
id_of_handle(handle.handle_type, handle.handle_bytes, handle.f_handle)
}
pub(crate) fn id_of_handle(handle_type: libc::c_int, handle_bytes: libc::c_uint, bytes: [u8; 8]) -> io::Result<u64> {
if handle_type != FILEID_KERNFS || handle_bytes != 8 {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("not a cgroup's file handle (type {handle_type:#x}, {handle_bytes} bytes)"),
));
}
Ok(u64::from_ne_bytes(bytes))
}
pub(crate) struct LeafDir {
parent: OwnedFd,
dir: std::sync::Arc<OwnedFd>,
swept: Swept,
name: OsString,
}
impl LeafDir {
pub(crate) fn create(parent: &Path, name: &str) -> io::Result<LeafDir> {
let parent = open_dir(rustix::fs::CWD, parent)?;
rustix::fs::mkdirat(&parent, name, Mode::from_raw_mode(0o777))?;
#[cfg(test)]
let held = if super::fault::take_force_leaf_open_failure() {
Err(io::Error::from_raw_os_error(libc::EMFILE))
} else {
open_dir(&parent, name)
};
#[cfg(not(test))]
let held = open_dir(&parent, name);
let dir = match held {
Ok(dir) => dir,
Err(e) => {
if let Err(rm) = rustix::fs::unlinkat(&parent, name, AtFlags::REMOVEDIR) {
log::warn!(
"cgroup leaf {name} was not removed: rmdir failed ({rm}) after it could not be opened \
({e}); it stays on this host until a cgroup manager reaps it"
);
}
return Err(e);
}
};
Ok(LeafDir {
parent,
dir: std::sync::Arc::new(dir),
swept: Swept::default(),
name: name.into(),
})
}
#[cfg(test)]
pub(crate) fn open_for_test(path: &Path) -> LeafDir {
let name = path.file_name().expect("a leaf path has a name").to_os_string();
if path.exists() {
let parent = open_dir(rustix::fs::CWD, path.parent().expect("a leaf path has a parent"))
.expect("open the leaf's parent");
let dir = open_dir(&parent, &name).expect("open the leaf");
return LeafDir {
parent,
dir: std::sync::Arc::new(dir),
swept: Swept::default(),
name,
};
}
let gone = tempfile::tempdir().expect("tempdir");
let parent = open_dir(rustix::fs::CWD, gone.path()).expect("open a stand-in parent");
rustix::fs::mkdirat(&parent, &name, Mode::from_raw_mode(0o777)).expect("make a stand-in leaf");
let dir = open_dir(&parent, &name).expect("open the stand-in leaf");
rustix::fs::unlinkat(&parent, &name, AtFlags::REMOVEDIR).expect("remove the stand-in leaf");
LeafDir {
parent,
dir: std::sync::Arc::new(dir),
swept: Swept::default(),
name,
}
}
pub(crate) fn dir(&self) -> BorrowedFd<'_> {
self.dir.as_fd()
}
pub(crate) fn shared(&self) -> std::sync::Arc<OwnedFd> {
std::sync::Arc::clone(&self.dir)
}
pub(crate) fn swept(&self) -> Swept {
self.swept.clone()
}
pub(crate) fn parent(&self) -> BorrowedFd<'_> {
self.parent.as_fd()
}
pub(crate) fn name(&self) -> &OsStr {
&self.name
}
pub(crate) fn open(&self, file: &str, flags: OFlags) -> io::Result<OwnedFd> {
Ok(rustix::fs::openat(
&self.dir,
file,
flags | OFlags::CLOEXEC,
Mode::empty(),
)?)
}
pub(crate) fn read(&self, file: &str) -> io::Result<String> {
io::read_to_string(std::fs::File::from(self.open(file, OFlags::RDONLY)?))
}
pub(crate) fn write(&self, file: &str, bytes: &[u8]) -> io::Result<()> {
use std::io::Write as _;
let fd = rustix::fs::openat(
&self.dir,
file,
OFlags::WRONLY | OFlags::CREATE | OFlags::TRUNC | OFlags::CLOEXEC,
Mode::from_raw_mode(0o666),
)?;
std::fs::File::from(fd).write_all(bytes)
}
pub(crate) fn rmdir(&self) -> io::Result<()> {
use rustix::fs::ResolveFlags;
use rustix::io::Errno;
let named = rustix::fs::openat2(
&self.parent,
&self.name,
OFlags::PATH | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
ResolveFlags::NO_XDEV | ResolveFlags::NO_SYMLINKS | ResolveFlags::BENEATH,
);
let ours = match named {
Ok(named) => {
let (named, held) = (rustix::fs::fstat(&named)?, rustix::fs::fstat(&self.dir)?);
(named.st_dev, named.st_ino) == (held.st_dev, held.st_ino)
}
Err(Errno::XDEV) => return Err(io::Error::from_raw_os_error(libc::EBUSY)),
Err(Errno::NOENT | Errno::LOOP | Errno::NOTDIR) => false,
Err(e) => return Err(e.into()),
};
if !ours {
return Err(match self.open("cgroup.events", OFlags::PATH) {
Err(e) if super::removed_after_drain(&e) => io::Error::from_raw_os_error(libc::ENOENT),
Err(e) => e,
Ok(_) => io::Error::other(format!(
"{} no longer names the leaf, which is still there",
self.name.to_string_lossy()
)),
});
}
Ok(rustix::fs::unlinkat(&self.parent, &self.name, AtFlags::REMOVEDIR)?)
}
pub(crate) fn id(&self) -> io::Result<u64> {
cgroup_id(self.dir.as_fd())
}
pub(crate) fn remove_children(&self) -> io::Result<usize> {
remove_children(self.dir.as_fd(), &self.swept)
}
}
#[derive(Debug, Clone, Default)]
pub(crate) struct Swept(std::sync::Arc<std::sync::Mutex<Vec<u64>>>);
impl Swept {
fn record(&self, id: u64) {
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(id);
}
pub(crate) fn holds(&self, id: u64) -> bool {
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.contains(&id)
}
}
#[derive(Debug)]
pub(crate) enum Walked {
Found,
Absent,
Unknown(io::Error),
}
pub(crate) fn find_descendant(dir: BorrowedFd<'_>, id: u64) -> Walked {
match walk(dir, id) {
Ok(Some(())) => Walked::Found,
Ok(None) => Walked::Absent,
Err(e) => Walked::Unknown(e),
}
}
fn walk(dir: BorrowedFd<'_>, id: u64) -> io::Result<Option<()>> {
use std::collections::VecDeque;
use std::os::unix::ffi::OsStrExt as _;
let gone = |e: rustix::io::Errno| matches!(e, rustix::io::Errno::NOENT | rustix::io::Errno::NODEV);
let mut pending: VecDeque<std::path::PathBuf> = VecDeque::from([std::path::PathBuf::from(".")]);
let mut behind_a_mount = None;
while let Some(path) = pending.pop_front() {
#[cfg(test)]
super::fault::run_before_walk_open(&path);
let is_root = path.as_os_str() == ".";
let skippable = |e: rustix::io::Errno| gone(e) && !is_root;
let cgroup = match step_fault(&path, WalkStep::Open).and_then(|()| open_beneath(dir, &path)) {
Ok(cgroup) => cgroup,
Err(e) if skippable(e) => continue,
Err(rustix::io::Errno::XDEV) => {
behind_a_mount.get_or_insert(path);
continue;
}
Err(e) => return Err(named(e, &path)),
};
if !is_root {
match step_fault(&path, WalkStep::Id)
.map_err(io::Error::from)
.and_then(|()| cgroup_id(cgroup.as_fd()))
{
Ok(found) if found == id => return Ok(Some(())),
Ok(_) => {}
Err(e)
if e.raw_os_error()
.is_some_and(|errno| gone(rustix::io::Errno::from_raw_os_error(errno))) =>
{
continue
}
Err(e) => return Err(io::Error::new(e.kind(), format!("{}: {e}", path.display()))),
}
}
let entries = match step_fault(&path, WalkStep::List)
.and_then(|()| {
rustix::fs::openat(
&cgroup,
".",
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)
})
.and_then(rustix::fs::Dir::new)
{
Ok(entries) => entries,
Err(e) if skippable(e) => continue,
Err(e) => return Err(named(e, &path)),
};
let mut first = true;
for entry in entries {
let entry = if std::mem::take(&mut first) {
step_fault(&path, WalkStep::Entries).and(entry)
} else {
entry
};
let entry = match entry {
Ok(entry) => entry,
Err(e) if skippable(e) => break,
Err(e) => return Err(named(e, &path)),
};
let name = entry.file_name();
if !matches!(name.to_bytes(), b"." | b"..") && is_dir(cgroup.as_fd(), &entry)? {
pending.push_back(path.join(std::ffi::OsStr::from_bytes(name.to_bytes())));
}
}
if is_root {
step_fault(&path, WalkStep::Alive)
.and_then(|()| {
rustix::fs::openat(&cgroup, "cgroup.events", OFlags::PATH | OFlags::CLOEXEC, Mode::empty())
})
.map_err(|e| named(e, &path))?;
}
}
match behind_a_mount {
Some(path) => Err(io::Error::other(format!(
"{} is behind a mount, so the cgroups under it cannot be listed",
path.display()
))),
None => Ok(None),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum WalkStep {
Open,
Id,
List,
Entries,
Alive,
}
fn step_fault(path: &std::path::Path, step: WalkStep) -> rustix::io::Result<()> {
#[cfg(test)]
if let Some(errno) = super::fault::walk_step_failure(path, step) {
return Err(rustix::io::Errno::from_raw_os_error(errno));
}
let _ = (path, step);
Ok(())
}
fn named(errno: rustix::io::Errno, path: &std::path::Path) -> io::Error {
let e = io::Error::from(errno);
let at = if path.as_os_str() == "." {
"the root of the walk".to_owned()
} else {
path.display().to_string()
};
io::Error::new(e.kind(), format!("{at}: {e}"))
}
fn open_beneath(dir: BorrowedFd<'_>, path: &std::path::Path) -> rustix::io::Result<OwnedFd> {
use rustix::fs::ResolveFlags;
rustix::fs::openat2(
dir,
path,
OFlags::PATH | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
ResolveFlags::NO_XDEV | ResolveFlags::NO_SYMLINKS | ResolveFlags::BENEATH,
)
}
fn is_dir(at: BorrowedFd<'_>, entry: &rustix::fs::DirEntry) -> io::Result<bool> {
Ok(match entry.file_type() {
rustix::fs::FileType::Directory => true,
rustix::fs::FileType::Unknown => match rustix::fs::statat(at, entry.file_name(), AtFlags::SYMLINK_NOFOLLOW) {
Ok(st) => rustix::fs::FileType::from_raw_mode(st.st_mode) == rustix::fs::FileType::Directory,
Err(rustix::io::Errno::NOENT | rustix::io::Errno::NODEV) => false,
Err(e) => return Err(e.into()),
},
_ => false,
})
}
pub(crate) fn fd_path(fd: BorrowedFd<'_>) -> String {
format!("/proc/thread-self/fd/{}", fd.as_raw_fd())
}
fn open_dir(at: impl AsFd, path: impl rustix::path::Arg) -> io::Result<OwnedFd> {
above_stdio(rustix::fs::openat(
at,
path,
OFlags::PATH | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)?)
}
pub(crate) use crate::above_stdio::above_stdio;
fn open_child_on_this_mount(dir: BorrowedFd<'_>, name: &std::ffi::CStr) -> rustix::io::Result<OwnedFd> {
use rustix::fs::ResolveFlags;
let fd = rustix::fs::openat2(
dir,
name,
OFlags::PATH | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
ResolveFlags::NO_XDEV | ResolveFlags::NO_SYMLINKS | ResolveFlags::BENEATH,
)?;
above_stdio(fd).map_err(|e| rustix::io::Errno::from_io_error(&e).unwrap_or(rustix::io::Errno::IO))
}
fn remove_children(dir: BorrowedFd<'_>, swept: &Swept) -> io::Result<usize> {
let gone = |e: rustix::io::Errno| matches!(e, rustix::io::Errno::NOENT | rustix::io::Errno::NODEV);
let listing = rustix::fs::openat(
dir,
".",
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)
.and_then(rustix::fs::Dir::new);
let entries = match listing {
Ok(entries) => entries,
Err(e) if gone(e) => return Ok(0),
Err(e) => return Err(e.into()),
};
let mut removed = 0;
for entry in entries {
let entry = match entry {
Ok(entry) => entry,
Err(e) if gone(e) => return Ok(removed),
Err(e) => return Err(e.into()),
};
let name = entry.file_name();
if matches!(name.to_bytes(), b"." | b"..") {
continue;
}
let is_dir = match entry.file_type() {
rustix::fs::FileType::Directory => true,
rustix::fs::FileType::Unknown => match rustix::fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW) {
Ok(st) => rustix::fs::FileType::from_raw_mode(st.st_mode) == rustix::fs::FileType::Directory,
Err(e) if gone(e) => false,
Err(e) => return Err(e.into()),
},
_ => false,
};
if !is_dir {
continue;
}
let child = match open_child_on_this_mount(dir, name) {
Ok(child) => child,
Err(e) if gone(e) || e == rustix::io::Errno::XDEV => continue,
Err(e) => return Err(e.into()),
};
let child_id = match cgroup_id(child.as_fd()) {
Ok(id) => Some(id),
Err(e)
if e.raw_os_error()
.is_some_and(|errno| gone(rustix::io::Errno::from_raw_os_error(errno))) =>
{
continue
}
Err(e) => {
log::debug!(
"cgroup v2: the id of child cgroup {} cannot be read ({e}); it is removed unrecorded",
name.to_string_lossy()
);
None
}
};
removed += remove_children(child.as_fd(), swept)?;
match rustix::fs::unlinkat(dir, name, AtFlags::REMOVEDIR) {
Ok(()) => {
removed += 1;
if let Some(child_id) = child_id {
swept.record(child_id);
}
}
Err(e) if gone(e) || e == rustix::io::Errno::BUSY => {}
Err(e) => return Err(e.into()),
}
}
Ok(removed)
}
#[cfg(test)]
#[path = "dir_tests.rs"]
mod dir_tests;
#[cfg(test)]
#[path = "dir_walk_tests.rs"]
pub(crate) mod dir_walk_tests;