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 nmbrs_host::category::Categories;
14
15use super::SysmonSample;
16
17/// One gauge family the sampler publishes.
18pub struct Family {
19    pub name: &'static str,
20    /// True when the category that publishes it is enabled.
21    enabled: fn(&Categories) -> bool,
22    /// The labels its series are told apart by, outermost first, for
23    /// a family with one series per device, core, mount, interface,
24    /// process or control group. Empty for a family that describes
25    /// the host as a whole.
26    pub subject: &'static [&'static str],
27}
28
29const fn host(name: &'static str, enabled: fn(&Categories) -> bool) -> Family {
30    Family {
31        name,
32        enabled,
33        subject: &[],
34    }
35}
36
37const fn per(
38    name: &'static str,
39    subject: &'static [&'static str],
40    enabled: fn(&Categories) -> bool,
41) -> Family {
42    Family {
43        name,
44        enabled,
45        subject,
46    }
47}
48
49/// A control group's I/O is told apart by the group and the device.
50const GROUP_DEVICE: &[&str] = &["cgroup", "device"];
51
52/// Every family, by category. This table is what is registered, and
53/// SRD-118 §4 lists the same families.
54pub const FAMILIES: &[Family] = &[
55    host("sysmon_cpu_util", |c| c.cpu),
56    host("sysmon_cpu_core_p25", |c| c.cpu),
57    host("sysmon_cpu_core_p50", |c| c.cpu),
58    host("sysmon_cpu_core_p75", |c| c.cpu),
59    per("sysmon_cpu_core_max", &["core"], |c| c.cpu),
60    per("sysmon_io_util", &["device"], |c| c.io),
61    per("sysmon_io_read_bytes_per_s", &["device"], |c| c.io),
62    per("sysmon_io_write_bytes_per_s", &["device"], |c| c.io),
63    per("sysmon_io_read_ops_per_s", &["device"], |c| c.io),
64    per("sysmon_io_write_ops_per_s", &["device"], |c| c.io),
65    host("sysmon_ram_util", |c| c.ram),
66    host("sysmon_ram_util_cached", |c| c.ram),
67    host("sysmon_rambw_util", |c| c.rambw),
68    per("sysmon_storage_util", &["mount"], |c| c.storage),
69    per("sysmon_net_rx_bytes_per_s", &["iface"], |c| c.net),
70    per("sysmon_net_tx_bytes_per_s", &["iface"], |c| c.net),
71    host("sysmon_pressure_cpu", |c| c.pressure),
72    host("sysmon_pressure_mem", |c| c.pressure),
73    host("sysmon_pressure_mem_full", |c| c.pressure),
74    host("sysmon_pressure_io", |c| c.pressure),
75    host("sysmon_pressure_io_full", |c| c.pressure),
76    per("sysmon_proc_cpu_cores", &["proc"], |c| c.proc),
77    per("sysmon_proc_rss_bytes", &["proc"], |c| c.proc),
78    per("sysmon_proc_threads", &["proc"], |c| c.proc),
79    per("sysmon_proc_read_bytes_per_s", &["proc"], |c| c.proc),
80    per("sysmon_proc_write_bytes_per_s", &["proc"], |c| c.proc),
81    per("sysmon_cgroup_cpu_cores", &["cgroup"], |c| c.cgroup),
82    per("sysmon_cgroup_mem_bytes", &["cgroup"], |c| c.cgroup),
83    per("sysmon_cgroup_io_read_bytes_per_s", GROUP_DEVICE, |c| {
84        c.cgroup
85    }),
86    per("sysmon_cgroup_io_write_bytes_per_s", GROUP_DEVICE, |c| {
87        c.cgroup
88    }),
89    per("sysmon_cgroup_io_read_ops_per_s", GROUP_DEVICE, |c| {
90        c.cgroup
91    }),
92    per("sysmon_cgroup_io_write_ops_per_s", GROUP_DEVICE, |c| {
93        c.cgroup
94    }),
95];
96
97/// A gauge family whose series are one-per-SUBJECT — the device, core, or
98/// mount the measurement is about. Each distinct subject value materialises
99/// a dimensional cell under the session component
100/// ([`nmbrs_metrics::cells::resolve_under`]) and registers the family there
101/// once; after that a sample is a hash lookup and a `set`.
102///
103/// This is what "submitted to metrics with the appropriate dimensional
104/// labels, keyed by the session component" means concretely:
105/// `sysmon_io_util{session="…",device="nvme1n1"}` — the subject is a label,
106/// the cell refines the session's identity, and a sweep that shifts between
107/// devices yields one honestly-labeled series per device rather than one
108/// anonymous series whose subject silently changes.
109struct SubjectGauge {
110    family: &'static str,
111    /// The dimensions this family's subject occupies (`device`, `core`,
112    /// `mount`; `cgroup` and `device` together).
113    label_keys: &'static [&'static str],
114    parent: Arc<RwLock<Component>>,
115    /// Instruments already materialised, by subject values.
116    instances: std::collections::HashMap<Vec<String>, Arc<ValueGauge>>,
117}
118
119impl SubjectGauge {
120    fn new(
121        family: &'static str,
122        label_keys: &'static [&'static str],
123        parent: Arc<RwLock<Component>>,
124    ) -> Self {
125        Self {
126            family,
127            label_keys,
128            parent,
129            instances: Default::default(),
130        }
131    }
132
133    /// Set the gauge of one subject, given as one value for each of
134    /// the family's subject labels.
135    fn set(&mut self, subject: &[&str], value: f64) {
136        let key: Vec<String> = subject.iter().map(|s| s.to_string()).collect();
137        if let Some(g) = self.instances.get(&key) {
138            g.set(value);
139            return;
140        }
141        let mut pairs = self.label_keys.iter().zip(subject);
142        let Some((first_key, first_value)) = pairs.next() else {
143            return;
144        };
145        let coord = pairs.fold(
146            nmbrs_metrics::labels::Labels::of(*first_key, *first_value),
147            |labels, (k, v)| labels.with(*k, *v),
148        );
149        let cell = nmbrs_metrics::cells::resolve_under(&self.parent, &coord);
150        let labels = {
151            let guard = cell.read().unwrap_or_else(|e| e.into_inner());
152            guard.effective_labels().clone()
153        };
154        let g = Arc::new(ValueGauge::new(labels.with("family", self.family)));
155        let registered = cell
156            .write()
157            .unwrap_or_else(|e| e.into_inner())
158            .register_instrument(
159                self.family,
160                nmbrs_metrics::component::InstrumentRef::Gauge(g.clone()),
161            );
162        if let Err(e) = registered {
163            // One cell, one family: a second registration here is a
164            // programming error worth hearing about once, not per sample.
165            crate::diag!(
166                crate::observer::LogLevel::Warn,
167                "sysmon: {family} cell {subject}: {e}",
168                family = self.family,
169                subject = key.join("/")
170            );
171        }
172        g.set(value);
173        self.instances.insert(key, g);
174    }
175}
176
177/// The gauges of the enabled categories.
178pub(super) struct Gauges {
179    /// Host-scalar measures — no subject, so they live on the session root
180    /// itself and carry exactly its labels.
181    host: HashMap<&'static str, Arc<ValueGauge>>,
182    /// Subject-dimensioned measures — one cell per device / core / mount /
183    /// interface / process.
184    subject: HashMap<&'static str, SubjectGauge>,
185}
186
187impl Gauges {
188    /// Register gauges for the ENABLED categories on the session component.
189    /// Direct registration on the session root — no child component, no new
190    /// labels: the samples describe the whole host, which is exactly the
191    /// session's dimensional cell.
192    ///
193    /// Subject-dimensioned families register per cell at first sight of
194    /// each subject, NOT here — registering on the root as well would claim
195    /// the family for the un-refined identity and collide with the first
196    /// cell.
197    pub fn register(component: &Arc<RwLock<Component>>, cats: Categories) -> Result<Self, String> {
198        let mut gauges = Self {
199            host: HashMap::new(),
200            subject: HashMap::new(),
201        };
202        let mut guard = component.write().unwrap_or_else(|e| e.into_inner());
203        let labels = guard.effective_labels().clone();
204        for family in FAMILIES.iter().filter(|f| (f.enabled)(&cats)) {
205            match family.subject {
206                label_keys if !label_keys.is_empty() => {
207                    gauges.subject.insert(
208                        family.name,
209                        SubjectGauge::new(family.name, label_keys, component.clone()),
210                    );
211                }
212                _ => {
213                    let g = Arc::new(ValueGauge::new(labels.with("family", family.name)));
214                    guard.register_instrument(
215                        family.name,
216                        nmbrs_metrics::component::InstrumentRef::Gauge(g.clone()),
217                    )?;
218                    gauges.host.insert(family.name, g);
219                }
220            }
221        }
222        Ok(gauges)
223    }
224
225    /// Set a host-wide gauge. A family whose category is off has no
226    /// gauge, and nothing is done.
227    fn set(&self, family: &str, value: f64) {
228        if let Some(g) = self.host.get(family) {
229            g.set(value);
230        }
231    }
232
233    /// Set one subject's gauge, likewise.
234    fn set_for(&mut self, family: &str, subject: &str, value: f64) {
235        self.set_at(family, &[subject], value);
236    }
237
238    /// Set the gauge of a subject with several labels, likewise.
239    fn set_at(&mut self, family: &str, subject: &[&str], value: f64) {
240        if let Some(g) = self.subject.get_mut(family) {
241            g.set(subject, value);
242        }
243    }
244
245    /// Write one sample window to the gauges.
246    pub fn publish(&mut self, sample: &SysmonSample) {
247        if let Some(cpu) = &sample.cpu {
248            self.set("sysmon_cpu_util", cpu.mean);
249            self.set("sysmon_cpu_core_p25", cpu.p25);
250            self.set("sysmon_cpu_core_p50", cpu.p50);
251            self.set("sysmon_cpu_core_p75", cpu.p75);
252            self.set_for(
253                "sysmon_cpu_core_max",
254                &cpu.top_core.to_string(),
255                cpu.max_core,
256            );
257        }
258        if let Some((device, util)) = &sample.io {
259            self.set_for("sysmon_io_util", device, *util);
260        }
261        for rate in &sample.io_rates {
262            let device = rate.device.as_str();
263            self.set_for("sysmon_io_read_bytes_per_s", device, rate.read_bytes_per_s);
264            self.set_for(
265                "sysmon_io_write_bytes_per_s",
266                device,
267                rate.write_bytes_per_s,
268            );
269            self.set_for("sysmon_io_read_ops_per_s", device, rate.read_ops_per_s);
270            self.set_for("sysmon_io_write_ops_per_s", device, rate.write_ops_per_s);
271        }
272        if let Some((committed, cached)) = sample.ram {
273            self.set("sysmon_ram_util", committed);
274            self.set("sysmon_ram_util_cached", cached);
275        }
276        if let Some(util) = sample.rambw {
277            self.set("sysmon_rambw_util", util);
278        }
279        if let Some((mount, util)) = &sample.storage {
280            self.set_for("sysmon_storage_util", mount, *util);
281        }
282        for rate in &sample.net {
283            self.set_for(
284                "sysmon_net_rx_bytes_per_s",
285                &rate.iface,
286                rate.rx_bytes_per_s,
287            );
288            self.set_for(
289                "sysmon_net_tx_bytes_per_s",
290                &rate.iface,
291                rate.tx_bytes_per_s,
292            );
293        }
294        if let Some(p) = &sample.pressure {
295            self.set("sysmon_pressure_cpu", p.cpu);
296            self.set("sysmon_pressure_mem", p.mem);
297            self.set("sysmon_pressure_mem_full", p.mem_full);
298            self.set("sysmon_pressure_io", p.io);
299            self.set("sysmon_pressure_io_full", p.io_full);
300        }
301        for p in &sample.procs {
302            let name = p.name.as_str();
303            self.set_for("sysmon_proc_cpu_cores", name, p.cpu_cores);
304            self.set_for("sysmon_proc_rss_bytes", name, p.rss_bytes);
305            self.set_for("sysmon_proc_threads", name, p.threads);
306            if let Some((read, write)) = p.io_bytes_per_s {
307                self.set_for("sysmon_proc_read_bytes_per_s", name, read);
308                self.set_for("sysmon_proc_write_bytes_per_s", name, write);
309            }
310        }
311        for group in &sample.cgroups {
312            let name = group.name.as_str();
313            if let Some(cores) = group.cpu_cores {
314                self.set_for("sysmon_cgroup_cpu_cores", name, cores);
315            }
316            if let Some(bytes) = group.mem_bytes {
317                self.set_for("sysmon_cgroup_mem_bytes", name, bytes);
318            }
319            for io in &group.io {
320                let at = [name, io.device.as_str()];
321                self.set_at(
322                    "sysmon_cgroup_io_read_bytes_per_s",
323                    &at,
324                    io.read_bytes_per_s,
325                );
326                self.set_at(
327                    "sysmon_cgroup_io_write_bytes_per_s",
328                    &at,
329                    io.write_bytes_per_s,
330                );
331                self.set_at("sysmon_cgroup_io_read_ops_per_s", &at, io.read_ops_per_s);
332                self.set_at("sysmon_cgroup_io_write_ops_per_s", &at, io.write_ops_per_s);
333            }
334        }
335    }
336}
337
338#[cfg(test)]
339mod tests {
340    use super::*;
341
342    /// A subject-dimensioned gauge materialises ONE cell per subject under
343    /// the session component, each series carrying the subject as a label —
344    /// and re-setting an existing subject attaches no twin.
345    #[test]
346    fn subject_gauges_dimension_by_cell_under_the_session_component() {
347        let session = Arc::new(RwLock::new(nmbrs_metrics::component::Component::new(
348            nmbrs_metrics::labels::Labels::of("session", "s1"),
349            std::collections::HashMap::new(),
350        )));
351        let mut g = SubjectGauge::new("sysmon_io_util", &["device"], session.clone());
352        g.set(&["nvme1n1"], 0.97);
353        g.set(&["nvme2n1"], 0.40);
354        g.set(&["nvme1n1"], 0.98);
355
356        let guard = session.read().unwrap();
357        assert_eq!(
358            guard.child_count(),
359            2,
360            "one cell per device, re-sets attach no twin"
361        );
362        drop(guard);
363        assert_eq!(g.instances.len(), 2);
364        // The series carries session + device + family — the session's
365        // identity refined by the subject, never replaced.
366        let labels = g.instances[&vec!["nvme1n1".to_string()]]
367            .labels()
368            .to_prometheus();
369        for owned in ["session=", "device=\"nvme1n1\"", "family="] {
370            assert!(labels.contains(owned), "{owned} missing from {labels}");
371        }
372    }
373
374    /// Only the enabled categories' families are registered, and a
375    /// sample for a category that is off is not written anywhere.
376    #[test]
377    fn only_enabled_categories_have_gauges() {
378        let session = Arc::new(RwLock::new(nmbrs_metrics::component::Component::new(
379            nmbrs_metrics::labels::Labels::of("session", "s1"),
380            std::collections::HashMap::new(),
381        )));
382        let cats = Categories {
383            ram: true,
384            net: true,
385            ..Categories::default()
386        };
387        let mut gauges = Gauges::register(&session, cats).unwrap();
388        assert_eq!(gauges.host.len(), 2);
389        assert_eq!(gauges.subject.len(), 2);
390        gauges.publish(&SysmonSample {
391            ram: Some((0.25, 0.5)),
392            pressure: Some(Default::default()),
393            net: vec![nmbrs_host::net::NetRate {
394                iface: "eth0".into(),
395                rx_bytes_per_s: 10.0,
396                tx_bytes_per_s: 20.0,
397            }],
398            ..SysmonSample::default()
399        });
400        assert_eq!(gauges.host["sysmon_ram_util"].get(), 0.25);
401        assert_eq!(
402            gauges.subject["sysmon_net_tx_bytes_per_s"].instances[&vec!["eth0".to_string()]].get(),
403            20.0
404        );
405    }
406
407    /// A control group's I/O is one series per group and device, each
408    /// carrying both labels.
409    #[test]
410    fn a_groups_io_is_dimensioned_by_group_and_device() {
411        let session = Arc::new(RwLock::new(nmbrs_metrics::component::Component::new(
412            nmbrs_metrics::labels::Labels::of("session", "s1"),
413            std::collections::HashMap::new(),
414        )));
415        let cats = Categories {
416            cgroup: true,
417            ..Categories::default()
418        };
419        let mut gauges = Gauges::register(&session, cats).unwrap();
420        gauges.publish(&SysmonSample {
421            cgroups: vec![nmbrs_host::cgroup::CgroupReading {
422                name: "node".into(),
423                cpu_cores: Some(1.5),
424                mem_bytes: None,
425                io: vec![nmbrs_host::cgroup::CgroupIoRate {
426                    device: "md0".into(),
427                    read_bytes_per_s: 1.0,
428                    write_bytes_per_s: 2.0,
429                    read_ops_per_s: 3.0,
430                    write_ops_per_s: 4.0,
431                }],
432            }],
433            ..SysmonSample::default()
434        });
435        let key = vec!["node".to_string(), "md0".to_string()];
436        let written = &gauges.subject["sysmon_cgroup_io_write_bytes_per_s"].instances[&key];
437        assert_eq!(written.get(), 2.0);
438        let labels = written.labels().to_prometheus();
439        for owned in ["cgroup=\"node\"", "device=\"md0\""] {
440            assert!(labels.contains(owned), "{owned} missing from {labels}");
441        }
442        // The controller that was off has no series.
443        assert!(
444            gauges.subject["sysmon_cgroup_mem_bytes"]
445                .instances
446                .is_empty()
447        );
448    }
449
450    /// A family name is given once, and each is under `sysmon_`.
451    #[test]
452    fn family_names_are_unique() {
453        let mut names: Vec<&str> = FAMILIES.iter().map(|f| f.name).collect();
454        assert!(names.iter().all(|n| n.starts_with("sysmon_")));
455        names.sort_unstable();
456        let total = names.len();
457        names.dedup();
458        assert_eq!(names.len(), total);
459    }
460}