1use std::fs;
2
3#[derive(Clone, Copy, Debug, Default)]
4pub struct Usage {
5 pub cpu_usec: u64,
6 pub mem_bytes: u64,
7}
8
9pub fn container_usage(root: &str, id: &str) -> Option<Usage> {
10 let candidates = [
11 format!("{root}/system.slice/docker-{id}.scope"),
12 format!("{root}/docker/{id}"),
13 format!("{root}/kubepods.slice/docker-{id}.scope"),
14 ];
15 candidates.iter().find_map(|dir| read_dir(dir))
16}
17
18fn read_dir(dir: &str) -> Option<Usage> {
19 let mem = fs::read_to_string(format!("{dir}/memory.current")).ok()?;
20 let cpu = fs::read_to_string(format!("{dir}/cpu.stat")).ok()?;
21 let cpu_usec = cpu
22 .lines()
23 .find_map(|l| l.strip_prefix("usage_usec "))
24 .and_then(|v| v.trim().parse().ok())?;
25 Some(Usage {
26 cpu_usec,
27 mem_bytes: mem.trim().parse().ok()?,
28 })
29}
30
31pub fn parse_stat_cpu(stat: &str) -> Option<u64> {
32 let line = stat.lines().next()?;
33 let mut it = line.split_whitespace();
34 if it.next()? != "cpu" {
35 return None;
36 }
37 let v: Vec<u64> = it.filter_map(|x| x.parse().ok()).collect();
38 if v.len() < 4 {
39 return None;
40 }
41 let busy = v[0]
42 + v[1]
43 + v[2]
44 + v.get(5).copied().unwrap_or(0)
45 + v.get(6).copied().unwrap_or(0)
46 + v.get(7).copied().unwrap_or(0);
47 Some(busy)
48}
49
50#[cfg(test)]
51mod tests {
52 use super::*;
53
54 #[test]
55 fn parses_proc_stat() {
56 let s = "cpu 100 0 50 800 10 0 5 0 0 0\ncpu0 1 1 1 1\n";
57 assert_eq!(parse_stat_cpu(s), Some(155));
58 }
59}