Skip to main content

substrate_kit/
cgroup.rs

1//! `cgroup` — Namespace and cgroup resource-isolation primitives.
2//!
3//! **This slice's concrete target:** resolving the real cgroup path of an
4//! already-running process on the host, by pid — filling
5//! `principal::ContainerRef::cgroup`, which is unconditionally `None` until
6//! something actually resolves it. `lifecycle::Lifecycle::container_ref`
7//! is the caller that wires this in for a real dockerd container.
8//!
9//! **Scope boundary (hard constraint, same as every substrate-kit
10//! module):** this is OS mechanics only. It resolves *what a cgroup path
11//! is*, never *why* a cgroup limit is set to a given value or *who* should
12//! be allowed to see/change it — that's an authorization/policy question
13//! for identity-kit to answer, not this crate. See `principal.rs`'s
14//! module doc for the full hard-constraint statement.
15//!
16//! **Known limitation, not an oversight:** this resolver only understands
17//! the cgroup v2 unified hierarchy (`/proc/<pid>/cgroup`'s `0::<path>`
18//! line), matching the target hosts (dockerd with the systemd
19//! cgroup driver defaults to cgroup v2 on any reasonably current kernel).
20//! A cgroup v1 or hybrid host — no `0::` line present — resolves to
21//! [`SubstrateError::Resolve`] rather than guessing at a v1 controller
22//! hierarchy; broader support is real follow-up work if a v1 host ever
23//! needs to run this substrate.
24//!
25//! Full namespace/cgroup *isolation* primitives (creating/limiting a
26//! cgroup, not just reading one back) remain deferred; resource limits on a
27//! container are not yet part of `lifecycle::ContainerSpec` either.
28
29use crate::error::SubstrateError;
30
31/// The cgroup v2 unified hierarchy's standard mount point. Universal on
32/// every distro this substrate targets — not configurable here because
33/// none of its target hosts mounts cgroup v2 anywhere else.
34pub const CGROUP_V2_MOUNT: &str = "/sys/fs/cgroup";
35
36/// Resolve the real, absolute cgroup v2 path for a running process on the
37/// host, by pid.
38///
39/// Reads `/proc/<pid>/cgroup` — world-readable for any process on a normal
40/// Linux host, unlike `/proc/<pid>/ns/*` (see `mount::resolve_mount_namespace`'s
41/// doc for that contrast) — so this does not need elevated privilege to
42/// resolve another user's (e.g. a root-owned dockerd container's) cgroup.
43pub fn resolve_cgroup_path(pid: u32) -> Result<String, SubstrateError> {
44    let raw = std::fs::read_to_string(format!("/proc/{pid}/cgroup"))?;
45    let relative = parse_unified_cgroup_path(&raw).ok_or_else(|| {
46        SubstrateError::Resolve(format!(
47            "no cgroup v2 unified (`0::`) entry in /proc/{pid}/cgroup — \
48             cgroup v1/hybrid hosts are not resolved by this function"
49        ))
50    })?;
51    Ok(format!("{CGROUP_V2_MOUNT}{relative}"))
52}
53
54/// Extract the path component of `/proc/<pid>/cgroup`'s cgroup v2 unified
55/// hierarchy line (`0::<path>`). Cgroup v1/hybrid hosts emit additional
56/// numbered per-controller lines (`N:<controllers>:<path>`) that this
57/// deliberately ignores — see this module's doc for why.
58fn parse_unified_cgroup_path(raw: &str) -> Option<String> {
59    raw.lines()
60        .find_map(|line| line.strip_prefix("0::"))
61        .map(|s| s.to_string())
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67
68    #[test]
69    fn parse_unified_cgroup_path_extracts_the_v2_line() {
70        let raw = "0::/system.slice/docker-abc123.scope\n";
71        assert_eq!(
72            parse_unified_cgroup_path(raw),
73            Some("/system.slice/docker-abc123.scope".to_string())
74        );
75    }
76
77    #[test]
78    fn parse_unified_cgroup_path_is_none_without_a_v2_entry() {
79        // A cgroup v1/hybrid host's shape — numbered per-controller lines,
80        // no `0::` unified entry.
81        let raw = "12:memory:/docker/abc123\n11:cpu,cpuacct:/docker/abc123\n";
82        assert_eq!(parse_unified_cgroup_path(raw), None);
83    }
84
85    #[test]
86    #[cfg(target_os = "linux")]
87    fn resolve_cgroup_path_resolves_this_process_own_cgroup_for_real() {
88        // A real `/proc` read against this test process itself — no
89        // Docker needed for this sanity check. The container-based, real
90        // dockerd resolution is exercised by `lifecycle`'s live tests via
91        // `Lifecycle::container_ref`.
92        let pid = std::process::id();
93        let path = resolve_cgroup_path(pid).expect(
94            "resolve own cgroup path (fails on a cgroup v1/hybrid host — see this module's doc)",
95        );
96        assert!(
97            path.starts_with(CGROUP_V2_MOUNT),
98            "expected a path under {CGROUP_V2_MOUNT}, got: {path}"
99        );
100    }
101
102    #[test]
103    fn resolve_cgroup_path_fails_cleanly_for_a_nonexistent_pid() {
104        let bogus_pid = u32::MAX;
105        let err = resolve_cgroup_path(bogus_pid).expect_err("nonexistent pid must fail");
106        assert!(matches!(err, SubstrateError::Io(_)));
107    }
108}