nmbrs-runtime 0.7.3

Workload execution runtime for nmbrs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! The sampler's gauges (SRD-118 §4): which families each category
//! publishes, and writing a sample to them.

use std::collections::HashMap;
use std::sync::{Arc, RwLock};

use nmbrs_metrics::component::Component;
use nmbrs_metrics::instruments::gauge::ValueGauge;

use nmbrs_host::category::Categories;

use super::SysmonSample;

/// One gauge family the sampler publishes.
pub struct Family {
    pub name: &'static str,
    /// True when the category that publishes it is enabled.
    enabled: fn(&Categories) -> bool,
    /// The labels its series are told apart by, outermost first, for
    /// a family with one series per device, core, mount, interface,
    /// process or control group. Empty for a family that describes
    /// the host as a whole.
    pub subject: &'static [&'static str],
}

const fn host(name: &'static str, enabled: fn(&Categories) -> bool) -> Family {
    Family {
        name,
        enabled,
        subject: &[],
    }
}

const fn per(
    name: &'static str,
    subject: &'static [&'static str],
    enabled: fn(&Categories) -> bool,
) -> Family {
    Family {
        name,
        enabled,
        subject,
    }
}

/// A control group's I/O is told apart by the group and the device.
const GROUP_DEVICE: &[&str] = &["cgroup", "device"];

/// Every family, by category. This table is what is registered, and
/// SRD-118 §4 lists the same families.
pub const FAMILIES: &[Family] = &[
    host("sysmon_cpu_util", |c| c.cpu),
    host("sysmon_cpu_core_p25", |c| c.cpu),
    host("sysmon_cpu_core_p50", |c| c.cpu),
    host("sysmon_cpu_core_p75", |c| c.cpu),
    per("sysmon_cpu_core_max", &["core"], |c| c.cpu),
    per("sysmon_io_util", &["device"], |c| c.io),
    per("sysmon_io_read_bytes_per_s", &["device"], |c| c.io),
    per("sysmon_io_write_bytes_per_s", &["device"], |c| c.io),
    per("sysmon_io_read_ops_per_s", &["device"], |c| c.io),
    per("sysmon_io_write_ops_per_s", &["device"], |c| c.io),
    host("sysmon_ram_util", |c| c.ram),
    host("sysmon_ram_util_cached", |c| c.ram),
    host("sysmon_rambw_util", |c| c.rambw),
    per("sysmon_storage_util", &["mount"], |c| c.storage),
    per("sysmon_net_rx_bytes_per_s", &["iface"], |c| c.net),
    per("sysmon_net_tx_bytes_per_s", &["iface"], |c| c.net),
    host("sysmon_pressure_cpu", |c| c.pressure),
    host("sysmon_pressure_mem", |c| c.pressure),
    host("sysmon_pressure_mem_full", |c| c.pressure),
    host("sysmon_pressure_io", |c| c.pressure),
    host("sysmon_pressure_io_full", |c| c.pressure),
    per("sysmon_proc_cpu_cores", &["proc"], |c| c.proc),
    per("sysmon_proc_rss_bytes", &["proc"], |c| c.proc),
    per("sysmon_proc_threads", &["proc"], |c| c.proc),
    per("sysmon_proc_read_bytes_per_s", &["proc"], |c| c.proc),
    per("sysmon_proc_write_bytes_per_s", &["proc"], |c| c.proc),
    per("sysmon_cgroup_cpu_cores", &["cgroup"], |c| c.cgroup),
    per("sysmon_cgroup_mem_bytes", &["cgroup"], |c| c.cgroup),
    per("sysmon_cgroup_io_read_bytes_per_s", GROUP_DEVICE, |c| {
        c.cgroup
    }),
    per("sysmon_cgroup_io_write_bytes_per_s", GROUP_DEVICE, |c| {
        c.cgroup
    }),
    per("sysmon_cgroup_io_read_ops_per_s", GROUP_DEVICE, |c| {
        c.cgroup
    }),
    per("sysmon_cgroup_io_write_ops_per_s", GROUP_DEVICE, |c| {
        c.cgroup
    }),
];

/// A gauge family whose series are one-per-SUBJECT — the device, core, or
/// mount the measurement is about. Each distinct subject value materialises
/// a dimensional cell under the session component
/// ([`nmbrs_metrics::cells::resolve_under`]) and registers the family there
/// once; after that a sample is a hash lookup and a `set`.
///
/// This is what "submitted to metrics with the appropriate dimensional
/// labels, keyed by the session component" means concretely:
/// `sysmon_io_util{session="…",device="nvme1n1"}` — the subject is a label,
/// the cell refines the session's identity, and a sweep that shifts between
/// devices yields one honestly-labeled series per device rather than one
/// anonymous series whose subject silently changes.
struct SubjectGauge {
    family: &'static str,
    /// The dimensions this family's subject occupies (`device`, `core`,
    /// `mount`; `cgroup` and `device` together).
    label_keys: &'static [&'static str],
    parent: Arc<RwLock<Component>>,
    /// Instruments already materialised, by subject values.
    instances: std::collections::HashMap<Vec<String>, Arc<ValueGauge>>,
}

impl SubjectGauge {
    fn new(
        family: &'static str,
        label_keys: &'static [&'static str],
        parent: Arc<RwLock<Component>>,
    ) -> Self {
        Self {
            family,
            label_keys,
            parent,
            instances: Default::default(),
        }
    }

    /// Set the gauge of one subject, given as one value for each of
    /// the family's subject labels.
    fn set(&mut self, subject: &[&str], value: f64) {
        let key: Vec<String> = subject.iter().map(|s| s.to_string()).collect();
        if let Some(g) = self.instances.get(&key) {
            g.set(value);
            return;
        }
        let mut pairs = self.label_keys.iter().zip(subject);
        let Some((first_key, first_value)) = pairs.next() else {
            return;
        };
        let coord = pairs.fold(
            nmbrs_metrics::labels::Labels::of(*first_key, *first_value),
            |labels, (k, v)| labels.with(*k, *v),
        );
        let cell = nmbrs_metrics::cells::resolve_under(&self.parent, &coord);
        let labels = {
            let guard = cell.read().unwrap_or_else(|e| e.into_inner());
            guard.effective_labels().clone()
        };
        let g = Arc::new(ValueGauge::new(labels.with("family", self.family)));
        let registered = cell
            .write()
            .unwrap_or_else(|e| e.into_inner())
            .register_instrument(
                self.family,
                nmbrs_metrics::component::InstrumentRef::Gauge(g.clone()),
            );
        if let Err(e) = registered {
            // One cell, one family: a second registration here is a
            // programming error worth hearing about once, not per sample.
            crate::diag!(
                crate::observer::LogLevel::Warn,
                "sysmon: {family} cell {subject}: {e}",
                family = self.family,
                subject = key.join("/")
            );
        }
        g.set(value);
        self.instances.insert(key, g);
    }
}

/// The gauges of the enabled categories.
pub(super) struct Gauges {
    /// Host-scalar measures — no subject, so they live on the session root
    /// itself and carry exactly its labels.
    host: HashMap<&'static str, Arc<ValueGauge>>,
    /// Subject-dimensioned measures — one cell per device / core / mount /
    /// interface / process.
    subject: HashMap<&'static str, SubjectGauge>,
}

impl Gauges {
    /// Register gauges for the ENABLED categories on the session component.
    /// Direct registration on the session root — no child component, no new
    /// labels: the samples describe the whole host, which is exactly the
    /// session's dimensional cell.
    ///
    /// Subject-dimensioned families register per cell at first sight of
    /// each subject, NOT here — registering on the root as well would claim
    /// the family for the un-refined identity and collide with the first
    /// cell.
    pub fn register(component: &Arc<RwLock<Component>>, cats: Categories) -> Result<Self, String> {
        let mut gauges = Self {
            host: HashMap::new(),
            subject: HashMap::new(),
        };
        let mut guard = component.write().unwrap_or_else(|e| e.into_inner());
        let labels = guard.effective_labels().clone();
        for family in FAMILIES.iter().filter(|f| (f.enabled)(&cats)) {
            match family.subject {
                label_keys if !label_keys.is_empty() => {
                    gauges.subject.insert(
                        family.name,
                        SubjectGauge::new(family.name, label_keys, component.clone()),
                    );
                }
                _ => {
                    let g = Arc::new(ValueGauge::new(labels.with("family", family.name)));
                    guard.register_instrument(
                        family.name,
                        nmbrs_metrics::component::InstrumentRef::Gauge(g.clone()),
                    )?;
                    gauges.host.insert(family.name, g);
                }
            }
        }
        Ok(gauges)
    }

    /// Set a host-wide gauge. A family whose category is off has no
    /// gauge, and nothing is done.
    fn set(&self, family: &str, value: f64) {
        if let Some(g) = self.host.get(family) {
            g.set(value);
        }
    }

    /// Set one subject's gauge, likewise.
    fn set_for(&mut self, family: &str, subject: &str, value: f64) {
        self.set_at(family, &[subject], value);
    }

    /// Set the gauge of a subject with several labels, likewise.
    fn set_at(&mut self, family: &str, subject: &[&str], value: f64) {
        if let Some(g) = self.subject.get_mut(family) {
            g.set(subject, value);
        }
    }

    /// Write one sample window to the gauges.
    pub fn publish(&mut self, sample: &SysmonSample) {
        if let Some(cpu) = &sample.cpu {
            self.set("sysmon_cpu_util", cpu.mean);
            self.set("sysmon_cpu_core_p25", cpu.p25);
            self.set("sysmon_cpu_core_p50", cpu.p50);
            self.set("sysmon_cpu_core_p75", cpu.p75);
            self.set_for(
                "sysmon_cpu_core_max",
                &cpu.top_core.to_string(),
                cpu.max_core,
            );
        }
        if let Some((device, util)) = &sample.io {
            self.set_for("sysmon_io_util", device, *util);
        }
        for rate in &sample.io_rates {
            let device = rate.device.as_str();
            self.set_for("sysmon_io_read_bytes_per_s", device, rate.read_bytes_per_s);
            self.set_for(
                "sysmon_io_write_bytes_per_s",
                device,
                rate.write_bytes_per_s,
            );
            self.set_for("sysmon_io_read_ops_per_s", device, rate.read_ops_per_s);
            self.set_for("sysmon_io_write_ops_per_s", device, rate.write_ops_per_s);
        }
        if let Some((committed, cached)) = sample.ram {
            self.set("sysmon_ram_util", committed);
            self.set("sysmon_ram_util_cached", cached);
        }
        if let Some(util) = sample.rambw {
            self.set("sysmon_rambw_util", util);
        }
        if let Some((mount, util)) = &sample.storage {
            self.set_for("sysmon_storage_util", mount, *util);
        }
        for rate in &sample.net {
            self.set_for(
                "sysmon_net_rx_bytes_per_s",
                &rate.iface,
                rate.rx_bytes_per_s,
            );
            self.set_for(
                "sysmon_net_tx_bytes_per_s",
                &rate.iface,
                rate.tx_bytes_per_s,
            );
        }
        if let Some(p) = &sample.pressure {
            self.set("sysmon_pressure_cpu", p.cpu);
            self.set("sysmon_pressure_mem", p.mem);
            self.set("sysmon_pressure_mem_full", p.mem_full);
            self.set("sysmon_pressure_io", p.io);
            self.set("sysmon_pressure_io_full", p.io_full);
        }
        for p in &sample.procs {
            let name = p.name.as_str();
            self.set_for("sysmon_proc_cpu_cores", name, p.cpu_cores);
            self.set_for("sysmon_proc_rss_bytes", name, p.rss_bytes);
            self.set_for("sysmon_proc_threads", name, p.threads);
            if let Some((read, write)) = p.io_bytes_per_s {
                self.set_for("sysmon_proc_read_bytes_per_s", name, read);
                self.set_for("sysmon_proc_write_bytes_per_s", name, write);
            }
        }
        for group in &sample.cgroups {
            let name = group.name.as_str();
            if let Some(cores) = group.cpu_cores {
                self.set_for("sysmon_cgroup_cpu_cores", name, cores);
            }
            if let Some(bytes) = group.mem_bytes {
                self.set_for("sysmon_cgroup_mem_bytes", name, bytes);
            }
            for io in &group.io {
                let at = [name, io.device.as_str()];
                self.set_at(
                    "sysmon_cgroup_io_read_bytes_per_s",
                    &at,
                    io.read_bytes_per_s,
                );
                self.set_at(
                    "sysmon_cgroup_io_write_bytes_per_s",
                    &at,
                    io.write_bytes_per_s,
                );
                self.set_at("sysmon_cgroup_io_read_ops_per_s", &at, io.read_ops_per_s);
                self.set_at("sysmon_cgroup_io_write_ops_per_s", &at, io.write_ops_per_s);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A subject-dimensioned gauge materialises ONE cell per subject under
    /// the session component, each series carrying the subject as a label —
    /// and re-setting an existing subject attaches no twin.
    #[test]
    fn subject_gauges_dimension_by_cell_under_the_session_component() {
        let session = Arc::new(RwLock::new(nmbrs_metrics::component::Component::new(
            nmbrs_metrics::labels::Labels::of("session", "s1"),
            std::collections::HashMap::new(),
        )));
        let mut g = SubjectGauge::new("sysmon_io_util", &["device"], session.clone());
        g.set(&["nvme1n1"], 0.97);
        g.set(&["nvme2n1"], 0.40);
        g.set(&["nvme1n1"], 0.98);

        let guard = session.read().unwrap();
        assert_eq!(
            guard.child_count(),
            2,
            "one cell per device, re-sets attach no twin"
        );
        drop(guard);
        assert_eq!(g.instances.len(), 2);
        // The series carries session + device + family — the session's
        // identity refined by the subject, never replaced.
        let labels = g.instances[&vec!["nvme1n1".to_string()]]
            .labels()
            .to_prometheus();
        for owned in ["session=", "device=\"nvme1n1\"", "family="] {
            assert!(labels.contains(owned), "{owned} missing from {labels}");
        }
    }

    /// Only the enabled categories' families are registered, and a
    /// sample for a category that is off is not written anywhere.
    #[test]
    fn only_enabled_categories_have_gauges() {
        let session = Arc::new(RwLock::new(nmbrs_metrics::component::Component::new(
            nmbrs_metrics::labels::Labels::of("session", "s1"),
            std::collections::HashMap::new(),
        )));
        let cats = Categories {
            ram: true,
            net: true,
            ..Categories::default()
        };
        let mut gauges = Gauges::register(&session, cats).unwrap();
        assert_eq!(gauges.host.len(), 2);
        assert_eq!(gauges.subject.len(), 2);
        gauges.publish(&SysmonSample {
            ram: Some((0.25, 0.5)),
            pressure: Some(Default::default()),
            net: vec![nmbrs_host::net::NetRate {
                iface: "eth0".into(),
                rx_bytes_per_s: 10.0,
                tx_bytes_per_s: 20.0,
            }],
            ..SysmonSample::default()
        });
        assert_eq!(gauges.host["sysmon_ram_util"].get(), 0.25);
        assert_eq!(
            gauges.subject["sysmon_net_tx_bytes_per_s"].instances[&vec!["eth0".to_string()]].get(),
            20.0
        );
    }

    /// A control group's I/O is one series per group and device, each
    /// carrying both labels.
    #[test]
    fn a_groups_io_is_dimensioned_by_group_and_device() {
        let session = Arc::new(RwLock::new(nmbrs_metrics::component::Component::new(
            nmbrs_metrics::labels::Labels::of("session", "s1"),
            std::collections::HashMap::new(),
        )));
        let cats = Categories {
            cgroup: true,
            ..Categories::default()
        };
        let mut gauges = Gauges::register(&session, cats).unwrap();
        gauges.publish(&SysmonSample {
            cgroups: vec![nmbrs_host::cgroup::CgroupReading {
                name: "node".into(),
                cpu_cores: Some(1.5),
                mem_bytes: None,
                io: vec![nmbrs_host::cgroup::CgroupIoRate {
                    device: "md0".into(),
                    read_bytes_per_s: 1.0,
                    write_bytes_per_s: 2.0,
                    read_ops_per_s: 3.0,
                    write_ops_per_s: 4.0,
                }],
            }],
            ..SysmonSample::default()
        });
        let key = vec!["node".to_string(), "md0".to_string()];
        let written = &gauges.subject["sysmon_cgroup_io_write_bytes_per_s"].instances[&key];
        assert_eq!(written.get(), 2.0);
        let labels = written.labels().to_prometheus();
        for owned in ["cgroup=\"node\"", "device=\"md0\""] {
            assert!(labels.contains(owned), "{owned} missing from {labels}");
        }
        // The controller that was off has no series.
        assert!(
            gauges.subject["sysmon_cgroup_mem_bytes"]
                .instances
                .is_empty()
        );
    }

    /// A family name is given once, and each is under `sysmon_`.
    #[test]
    fn family_names_are_unique() {
        let mut names: Vec<&str> = FAMILIES.iter().map(|f| f.name).collect();
        assert!(names.iter().all(|n| n.starts_with("sysmon_")));
        names.sort_unstable();
        let total = names.len();
        names.dedup();
        assert_eq!(names.len(), total);
    }
}