1use std::collections::BTreeMap;
14use std::collections::HashSet;
15use std::os::unix::fs::FileTypeExt;
16use std::path::Path;
17use std::path::PathBuf;
18use std::sync::Arc;
19use std::time::Duration;
20
21use futures_util::stream::TryStreamExt;
22use tokio::sync::RwLock;
23use tracing::debug;
24use tracing::warn;
25
26use crate::varlink::metrics::{ListOutput, Metrics, MetricsError};
27use crate::MonitordStats;
28
29pub const REPORT_DIR: &str = "/run/systemd/report";
31
32pub const SKIP_SOURCES: &[&str] = &[
40 "io.systemd.Manager",
41 "io.systemd.Network",
42 "io.monitord",
43 "io.systemd.CGroup",
44];
45
46pub const SKIP_SOURCE_PREFIXES: &[&str] = &["io.systemd.Report."];
50
51pub const METRICS_PER_SOURCE_MAX: usize = 16384;
53
54pub const SOURCES_MAX: usize = 128;
56
57#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default, PartialEq)]
59pub struct ReportSource {
60 pub up: bool,
62 pub dropped_metrics: u64,
65 pub colliding_metrics: u64,
71 pub metrics: BTreeMap<String, serde_json::Value>,
74}
75
76pub type ReportStats = BTreeMap<String, ReportSource>;
78
79pub fn interface_name_is_valid(name: &str) -> bool {
83 let segments: Vec<&str> = name.split('.').collect();
84 if segments.len() < 2 {
85 return false;
86 }
87 segments.iter().enumerate().all(|(idx, segment)| {
88 let bytes = segment.as_bytes();
89 let (Some(first), Some(last)) = (bytes.first(), bytes.last()) else {
90 return false;
91 };
92 let first_ok = if idx == 0 {
93 first.is_ascii_alphabetic()
94 } else {
95 first.is_ascii_alphanumeric()
96 };
97 first_ok
98 && last.is_ascii_alphanumeric()
99 && bytes
100 .iter()
101 .all(|b| b.is_ascii_alphanumeric() || *b == b'-')
102 })
103}
104
105pub fn field_name_is_valid(name: &str) -> bool {
108 let bytes = name.as_bytes();
109 let (Some(first), Some(last)) = (bytes.first(), bytes.last()) else {
110 return false;
111 };
112 first.is_ascii_alphabetic()
113 && *last != b'_'
114 && !name.contains("__")
115 && bytes
116 .iter()
117 .all(|b| b.is_ascii_alphanumeric() || *b == b'_')
118}
119
120pub fn metric_name_is_valid(metric_name: &str, source: &str) -> bool {
123 let Some((interface, field)) = metric_name.rsplit_once('.') else {
124 return false;
125 };
126 interface_name_is_valid(interface)
127 && field_name_is_valid(field)
128 && metric_name
129 .strip_prefix(source)
130 .is_some_and(|rest| rest.starts_with('.'))
131}
132
133pub fn should_collect_source(
138 name: &str,
139 allowlist: &HashSet<String>,
140 blocklist: &HashSet<String>,
141) -> bool {
142 if !interface_name_is_valid(name)
143 || SKIP_SOURCES.contains(&name)
144 || SKIP_SOURCE_PREFIXES
145 .iter()
146 .any(|prefix| name.starts_with(prefix))
147 {
148 return false;
149 }
150 let lowered = name.to_lowercase();
152 if blocklist.contains(&lowered) {
153 return false;
154 }
155 allowlist.is_empty() || allowlist.contains(&lowered)
156}
157
158pub fn metric_is_blocked(metric_name: &str, blocklist: &HashSet<String>) -> bool {
163 if blocklist.is_empty() {
164 return false;
165 }
166 let lowered = metric_name.to_lowercase();
167 let mut prefix = lowered.as_str();
168 loop {
169 if blocklist.contains(prefix) {
170 return true;
171 }
172 match prefix.rsplit_once('.') {
173 Some((parent, _)) => prefix = parent,
174 None => return false,
175 }
176 }
177}
178
179fn metric_key(metric: &ListOutput, source: &str) -> String {
182 let mut key = metric
183 .name()
184 .strip_prefix(source)
185 .and_then(|rest| rest.strip_prefix('.'))
186 .unwrap_or(metric.name())
187 .to_string();
188 if let Some(object) = metric.object() {
189 key.push('.');
190 key.push_str(object);
191 }
192 if let Some(fields) = metric.fields() {
193 let sorted: BTreeMap<&String, &serde_json::Value> = fields.iter().collect();
194 for (field, value) in sorted {
195 let value = match value {
196 serde_json::Value::String(s) => s.clone(),
197 other => other.to_string(),
198 };
199 key.push('.');
200 key.push_str(field);
201 key.push('_');
202 key.push_str(&value);
203 }
204 }
205 key
206}
207
208fn normalize_value(value: &serde_json::Value) -> serde_json::Value {
212 match value {
213 serde_json::Value::Bool(b) => u64::from(*b).into(),
214 serde_json::Value::Object(members) => members
215 .iter()
216 .map(|(member, value)| (member.clone(), normalize_value(value)))
217 .collect::<serde_json::Map<_, _>>()
218 .into(),
219 serde_json::Value::Array(items) => items.iter().map(normalize_value).collect(),
220 other => other.clone(),
221 }
222}
223
224pub fn flat_leaves(
230 key: String,
231 value: &serde_json::Value,
232 out: &mut Vec<(String, serde_json::Value)>,
233) {
234 match value {
235 serde_json::Value::Object(members) => {
236 for (member, member_value) in members {
237 flat_leaves(format!("{key}.{member}"), member_value, out);
238 }
239 }
240 serde_json::Value::Array(items) => {
241 for (idx, item) in items.iter().enumerate() {
242 flat_leaves(format!("{key}.{idx}"), item, out);
243 }
244 }
245 serde_json::Value::Null => {}
246 scalar => out.push((key, scalar.clone())),
247 }
248}
249
250pub fn normalize_metrics(
256 source: &str,
257 metrics: &[ListOutput],
258 metric_blocklist: &HashSet<String>,
259) -> ReportSource {
260 let mut report_source = ReportSource {
261 up: true,
262 ..Default::default()
263 };
264 let mut taken: HashSet<String> = HashSet::new();
267 for (idx, metric) in metrics.iter().enumerate() {
268 if idx >= METRICS_PER_SOURCE_MAX || !metric_name_is_valid(metric.name(), source) {
269 debug!("Dropping metric {:?} from report source {}", metric, source);
270 report_source.dropped_metrics += 1;
271 continue;
272 }
273 if metric.value().is_null() || metric_is_blocked(metric.name(), metric_blocklist) {
274 continue;
275 }
276 let key = metric_key(metric, source);
277 let value = normalize_value(metric.value());
278 let mut leaves = Vec::new();
279 flat_leaves(key.clone(), &value, &mut leaves);
280 let mut own: HashSet<&str> = HashSet::with_capacity(leaves.len());
281 let collides = report_source.metrics.contains_key(&key)
282 || leaves
283 .iter()
284 .any(|(leaf, _)| taken.contains(leaf) || !own.insert(leaf.as_str()));
285 if collides {
286 warn!(
287 "Report source {} metric {} maps to flat key {:?}, already in use; skipping it",
288 source,
289 metric.name(),
290 key
291 );
292 report_source.colliding_metrics += 1;
293 continue;
294 }
295 taken.extend(leaves.into_iter().map(|(leaf, _)| leaf));
296 report_source.metrics.insert(key, value);
297 }
298 report_source
299}
300
301pub async fn list_sources(
303 dir: &Path,
304 allowlist: &HashSet<String>,
305 blocklist: &HashSet<String>,
306) -> anyhow::Result<Vec<String>> {
307 let mut entries = match tokio::fs::read_dir(dir).await {
308 Ok(entries) => entries,
309 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
310 debug!(
311 "{} does not exist (systemd < v260?): no report sources",
312 dir.display()
313 );
314 return Ok(Vec::new());
315 }
316 Err(err) => return Err(err.into()),
317 };
318 let mut sources = Vec::new();
319 while let Some(entry) = entries.next_entry().await? {
320 let file_type = entry.file_type().await?;
321 if !file_type.is_socket() && !file_type.is_symlink() {
322 continue;
323 }
324 let Some(name) = entry.file_name().to_str().map(str::to_string) else {
325 continue;
326 };
327 if should_collect_source(&name, allowlist, blocklist) {
328 sources.push(name);
329 }
330 }
331 sources.sort();
332 if sources.len() > SOURCES_MAX {
333 warn!(
334 "Reached limit of {} report sources, skipping {}",
335 SOURCES_MAX,
336 sources.len() - SOURCES_MAX
337 );
338 sources.truncate(SOURCES_MAX);
339 }
340 Ok(sources)
341}
342
343async fn list_source(path: PathBuf, timeout: Duration) -> anyhow::Result<Vec<ListOutput>> {
349 tokio::task::spawn_blocking(move || {
350 let rt = tokio::runtime::Builder::new_current_thread()
351 .enable_all()
352 .build()?;
353 rt.block_on(async move {
354 tokio::time::timeout(timeout, async move {
355 let mut conn = zlink::tokio::unix::connect(&path).await?;
356 let stream = conn.list().await?;
357 futures_util::pin_mut!(stream);
358 let mut metrics = Vec::new();
359 while let Some(reply) = stream.try_next().await? {
360 match reply {
361 Ok(metric) => metrics.push(metric),
362 Err(MetricsError::NoSuchMetric) => break,
363 }
364 if metrics.len() > METRICS_PER_SOURCE_MAX {
367 break;
368 }
369 }
370 Ok::<_, anyhow::Error>(metrics)
371 })
372 .await
373 .map_err(|_| anyhow::anyhow!("timed out after {:?}", timeout))?
374 })
375 })
376 .await?
377}
378
379pub async fn collect_report_stats(
382 dir: &Path,
383 allowlist: &HashSet<String>,
384 blocklist: &HashSet<String>,
385 metric_blocklist: &HashSet<String>,
386 timeout: Duration,
387) -> anyhow::Result<ReportStats> {
388 let sources = list_sources(dir, allowlist, blocklist).await?;
389 let results = futures_util::future::join_all(
390 sources
391 .iter()
392 .map(|source| list_source(dir.join(source), timeout)),
393 )
394 .await;
395
396 let mut stats = ReportStats::new();
397 for (source, result) in sources.into_iter().zip(results) {
398 let report_source = match result {
399 Ok(metrics) => normalize_metrics(&source, &metrics, metric_blocklist),
400 Err(err) => {
401 warn!("Unable to collect report source {}: {:#}", source, err);
402 ReportSource::default()
403 }
404 };
405 stats.insert(source, report_source);
406 }
407 Ok(stats)
408}
409
410pub async fn update_report_stats(
412 config: Arc<crate::config::Config>,
413 locked_monitord_stats: Arc<RwLock<MonitordStats>>,
414) -> anyhow::Result<()> {
415 let stats = collect_report_stats(
416 Path::new(REPORT_DIR),
417 &config.report.allowlist,
418 &config.report.blocklist,
419 &config.report.metric_blocklist,
420 Duration::from_secs(config.monitord.dbus_timeout),
421 )
422 .await?;
423 locked_monitord_stats.write().await.report = Some(stats);
424 Ok(())
425}
426
427#[cfg(test)]
428mod tests {
429 use super::*;
430 use std::collections::HashMap;
431
432 fn metric(
433 name: &str,
434 object: Option<&str>,
435 fields: Option<&[(&str, serde_json::Value)]>,
436 value: serde_json::Value,
437 ) -> ListOutput {
438 ListOutput {
439 name: name.to_string(),
440 value,
441 object: object.map(str::to_string),
442 fields: fields.map(|f| {
443 f.iter()
444 .map(|(k, v)| (k.to_string(), v.clone()))
445 .collect::<HashMap<_, _>>()
446 }),
447 }
448 }
449
450 #[test]
451 fn test_interface_name_is_valid() {
452 for valid in ["io.systemd.Basic", "io.monitord", "a.b", "org.foo-bar.X1"] {
453 assert!(interface_name_is_valid(valid), "{valid}");
454 }
455 for invalid in [
456 "",
457 "io",
458 "io.",
459 ".io",
460 "1io.systemd",
461 "io.-systemd",
462 "io.systemd-",
463 "io.sys_temd",
464 "io..systemd",
465 ] {
466 assert!(!interface_name_is_valid(invalid), "{invalid}");
467 }
468 }
469
470 #[test]
471 fn test_field_name_is_valid() {
472 for valid in ["UnitsTotal", "unitActiveState", "a_b", "x1"] {
473 assert!(field_name_is_valid(valid), "{valid}");
474 }
475 for invalid in ["", "_a", "a_", "a__b", "1a", "a-b", "a.b"] {
476 assert!(!field_name_is_valid(invalid), "{invalid}");
477 }
478 }
479
480 #[test]
481 fn test_metric_name_is_valid() {
482 assert!(metric_name_is_valid(
483 "io.systemd.Basic.BootId",
484 "io.systemd.Basic"
485 ));
486 assert!(metric_name_is_valid(
487 "io.systemd.Basic.Sub.Value",
488 "io.systemd.Basic"
489 ));
490 assert!(!metric_name_is_valid(
492 "io.systemd.Other.BootId",
493 "io.systemd.Basic"
494 ));
495 assert!(!metric_name_is_valid(
497 "io.systemd.BasicX.BootId",
498 "io.systemd.Basic"
499 ));
500 assert!(!metric_name_is_valid(
502 "io.systemd.Basic",
503 "io.systemd.Basic"
504 ));
505 assert!(!metric_name_is_valid(
506 "io.systemd.Basic.bad-field",
507 "io.systemd.Basic"
508 ));
509 }
510
511 #[test]
512 fn test_should_collect_source() {
513 let empty = HashSet::new();
514 assert!(should_collect_source("io.systemd.Basic", &empty, &empty));
515 for skipped in SKIP_SOURCES {
516 assert!(!should_collect_source(skipped, &empty, &empty), "{skipped}");
517 }
518 assert!(!should_collect_source("not-an-interface", &empty, &empty));
519 assert!(!should_collect_source(
521 "io.systemd.Report.SignPlain",
522 &empty,
523 &empty
524 ));
525 assert!(!should_collect_source(
526 "io.systemd.Report.SignTPM2",
527 &empty,
528 &empty
529 ));
530 assert!(should_collect_source("io.systemd.Reporter", &empty, &empty));
532
533 let allow = HashSet::from([String::from("io.systemd.basic")]);
534 assert!(should_collect_source("io.systemd.Basic", &allow, &empty));
535 assert!(!should_collect_source(
536 "io.systemd.DiskSpace",
537 &allow,
538 &empty
539 ));
540 let allow_manager = HashSet::from([String::from("io.systemd.manager")]);
542 assert!(!should_collect_source(
543 "io.systemd.Manager",
544 &allow_manager,
545 &empty
546 ));
547
548 assert!(!should_collect_source("io.systemd.Basic", &allow, &allow));
550 }
551
552 #[test]
553 fn test_normalize_metrics() {
554 let source = "io.systemd.Basic";
555 let metrics = vec![
556 metric(
557 "io.systemd.Basic.Hostname",
558 None,
559 None,
560 serde_json::json!("box"),
561 ),
562 metric(
563 "io.systemd.Basic.UnitActive",
564 Some("foo.service"),
565 None,
566 serde_json::json!(true),
567 ),
568 metric(
569 "io.systemd.Basic.Bytes",
570 Some("sda"),
571 Some(&[
572 ("op", serde_json::json!("write")),
573 ("cpu", serde_json::json!(0)),
574 ]),
575 serde_json::json!(4096),
576 ),
577 metric(
578 "io.systemd.Basic.Info",
579 None,
580 None,
581 serde_json::json!({"a": 1}),
582 ),
583 metric(
584 "io.systemd.Basic.Nothing",
585 None,
586 None,
587 serde_json::Value::Null,
588 ),
589 metric("io.systemd.Other.Value", None, None, serde_json::json!(1)),
591 metric(
592 "io.systemd.Basic.bad-name",
593 None,
594 None,
595 serde_json::json!(1),
596 ),
597 ];
598 let normalized = normalize_metrics(source, &metrics, &HashSet::new());
599 assert!(normalized.up);
600 assert_eq!(normalized.dropped_metrics, 2);
601 assert_eq!(
602 normalized.metrics,
603 BTreeMap::from([
604 ("Hostname".to_string(), serde_json::json!("box")),
605 ("UnitActive.foo.service".to_string(), serde_json::json!(1)),
606 (
608 "Bytes.sda.cpu_0.op_write".to_string(),
609 serde_json::json!(4096)
610 ),
611 ("Info".to_string(), serde_json::json!({"a": 1})),
612 ])
613 );
614 }
615
616 #[test]
617 fn test_metric_is_blocked() {
618 let blocklist = HashSet::from([
619 "io.systemd.basic.machineid".to_string(),
620 "io.systemd.basic.smbios".to_string(),
621 ]);
622 assert!(metric_is_blocked("io.systemd.Basic.MachineID", &blocklist));
623 assert!(metric_is_blocked(
625 "io.systemd.Basic.SMBIOS.SystemProductName",
626 &blocklist
627 ));
628 assert!(!metric_is_blocked("io.systemd.Basic.SMBIOSish", &blocklist));
630 assert!(!metric_is_blocked(
631 "io.systemd.Basic.MachineIDs",
632 &blocklist
633 ));
634 assert!(!metric_is_blocked(
635 "io.systemd.Basic.CPUsOnline",
636 &blocklist
637 ));
638 assert!(!metric_is_blocked(
639 "io.systemd.Basic.MachineID",
640 &HashSet::new()
641 ));
642 }
643
644 #[test]
645 fn test_normalize_metrics_skips_blocked_without_counting_drops() {
646 let metrics = vec![
647 metric(
648 "io.systemd.Basic.MachineID",
649 None,
650 None,
651 serde_json::json!("7000"),
652 ),
653 metric(
654 "io.systemd.Basic.SMBIOS.SystemVendor",
655 None,
656 None,
657 serde_json::json!("acme"),
658 ),
659 metric(
660 "io.systemd.Basic.CPUsOnline",
661 None,
662 None,
663 serde_json::json!(4),
664 ),
665 ];
666 let blocklist = HashSet::from([
667 "io.systemd.basic.machineid".to_string(),
668 "io.systemd.basic.smbios".to_string(),
669 ]);
670 let normalized = normalize_metrics("io.systemd.Basic", &metrics, &blocklist);
671 assert_eq!(normalized.dropped_metrics, 0);
672 assert_eq!(
673 normalized.metrics,
674 BTreeMap::from([("CPUsOnline".to_string(), serde_json::json!(4))])
675 );
676 }
677
678 #[test]
679 fn test_normalize_metrics_counts_dimension_collisions() {
680 let metrics = vec![
682 metric(
683 "io.systemd.Basic.Value",
684 None,
685 Some(&[("x", serde_json::json!("a")), ("y", serde_json::json!("b"))]),
686 serde_json::json!(1),
687 ),
688 metric(
689 "io.systemd.Basic.Value",
690 None,
691 Some(&[("x", serde_json::json!("a.y_b"))]),
692 serde_json::json!(2),
693 ),
694 metric(
696 "io.systemd.Basic.Value",
697 Some("x_a.y_b"),
698 None,
699 serde_json::json!(3),
700 ),
701 ];
702 let normalized = normalize_metrics("io.systemd.Basic", &metrics, &HashSet::new());
703 assert_eq!(normalized.colliding_metrics, 2);
704 assert_eq!(normalized.dropped_metrics, 0);
705 assert_eq!(
707 normalized.metrics,
708 BTreeMap::from([("Value.x_a.y_b".to_string(), serde_json::json!(1))])
709 );
710 }
711
712 #[test]
713 fn test_normalize_metrics_counts_flattened_path_collisions() {
714 let metrics = vec![
715 metric(
718 "io.systemd.Basic.Info",
719 None,
720 None,
721 serde_json::json!({"a": {"b": 1}, "a.b": 2}),
722 ),
723 metric(
725 "io.systemd.Basic.Other",
726 Some("a"),
727 None,
728 serde_json::json!(3),
729 ),
730 metric(
731 "io.systemd.Basic.Other",
732 None,
733 None,
734 serde_json::json!({"a": 4, "b": 5}),
735 ),
736 ];
737 let normalized = normalize_metrics("io.systemd.Basic", &metrics, &HashSet::new());
738 assert_eq!(normalized.colliding_metrics, 2);
739 assert_eq!(
740 normalized.metrics,
741 BTreeMap::from([("Other.a".to_string(), serde_json::json!(3))])
742 );
743 }
744
745 #[test]
746 fn test_normalize_metrics_converts_nested_booleans() {
747 let metrics = vec![metric(
748 "io.systemd.Basic.Info",
749 None,
750 None,
751 serde_json::json!({"enabled": true, "flags": [false, true], "inner": {"on": false}}),
752 )];
753 let normalized = normalize_metrics("io.systemd.Basic", &metrics, &HashSet::new());
754 assert_eq!(
755 normalized.metrics["Info"],
756 serde_json::json!({"enabled": 1, "flags": [0, 1], "inner": {"on": 0}})
757 );
758 }
759
760 #[test]
761 fn test_normalize_metrics_caps_per_source() {
762 let metrics: Vec<ListOutput> = (0..METRICS_PER_SOURCE_MAX + 2)
763 .map(|i| {
764 metric(
765 "io.systemd.Basic.Value",
766 Some(&format!("o{i}")),
767 None,
768 serde_json::json!(i),
769 )
770 })
771 .collect();
772 let normalized = normalize_metrics("io.systemd.Basic", &metrics, &HashSet::new());
773 assert_eq!(normalized.metrics.len(), METRICS_PER_SOURCE_MAX);
774 assert_eq!(normalized.dropped_metrics, 2);
775 }
776
777 #[tokio::test]
778 async fn test_list_sources_filters_entries() {
779 let dir = tempfile::tempdir().expect("tempdir");
780 let _basic =
781 std::os::unix::net::UnixListener::bind(dir.path().join("io.systemd.Basic")).unwrap();
782 let _manager =
783 std::os::unix::net::UnixListener::bind(dir.path().join("io.systemd.Manager")).unwrap();
784 let _bad = std::os::unix::net::UnixListener::bind(dir.path().join("bad")).unwrap();
785 std::fs::write(dir.path().join("io.systemd.File"), b"").unwrap();
786 std::os::unix::fs::symlink(
787 dir.path().join("io.systemd.Basic"),
788 dir.path().join("io.systemd.Link"),
789 )
790 .unwrap();
791
792 let empty = HashSet::new();
793 let sources = list_sources(dir.path(), &empty, &empty).await.unwrap();
794 assert_eq!(sources, vec!["io.systemd.Basic", "io.systemd.Link"]);
795
796 let missing = list_sources(&dir.path().join("nope"), &empty, &empty)
797 .await
798 .unwrap();
799 assert!(missing.is_empty());
800 }
801
802 #[tokio::test]
803 async fn test_collect_report_stats_marks_dead_source_down() {
804 let dir = tempfile::tempdir().expect("tempdir");
805 let good = tokio::net::UnixListener::bind(dir.path().join("io.example.Good")).unwrap();
807 let server = tokio::spawn(async move {
808 let (mut socket, _) = good.accept().await.expect("accept");
809 let mut request = vec![0u8; 4096];
810 let _ = tokio::io::AsyncReadExt::read(&mut socket, &mut request).await;
811 tokio::io::AsyncWriteExt::write_all(
812 &mut socket,
813 b"{\"parameters\":{\"name\":\"io.example.Good.Value\",\"value\":1},\"continues\":true}\0\
814 {\"parameters\":{\"name\":\"io.example.Good.Other\",\"object\":\"x\",\"value\":\"y\"}}\0",
815 )
816 .await
817 .expect("write reply");
818 });
819 drop(std::os::unix::net::UnixListener::bind(dir.path().join("io.example.Dead")).unwrap());
821
822 let empty = HashSet::new();
823 let stats =
824 collect_report_stats(dir.path(), &empty, &empty, &empty, Duration::from_secs(5))
825 .await
826 .unwrap();
827 server.await.expect("server");
828
829 assert_eq!(stats.len(), 2);
830 assert_eq!(stats["io.example.Dead"], ReportSource::default());
831 let good = &stats["io.example.Good"];
832 assert!(good.up);
833 assert_eq!(good.metrics["Value"], serde_json::json!(1));
834 assert_eq!(good.metrics["Other.x"], serde_json::json!("y"));
835 }
836}