Skip to main content

feldera_observability/
system.rs

1//! System introspection utilities.
2
3use std::fs;
4use std::path::{Path, PathBuf};
5
6/// Returns the memory, in megabytes (MB), of the current system, or `None`
7/// when the operating system does not report it.
8///
9/// This is the min of the host's available memory and the cgroup budget
10/// (what a container or Kubernetes pod memory limit sets).
11pub fn total_memory_megabyte() -> Option<u64> {
12    total_memory_bytes()
13        .map(|bytes| bytes / 1_000_000)
14        .filter(|&mb| mb > 0)
15}
16
17/// Same as [`total_memory_megabyte`], but in bytes.
18pub fn total_memory_bytes() -> Option<u64> {
19    let mut system = sysinfo::System::new();
20    system.refresh_memory();
21    let mut available = system.total_memory();
22    if let Some(limits) = own_cgroup_limits(&mut system).or_else(|| system.cgroup_limits()) {
23        available = available.min(limits.total_memory);
24    }
25    // `sysinfo` reports 0 on platforms it does not support.
26    if available > 0 { Some(available) } else { None }
27}
28
29/// Returns the resident set size of this process, in bytes, or `None` when the
30/// operating system does not report it.
31pub fn process_rss_bytes() -> Option<u64> {
32    memory_stats::memory_stats().map(|usage| usage.physical_mem as u64)
33}
34
35/// Memory use and limit of a cgroup v2 cgroup.
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub struct CgroupMemory {
38    /// `memory.max`, or `None` when the cgroup has no limit.
39    pub max: Option<u64>,
40    /// `memory.current`, which counts page cache too.
41    pub current: u64,
42    /// `file` in `memory.stat`: the page cache.
43    pub file: u64,
44}
45
46/// This process's own cgroup v2 cgroup.
47#[derive(Clone, Debug)]
48pub struct Cgroup {
49    dir: PathBuf,
50}
51
52impl Cgroup {
53    /// Returns this process's cgroup, or `None` without cgroup v2.
54    pub fn own() -> Option<Self> {
55        let cgroups = fs::read_to_string("/proc/self/cgroup").ok()?;
56        let path = cgroup_v2_path(&cgroups)?;
57        Some(Self::at(
58            Path::new("/sys/fs/cgroup").join(path.trim_start_matches('/')),
59        ))
60    }
61
62    /// Returns the cgroup whose files are in `dir`.
63    pub fn at(dir: PathBuf) -> Self {
64        Self { dir }
65    }
66
67    fn read(&self, name: &str) -> Option<String> {
68        fs::read_to_string(self.dir.join(name)).ok()
69    }
70
71    /// Returns `memory.current`, which is cheaper to read than
72    /// [`Self::memory`].
73    pub fn memory_current(&self) -> Option<u64> {
74        self.read("memory.current")?.trim().parse().ok()
75    }
76
77    /// Returns the cgroup's memory use and limit.
78    pub fn memory(&self) -> Option<CgroupMemory> {
79        let max = match self.read("memory.max")?.trim() {
80            "max" => None,
81            max => Some(max.parse().ok()?),
82        };
83        let file = self
84            .read("memory.stat")?
85            .lines()
86            .find_map(|line| line.strip_prefix("file ")?.parse().ok())?;
87        Some(CgroupMemory {
88            max,
89            current: self.memory_current()?,
90            file,
91        })
92    }
93}
94
95/// Returns the cgroup v2 path in `cgroups`, the contents of `/proc/self/cgroup`.
96fn cgroup_v2_path(cgroups: &str) -> Option<&str> {
97    cgroups.lines().find_map(|line| line.strip_prefix("0::"))
98}
99
100/// Returns the limits of this process's own cgroup, including limits set on
101/// its parent cgroups. Unlike [`sysinfo::System::cgroup_limits`], this works
102/// without a cgroup namespace, where `/sys/fs/cgroup` is the host's root.
103fn own_cgroup_limits(system: &mut sysinfo::System) -> Option<sysinfo::CGroupLimits> {
104    let pid = sysinfo::get_current_pid().ok()?;
105    system.refresh_processes_specifics(
106        sysinfo::ProcessesToUpdate::Some(&[pid]),
107        false,
108        sysinfo::ProcessRefreshKind::nothing(),
109    );
110    system.process(pid)?.cgroup_limits()
111}
112
113#[cfg(test)]
114mod tests {
115    use super::{Cgroup, CgroupMemory, cgroup_v2_path};
116
117    #[test]
118    fn finds_the_cgroup_v2_path() {
119        assert_eq!(cgroup_v2_path("0::/\n"), Some("/"));
120        assert_eq!(
121            cgroup_v2_path("1:name=systemd:/a\n0::/kubepods/pod1/c1\n"),
122            Some("/kubepods/pod1/c1")
123        );
124        assert_eq!(cgroup_v2_path("4:memory:/docker/c1\n"), None);
125    }
126
127    #[test]
128    fn reads_cgroup_memory() {
129        let dir = tempfile::tempdir().unwrap();
130        let write = |name: &str, contents: &str| std::fs::write(dir.path().join(name), contents);
131        let cgroup = Cgroup::at(dir.path().to_path_buf());
132        assert_eq!(cgroup.memory(), None);
133
134        write("memory.max", "max\n").unwrap();
135        write("memory.current", "3000\n").unwrap();
136        write("memory.stat", "anon 1000\nfile 2000\nfile_mapped 10\n").unwrap();
137        assert_eq!(cgroup.memory_current(), Some(3000));
138        assert_eq!(
139            cgroup.memory(),
140            Some(CgroupMemory {
141                max: None,
142                current: 3000,
143                file: 2000,
144            })
145        );
146
147        write("memory.max", "4096\n").unwrap();
148        assert_eq!(cgroup.memory().unwrap().max, Some(4096));
149    }
150
151    /// Guards the `sysinfo` call sequence (`cgroup_limits` panics when memory
152    /// was not refreshed first).
153    #[cfg(target_os = "linux")]
154    #[test]
155    fn reports_nonzero_memory() {
156        let mb = super::total_memory_megabyte().expect("Linux reports available memory");
157        assert!(mb > 0, "available memory must be positive, got {mb} MB");
158    }
159
160    /// A running process always has a resident set.
161    #[cfg(any(target_os = "linux", target_os = "macos"))]
162    #[test]
163    fn reports_the_resident_set_of_this_process() {
164        let bytes = super::process_rss_bytes().expect("Linux and macOS report the resident set");
165        assert!(
166            bytes > 0,
167            "the resident set must be positive, got {bytes} bytes"
168        );
169    }
170
171    /// Runs the real cgroup lookup, which the DBSP tests mock out.
172    #[cfg(target_os = "linux")]
173    #[test]
174    fn available_memory_is_at_most_host_memory() {
175        let mut system = sysinfo::System::new();
176        system.refresh_memory();
177        let bytes = super::total_memory_bytes().expect("Linux reports available memory");
178        assert!(
179            bytes <= system.total_memory(),
180            "available memory {bytes} exceeds host memory {}",
181            system.total_memory()
182        );
183    }
184}