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::io::Errno;
let named = open_beneath(self.parent.as_fd(), &self.name);
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<std::collections::HashSet<u64>>>);
impl Swept {
fn record(&self, id: u64) {
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(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<()>> {
let traversed = traverse(&mut Tree::new(), dir, true, |tree, node, cgroup| {
match step_fault(tree, node, WalkStep::Id)
.map_err(io::Error::from)
.and_then(|()| cgroup_id(cgroup))
{
Ok(found) if found == id => Ok(Visit::Stop),
Ok(_) => Ok(Visit::Continue),
Err(e) if gone_io(&e) => Ok(Visit::Skip),
Err(e) => Err(at_cgroup(e, tree, node)),
}
})
.map_err(Failure::into_error)?;
match traversed {
Traversed::Stopped => Ok(Some(())),
Traversed::Listed { behind_a_mount: false } => Ok(None),
Traversed::Listed { behind_a_mount: true } => Err(io::Error::from_raw_os_error(libc::EXDEV)),
}
}
enum Visit {
Continue,
Skip,
Stop,
}
enum Traversed {
Stopped,
Listed { behind_a_mount: bool },
}
enum Failure {
RootGone(io::Error),
Other(io::Error),
}
impl Failure {
fn into_error(self) -> io::Error {
match self {
Failure::RootGone(e) | Failure::Other(e) => e,
}
}
}
struct Tree {
nodes: Vec<Node>,
}
struct Node {
parent: usize,
name: std::ffi::OsString,
}
impl Tree {
const ROOT: usize = 0;
fn new() -> Tree {
Tree {
nodes: vec![Node {
parent: Self::ROOT,
name: std::ffi::OsString::new(),
}],
}
}
fn push(&mut self, parent: usize, name: &OsStr) -> usize {
self.nodes.push(Node {
parent,
name: name.to_owned(),
});
self.nodes.len() - 1
}
fn parent(&self, node: usize) -> usize {
self.nodes[node].parent
}
fn name(&self, node: usize) -> &OsStr {
debug_assert_ne!(node, Self::ROOT, "the root has no name");
&self.nodes[node].name
}
fn names(&self, node: usize) -> Vec<&OsStr> {
let mut names = Vec::new();
let mut at = node;
while at != Self::ROOT {
names.push(self.name(at));
at = self.parent(at);
}
names.reverse();
names
}
fn path(&self, node: usize) -> std::path::PathBuf {
let mut path = std::path::PathBuf::from(".");
path.extend(self.names(node));
path
}
}
fn traverse(
tree: &mut Tree,
dir: BorrowedFd<'_>,
confirm_root: bool,
mut visit: impl FnMut(&Tree, usize, BorrowedFd<'_>) -> io::Result<Visit>,
) -> Result<Traversed, Failure> {
use std::collections::VecDeque;
use std::os::unix::ffi::OsStrExt as _;
debug_assert_eq!(tree.nodes.len(), 1, "a traversal starts from a tree of its root alone");
let mut pending: VecDeque<usize> = VecDeque::from([Tree::ROOT]);
let mut behind_a_mount = false;
while let Some(node) = pending.pop_front() {
#[cfg(test)]
super::fault::run_before_walk_open(&tree.path(node));
let is_root = node == Tree::ROOT;
let skippable = |e: rustix::io::Errno| gone(e) && !is_root;
let failed = |tree: &Tree, e: rustix::io::Errno| {
if is_root && gone(e) {
Failure::RootGone(named(e, tree, node))
} else {
Failure::Other(named(e, tree, node))
}
};
let cgroup = match step_fault(tree, node, WalkStep::Open).and_then(|()| open_cgroup(dir, &tree.names(node))) {
Ok(cgroup) => cgroup,
Err(e) if skippable(e) => continue,
Err(rustix::io::Errno::XDEV) => {
log::debug!(
"cgroup v2: {} is behind a mount, so the cgroups under it are not listed",
tree.path(node).display()
);
behind_a_mount = true;
continue;
}
Err(e) => return Err(failed(tree, e)),
};
if !is_root {
match visit(tree, node, cgroup.as_fd()).map_err(Failure::Other)? {
Visit::Continue => {}
Visit::Skip => continue,
Visit::Stop => return Ok(Traversed::Stopped),
}
}
let listing = match step_fault(tree, node, WalkStep::List).and_then(|()| {
rustix::fs::openat(
&cgroup,
".",
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)
}) {
Ok(listing) => listing,
Err(e) if skippable(e) => continue,
Err(e) => return Err(failed(tree, e)),
};
let mut buf = [std::mem::MaybeUninit::<u8>::uninit(); LISTING_BUFFER];
let mut entries = rustix::fs::RawDir::new(&listing, &mut buf);
while let Some(entry) = entries.next() {
let entry = match step_fault(tree, node, WalkStep::Entries).and(entry) {
Ok(entry) => entry,
Err(e) if skippable(e) => break,
Err(e) => return Err(failed(tree, e)),
};
let name = entry.file_name();
if !matches!(name.to_bytes(), b"." | b"..")
&& is_dir(cgroup.as_fd(), entry.file_type(), name).map_err(Failure::Other)?
{
pending.push_back(tree.push(node, OsStr::from_bytes(name.to_bytes())));
}
}
if is_root && confirm_root {
step_fault(tree, node, WalkStep::Alive)
.and_then(|()| {
rustix::fs::openat(&cgroup, "cgroup.events", OFlags::PATH | OFlags::CLOEXEC, Mode::empty())
})
.map_err(|e| failed(tree, e))?;
}
}
Ok(Traversed::Listed { behind_a_mount })
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum WalkStep {
Open,
Id,
List,
Entries,
Alive,
}
fn step_fault(tree: &Tree, node: usize, step: WalkStep) -> rustix::io::Result<()> {
#[cfg(test)]
if let Some(errno) = super::fault::walk_step_failure(&tree.path(node), step) {
return Err(rustix::io::Errno::from_raw_os_error(errno));
}
let _ = (tree, node, step);
Ok(())
}
fn named(errno: rustix::io::Errno, tree: &Tree, node: usize) -> io::Error {
at_cgroup(io::Error::from(errno), tree, node)
}
fn at_cgroup(e: io::Error, tree: &Tree, node: usize) -> io::Error {
log::debug!("cgroup v2: {}: {e}", tree.path(node).display());
e
}
const LISTING_BUFFER: usize = 8192;
const PATH_MAX_BYTES: usize = libc::PATH_MAX as usize - 1;
fn pieces(names: &[&OsStr], max: usize) -> Vec<std::ops::Range<usize>> {
let mut runs = Vec::new();
let (mut start, mut len) = (0, 0);
for (i, name) in names.iter().enumerate() {
let joined = len + usize::from(i > start) + name.len();
if i > start && joined > max {
runs.push(start..i);
(start, len) = (i, name.len());
} else {
len = joined;
}
}
if start < names.len() {
runs.push(start..names.len());
}
runs
}
fn open_cgroup(dir: BorrowedFd<'_>, names: &[&OsStr]) -> rustix::io::Result<OwnedFd> {
use std::os::unix::ffi::OsStrExt as _;
debug_assert!(
names.iter().all(|n| {
let mut parts = std::path::Path::new(n).components();
matches!(parts.next(), Some(std::path::Component::Normal(_))) && parts.next().is_none()
}),
"every name is one plain path component: {names:?}"
);
let mut held: Option<OwnedFd> = None;
for run in pieces(names, PATH_MAX_BYTES) {
let mut piece = names[run.start].as_bytes().to_vec();
for name in &names[run.start + 1..run.end] {
piece.push(b'/');
piece.extend_from_slice(name.as_bytes());
}
let opened = open_beneath(held.as_ref().map_or(dir, AsFd::as_fd), OsStr::from_bytes(&piece))?;
held = Some(opened);
}
match held {
Some(held) => Ok(held),
None => open_beneath(dir, "."),
}
}
fn open_beneath(dir: BorrowedFd<'_>, path: impl rustix::path::Arg) -> rustix::io::Result<OwnedFd> {
use rustix::fs::ResolveFlags;
let fd = rustix::fs::openat2(
dir,
path,
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 gone(e: rustix::io::Errno) -> bool {
matches!(e, rustix::io::Errno::NOENT | rustix::io::Errno::NODEV)
}
fn gone_io(e: &io::Error) -> bool {
e.raw_os_error()
.is_some_and(|errno| gone(rustix::io::Errno::from_raw_os_error(errno)))
}
fn is_dir(at: BorrowedFd<'_>, file_type: rustix::fs::FileType, name: &std::ffi::CStr) -> io::Result<bool> {
Ok(match file_type {
rustix::fs::FileType::Directory => true,
rustix::fs::FileType::Unknown => match rustix::fs::statat(at, 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,
})
}
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 remove_children(dir: BorrowedFd<'_>, swept: &Swept) -> io::Result<usize> {
let mut found: Vec<(usize, Option<u64>)> = Vec::new();
let mut tree = Tree::new();
let traversed = traverse(&mut tree, dir, false, |tree, node, cgroup| {
let id = match cgroup_id(cgroup) {
Ok(id) => Some(id),
Err(e) if gone_io(&e) => return Ok(Visit::Skip),
Err(e) => {
log::debug!(
"cgroup v2: the id of child cgroup {} cannot be read ({e}); it is removed unrecorded",
tree.name(node).to_string_lossy()
);
None
}
};
found.push((node, id));
Ok(Visit::Continue)
});
let mut removed = 0;
for &(node, id) in found.iter().rev() {
#[cfg(test)]
super::fault::run_before_sweep_remove(&tree.path(node));
let parent = match open_cgroup(dir, &tree.names(tree.parent(node))) {
Ok(parent) => parent,
Err(e) if gone(e) => continue,
Err(e @ rustix::io::Errno::XDEV) => {
log::debug!(
"cgroup v2: {} is under a mount, so it is not removed ({e})",
tree.path(node).display()
);
continue;
}
Err(e) => return Err(e.into()),
};
match rustix::fs::unlinkat(&parent, tree.name(node), AtFlags::REMOVEDIR) {
Ok(()) => {
removed += 1;
if let Some(id) = id {
swept.record(id);
}
}
Err(e) if gone(e) => {}
Err(e @ rustix::io::Errno::BUSY) => {
log::debug!("cgroup v2: {} is busy, so it is left ({e})", tree.path(node).display());
}
Err(e) => return Err(e.into()),
}
}
match traversed {
Ok(_) => Ok(removed),
Err(Failure::RootGone(_)) => Ok(removed),
Err(Failure::Other(e)) => Err(e),
}
}
#[cfg(test)]
#[path = "dir_tests.rs"]
mod dir_tests;
#[cfg(test)]
#[path = "dir_walk_tests.rs"]
pub(crate) mod dir_walk_tests;
#[cfg(test)]
#[path = "dir_sweep_tests.rs"]
mod dir_sweep_tests;
#[cfg(test)]
#[path = "dir_pieces_tests.rs"]
mod dir_pieces_tests;