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
72
73
74
75
76
77
78
79
80
81
82
83
84
use crate::error::{Error, Result};
use crate::util::parse;
use std::os::unix::ffi::OsStrExt;
/// A single cgroup membership entry from `/proc/PID/cgroup`.
///
/// Each line describes one cgroup hierarchy the process belongs to:
/// ```text
/// 0::/
/// 1:name=systemd:/user.slice/user-1000.slice/session-1.scope
/// ```
///
/// With cgroup v2, there is typically a single entry with hierarchy
/// ID 0 and an empty controller list.
#[derive(Debug)]
pub struct CgroupEntry {
/// Hierarchy ID. For cgroup v2 unified hierarchy this is always 0.
pub hierarchy: u32,
/// Comma-separated list of controllers bound to this hierarchy.
///
/// Empty for the cgroup v2 unified hierarchy (controllers are
/// enabled per-cgroup, not per-hierarchy).
pub controllers: Vec<Box<str>>,
/// Cgroup path within the hierarchy.
pub path: std::path::PathBuf,
}
impl CgroupEntry {
/// Parses all lines of a `/proc/PID/cgroup` file.
pub fn from_bytes(bytes: &[u8]) -> Result<Vec<Self>> {
let mut entries = Vec::new();
for line in bytes.split(|&b| b == b'\n').filter(|l| !l.is_empty()) {
entries.push(Self::parse_line(line)?);
}
Ok(entries)
}
fn parse_line(line: &[u8]) -> Result<Self> {
// /proc/PID/cgroup uses colon-separated fields:
// hierarchy:controllers:path
let fields: Vec<&[u8]> = line.splitn(3, |&b| b == b':').collect();
if fields.len() < 3 {
return Err(Error::Parse {
path: std::path::PathBuf::from("<cgroup>"),
line: 0,
msg: "not enough fields",
});
}
let hierarchy = parse::parse_dec_u32_fast(fields[0])?;
// Controller list is comma-separated. An empty string means
// no controllers (cgroup v2 unified hierarchy).
let controllers_raw = fields[1];
let controllers: Vec<Box<str>> = if controllers_raw.is_empty() {
Vec::new()
} else {
controllers_raw
.split(|&b| b == b',')
.filter(|c| !c.is_empty())
.map(|c| {
std::str::from_utf8(c)
.map(str::to_owned)
.map(String::into_boxed_str)
.map_err(|_| Error::Parse {
path: std::path::PathBuf::from("<cgroup>"),
line: 0,
msg: "controller name is not valid UTF-8",
})
})
.collect::<Result<Vec<_>>>()?
};
let path = std::path::PathBuf::from(std::ffi::OsStr::from_bytes(fields[2]));
Ok(CgroupEntry {
hierarchy,
controllers,
path,
})
}
}