use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use super::*;
const PROC_SELF_CGROUP: &str = "/proc/self/cgroup";
const CGROUP_ROOT: &str = "/sys/fs/cgroup";
#[derive(Debug)]
pub(crate) struct OwnCgroup {
rel_path: String,
dir: PathBuf,
}
impl OwnCgroup {
pub(super) fn rel_path(&self) -> &str {
&self.rel_path
}
pub(super) fn dir(&self) -> &Path {
&self.dir
}
}
fn find_in(file: io::Result<String>, root: &Path) -> Result<OwnCgroup, LeafError> {
let file = file.map_err(LeafError::ReadProcSelfCgroup)?;
let rel_path = parse_v2_relative_path(&file).ok_or_else(|| {
let (line_count, controllers) = summarize_cgroup_controllers(&file);
LeafError::NoUnifiedLine {
line_count,
controllers,
}
})?;
Ok(OwnCgroup {
dir: root.join(rel_path.trim_start_matches('/')),
rel_path: rel_path.to_owned(),
})
}
pub(super) fn find_own_cgroup() -> Result<OwnCgroup, LeafError> {
#[cfg(test)]
if let Some((file, root)) = fault::take_force_own_cgroup() {
return find_in(Ok(file), &root);
}
find_in(fs::read_to_string(PROC_SELF_CGROUP), Path::new(CGROUP_ROOT))
}
pub(crate) fn offered_cgroup() -> Result<Option<OwnCgroup>, LeafError> {
offered_from(find_own_cgroup())
}
fn offered_from(found: Result<OwnCgroup, LeafError>) -> Result<Option<OwnCgroup>, LeafError> {
match found {
Ok(own) => Ok(Some(own)),
Err(LeafError::ReadProcSelfCgroup(e)) if e.kind() == io::ErrorKind::NotFound => {
log::debug!("cgroup v2: no /proc/self/cgroup, so no cgroup is offered");
Ok(None)
}
Err(e @ LeafError::NoUnifiedLine { .. }) => {
log::debug!(
"cgroup v2: no cgroup is offered: {report}",
report = crate::error::Report(&e)
);
Ok(None)
}
Err(e) => Err(e),
}
}
pub(crate) fn leaf_if_offered(
offered: Result<Option<OwnCgroup>, LeafError>,
kernel: &crate::identity::SpawnKernel,
teardown_warn_after: Option<std::time::Duration>,
) -> Result<Option<CgroupLeaf>, crate::error::Error> {
let Some(own) = offered.map_err(LeafError::into_containment)? else {
return Ok(None);
};
let e = match create_leaf_in(&own, kernel, teardown_warn_after) {
Ok(leaf) => return Ok(Some(leaf)),
Err(e) => e,
};
let refused = |source: &io::Error, missing_too: bool| {
matches!(source.raw_os_error(), Some(libc::EACCES | libc::EPERM | libc::EROFS))
|| (missing_too && source.raw_os_error() == Some(libc::ENOENT))
};
let not_offered = match &e {
LeafError::KillUnsupported { .. } => true,
LeafError::OpenOwnCgroup { source, .. } => refused(source, true),
LeafError::CreateLeafDir { source, .. } | LeafError::OpenProcs { source, .. } => refused(source, false),
_ => false,
};
if not_offered {
log::debug!(
"cgroup v2: no cgroup is offered: {report}",
report = crate::error::Report(&e)
);
return Ok(None);
}
Err(e.into_containment())
}
#[cfg(test)]
#[path = "own_tests.rs"]
mod own_tests;