1use std::path::{Path, PathBuf};
12
13pub const ROOT: &str = "/sys/fs/cgroup";
15
16pub fn hierarchy_available() -> bool {
18 Path::new(ROOT).join("cgroup.controllers").exists()
19}
20
21#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct CgroupTarget {
24 pub name: String,
25 pub dir: PathBuf,
27}
28
29fn group_dir(path: &str) -> PathBuf {
32 if Path::new(path).starts_with(ROOT) {
33 PathBuf::from(path)
34 } else {
35 Path::new(ROOT).join(path.trim_start_matches('/'))
36 }
37}
38
39pub fn parse_cgroups(value: &str) -> Result<Vec<CgroupTarget>, String> {
43 let mut targets: Vec<CgroupTarget> = Vec::new();
44 for item in value.split(',').map(str::trim).filter(|i| !i.is_empty()) {
45 let Some((name, path)) = item.split_once(':') else {
46 return Err(format!("'{item}' is not `name:path`"));
47 };
48 let (name, path) = (name.trim(), path.trim());
49 if !crate::is_subject_name(name) {
50 return Err(format!(
51 "'{name}' is not a name; a name is letters, digits, `_` and `-`"
52 ));
53 }
54 if targets.iter().any(|t| t.name == name) {
55 return Err(format!("the name '{name}' is given twice"));
56 }
57 if path.is_empty() {
58 return Err(format!("'{name}' has no control group path"));
59 }
60 targets.push(CgroupTarget {
61 name: name.to_string(),
62 dir: group_dir(path),
63 });
64 }
65 Ok(targets)
66}
67
68#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct CgroupIo {
71 pub device: String,
74 pub read_bytes: u64,
75 pub write_bytes: u64,
76 pub reads: u64,
77 pub writes: u64,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, Default)]
84pub struct CgroupCounters {
85 pub cpu_usec: Option<u64>,
87 pub mem_bytes: Option<u64>,
88 pub io: Vec<CgroupIo>,
89}
90
91pub fn parse_cpu_stat(text: &str) -> Option<u64> {
93 text.lines()
94 .find_map(|line| line.strip_prefix("usage_usec "))?
95 .trim()
96 .parse()
97 .ok()
98}
99
100pub fn parse_io_stat(text: &str, devices: &[((u32, u32), String)]) -> Vec<CgroupIo> {
104 text.lines()
105 .filter_map(|line| {
106 let mut tokens = line.split_whitespace();
107 let number = tokens.next()?;
108 let (major, minor) = number.split_once(':')?;
109 let number_pair: (u32, u32) = (major.parse().ok()?, minor.parse().ok()?);
110 let pairs: Vec<(&str, u64)> = tokens
111 .filter_map(|t| {
112 let (key, value) = t.split_once('=')?;
113 Some((key, value.parse().ok()?))
114 })
115 .collect();
116 let value = |key: &str| pairs.iter().find(|(k, _)| *k == key).map(|(_, v)| *v);
117 Some(CgroupIo {
118 device: devices
119 .iter()
120 .find(|(n, _)| *n == number_pair)
121 .map(|(_, name)| name.clone())
122 .unwrap_or_else(|| number.to_string()),
123 read_bytes: value("rbytes")?,
124 write_bytes: value("wbytes")?,
125 reads: value("rios")?,
126 writes: value("wios")?,
127 })
128 })
129 .collect()
130}
131
132pub fn read_counters(dir: &Path, devices: &[((u32, u32), String)]) -> Option<CgroupCounters> {
134 if !dir.is_dir() {
135 return None;
136 }
137 let read = |file: &str| std::fs::read_to_string(dir.join(file)).ok();
138 Some(CgroupCounters {
139 cpu_usec: read("cpu.stat").and_then(|t| parse_cpu_stat(&t)),
140 mem_bytes: read("memory.current").and_then(|t| t.trim().parse().ok()),
141 io: read("io.stat")
142 .map(|t| parse_io_stat(&t, devices))
143 .unwrap_or_default(),
144 })
145}
146
147#[derive(Debug, Clone, PartialEq)]
149pub struct CgroupIoRate {
150 pub device: String,
151 pub read_bytes_per_s: f64,
152 pub write_bytes_per_s: f64,
153 pub read_ops_per_s: f64,
154 pub write_ops_per_s: f64,
155}
156
157#[derive(Debug, Clone, PartialEq)]
159pub struct CgroupReading {
160 pub name: String,
161 pub cpu_cores: Option<f64>,
163 pub mem_bytes: Option<f64>,
164 pub io: Vec<CgroupIoRate>,
166}
167
168pub fn reading(
171 name: &str,
172 prev: &CgroupCounters,
173 cur: &CgroupCounters,
174 dt_s: f64,
175) -> CgroupReading {
176 let per_s = |before: u64, now: u64| -> f64 {
177 if dt_s <= 0.0 {
178 0.0
179 } else {
180 now.saturating_sub(before) as f64 / dt_s
181 }
182 };
183 CgroupReading {
184 name: name.to_string(),
185 cpu_cores: match (prev.cpu_usec, cur.cpu_usec) {
186 (Some(before), Some(now)) => Some(per_s(before, now) / 1e6),
187 _ => None,
188 },
189 mem_bytes: cur.mem_bytes.map(|b| b as f64),
190 io: cur
191 .io
192 .iter()
193 .filter_map(|now| {
194 let before = prev.io.iter().find(|d| d.device == now.device)?;
195 Some(CgroupIoRate {
196 device: now.device.clone(),
197 read_bytes_per_s: per_s(before.read_bytes, now.read_bytes),
198 write_bytes_per_s: per_s(before.write_bytes, now.write_bytes),
199 read_ops_per_s: per_s(before.reads, now.reads),
200 write_ops_per_s: per_s(before.writes, now.writes),
201 })
202 })
203 .collect(),
204 }
205}
206
207pub struct WatchedCgroup {
210 pub target: CgroupTarget,
211 last: Option<CgroupCounters>,
212 missing_reported: bool,
215}
216
217impl WatchedCgroup {
218 pub fn new(target: CgroupTarget) -> Self {
219 Self {
220 target,
221 last: None,
222 missing_reported: false,
223 }
224 }
225
226 pub fn sample(
231 &mut self,
232 dt_s: f64,
233 devices: &[((u32, u32), String)],
234 missing: &mut dyn FnMut(&str),
235 ) -> Option<CgroupReading> {
236 let Some(cur) = read_counters(&self.target.dir, devices) else {
237 if !self.missing_reported {
238 self.missing_reported = true;
239 missing(&self.target.name);
240 }
241 self.last = None;
242 return None;
243 };
244 self.missing_reported = false;
245 let prev = self.last.replace(cur.clone())?;
246 Some(reading(&self.target.name, &prev, &cur, dt_s))
247 }
248}
249
250#[cfg(test)]
251mod tests {
252 use super::*;
253
254 #[test]
255 fn groups_are_names_with_a_path_under_the_hierarchy() {
256 assert_eq!(
257 parse_cgroups("node:system.slice/db.service, me:/sys/fs/cgroup/user.slice").unwrap(),
258 vec![
259 CgroupTarget {
260 name: "node".into(),
261 dir: "/sys/fs/cgroup/system.slice/db.service".into()
262 },
263 CgroupTarget {
264 name: "me".into(),
265 dir: "/sys/fs/cgroup/user.slice".into()
266 },
267 ]
268 );
269 assert_eq!(
271 parse_cgroups("a:/system.slice").unwrap()[0].dir,
272 PathBuf::from("/sys/fs/cgroup/system.slice")
273 );
274 for (value, says) in [
275 ("node", "is not `name:path`"),
276 ("a b:x", "is not a name"),
277 ("a:x,a:y", "given twice"),
278 ("a:", "no control group path"),
279 ] {
280 let err = parse_cgroups(value).unwrap_err();
281 assert!(err.contains(says), "{value}: {err}");
282 }
283 }
284
285 #[test]
286 fn cpu_stat_gives_the_time_taken() {
287 let text = "usage_usec 2500000\nuser_usec 2000000\nsystem_usec 500000\n";
288 assert_eq!(parse_cpu_stat(text), Some(2_500_000));
289 assert_eq!(parse_cpu_stat("user_usec 1\n"), None);
290 }
291
292 #[test]
295 fn io_stat_is_read_per_device() {
296 let devices = vec![((259, 0), "nvme0n1".to_string())];
297 let text = "\
298259:0 rbytes=4096 wbytes=8192 rios=1 wios=2 dbytes=0 dios=0
2999:127 rbytes=10 wbytes=20 rios=3 wios=4 dbytes=0 dios=0
3008:0
301";
302 assert_eq!(
303 parse_io_stat(text, &devices),
304 vec![
305 CgroupIo {
306 device: "nvme0n1".into(),
307 read_bytes: 4096,
308 write_bytes: 8192,
309 reads: 1,
310 writes: 2,
311 },
312 CgroupIo {
313 device: "9:127".into(),
314 read_bytes: 10,
315 write_bytes: 20,
316 reads: 3,
317 writes: 4,
318 },
319 ]
320 );
321 }
322
323 #[test]
326 fn a_reading_is_the_difference_over_the_window() {
327 let io = |device: &str, write_bytes| CgroupIo {
328 device: device.into(),
329 read_bytes: 0,
330 write_bytes,
331 reads: 0,
332 writes: 0,
333 };
334 let prev = CgroupCounters {
335 cpu_usec: Some(1_000_000),
336 mem_bytes: Some(10),
337 io: vec![io("sda", 1000)],
338 };
339 let cur = CgroupCounters {
340 cpu_usec: Some(3_000_000),
341 mem_bytes: Some(4096),
342 io: vec![io("sda", 5000), io("sdb", 7)],
343 };
344 let got = reading("node", &prev, &cur, 2.0);
345 assert_eq!(got.cpu_cores, Some(1.0));
346 assert_eq!(got.mem_bytes, Some(4096.0));
347 assert_eq!(got.io.len(), 1);
348 assert_eq!(got.io[0].write_bytes_per_s, 2000.0);
349
350 let off = reading(
351 "node",
352 &CgroupCounters::default(),
353 &CgroupCounters::default(),
354 2.0,
355 );
356 assert_eq!(
357 (off.cpu_cores, off.mem_bytes, off.io.len()),
358 (None, None, 0)
359 );
360 }
361
362 #[test]
364 fn a_missing_group_is_said_once() {
365 let mut watched = WatchedCgroup::new(CgroupTarget {
366 name: "gone".into(),
367 dir: "/sys/fs/cgroup/no-such-group-for-this-test".into(),
368 });
369 let mut said = 0;
370 for _ in 0..3 {
371 assert!(watched.sample(1.0, &[], &mut |_| said += 1).is_none());
372 }
373 assert_eq!(said, 1);
374 }
375
376 #[cfg(target_os = "linux")]
379 #[test]
380 fn the_own_group_is_read() {
381 if !hierarchy_available() {
382 return;
383 }
384 let own = std::fs::read_to_string("/proc/self/cgroup").unwrap();
385 let Some(path) = own.lines().find_map(|line| line.strip_prefix("0::")) else {
386 return;
387 };
388 let mut watched =
389 WatchedCgroup::new(parse_cgroups(&format!("me:{path}")).unwrap().remove(0));
390 let mut missing = |name: &str| panic!("{name} reported missing");
391 assert!(watched.sample(1.0, &[], &mut missing).is_none());
392 assert_eq!(watched.sample(1.0, &[], &mut missing).unwrap().name, "me");
393 }
394}