Skip to main content

monitord/
json.rs

1//! # json module
2//!
3//! `json` is in charge of generating a flat BTreeMap like . serperated hierarchical
4//! JSON output. This is used by some metric parsing systems when running a command.
5
6use std::collections::BTreeMap;
7use std::collections::HashMap;
8
9use tracing::debug;
10
11use crate::dbus_stats;
12use crate::networkd;
13use crate::pid1;
14use crate::units;
15use crate::MachineStats;
16use crate::MonitordStats;
17
18/// Add a prefix if the config specifies one
19fn gen_base_metric_key(key_prefix: &str, metric_name: &str) -> String {
20    match key_prefix.is_empty() {
21        true => String::from(metric_name),
22        false => format!("{}.{}", key_prefix, metric_name),
23    }
24}
25
26fn flatten_networkd(
27    networkd_stats: &networkd::NetworkdState,
28    key_prefix: &str,
29) -> Vec<(String, serde_json::Value)> {
30    let mut flat_stats = vec![];
31    let base_metric_name = gen_base_metric_key(key_prefix, "networkd");
32
33    let managed_interfaces_key = format!("{}.managed_interfaces", base_metric_name);
34    flat_stats.push((
35        managed_interfaces_key,
36        networkd_stats.managed_interfaces.into(),
37    ));
38
39    if networkd_stats.interfaces_state.is_empty() {
40        debug!("No networkd interfaces to add to flat JSON");
41        return flat_stats;
42    }
43
44    for interface in &networkd_stats.interfaces_state {
45        let interface_base = format!("{}.{}", base_metric_name, interface.name);
46        flat_stats.push((
47            format!("{interface_base}.address_state"),
48            (interface.address_state as u64).into(),
49        ));
50        flat_stats.push((
51            format!("{interface_base}.admin_state"),
52            (interface.admin_state as u64).into(),
53        ));
54        flat_stats.push((
55            format!("{interface_base}.carrier_state"),
56            (interface.carrier_state as u64).into(),
57        ));
58        flat_stats.push((
59            format!("{interface_base}.ipv4_address_state"),
60            (interface.ipv4_address_state as u64).into(),
61        ));
62        flat_stats.push((
63            format!("{interface_base}.ipv6_address_state"),
64            (interface.ipv6_address_state as u64).into(),
65        ));
66        flat_stats.push((
67            format!("{interface_base}.oper_state"),
68            (interface.oper_state as u64).into(),
69        ));
70        flat_stats.push((
71            format!("{interface_base}.required_for_online"),
72            (interface.required_for_online as u64).into(),
73        ));
74    }
75    flat_stats
76}
77
78fn flatten_pid1(
79    optional_pid1_stats: &Option<pid1::Pid1Stats>,
80    key_prefix: &str,
81) -> Vec<(String, serde_json::Value)> {
82    // If we're not collecting pid1 stats don't add
83    let pid1_stats = match optional_pid1_stats {
84        Some(ps) => ps,
85        None => {
86            debug!("Skipping flattening pid1 stats as we got None ...");
87            return Vec::new();
88        }
89    };
90
91    let base_metric_name = gen_base_metric_key(key_prefix, "pid1");
92
93    vec![
94        (
95            format!("{}.cpu_time_kernel", base_metric_name),
96            pid1_stats.cpu_time_kernel.into(),
97        ),
98        (
99            format!("{}.cpu_user_kernel", base_metric_name),
100            pid1_stats.cpu_time_user.into(),
101        ),
102        (
103            format!("{}.memory_usage_bytes", base_metric_name),
104            pid1_stats.memory_usage_bytes.into(),
105        ),
106        (
107            format!("{}.fd_count", base_metric_name),
108            pid1_stats.fd_count.into(),
109        ),
110        (
111            format!("{}.tasks", base_metric_name),
112            pid1_stats.tasks.into(),
113        ),
114    ]
115}
116
117fn flatten_unit_files_scope(
118    scope: &units::UnitFilesScope,
119    base: &str,
120) -> Vec<(String, serde_json::Value)> {
121    let mut flat_stats = Vec::new();
122    for (unit_type, count) in &scope.generated {
123        flat_stats.push((
124            format!("{base}.generated.{unit_type}_units"),
125            (*count).into(),
126        ));
127    }
128    for (unit_type, count) in &scope.transient {
129        flat_stats.push((
130            format!("{base}.transient.{unit_type}_units"),
131            (*count).into(),
132        ));
133    }
134    flat_stats
135}
136
137fn flatten_unit_files(
138    unit_files: &units::UnitFilesStats,
139    key_prefix: &str,
140) -> Vec<(String, serde_json::Value)> {
141    let base = gen_base_metric_key(key_prefix, "unit_files");
142    let mut flat_stats = flatten_unit_files_scope(&unit_files.root, &format!("{base}.root"));
143    flat_stats.extend(flatten_unit_files_scope(
144        &unit_files.user,
145        &format!("{base}.user"),
146    ));
147    flat_stats
148}
149
150fn flatten_services(
151    service_stats_hash: &HashMap<String, units::ServiceStats>,
152    key_prefix: &str,
153) -> Vec<(String, serde_json::Value)> {
154    let mut flat_stats = Vec::new();
155    let base_metric_name = gen_base_metric_key(key_prefix, "services");
156
157    for (service_name, service_stats) in service_stats_hash.iter() {
158        if let Ok(serde_json::Value::Object(map)) = serde_json::to_value(service_stats) {
159            for (field_name, value) in map {
160                if value.is_number() {
161                    let key = format!("{base_metric_name}.{service_name}.{field_name}");
162                    flat_stats.push((key, value));
163                }
164            }
165        }
166    }
167    flat_stats
168}
169
170fn flatten_timers(
171    timer_stats_hash: &HashMap<String, crate::timer::TimerStats>,
172    key_prefix: &str,
173) -> Vec<(String, serde_json::Value)> {
174    let mut flat_stats = Vec::new();
175    let base_metric_name = gen_base_metric_key(key_prefix, "timers");
176
177    for (timer_name, timer_stats) in timer_stats_hash.iter() {
178        if let Ok(serde_json::Value::Object(map)) = serde_json::to_value(timer_stats) {
179            for (field_name, value) in map {
180                let key = format!("{base_metric_name}.{timer_name}.{field_name}");
181                if value.is_number() {
182                    flat_stats.push((key, value));
183                } else if let Some(b) = value.as_bool() {
184                    flat_stats.push((key, (b as u64).into()));
185                }
186            }
187        }
188    }
189    flat_stats
190}
191
192fn flatten_unit_states(
193    unit_states_hash: &HashMap<String, units::UnitStates>,
194    key_prefix: &str,
195) -> Vec<(String, serde_json::Value)> {
196    let mut flat_stats = Vec::new();
197    let base_metric_name = gen_base_metric_key(key_prefix, "unit_states");
198
199    for (unit_name, unit_state_stats) in unit_states_hash.iter() {
200        if let Ok(serde_json::Value::Object(map)) = serde_json::to_value(unit_state_stats) {
201            for (field_name, value) in map {
202                let key = format!("{base_metric_name}.{unit_name}.{field_name}");
203                if value.is_number() {
204                    flat_stats.push((key, value));
205                } else if let Some(b) = value.as_bool() {
206                    flat_stats.push((key, (b as u64).into()));
207                }
208            }
209        }
210    }
211
212    flat_stats
213}
214
215/// Lightweight view of `SystemdUnitStats` containing only the numeric counters.
216/// Used by `flatten_units` to avoid serializing the nested `service_stats`,
217/// `timer_stats`, and `unit_states` hashmaps, keeping flattening O(number_of_counters).
218#[derive(serde::Serialize)]
219struct UnitCounters {
220    activating_units: u64,
221    active_units: u64,
222    automount_units: u64,
223    device_units: u64,
224    failed_units: u64,
225    inactive_units: u64,
226    jobs_queued: u64,
227    loaded_units: u64,
228    masked_units: u64,
229    mount_units: u64,
230    not_found_units: u64,
231    path_units: u64,
232    scope_units: u64,
233    service_units: u64,
234    slice_units: u64,
235    socket_units: u64,
236    target_units: u64,
237    timer_units: u64,
238    timer_persistent_units: u64,
239    timer_remain_after_elapse: u64,
240    total_units: u64,
241}
242
243impl From<&units::SystemdUnitStats> for UnitCounters {
244    fn from(s: &units::SystemdUnitStats) -> Self {
245        Self {
246            activating_units: s.activating_units,
247            active_units: s.active_units,
248            automount_units: s.automount_units,
249            device_units: s.device_units,
250            failed_units: s.failed_units,
251            inactive_units: s.inactive_units,
252            jobs_queued: s.jobs_queued,
253            loaded_units: s.loaded_units,
254            masked_units: s.masked_units,
255            mount_units: s.mount_units,
256            not_found_units: s.not_found_units,
257            path_units: s.path_units,
258            scope_units: s.scope_units,
259            service_units: s.service_units,
260            slice_units: s.slice_units,
261            socket_units: s.socket_units,
262            target_units: s.target_units,
263            timer_units: s.timer_units,
264            timer_persistent_units: s.timer_persistent_units,
265            timer_remain_after_elapse: s.timer_remain_after_elapse,
266            total_units: s.total_units,
267        }
268    }
269}
270
271fn flatten_units(
272    units_stats: &units::SystemdUnitStats,
273    key_prefix: &str,
274) -> Vec<(String, serde_json::Value)> {
275    let mut flat_stats = Vec::new();
276    let base_metric_name = gen_base_metric_key(key_prefix, "units");
277
278    if let Ok(serde_json::Value::Object(map)) =
279        serde_json::to_value(UnitCounters::from(units_stats))
280    {
281        for (field_name, value) in map {
282            if value.is_number() {
283                let key = format!("{base_metric_name}.{field_name}");
284                flat_stats.push((key, value));
285            }
286        }
287    }
288    flat_stats
289}
290
291fn flatten_machines(
292    machines_stats: &HashMap<String, MachineStats>,
293    key_prefix: &str,
294) -> BTreeMap<String, serde_json::Value> {
295    let mut flat_stats = BTreeMap::new();
296
297    if machines_stats.is_empty() {
298        return flat_stats;
299    }
300
301    for (machine, stats) in machines_stats {
302        let machine_key_prefix = match key_prefix.is_empty() {
303            true => format!("machines.{}", machine),
304            false => format!("{}.machines.{}", key_prefix, machine),
305        };
306        flat_stats.extend(flatten_networkd(&stats.networkd, &machine_key_prefix));
307        flat_stats.extend(flatten_varlink_usage(
308            &stats.varlink_usage,
309            &machine_key_prefix,
310        ));
311        flat_stats.extend(flatten_units(&stats.units, &machine_key_prefix));
312        flat_stats.extend(flatten_unit_files(
313            &stats.units.unit_files,
314            &machine_key_prefix,
315        ));
316        flat_stats.extend(flatten_units_collection_timings(
317            &stats.units.collection_timings,
318            &machine_key_prefix,
319        ));
320        flat_stats.extend(flatten_pid1(&stats.pid1, &machine_key_prefix));
321        flat_stats.insert(
322            gen_base_metric_key(&machine_key_prefix, "system-state"),
323            (stats.system_state as u64).into(),
324        );
325        flat_stats.extend(flatten_services(
326            &stats.units.service_stats,
327            &machine_key_prefix,
328        ));
329        flat_stats.extend(flatten_timers(
330            &stats.units.timer_stats,
331            &machine_key_prefix,
332        ));
333        flat_stats.extend(flatten_boot_blame(&stats.boot_blame, &machine_key_prefix));
334        flat_stats.extend(flatten_verify_stats(
335            &stats.verify_stats,
336            &machine_key_prefix,
337        ));
338    }
339
340    flat_stats
341}
342
343fn flatten_dbus_stats(
344    optional_dbus_stats: &Option<dbus_stats::DBusStats>,
345    key_prefix: &str,
346) -> BTreeMap<String, serde_json::Value> {
347    let mut flat_stats: BTreeMap<String, serde_json::Value> = BTreeMap::new();
348    let dbus_stats = match optional_dbus_stats {
349        Some(ds) => ds,
350        None => {
351            debug!("Skipping flattening dbus stats as we got None ...");
352            return flat_stats;
353        }
354    };
355
356    let base_metric_name = gen_base_metric_key(key_prefix, "dbus");
357    let fields = [
358        // ignore serial
359        ("active_connections", dbus_stats.active_connections),
360        ("incomplete_connections", dbus_stats.incomplete_connections),
361        ("bus_names", dbus_stats.bus_names),
362        ("peak_bus_names", dbus_stats.peak_bus_names),
363        (
364            "peak_bus_names_per_connection",
365            dbus_stats.peak_bus_names_per_connection,
366        ),
367        ("match_rules", dbus_stats.match_rules),
368        ("peak_match_rules", dbus_stats.peak_match_rules),
369        (
370            "peak_match_rules_per_connection",
371            dbus_stats.peak_match_rules_per_connection,
372        ),
373        ("stale_fds", dbus_stats.stale_fds),
374    ];
375
376    for (field_name, value) in fields {
377        if let Some(val) = value {
378            flat_stats.insert(format!("{base_metric_name}.{field_name}"), val.into());
379        }
380    }
381
382    if let Some(peer_accounting) = dbus_stats.peer_accounting() {
383        for peer in peer_accounting.values() {
384            let peer_name = peer.get_name();
385            let peer_fields = [
386                ("name_objects", peer.name_objects),
387                ("match_bytes", peer.match_bytes),
388                ("matches", peer.matches),
389                ("reply_objects", peer.reply_objects),
390                ("incoming_bytes", peer.incoming_bytes),
391                ("incoming_fds", peer.incoming_fds),
392                ("outgoing_bytes", peer.outgoing_bytes),
393                ("outgoing_fds", peer.outgoing_fds),
394                ("activation_request_bytes", peer.activation_request_bytes),
395                ("activation_request_fds", peer.activation_request_fds),
396            ];
397
398            for (field_name, value) in peer_fields {
399                if let Some(val) = value {
400                    flat_stats.insert(
401                        format!("{base_metric_name}.peer.{peer_name}.{field_name}"),
402                        val.into(),
403                    );
404                }
405            }
406        }
407    }
408
409    if let Some(cgroup_accounting) = dbus_stats.cgroup_accounting() {
410        for cgroup in cgroup_accounting.values() {
411            let cgroup_name = &cgroup.name;
412            let cgroup_fields = [
413                ("name_objects", cgroup.name_objects),
414                ("match_bytes", cgroup.match_bytes),
415                ("matches", cgroup.matches),
416                ("reply_objects", cgroup.reply_objects),
417                ("incoming_bytes", cgroup.incoming_bytes),
418                ("incoming_fds", cgroup.incoming_fds),
419                ("outgoing_bytes", cgroup.outgoing_bytes),
420                ("outgoing_fds", cgroup.outgoing_fds),
421                ("activation_request_bytes", cgroup.activation_request_bytes),
422                ("activation_request_fds", cgroup.activation_request_fds),
423            ];
424
425            for (field_name, value) in cgroup_fields {
426                if let Some(val) = value {
427                    flat_stats.insert(
428                        format!("{base_metric_name}.cgroup.{cgroup_name}.{field_name}"),
429                        val.into(),
430                    );
431                }
432            }
433        }
434    }
435
436    if let Some(user_accounting) = dbus_stats.user_accounting() {
437        // process user accounting if present
438        for user in user_accounting.values() {
439            let user_name = &user.username;
440            let user_fields = [
441                ("bytes", user.bytes.clone()),
442                ("fds", user.fds.clone()),
443                ("matches", user.matches.clone()),
444                ("objects", user.objects.clone()),
445            ];
446
447            for (field_name, value) in user_fields {
448                if let Some(val) = value {
449                    flat_stats.insert(
450                        format!("{base_metric_name}.user.{user_name}.{field_name}"),
451                        val.get_usage().into(),
452                    );
453                }
454            }
455
456            if let Some(stale_fds) = user.stale_fds {
457                flat_stats.insert(
458                    format!("{base_metric_name}.user.{user_name}.stale_fds"),
459                    stale_fds.into(),
460                );
461            }
462        }
463    }
464
465    flat_stats
466}
467
468fn flatten_boot_blame(
469    optional_boot_blame: &Option<crate::boot::BootBlameStats>,
470    key_prefix: &str,
471) -> BTreeMap<String, serde_json::Value> {
472    let mut flat_stats: BTreeMap<String, serde_json::Value> = BTreeMap::new();
473    let boot_blame_stats = match optional_boot_blame {
474        Some(bb) => bb,
475        None => {
476            debug!("Skipping flattening boot blame stats as we got None ...");
477            return flat_stats;
478        }
479    };
480
481    let base_metric_name = gen_base_metric_key(key_prefix, "boot.blame");
482
483    for (unit_name, activation_time) in boot_blame_stats.iter() {
484        let key = format!("{}.{}", base_metric_name, unit_name);
485        flat_stats.insert(key, (*activation_time).into());
486    }
487
488    flat_stats
489}
490
491fn flatten_verify_stats(
492    optional_verify_stats: &Option<crate::verify::VerifyStats>,
493    key_prefix: &str,
494) -> BTreeMap<String, serde_json::Value> {
495    let mut flat_stats: BTreeMap<String, serde_json::Value> = BTreeMap::new();
496    let verify_stats = match optional_verify_stats {
497        Some(vs) => vs,
498        None => {
499            debug!("Skipping flattening verify stats as we got None ...");
500            return flat_stats;
501        }
502    };
503
504    let base_metric_name = gen_base_metric_key(key_prefix, "verify.failing");
505
506    // Add total count
507    flat_stats.insert(
508        format!("{base_metric_name}.total"),
509        verify_stats.total.into(),
510    );
511
512    // Add counts by type (only if they exist)
513    for (unit_type, count) in &verify_stats.by_type {
514        flat_stats.insert(format!("{base_metric_name}.{unit_type}"), (*count).into());
515    }
516
517    flat_stats
518}
519
520fn flatten_report(
521    optional_report: &Option<crate::report_collector::ReportStats>,
522    key_prefix: &str,
523) -> BTreeMap<String, serde_json::Value> {
524    let mut flat_stats: BTreeMap<String, serde_json::Value> = BTreeMap::new();
525    let report = match optional_report {
526        Some(report) => report,
527        None => return flat_stats,
528    };
529    let base_metric_name = gen_base_metric_key(key_prefix, "report");
530    for (source_name, source) in report {
531        let source_key = format!("{base_metric_name}.{source_name}");
532        flat_stats.insert(format!("{source_key}.up"), u64::from(source.up).into());
533        flat_stats.insert(
534            format!("{source_key}.dropped_metrics"),
535            source.dropped_metrics.into(),
536        );
537        flat_stats.insert(
538            format!("{source_key}.colliding_metrics"),
539            source.colliding_metrics.into(),
540        );
541        // normalize_metrics already rejected anything whose leaves collide,
542        // so every leaf here lands on a key of its own.
543        let mut leaves = Vec::new();
544        for (metric_key, value) in &source.metrics {
545            crate::report_collector::flat_leaves(
546                format!("{source_key}.metrics.{metric_key}"),
547                value,
548                &mut leaves,
549            );
550        }
551        flat_stats.extend(leaves);
552    }
553    flat_stats
554}
555
556/// Emit one `varlink_usage.<collector>` 0/1 gauge per collector that ran.
557///
558/// Only collectors whose `Option<CollectorTransport>` is `Some` emit a gauge:
559/// disabled collectors (and any re-validation the caller does over the
560/// enabled sections) stay absent, so `count()` over the `varlink_usage_*`
561/// gauges is the enabled set and `sum() / count()` is the share of
562/// collectors served by varlink this run. Downstream metric consumers (e.g.
563/// monitord-exporter) aggregate the gauges from there; monitord itself only
564/// makes them available in its output formats.
565fn flatten_varlink_usage(
566    usage: &crate::VarlinkUsage,
567    key_prefix: &str,
568) -> BTreeMap<String, serde_json::Value> {
569    let mut flat_stats: BTreeMap<String, serde_json::Value> = BTreeMap::new();
570    let base_metric_name = gen_base_metric_key(key_prefix, "varlink_usage");
571    let fields: [(&str, Option<crate::CollectorTransport>); 7] = [
572        ("version", usage.version),
573        ("system_state", usage.system_state),
574        ("units", usage.units),
575        ("networkd", usage.networkd),
576        ("machines", usage.machines),
577        ("boot_blame", usage.boot_blame),
578        ("verify", usage.verify),
579    ];
580    for (name, transport) in fields {
581        if let Some(transport) = transport {
582            flat_stats.insert(
583                format!("{base_metric_name}.{name}"),
584                transport.as_u64().into(),
585            );
586        }
587    }
588    flat_stats
589}
590
591fn flatten_collector_timings(
592    timings: &[crate::CollectorTiming],
593    key_prefix: &str,
594) -> BTreeMap<String, serde_json::Value> {
595    let mut flat_stats: BTreeMap<String, serde_json::Value> = BTreeMap::new();
596    let base_metric_name = gen_base_metric_key(key_prefix, "collector_timings");
597    for t in timings {
598        flat_stats.insert(
599            format!("{base_metric_name}.{}.start_offset_ms", t.name),
600            t.start_offset_ms.into(),
601        );
602        flat_stats.insert(
603            format!("{base_metric_name}.{}.elapsed_ms", t.name),
604            t.elapsed_ms.into(),
605        );
606        flat_stats.insert(
607            format!("{base_metric_name}.{}.success", t.name),
608            (if t.success { 1u64 } else { 0u64 }).into(),
609        );
610    }
611    flat_stats
612}
613
614fn flatten_units_collection_timings(
615    timings: &units::UnitsCollectionTimings,
616    key_prefix: &str,
617) -> BTreeMap<String, serde_json::Value> {
618    let mut flat_stats: BTreeMap<String, serde_json::Value> = BTreeMap::new();
619    let base_metric_name = gen_base_metric_key(key_prefix, "collection_timings");
620    flat_stats.insert(
621        format!("{base_metric_name}.list_units_ms"),
622        timings.list_units_ms.into(),
623    );
624    flat_stats.insert(
625        format!("{base_metric_name}.per_unit_loop_ms"),
626        timings.per_unit_loop_ms.into(),
627    );
628    flat_stats.insert(
629        format!("{base_metric_name}.timer_dbus_fetches"),
630        timings.timer_dbus_fetches.into(),
631    );
632    flat_stats.insert(
633        format!("{base_metric_name}.state_dbus_fetches"),
634        timings.state_dbus_fetches.into(),
635    );
636    flat_stats.insert(
637        format!("{base_metric_name}.service_dbus_fetches"),
638        timings.service_dbus_fetches.into(),
639    );
640    flat_stats.insert(
641        format!("{base_metric_name}.varlink_service_cache_hits"),
642        timings.varlink_service_cache_hits.into(),
643    );
644    flat_stats.insert(
645        format!("{base_metric_name}.varlink_unit_list_fetches"),
646        timings.varlink_unit_list_fetches.into(),
647    );
648    flat_stats.insert(
649        format!("{base_metric_name}.varlink_unit_list_max_ms"),
650        timings.varlink_unit_list_max_ms.into(),
651    );
652    flat_stats.insert(
653        format!("{base_metric_name}.varlink_unit_list_ms"),
654        timings.varlink_unit_list_ms.into(),
655    );
656    // Rank is encoded in the key (not just the unit name) so ordering survives
657    // flattening; the leaf value stays a plain number like every other key here.
658    for (idx, (unit_name, duration_ms)) in timings.slowest_units.iter().enumerate() {
659        flat_stats.insert(
660            format!("{base_metric_name}.slowest_units.{idx}.{unit_name}"),
661            (*duration_ms).into(),
662        );
663    }
664    flat_stats
665}
666
667/// Take the standard returned structs and move all to a flat BTreeMap<str, float|int> like JSON
668fn flatten_stats(
669    stats_struct: &MonitordStats,
670    key_prefix: &str,
671) -> BTreeMap<String, serde_json::Value> {
672    let mut flat_stats: BTreeMap<String, serde_json::Value> = BTreeMap::new();
673    flat_stats.insert(
674        gen_base_metric_key(key_prefix, "stat_collection_run_time_ms"),
675        stats_struct.stat_collection_run_time_ms.into(),
676    );
677    flat_stats.extend(flatten_collector_timings(
678        &stats_struct.collector_timings,
679        key_prefix,
680    ));
681    flat_stats.extend(flatten_varlink_usage(
682        &stats_struct.varlink_usage,
683        key_prefix,
684    ));
685    flat_stats.extend(flatten_units_collection_timings(
686        &stats_struct.units.collection_timings,
687        key_prefix,
688    ));
689    flat_stats.extend(flatten_networkd(&stats_struct.networkd, key_prefix));
690    flat_stats.extend(flatten_pid1(&stats_struct.pid1, key_prefix));
691    flat_stats.insert(
692        gen_base_metric_key(key_prefix, "system-state"),
693        (stats_struct.system_state as u64).into(),
694    );
695    flat_stats.extend(flatten_services(
696        &stats_struct.units.service_stats,
697        key_prefix,
698    ));
699    flat_stats.extend(flatten_timers(&stats_struct.units.timer_stats, key_prefix));
700    flat_stats.extend(flatten_unit_states(
701        &stats_struct.units.unit_states,
702        key_prefix,
703    ));
704    flat_stats.extend(flatten_units(&stats_struct.units, key_prefix));
705    flat_stats.extend(flatten_unit_files(
706        &stats_struct.units.unit_files,
707        key_prefix,
708    ));
709    flat_stats.insert(
710        gen_base_metric_key(key_prefix, "version"),
711        stats_struct.version.to_string().into(),
712    );
713    flat_stats.extend(flatten_machines(&stats_struct.machines, key_prefix));
714    flat_stats.extend(flatten_dbus_stats(&stats_struct.dbus_stats, key_prefix));
715    flat_stats.extend(flatten_boot_blame(&stats_struct.boot_blame, key_prefix));
716    flat_stats.extend(flatten_verify_stats(&stats_struct.verify_stats, key_prefix));
717    flat_stats.extend(flatten_report(&stats_struct.report, key_prefix));
718    flat_stats
719}
720
721/// Take the standard returned structs and move all to a flat JSON str
722pub fn flatten(
723    stats_struct: &MonitordStats,
724    key_prefix: &str,
725) -> Result<String, serde_json::Error> {
726    serde_json::to_string_pretty(&flatten_stats(stats_struct, key_prefix))
727}
728
729#[cfg(test)]
730mod tests {
731    use crate::timer;
732
733    use super::*;
734
735    // This will always be sorted / deterministic ...
736    const EXPECTED_FLAT_JSON: &str = r###"{
737  "boot.blame.cpe_chef.service": 103.05,
738  "boot.blame.dnf5-automatic.service": 204.159,
739  "boot.blame.sys-module-fuse.device": 16.21,
740  "collection_timings.list_units_ms": 5.0,
741  "collection_timings.per_unit_loop_ms": 37.0,
742  "collection_timings.service_dbus_fetches": 1,
743  "collection_timings.slowest_units.0.unittest.service": 12.5,
744  "collection_timings.slowest_units.1.unittest.timer": 8.25,
745  "collection_timings.state_dbus_fetches": 0,
746  "collection_timings.timer_dbus_fetches": 4,
747  "collection_timings.varlink_service_cache_hits": 9,
748  "collection_timings.varlink_unit_list_fetches": 3,
749  "collection_timings.varlink_unit_list_max_ms": 1.5,
750  "collection_timings.varlink_unit_list_ms": 2.25,
751  "collector_timings.boot_blame.elapsed_ms": 12.5,
752  "collector_timings.boot_blame.start_offset_ms": 0.25,
753  "collector_timings.boot_blame.success": 0,
754  "collector_timings.units.elapsed_ms": 42.0,
755  "collector_timings.units.start_offset_ms": 0.5,
756  "collector_timings.units.success": 1,
757  "machines.foo.collection_timings.list_units_ms": 0.0,
758  "machines.foo.collection_timings.per_unit_loop_ms": 0.0,
759  "machines.foo.collection_timings.service_dbus_fetches": 0,
760  "machines.foo.collection_timings.state_dbus_fetches": 0,
761  "machines.foo.collection_timings.timer_dbus_fetches": 0,
762  "machines.foo.collection_timings.varlink_service_cache_hits": 0,
763  "machines.foo.collection_timings.varlink_unit_list_fetches": 0,
764  "machines.foo.collection_timings.varlink_unit_list_max_ms": 0.0,
765  "machines.foo.collection_timings.varlink_unit_list_ms": 0.0,
766  "machines.foo.networkd.managed_interfaces": 0,
767  "machines.foo.system-state": 0,
768  "machines.foo.timers.unittest.timer.accuracy_usec": 69,
769  "machines.foo.timers.unittest.timer.fixed_random_delay": 1,
770  "machines.foo.timers.unittest.timer.last_trigger_usec": 69,
771  "machines.foo.timers.unittest.timer.last_trigger_usec_monotonic": 69,
772  "machines.foo.timers.unittest.timer.next_elapse_usec_monotonic": 69,
773  "machines.foo.timers.unittest.timer.next_elapse_usec_realtime": 69,
774  "machines.foo.timers.unittest.timer.persistent": 0,
775  "machines.foo.timers.unittest.timer.randomized_delay_usec": 69,
776  "machines.foo.timers.unittest.timer.remain_after_elapse": 1,
777  "machines.foo.timers.unittest.timer.service_unit_last_state_change_usec": 69,
778  "machines.foo.timers.unittest.timer.service_unit_last_state_change_usec_monotonic": 69,
779  "machines.foo.units.activating_units": 0,
780  "machines.foo.units.active_units": 0,
781  "machines.foo.units.automount_units": 0,
782  "machines.foo.units.device_units": 0,
783  "machines.foo.units.failed_units": 0,
784  "machines.foo.units.inactive_units": 0,
785  "machines.foo.units.jobs_queued": 0,
786  "machines.foo.units.loaded_units": 0,
787  "machines.foo.units.masked_units": 0,
788  "machines.foo.units.mount_units": 0,
789  "machines.foo.units.not_found_units": 0,
790  "machines.foo.units.path_units": 0,
791  "machines.foo.units.scope_units": 0,
792  "machines.foo.units.service_units": 0,
793  "machines.foo.units.slice_units": 0,
794  "machines.foo.units.socket_units": 0,
795  "machines.foo.units.target_units": 0,
796  "machines.foo.units.timer_persistent_units": 0,
797  "machines.foo.units.timer_remain_after_elapse": 0,
798  "machines.foo.units.timer_units": 0,
799  "machines.foo.units.total_units": 0,
800  "networkd.eth0.address_state": 3,
801  "networkd.eth0.admin_state": 4,
802  "networkd.eth0.carrier_state": 5,
803  "networkd.eth0.ipv4_address_state": 3,
804  "networkd.eth0.ipv6_address_state": 2,
805  "networkd.eth0.oper_state": 9,
806  "networkd.eth0.required_for_online": 1,
807  "networkd.managed_interfaces": 1,
808  "pid1.cpu_time_kernel": 69,
809  "pid1.cpu_user_kernel": 69,
810  "pid1.fd_count": 69,
811  "pid1.memory_usage_bytes": 69,
812  "pid1.tasks": 1,
813  "report.io.systemd.Basic.colliding_metrics": 0,
814  "report.io.systemd.Basic.dropped_metrics": 0,
815  "report.io.systemd.Basic.metrics.CpuTime.foo.service.mode_user": 69,
816  "report.io.systemd.Basic.metrics.KernelVersion": "unittest",
817  "report.io.systemd.Basic.metrics.OsRelease.ID": "fedora",
818  "report.io.systemd.Basic.metrics.OsRelease.VERSION_ID": "40",
819  "report.io.systemd.Basic.up": 1,
820  "report.io.systemd.DiskSpace.colliding_metrics": 0,
821  "report.io.systemd.DiskSpace.dropped_metrics": 0,
822  "report.io.systemd.DiskSpace.up": 0,
823  "services.unittest.service.active_enter_timestamp": 0,
824  "services.unittest.service.active_exit_timestamp": 0,
825  "services.unittest.service.cpuusage_nsec": 0,
826  "services.unittest.service.inactive_exit_timestamp": 0,
827  "services.unittest.service.ioread_bytes": 0,
828  "services.unittest.service.ioread_operations": 0,
829  "services.unittest.service.memory_available": 0,
830  "services.unittest.service.memory_current": 0,
831  "services.unittest.service.nrestarts": 0,
832  "services.unittest.service.processes": 0,
833  "services.unittest.service.restart_usec": 0,
834  "services.unittest.service.state_change_timestamp": 0,
835  "services.unittest.service.status_errno": -69,
836  "services.unittest.service.tasks_current": 0,
837  "services.unittest.service.timeout_clean_usec": 0,
838  "services.unittest.service.watchdog_usec": 0,
839  "stat_collection_run_time_ms": 69.0,
840  "system-state": 3,
841  "timers.unittest.timer.accuracy_usec": 69,
842  "timers.unittest.timer.fixed_random_delay": 1,
843  "timers.unittest.timer.last_trigger_usec": 69,
844  "timers.unittest.timer.last_trigger_usec_monotonic": 69,
845  "timers.unittest.timer.next_elapse_usec_monotonic": 69,
846  "timers.unittest.timer.next_elapse_usec_realtime": 69,
847  "timers.unittest.timer.persistent": 0,
848  "timers.unittest.timer.randomized_delay_usec": 69,
849  "timers.unittest.timer.remain_after_elapse": 1,
850  "timers.unittest.timer.service_unit_last_state_change_usec": 69,
851  "timers.unittest.timer.service_unit_last_state_change_usec_monotonic": 69,
852  "unit_states.nvme\\x2dWDC_CL_SN730_SDBQNTY\\x2d512G\\x2d2020_37222H80070511\\x2dpart3.device.active_state": 1,
853  "unit_states.nvme\\x2dWDC_CL_SN730_SDBQNTY\\x2d512G\\x2d2020_37222H80070511\\x2dpart3.device.load_state": 1,
854  "unit_states.nvme\\x2dWDC_CL_SN730_SDBQNTY\\x2d512G\\x2d2020_37222H80070511\\x2dpart3.device.unhealthy": 0,
855  "unit_states.unittest.service.active_state": 1,
856  "unit_states.unittest.service.load_state": 1,
857  "unit_states.unittest.service.time_in_state_usecs": 69,
858  "unit_states.unittest.service.unhealthy": 0,
859  "units.activating_units": 0,
860  "units.active_units": 0,
861  "units.automount_units": 0,
862  "units.device_units": 0,
863  "units.failed_units": 0,
864  "units.inactive_units": 0,
865  "units.jobs_queued": 0,
866  "units.loaded_units": 0,
867  "units.masked_units": 0,
868  "units.mount_units": 0,
869  "units.not_found_units": 0,
870  "units.path_units": 0,
871  "units.scope_units": 0,
872  "units.service_units": 0,
873  "units.slice_units": 0,
874  "units.socket_units": 0,
875  "units.target_units": 0,
876  "units.timer_persistent_units": 0,
877  "units.timer_remain_after_elapse": 0,
878  "units.timer_units": 0,
879  "units.total_units": 0,
880  "varlink_usage.boot_blame": 1,
881  "varlink_usage.machines": 0,
882  "varlink_usage.networkd": 1,
883  "varlink_usage.system_state": 1,
884  "varlink_usage.units": 0,
885  "varlink_usage.verify": 0,
886  "varlink_usage.version": 1,
887  "verify.failing.service": 2,
888  "verify.failing.slice": 1,
889  "verify.failing.total": 3,
890  "version": "255.7-1.fc40"
891}"###;
892
893    fn return_monitord_stats() -> MonitordStats {
894        let mut stats = MonitordStats {
895            networkd: networkd::NetworkdState {
896                interfaces_state: vec![networkd::InterfaceState {
897                    address_state: networkd::AddressState::routable,
898                    admin_state: networkd::AdminState::configured,
899                    carrier_state: networkd::CarrierState::carrier,
900                    ipv4_address_state: networkd::AddressState::routable,
901                    ipv6_address_state: networkd::AddressState::degraded,
902                    name: "eth0".to_string(),
903                    network_file: "/etc/systemd/network/69-eno4.network".to_string(),
904                    oper_state: networkd::OperState::routable,
905                    required_for_online: networkd::BoolState::True,
906                }],
907                managed_interfaces: 1,
908            },
909            pid1: Some(crate::pid1::Pid1Stats {
910                cpu_time_kernel: 69,
911                cpu_time_user: 69,
912                memory_usage_bytes: 69,
913                fd_count: 69,
914                tasks: 1,
915            }),
916            system_state: crate::system::SystemdSystemState::running,
917            units: crate::units::SystemdUnitStats::default(),
918            version: String::from("255.7-1.fc40")
919                .try_into()
920                .expect("Unable to make SystemdVersion struct"),
921            machines: HashMap::from([(String::from("foo"), MachineStats::default())]),
922            dbus_stats: None,
923            boot_blame: None,
924            verify_stats: Some(crate::verify::VerifyStats {
925                total: 3,
926                by_type: HashMap::from([("service".to_string(), 2), ("slice".to_string(), 1)]),
927            }),
928            stat_collection_run_time_ms: 69.0,
929            collector_timings: vec![
930                crate::CollectorTiming {
931                    name: "units".to_string(),
932                    start_offset_ms: 0.5,
933                    elapsed_ms: 42.0,
934                    success: true,
935                },
936                crate::CollectorTiming {
937                    name: "boot_blame".to_string(),
938                    start_offset_ms: 0.25,
939                    elapsed_ms: 12.5,
940                    success: false,
941                },
942            ],
943            // Exhaustive init (no `..Default::default()`): adding a new
944            // gauge forces this fixture — and EXPECTED_FLAT_JSON — to be
945            // updated, so the example flat output can't silently go stale.
946            varlink_usage: crate::VarlinkUsage {
947                version: Some(crate::CollectorTransport::Varlink),
948                system_state: Some(crate::CollectorTransport::Varlink),
949                units: Some(crate::CollectorTransport::Dbus),
950                networkd: Some(crate::CollectorTransport::Varlink),
951                machines: Some(crate::CollectorTransport::Dbus),
952                boot_blame: Some(crate::CollectorTransport::Varlink),
953                verify: Some(crate::CollectorTransport::Dbus),
954            },
955            report: Some(BTreeMap::from([
956                (
957                    String::from("io.systemd.Basic"),
958                    crate::report_collector::ReportSource {
959                        up: true,
960                        dropped_metrics: 0,
961                        colliding_metrics: 0,
962                        metrics: BTreeMap::from([
963                            (String::from("KernelVersion"), serde_json::json!("unittest")),
964                            (
965                                String::from("CpuTime.foo.service.mode_user"),
966                                serde_json::json!(69),
967                            ),
968                            (
969                                String::from("OsRelease"),
970                                serde_json::json!({"ID": "fedora", "VERSION_ID": "40"}),
971                            ),
972                        ]),
973                    },
974                ),
975                (
976                    String::from("io.systemd.DiskSpace"),
977                    crate::report_collector::ReportSource::default(),
978                ),
979            ])),
980        };
981        stats.units.collection_timings = units::UnitsCollectionTimings {
982            list_units_ms: 5.0,
983            unit_files_ms: 2.0,
984            per_unit_loop_ms: 37.0,
985            timer_dbus_fetches: 4,
986            state_dbus_fetches: 0,
987            service_dbus_fetches: 1,
988            slowest_units: vec![
989                ("unittest.service".to_string(), 12.5),
990                ("unittest.timer".to_string(), 8.25),
991            ],
992            varlink_unit_list_fetches: 3,
993            varlink_unit_list_ms: 2.25,
994            varlink_unit_list_max_ms: 1.5,
995            varlink_service_cache_hits: 9,
996        };
997        let service_unit_name = String::from("unittest.service");
998        stats.units.service_stats.insert(
999            service_unit_name.clone(),
1000            units::ServiceStats {
1001                // Ensure json-flat handles negative i32s
1002                status_errno: -69,
1003                ..Default::default()
1004            },
1005        );
1006        stats.units.unit_states.insert(
1007            String::from("unittest.service"),
1008            units::UnitStates {
1009                active_state: units::SystemdUnitActiveState::active,
1010                load_state: units::SystemdUnitLoadState::loaded,
1011                unhealthy: false,
1012                time_in_state_usecs: Some(69),
1013            },
1014        );
1015        let timer_unit = String::from("unittest.timer");
1016        let timer_stats = timer::TimerStats {
1017            accuracy_usec: 69,
1018            fixed_random_delay: true,
1019            last_trigger_usec: 69,
1020            last_trigger_usec_monotonic: 69,
1021            next_elapse_usec_monotonic: 69,
1022            next_elapse_usec_realtime: 69,
1023            persistent: false,
1024            randomized_delay_usec: 69,
1025            remain_after_elapse: true,
1026            service_unit_last_state_change_usec: 69,
1027            service_unit_last_state_change_usec_monotonic: 69,
1028        };
1029        stats
1030            .units
1031            .timer_stats
1032            .insert(timer_unit.clone(), timer_stats.clone());
1033        stats
1034            .machines
1035            .get_mut("foo")
1036            .expect("No machine foo? WTF")
1037            .units
1038            .timer_stats
1039            .insert(timer_unit, timer_stats);
1040        // Ensure we escape keys correctly
1041        stats.units.unit_states.insert(
1042            String::from(
1043                r"nvme\x2dWDC_CL_SN730_SDBQNTY\x2d512G\x2d2020_37222H80070511\x2dpart3.device",
1044            ),
1045            units::UnitStates {
1046                active_state: units::SystemdUnitActiveState::active,
1047                load_state: units::SystemdUnitLoadState::loaded,
1048                unhealthy: false,
1049                time_in_state_usecs: None,
1050            },
1051        );
1052        // Add boot blame stats
1053        let mut boot_blame = crate::boot::BootBlameStats::new();
1054        boot_blame.insert(String::from("dnf5-automatic.service"), 204.159);
1055        boot_blame.insert(String::from("cpe_chef.service"), 103.050);
1056        boot_blame.insert(String::from("sys-module-fuse.device"), 16.210);
1057        stats.boot_blame = Some(boot_blame);
1058        stats
1059    }
1060
1061    #[test]
1062    fn test_flatten_map() {
1063        let json_flat_map = flatten_stats(&return_monitord_stats(), "");
1064        assert_eq!(154, json_flat_map.len());
1065    }
1066
1067    #[test]
1068    fn test_collector_transport_serializes_as_integer_everywhere() {
1069        // The repr discriminants are the gauge values, so json/json-pretty
1070        // report the same integers as json-flat — not strings.
1071        let usage = crate::VarlinkUsage {
1072            version: Some(crate::CollectorTransport::Varlink),
1073            units: Some(crate::CollectorTransport::Dbus),
1074            ..Default::default()
1075        };
1076        let value = serde_json::to_value(&usage).expect("serialize");
1077        assert_eq!(value["version"], serde_json::Value::from(1u64));
1078        assert_eq!(value["units"], serde_json::Value::from(0u64));
1079        assert!(value.get("networkd").is_none());
1080    }
1081
1082    #[test]
1083    fn test_flatten_varlink_usage_only_emits_ran_collectors() {
1084        // Disabled collectors stay None and emit no gauge: count() over the
1085        // gauges is the enabled set, which is what makes sum/count a valid
1086        // Grafana adoption ratio without a separate enabled counter.
1087        let flat = flatten_varlink_usage(
1088            &crate::VarlinkUsage {
1089                version: Some(crate::CollectorTransport::Varlink),
1090                units: Some(crate::CollectorTransport::Dbus),
1091                ..Default::default()
1092            },
1093            "",
1094        );
1095        assert_eq!(flat.len(), 2);
1096        assert_eq!(flat["varlink_usage.version"], serde_json::Value::from(1u64));
1097        assert_eq!(flat["varlink_usage.units"], serde_json::Value::from(0u64));
1098        assert!(flatten_varlink_usage(&crate::VarlinkUsage::default(), "").is_empty());
1099    }
1100
1101    #[test]
1102    fn test_flatten() {
1103        let json_flat = flatten(&return_monitord_stats(), "").expect("JSON serialize failed");
1104        assert_eq!(EXPECTED_FLAT_JSON, json_flat);
1105    }
1106
1107    #[test]
1108    fn test_flatten_prefixed() {
1109        let json_flat =
1110            flatten(&return_monitord_stats(), "monitord").expect("JSON serialize failed");
1111        let json_flat_unserialized: BTreeMap<String, serde_json::Value> =
1112            serde_json::from_str(&json_flat).expect("JSON from_str failed");
1113        for (key, _value) in json_flat_unserialized.iter() {
1114            assert!(key.starts_with("monitord."));
1115        }
1116    }
1117
1118    /// Ensure `UnitCounters` covers every scalar (non-hashmap) field of `SystemdUnitStats`.
1119    ///
1120    /// If a new counter field is added to `SystemdUnitStats` but not to `UnitCounters`
1121    /// (and its `From` impl), this test will fail, preventing silent omissions from the
1122    /// flat JSON output.
1123    #[test]
1124    fn test_unit_counters_covers_all_scalar_fields() {
1125        // Fields of SystemdUnitStats that are nested maps, not scalar counters.
1126        const NON_COUNTER_FIELDS: &[&str] = &[
1127            "unit_files",
1128            "service_stats",
1129            "timer_stats",
1130            "unit_states",
1131            "collection_timings",
1132        ];
1133
1134        // Scalar counter field names expected from SystemdUnitStats.
1135        let expected: std::collections::BTreeSet<&str> = units::UNIT_FIELD_NAMES
1136            .iter()
1137            .copied()
1138            .filter(|f| !NON_COUNTER_FIELDS.contains(f))
1139            .collect();
1140
1141        // Field names actually present in UnitCounters (via serde serialization).
1142        let counters_json =
1143            serde_json::to_value(UnitCounters::from(&units::SystemdUnitStats::default()))
1144                .expect("UnitCounters serialization failed");
1145        let actual: std::collections::BTreeSet<&str> = counters_json
1146            .as_object()
1147            .expect("UnitCounters must serialize to a JSON object")
1148            .keys()
1149            .map(|s| s.as_str())
1150            .collect();
1151
1152        assert_eq!(
1153            expected,
1154            actual,
1155            "UnitCounters is out of sync with SystemdUnitStats scalar fields.\n\
1156             Missing from UnitCounters: {:?}\n\
1157             Extra in UnitCounters: {:?}",
1158            expected.difference(&actual).collect::<Vec<_>>(),
1159            actual.difference(&expected).collect::<Vec<_>>(),
1160        );
1161    }
1162}