shadow_rs/core/
resource_usage.rs

1//! Utilities for getting system resource usage.
2
3use std::fs::File;
4use std::io::{Read, Seek};
5
6use serde::Serialize;
7
8/// Memory usage information parsed from '/proc/meminfo'. All units are converted to bytes.
9#[derive(Copy, Clone, Debug, Default, Serialize)]
10pub struct MemInfo {
11    mem_total: Option<u64>,
12    mem_free: Option<u64>,
13    swap_total: Option<u64>,
14    swap_free: Option<u64>,
15    buffers: Option<u64>,
16    cached: Option<u64>,
17    s_reclaimable: Option<u64>,
18    shmem: Option<u64>,
19}
20
21/// Collects some of the fields from '/proc/meminfo'. This function will seek to the start of the
22/// file before reading.
23pub fn meminfo(file: &mut File) -> std::io::Result<MemInfo> {
24    let mut buffer = String::new();
25    file.rewind()?;
26    file.read_to_string(&mut buffer)?;
27
28    let lines = buffer.lines().filter_map(|line| {
29        let Some((name, val)) = line.split_once(':') else {
30            // don't know how to parse this line
31            return None;
32        };
33
34        let name = name.trim();
35        let val = val.trim();
36
37        let (val, unit) = val
38            .rsplit_once(' ')
39            .map(|(x, y)| (x, Some(y)))
40            .unwrap_or((val, None));
41
42        Some((name, val, unit))
43    });
44
45    let mut mem = MemInfo::default();
46
47    for (name, val, unit) in lines {
48        let Some(val) = val.parse().ok() else {
49            // expected an integer
50            continue;
51        };
52
53        match name {
54            "MemTotal" => mem.mem_total = as_base_unit(val, unit),
55            "MemFree" => mem.mem_free = as_base_unit(val, unit),
56            "SwapTotal" => mem.swap_total = as_base_unit(val, unit),
57            "SwapFree" => mem.swap_free = as_base_unit(val, unit),
58            "Buffers" => mem.buffers = as_base_unit(val, unit),
59            "Cached" => mem.cached = as_base_unit(val, unit),
60            "SReclaimable" => mem.s_reclaimable = as_base_unit(val, unit),
61            "Shmem" => mem.shmem = as_base_unit(val, unit),
62            _ => {}
63        }
64    }
65
66    Ok(mem)
67}
68
69/// Returns `None` if either the `unit` wasn't known, or the base unit is too large.
70fn as_base_unit(val: u64, unit: Option<&str>) -> Option<u64> {
71    let mul = match unit {
72        None => 1,
73        Some("B") => 1,
74        Some("kB") => 1024,
75        Some(_) => return None,
76    };
77
78    val.checked_mul(mul)
79}