#[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(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) 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 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 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;