#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(crate) fn parse_v2_relative_path(proc_self_cgroup: &str) -> Option<&str> {
for line in proc_self_cgroup.lines() {
if let Some(rest) = line.strip_prefix("0::") {
return Some(rest);
}
}
None
}
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(crate) fn cgroup_procs_contains(contents: &str, pid: u32) -> bool {
for line in contents.lines() {
if let Ok(p) = line.trim().parse::<u32>() {
if p == pid {
return true;
}
}
}
false
}
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(crate) fn parse_populated(contents: &str) -> Option<bool> {
for line in contents.lines() {
if let Some(rest) = line.strip_prefix("populated ") {
return match rest.trim() {
"0" => Some(false),
"1" => Some(true),
_ => None,
};
}
}
None
}
#[cfg(target_os = "linux")]
use std::fs::{self, File, OpenOptions};
#[cfg(target_os = "linux")]
use std::io;
#[cfg(target_os = "linux")]
use std::os::fd::{IntoRawFd, RawFd};
#[cfg(target_os = "linux")]
use std::path::{Path, PathBuf};
#[cfg(target_os = "linux")]
use std::sync::atomic::{AtomicU64, Ordering};
#[cfg(target_os = "linux")]
static SEQ: AtomicU64 = AtomicU64::new(0);
#[cfg(target_os = "linux")]
use nix::sys::signal::{kill, Signal};
#[cfg(target_os = "linux")]
use nix::unistd::Pid;
#[cfg(target_os = "linux")]
pub(crate) fn removed_after_drain(e: &io::Error) -> bool {
matches!(e.raw_os_error(), Some(libc::ENODEV) | Some(libc::ENOENT))
}
#[cfg(target_os = "linux")]
pub(crate) fn read_populated(file: &mut File, buf: &mut String) -> Result<bool, crate::error::Error> {
use std::io::{Read, Seek, SeekFrom};
buf.clear();
if let Err(e) = file.seek(SeekFrom::Start(0)) {
return if removed_after_drain(&e) {
Ok(false)
} else {
Err(crate::error::Error::Io(e))
};
}
if let Err(e) = file.read_to_string(buf) {
return if removed_after_drain(&e) {
Ok(false)
} else {
Err(crate::error::Error::Io(e))
};
}
parse_populated(buf).ok_or_else(|| {
crate::error::Error::Io(io::Error::other(
"cgroup.events has no 'populated' field — unexpected kernel format",
))
})
}
#[cfg(target_os = "linux")]
pub(crate) struct CgroupLeaf {
leaf_path: PathBuf,
procs_fd: RawFd,
}
#[cfg(target_os = "linux")]
unsafe impl Send for CgroupLeaf {}
#[cfg(target_os = "linux")]
impl CgroupLeaf {
pub(crate) fn procs_fd(&self) -> RawFd {
self.procs_fd
}
pub(crate) fn events_path(&self) -> PathBuf {
self.leaf_path.join("cgroup.events")
}
pub(crate) fn contains_pid(&self, pid: u32) -> bool {
match fs::read_to_string(self.leaf_path.join("cgroup.procs")) {
Ok(contents) => cgroup_procs_contains(&contents, pid),
Err(_) => false,
}
}
pub(crate) fn hard_kill(&self) {
let _ = fs::write(self.leaf_path.join("cgroup.kill"), b"1");
}
pub(crate) fn wait_drained(
&self,
deadline: Option<Option<std::time::Instant>>,
) -> Result<crate::containment::TreeDrain, crate::error::Error> {
use rustix::event::{poll, PollFd, PollFlags};
use crate::containment::TreeDrain;
use crate::error::Error;
let mut file = match File::open(self.events_path()) {
Ok(f) => f,
Err(e) if removed_after_drain(&e) => return Ok(TreeDrain::AllMembersExited),
Err(e) => return Err(Error::Io(e)),
};
let mut buf = String::new();
loop {
if !read_populated(&mut file, &mut buf)? {
return Ok(TreeDrain::AllMembersExited);
}
let remaining = crate::wait::remaining(deadline);
if remaining == Some(std::time::Duration::ZERO) {
return Ok(TreeDrain::MembersRemain);
}
let ts = remaining.map(|d| rustix::event::Timespec {
tv_sec: d.as_secs().min(i64::MAX as u64) as i64,
tv_nsec: d.subsec_nanos() as _,
});
let mut fds = [PollFd::new(&file, PollFlags::PRI)];
match poll(&mut fds, ts.as_ref()) {
Ok(0) => return Ok(TreeDrain::MembersRemain), Ok(_) => continue, Err(rustix::io::Errno::INTR) => continue,
Err(e) => return Err(Error::Io(io::Error::from(e))),
}
}
}
pub(crate) fn terminate(&self) -> io::Result<()> {
let content = fs::read_to_string(self.leaf_path.join("cgroup.procs"))?;
for line in content.lines() {
if let Ok(pid) = line.trim().parse::<i32>() {
let _ = kill(Pid::from_raw(pid), Signal::SIGTERM);
}
}
Ok(())
}
}
#[cfg(all(target_os = "linux", test))]
impl CgroupLeaf {
pub(crate) fn placeholder_for_test() -> CgroupLeaf {
CgroupLeaf {
leaf_path: PathBuf::from("/nonexistent/cosca-cgroup-placeholder"),
procs_fd: -1,
}
}
}
#[cfg(target_os = "linux")]
impl Drop for CgroupLeaf {
fn drop(&mut self) {
unsafe { libc::close(self.procs_fd) };
if fs::remove_dir(&self.leaf_path).is_err() {
let _ = fs::write(self.leaf_path.join("cgroup.kill"), b"1");
let _ = fs::remove_dir(&self.leaf_path);
}
}
}
#[cfg(target_os = "linux")]
pub(crate) fn try_create_leaf() -> Option<CgroupLeaf> {
let cgroup_file = fs::read_to_string("/proc/self/cgroup").ok()?;
let rel_path = parse_v2_relative_path(&cgroup_file)?;
let current = Path::new("/sys/fs/cgroup").join(rel_path.trim_start_matches('/'));
let seq = SEQ.fetch_add(1, Ordering::Relaxed);
let leaf_name = format!("cosca-{}-{}", unsafe { libc::getpid() }, seq);
let leaf_path = current.join(&leaf_name);
fs::create_dir(&leaf_path).ok()?;
if !leaf_path.join("cgroup.kill").exists() {
let _ = fs::remove_dir(&leaf_path);
return None;
}
let procs_file: File = OpenOptions::new()
.write(true)
.open(leaf_path.join("cgroup.procs"))
.ok()?;
let procs_fd = procs_file.into_raw_fd();
let flags = unsafe { libc::fcntl(procs_fd, libc::F_GETFD) };
if flags == -1 {
unsafe { libc::close(procs_fd) };
let _ = fs::remove_dir(&leaf_path);
return None;
}
if unsafe { libc::fcntl(procs_fd, libc::F_SETFD, flags & !libc::FD_CLOEXEC) } == -1 {
unsafe { libc::close(procs_fd) };
let _ = fs::remove_dir(&leaf_path);
return None;
}
Some(CgroupLeaf { leaf_path, procs_fd })
}
#[cfg(target_os = "linux")]
pub(crate) unsafe fn place_self_in_cgroup_pre_exec(procs_fd: RawFd) -> io::Result<()> {
static ZERO: &[u8] = b"0";
let ret = unsafe { libc::write(procs_fd, ZERO.as_ptr().cast(), ZERO.len()) };
unsafe { libc::close(procs_fd) };
if ret == -1 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
#[cfg(test)]
#[path = "cgroup_tests.rs"]
mod cgroup_tests;