1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use std::path::Path;
use crate::error::{Error, Result};
use crate::util::parse;
/// System-wide cgroup hierarchy information from `/proc/cgroups`.
///
/// Lists each registered cgroup controller (subsystem) with its
/// hierarchy ID, number of cgroups, and enabled status.
#[derive(Debug)]
pub struct Cgroup {
/// Controller name (e.g. `cpu`, `memory`, `pids`).
pub subsys_name: Box<str>,
/// Hierarchy ID. Multiple controllers may share the same ID
/// if they are bound to the same hierarchy.
pub hierarchy: u32,
/// Number of cgroups in this hierarchy.
pub num_cgroups: u32,
/// Whether the controller is currently enabled.
pub enabled: bool,
}
/// Reads `/proc/cgroups` and returns all registered cgroup controllers.
///
/// The file has a one-line header followed by one line per controller:
/// ```text
/// #subsys_name hierarchy num_cgroups enabled
/// cpuset 2 1 1
/// cpu 3 42 1
/// memory 4 42 1
/// ```
pub fn cgroups() -> Result<Vec<Cgroup>> {
let path = Path::new("/proc/cgroups");
let bytes = parse::read_file(path)?;
let mut entries = Vec::new();
for line in bytes.split(|&b| b == b'\n').filter(|l| !l.is_empty()) {
// Skip the header line starting with '#'.
if line.starts_with(b"#") {
continue;
}
let fields: Vec<&[u8]> = parse::split_spaces(line);
if fields.len() < 4 {
return Err(Error::Parse {
path: path.to_path_buf(),
line: 0,
msg: "not enough fields",
});
}
let subsys_name = std::str::from_utf8(fields[0])
.unwrap_or("")
.to_string()
.into_boxed_str();
let hierarchy = parse::parse_dec_u32(fields[1]).unwrap_or(0);
let num_cgroups = parse::parse_dec_u32(fields[2]).unwrap_or(0);
let enabled = parse::parse_dec_u32(fields[3]).unwrap_or(0) != 0;
entries.push(Cgroup {
subsys_name,
hierarchy,
num_cgroups,
enabled,
});
}
Ok(entries)
}