Skip to main content

nmbrs_runtime/sysmon/
sampler.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! The sampler task: read each enabled subsystem once per interval,
5//! and publish the window to the session's gauges and the observer.
6
7use std::sync::{Arc, RwLock};
8use std::time::Instant;
9
10use nmbrs_metrics::component::Component;
11
12use nmbrs_host::category::Categories;
13use nmbrs_host::cgroup::WatchedCgroup;
14use nmbrs_host::process::{OWN_NAME, ProcSource, ProcTarget, Watched};
15use nmbrs_host::{cpu, disk, mem, net, pressure, process};
16
17use super::gauges::Gauges;
18use super::{SysmonConfig, SysmonSample};
19
20/// What the last window left behind for the next one to take a
21/// difference against.
22struct Previous {
23    at: Instant,
24    disks: Vec<disk::DiskCounters>,
25    cpu: Option<(cpu::CpuTicks, Vec<cpu::CpuTicks>)>,
26    membw: Option<u64>,
27    net: Vec<net::NetCounters>,
28    pressure: Option<pressure::PressureTotals>,
29    procs: Vec<Watched>,
30    proc_units: (f64, f64),
31    cgroups: Vec<WatchedCgroup>,
32}
33
34impl Previous {
35    /// The first reading, taken when the sampler starts.
36    fn first(config: &SysmonConfig) -> Self {
37        let cats = config.cats;
38        let mut procs = Vec::new();
39        if cats.proc {
40            procs.push(Watched::new(ProcTarget {
41                name: OWN_NAME.to_string(),
42                source: ProcSource::Own,
43            }));
44            procs.extend(config.procs.iter().cloned().map(Watched::new));
45        }
46        let mut previous = Self {
47            at: Instant::now(),
48            disks: if cats.io {
49                disk::read_diskstats()
50            } else {
51                Vec::new()
52            },
53            cpu: if cats.cpu {
54                cpu::read_proc_stat()
55            } else {
56                None
57            },
58            membw: if cats.rambw {
59                mem::read_membw_bytes()
60            } else {
61                None
62            },
63            net: if cats.net {
64                net::read_net_dev()
65            } else {
66                Vec::new()
67            },
68            pressure: if cats.pressure {
69                pressure::read_pressure()
70            } else {
71                None
72            },
73            procs,
74            proc_units: process::units(),
75            cgroups: if cats.cgroup {
76                config
77                    .cgroups
78                    .iter()
79                    .cloned()
80                    .map(WatchedCgroup::new)
81                    .collect()
82            } else {
83                Vec::new()
84            },
85        };
86        // The first read of a process or a group has no window; it
87        // only sets the counters the next one is measured from.
88        previous.sample_procs(0.0);
89        previous.sample_cgroups(0.0);
90        previous
91    }
92
93    fn sample_cgroups(&mut self, dt_s: f64) -> Vec<nmbrs_host::cgroup::CgroupReading> {
94        if self.cgroups.is_empty() {
95            return Vec::new();
96        }
97        let devices = disk::read_device_numbers();
98        let mut missing = |name: &str| {
99            crate::diag!(
100                crate::observer::LogLevel::Warn,
101                "sysmon: control group '{name}' is not there; it has no series until it is"
102            );
103        };
104        self.cgroups
105            .iter_mut()
106            .filter_map(|watched| watched.sample(dt_s, &devices, &mut missing))
107            .collect()
108    }
109
110    fn sample_procs(&mut self, dt_s: f64) -> Vec<process::ProcReading> {
111        let units = self.proc_units;
112        let mut missing = |name: &str| {
113            crate::diag!(
114                crate::observer::LogLevel::Warn,
115                "sysmon: process '{name}' is not running (or its pidfile is unreadable); \
116                 it has no series until it is"
117            );
118        };
119        self.procs
120            .iter_mut()
121            .filter_map(|watched| watched.sample(dt_s, units, &mut missing))
122            .collect()
123    }
124
125    /// Read every enabled subsystem and return the window since the
126    /// last read.
127    fn window(&mut self, cats: Categories, membw_peak: Option<f64>) -> SysmonSample {
128        let now = Instant::now();
129        let dt_s = now.duration_since(self.at).as_secs_f64();
130        self.at = now;
131        let mut sample = SysmonSample::default();
132
133        if cats.io {
134            let cur = disk::read_diskstats();
135            sample.io = disk::max_disk_util(&self.disks, &cur, dt_s * 1000.0);
136            sample.io_rates = disk::disk_rates(&self.disks, &cur, dt_s, &disk::is_whole_device);
137            self.disks = cur;
138        }
139        if cats.cpu {
140            let cur = cpu::read_proc_stat();
141            if let (Some((pa, pc)), Some((ca, cc))) = (&self.cpu, &cur) {
142                let (top_core, max_core) = cpu::max_core_util(pc, cc).unwrap_or((0, 0.0));
143                let (p25, p50, p75, cores) =
144                    cpu::core_util_quartiles(pc, cc).unwrap_or((0.0, 0.0, 0.0, 0));
145                sample.cpu = Some(cpu::CpuReading {
146                    mean: cpu::cpu_util(*pa, *ca),
147                    max_core,
148                    top_core,
149                    p25,
150                    p50,
151                    p75,
152                    cores,
153                });
154            }
155            self.cpu = cur;
156        }
157        if cats.ram {
158            sample.ram = std::fs::read_to_string("/proc/meminfo")
159                .ok()
160                .and_then(|t| mem::parse_meminfo(&t))
161                .map(mem::mem_utils);
162        }
163        if cats.rambw
164            && let Some(peak) = membw_peak
165        {
166            let cur = mem::read_membw_bytes();
167            if let (Some(p), Some(c)) = (self.membw, cur) {
168                sample.rambw =
169                    Some(((c.saturating_sub(p)) as f64 / dt_s.max(1e-9) / peak).clamp(0.0, 1.0));
170            }
171            self.membw = cur;
172        }
173        if cats.storage {
174            sample.storage = disk::max_storage_util();
175        }
176        if cats.net {
177            let cur = net::read_net_dev();
178            sample.net = net::net_rates(&self.net, &cur, dt_s);
179            self.net = cur;
180        }
181        if cats.pressure {
182            let cur = pressure::read_pressure();
183            if let (Some(p), Some(c)) = (self.pressure, cur) {
184                sample.pressure = Some(pressure::pressure_between(p, c, dt_s));
185            }
186            self.pressure = cur;
187        }
188        if cats.proc {
189            sample.procs = self.sample_procs(dt_s);
190        }
191        if cats.cgroup {
192            sample.cgroups = self.sample_cgroups(dt_s);
193        }
194        sample
195    }
196}
197
198/// Spawn the sampler. `check_requirements` must have passed first —
199/// the runner aborts the session on its Err rather than calling this.
200/// Runs until session shutdown; publishes each window to the session gauges
201/// and to `observer.sysmon_update`.
202pub fn spawn(
203    config: SysmonConfig,
204    component: Arc<RwLock<Component>>,
205    observer: Arc<dyn crate::observer::RunObserver>,
206) -> Result<tokio::task::JoinHandle<()>, String> {
207    super::check_requirements(&config)?;
208    let mut gauges = Gauges::register(&component, config.cats)?;
209    let mut shutdown = crate::session_signals::subscribe_shutdown();
210    Ok(tokio::spawn(async move {
211        let mut previous = Previous::first(&config);
212        loop {
213            tokio::select! {
214                _ = tokio::time::sleep(config.interval) => {}
215                _ = shutdown.changed() => break,
216            }
217            let sample = previous.window(config.cats, config.membw_peak_bytes_per_s);
218            gauges.publish(&sample);
219            observer.sysmon_update(&sample);
220        }
221    }))
222}