Skip to main content

feldera_observability/
system.rs

1//! System introspection utilities.
2
3/// True when this process runs inside a Kubernetes pod.
4///
5/// Kubernetes injects `KUBERNETES_SERVICE_HOST` into every pod, and the
6/// pipeline manager rejects user-supplied `KUBERNETES_*` variables in the
7/// pipeline's `env` config.
8pub fn running_in_kubernetes() -> bool {
9    std::env::var_os("KUBERNETES_SERVICE_HOST").is_some()
10}
11
12/// Returns the memory, in megabytes (MB), of the current system, or `None`
13/// when the operating system does not report it.
14///
15/// This is the min of the host's available memory and the cgroup budget
16/// (what a container or Kubernetes pod memory limit sets).
17pub fn total_memory_megabyte() -> Option<u64> {
18    total_memory_bytes()
19        .map(|bytes| bytes / 1_000_000)
20        .filter(|&mb| mb > 0)
21}
22
23/// Same as [`total_memory_megabyte`], but in bytes.
24pub fn total_memory_bytes() -> Option<u64> {
25    let mut system = sysinfo::System::new();
26    system.refresh_memory();
27    let mut available = system.total_memory();
28    if let Some(limits) = own_cgroup_limits(&mut system).or_else(|| system.cgroup_limits()) {
29        available = available.min(limits.total_memory);
30    }
31    // `sysinfo` reports 0 on platforms it does not support.
32    if available > 0 { Some(available) } else { None }
33}
34
35/// Returns the limits of this process's own cgroup, including limits set on
36/// its parent cgroups. Unlike [`sysinfo::System::cgroup_limits`], this works
37/// without a cgroup namespace, where `/sys/fs/cgroup` is the host's root.
38fn own_cgroup_limits(system: &mut sysinfo::System) -> Option<sysinfo::CGroupLimits> {
39    let pid = sysinfo::get_current_pid().ok()?;
40    system.refresh_processes_specifics(
41        sysinfo::ProcessesToUpdate::Some(&[pid]),
42        false,
43        sysinfo::ProcessRefreshKind::nothing(),
44    );
45    system.process(pid)?.cgroup_limits()
46}
47
48#[cfg(test)]
49mod tests {
50    /// Guards the `sysinfo` call sequence (`cgroup_limits` panics when memory
51    /// was not refreshed first).
52    #[cfg(target_os = "linux")]
53    #[test]
54    fn reports_nonzero_memory() {
55        let mb = super::total_memory_megabyte().expect("Linux reports available memory");
56        assert!(mb > 0, "available memory must be positive, got {mb} MB");
57    }
58
59    /// Runs the real cgroup lookup, which the DBSP tests mock out.
60    #[cfg(target_os = "linux")]
61    #[test]
62    fn available_memory_is_at_most_host_memory() {
63        let mut system = sysinfo::System::new();
64        system.refresh_memory();
65        let bytes = super::total_memory_bytes().expect("Linux reports available memory");
66        assert!(
67            bytes <= system.total_memory(),
68            "available memory {bytes} exceeds host memory {}",
69            system.total_memory()
70        );
71    }
72}