Skip to main content

nmbrs_runtime/sysmon/
gauges.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! The sampler's gauges (SRD-118 §4): which families each category
5//! publishes, and writing a sample to them.
6
7use std::collections::HashMap;
8use std::sync::{Arc, RwLock};
9
10use nmbrs_metrics::component::Component;
11use nmbrs_metrics::instruments::gauge::ValueGauge;
12
13use super::{Categories, SysmonSample};
14
15/// One gauge family the sampler publishes.
16pub struct Family {
17    pub name: &'static str,
18    /// True when the category that publishes it is enabled.
19    enabled: fn(&Categories) -> bool,
20    /// The label its series are told apart by, for a family with one
21    /// series per device, core, mount, interface or process. `None`
22    /// for a family that describes the host as a whole.
23    pub subject: Option<&'static str>,
24}
25
26const fn host(name: &'static str, enabled: fn(&Categories) -> bool) -> Family {
27    Family {
28        name,
29        enabled,
30        subject: None,
31    }
32}
33
34const fn per(
35    name: &'static str,
36    subject: &'static str,
37    enabled: fn(&Categories) -> bool,
38) -> Family {
39    Family {
40        name,
41        enabled,
42        subject: Some(subject),
43    }
44}
45
46/// Every family, by category. This table is what is registered, and
47/// SRD-118 §4 lists the same families.
48pub const FAMILIES: &[Family] = &[
49    host("sysmon_cpu_util", |c| c.cpu),
50    host("sysmon_cpu_core_p25", |c| c.cpu),
51    host("sysmon_cpu_core_p50", |c| c.cpu),
52    host("sysmon_cpu_core_p75", |c| c.cpu),
53    per("sysmon_cpu_core_max", "core", |c| c.cpu),
54    per("sysmon_io_util", "device", |c| c.io),
55    per("sysmon_io_read_bytes_per_s", "device", |c| c.io),
56    per("sysmon_io_write_bytes_per_s", "device", |c| c.io),
57    per("sysmon_io_read_ops_per_s", "device", |c| c.io),
58    per("sysmon_io_write_ops_per_s", "device", |c| c.io),
59    host("sysmon_ram_util", |c| c.ram),
60    host("sysmon_ram_util_cached", |c| c.ram),
61    host("sysmon_rambw_util", |c| c.rambw),
62    per("sysmon_storage_util", "mount", |c| c.storage),
63    per("sysmon_net_rx_bytes_per_s", "iface", |c| c.net),
64    per("sysmon_net_tx_bytes_per_s", "iface", |c| c.net),
65    host("sysmon_pressure_cpu", |c| c.pressure),
66    host("sysmon_pressure_mem", |c| c.pressure),
67    host("sysmon_pressure_mem_full", |c| c.pressure),
68    host("sysmon_pressure_io", |c| c.pressure),
69    host("sysmon_pressure_io_full", |c| c.pressure),
70    per("sysmon_proc_cpu_cores", "proc", |c| c.proc),
71    per("sysmon_proc_rss_bytes", "proc", |c| c.proc),
72    per("sysmon_proc_threads", "proc", |c| c.proc),
73    per("sysmon_proc_read_bytes_per_s", "proc", |c| c.proc),
74    per("sysmon_proc_write_bytes_per_s", "proc", |c| c.proc),
75];
76
77/// A gauge family whose series are one-per-SUBJECT — the device, core, or
78/// mount the measurement is about. Each distinct subject value materialises
79/// a dimensional cell under the session component
80/// ([`nmbrs_metrics::cells::resolve_under`]) and registers the family there
81/// once; after that a sample is a hash lookup and a `set`.
82///
83/// This is what "submitted to metrics with the appropriate dimensional
84/// labels, keyed by the session component" means concretely:
85/// `sysmon_io_util{session="…",device="nvme1n1"}` — the subject is a label,
86/// the cell refines the session's identity, and a sweep that shifts between
87/// devices yields one honestly-labeled series per device rather than one
88/// anonymous series whose subject silently changes.
89struct SubjectGauge {
90    family: &'static str,
91    /// The dimension this family's subject occupies (`device`, `core`,
92    /// `mount`).
93    label_key: &'static str,
94    parent: Arc<RwLock<Component>>,
95    /// Instruments already materialised, by subject value.
96    instances: std::collections::HashMap<String, Arc<ValueGauge>>,
97}
98
99impl SubjectGauge {
100    fn new(family: &'static str, label_key: &'static str, parent: Arc<RwLock<Component>>) -> Self {
101        Self {
102            family,
103            label_key,
104            parent,
105            instances: Default::default(),
106        }
107    }
108
109    fn set(&mut self, subject: &str, value: f64) {
110        if let Some(g) = self.instances.get(subject) {
111            g.set(value);
112            return;
113        }
114        let coord = nmbrs_metrics::labels::Labels::of(self.label_key, subject);
115        let cell = nmbrs_metrics::cells::resolve_under(&self.parent, &coord);
116        let labels = {
117            let guard = cell.read().unwrap_or_else(|e| e.into_inner());
118            guard.effective_labels().clone()
119        };
120        let g = Arc::new(ValueGauge::new(labels.with("family", self.family)));
121        let registered = cell
122            .write()
123            .unwrap_or_else(|e| e.into_inner())
124            .register_instrument(
125                self.family,
126                nmbrs_metrics::component::InstrumentRef::Gauge(g.clone()),
127            );
128        if let Err(e) = registered {
129            // One cell, one family: a second registration here is a
130            // programming error worth hearing about once, not per sample.
131            crate::diag!(
132                crate::observer::LogLevel::Warn,
133                "sysmon: {family} cell {subject}: {e}",
134                family = self.family
135            );
136        }
137        g.set(value);
138        self.instances.insert(subject.to_string(), g);
139    }
140}
141
142/// The gauges of the enabled categories.
143pub(super) struct Gauges {
144    /// Host-scalar measures — no subject, so they live on the session root
145    /// itself and carry exactly its labels.
146    host: HashMap<&'static str, Arc<ValueGauge>>,
147    /// Subject-dimensioned measures — one cell per device / core / mount /
148    /// interface / process.
149    subject: HashMap<&'static str, SubjectGauge>,
150}
151
152impl Gauges {
153    /// Register gauges for the ENABLED categories on the session component.
154    /// Direct registration on the session root — no child component, no new
155    /// labels: the samples describe the whole host, which is exactly the
156    /// session's dimensional cell.
157    ///
158    /// Subject-dimensioned families register per cell at first sight of
159    /// each subject, NOT here — registering on the root as well would claim
160    /// the family for the un-refined identity and collide with the first
161    /// cell.
162    pub fn register(component: &Arc<RwLock<Component>>, cats: Categories) -> Result<Self, String> {
163        let mut gauges = Self {
164            host: HashMap::new(),
165            subject: HashMap::new(),
166        };
167        let mut guard = component.write().unwrap_or_else(|e| e.into_inner());
168        let labels = guard.effective_labels().clone();
169        for family in FAMILIES.iter().filter(|f| (f.enabled)(&cats)) {
170            match family.subject {
171                Some(label_key) => {
172                    gauges.subject.insert(
173                        family.name,
174                        SubjectGauge::new(family.name, label_key, component.clone()),
175                    );
176                }
177                None => {
178                    let g = Arc::new(ValueGauge::new(labels.with("family", family.name)));
179                    guard.register_instrument(
180                        family.name,
181                        nmbrs_metrics::component::InstrumentRef::Gauge(g.clone()),
182                    )?;
183                    gauges.host.insert(family.name, g);
184                }
185            }
186        }
187        Ok(gauges)
188    }
189
190    /// Set a host-wide gauge. A family whose category is off has no
191    /// gauge, and nothing is done.
192    fn set(&self, family: &str, value: f64) {
193        if let Some(g) = self.host.get(family) {
194            g.set(value);
195        }
196    }
197
198    /// Set one subject's gauge, likewise.
199    fn set_for(&mut self, family: &str, subject: &str, value: f64) {
200        if let Some(g) = self.subject.get_mut(family) {
201            g.set(subject, value);
202        }
203    }
204
205    /// Write one sample window to the gauges.
206    pub fn publish(&mut self, sample: &SysmonSample) {
207        if let Some(cpu) = &sample.cpu {
208            self.set("sysmon_cpu_util", cpu.mean);
209            self.set("sysmon_cpu_core_p25", cpu.p25);
210            self.set("sysmon_cpu_core_p50", cpu.p50);
211            self.set("sysmon_cpu_core_p75", cpu.p75);
212            self.set_for(
213                "sysmon_cpu_core_max",
214                &cpu.top_core.to_string(),
215                cpu.max_core,
216            );
217        }
218        if let Some((device, util)) = &sample.io {
219            self.set_for("sysmon_io_util", device, *util);
220        }
221        for rate in &sample.io_rates {
222            let device = rate.device.as_str();
223            self.set_for("sysmon_io_read_bytes_per_s", device, rate.read_bytes_per_s);
224            self.set_for(
225                "sysmon_io_write_bytes_per_s",
226                device,
227                rate.write_bytes_per_s,
228            );
229            self.set_for("sysmon_io_read_ops_per_s", device, rate.read_ops_per_s);
230            self.set_for("sysmon_io_write_ops_per_s", device, rate.write_ops_per_s);
231        }
232        if let Some((committed, cached)) = sample.ram {
233            self.set("sysmon_ram_util", committed);
234            self.set("sysmon_ram_util_cached", cached);
235        }
236        if let Some(util) = sample.rambw {
237            self.set("sysmon_rambw_util", util);
238        }
239        if let Some((mount, util)) = &sample.storage {
240            self.set_for("sysmon_storage_util", mount, *util);
241        }
242        for rate in &sample.net {
243            self.set_for(
244                "sysmon_net_rx_bytes_per_s",
245                &rate.iface,
246                rate.rx_bytes_per_s,
247            );
248            self.set_for(
249                "sysmon_net_tx_bytes_per_s",
250                &rate.iface,
251                rate.tx_bytes_per_s,
252            );
253        }
254        if let Some(p) = &sample.pressure {
255            self.set("sysmon_pressure_cpu", p.cpu);
256            self.set("sysmon_pressure_mem", p.mem);
257            self.set("sysmon_pressure_mem_full", p.mem_full);
258            self.set("sysmon_pressure_io", p.io);
259            self.set("sysmon_pressure_io_full", p.io_full);
260        }
261        for p in &sample.procs {
262            let name = p.name.as_str();
263            self.set_for("sysmon_proc_cpu_cores", name, p.cpu_cores);
264            self.set_for("sysmon_proc_rss_bytes", name, p.rss_bytes);
265            self.set_for("sysmon_proc_threads", name, p.threads);
266            if let Some((read, write)) = p.io_bytes_per_s {
267                self.set_for("sysmon_proc_read_bytes_per_s", name, read);
268                self.set_for("sysmon_proc_write_bytes_per_s", name, write);
269            }
270        }
271    }
272}
273
274#[cfg(test)]
275mod tests {
276    use super::*;
277
278    /// A subject-dimensioned gauge materialises ONE cell per subject under
279    /// the session component, each series carrying the subject as a label —
280    /// and re-setting an existing subject attaches no twin.
281    #[test]
282    fn subject_gauges_dimension_by_cell_under_the_session_component() {
283        let session = Arc::new(RwLock::new(nmbrs_metrics::component::Component::new(
284            nmbrs_metrics::labels::Labels::of("session", "s1"),
285            std::collections::HashMap::new(),
286        )));
287        let mut g = SubjectGauge::new("sysmon_io_util", "device", session.clone());
288        g.set("nvme1n1", 0.97);
289        g.set("nvme2n1", 0.40);
290        g.set("nvme1n1", 0.98);
291
292        let guard = session.read().unwrap();
293        assert_eq!(
294            guard.child_count(),
295            2,
296            "one cell per device, re-sets attach no twin"
297        );
298        drop(guard);
299        assert_eq!(g.instances.len(), 2);
300        // The series carries session + device + family — the session's
301        // identity refined by the subject, never replaced.
302        let labels = g.instances["nvme1n1"].labels().to_prometheus();
303        for owned in ["session=", "device=\"nvme1n1\"", "family="] {
304            assert!(labels.contains(owned), "{owned} missing from {labels}");
305        }
306    }
307
308    /// Only the enabled categories' families are registered, and a
309    /// sample for a category that is off is not written anywhere.
310    #[test]
311    fn only_enabled_categories_have_gauges() {
312        let session = Arc::new(RwLock::new(nmbrs_metrics::component::Component::new(
313            nmbrs_metrics::labels::Labels::of("session", "s1"),
314            std::collections::HashMap::new(),
315        )));
316        let cats = Categories {
317            ram: true,
318            net: true,
319            ..Categories::default()
320        };
321        let mut gauges = Gauges::register(&session, cats).unwrap();
322        assert_eq!(gauges.host.len(), 2);
323        assert_eq!(gauges.subject.len(), 2);
324        gauges.publish(&SysmonSample {
325            ram: Some((0.25, 0.5)),
326            pressure: Some(Default::default()),
327            net: vec![super::super::net::NetRate {
328                iface: "eth0".into(),
329                rx_bytes_per_s: 10.0,
330                tx_bytes_per_s: 20.0,
331            }],
332            ..SysmonSample::default()
333        });
334        assert_eq!(gauges.host["sysmon_ram_util"].get(), 0.25);
335        assert_eq!(
336            gauges.subject["sysmon_net_tx_bytes_per_s"].instances["eth0"].get(),
337            20.0
338        );
339    }
340
341    /// A family name is given once, and each is under `sysmon_`.
342    #[test]
343    fn family_names_are_unique() {
344        let mut names: Vec<&str> = FAMILIES.iter().map(|f| f.name).collect();
345        assert!(names.iter().all(|n| n.starts_with("sysmon_")));
346        names.sort_unstable();
347        let total = names.len();
348        names.dedup();
349        assert_eq!(names.len(), total);
350    }
351}