monitord/lib.rs
1//! # monitord Crate
2//!
3//! `monitord` is a library to gather statistics about systemd.
4
5use std::sync::Arc;
6
7use std::collections::HashMap;
8use std::time::Duration;
9use std::time::Instant;
10
11use thiserror::Error;
12use tokio::sync::RwLock;
13use tracing::debug;
14use tracing::error;
15use tracing::info;
16use tracing::warn;
17use tracing::Instrument;
18
19#[derive(Error, Debug)]
20pub enum MonitordError {
21 #[error("D-Bus connection error: {0}")]
22 ZbusError(#[from] zbus::Error),
23}
24
25impl MonitordError {
26 /// Unwrap the inner zbus error. Exhaustive today: connection setup is
27 /// the only thing that produces this error, so there is exactly one
28 /// variant to unwrap.
29 pub fn into_zbus(self) -> zbus::Error {
30 match self {
31 MonitordError::ZbusError(inner) => inner,
32 }
33 }
34}
35
36pub mod boot;
37pub mod cgroup;
38pub mod config;
39pub(crate) mod dbus;
40pub mod dbus_stats;
41pub mod json;
42pub mod logging;
43pub mod machines;
44pub mod networkd;
45pub mod pid1;
46pub mod report;
47pub mod report_collector;
48pub mod system;
49pub mod timer;
50pub mod unit_constants;
51pub mod units;
52pub mod varlink;
53pub mod varlink_boot;
54pub mod varlink_fallback;
55pub mod varlink_networkd;
56pub mod varlink_system;
57pub mod varlink_unit;
58pub mod varlink_units;
59pub mod varlink_verify;
60pub mod verify;
61
62pub const DEFAULT_DBUS_ADDRESS: &str = "unix:path=/run/dbus/system_bus_socket";
63
64/// Per-collector timing for a single stat collection run.
65///
66/// `start_offset_ms` is the wall time between the top of the collection cycle and
67/// the moment this collector's future was first polled. A non-trivial offset
68/// indicates the spawn/scheduling loop or the runtime is delaying first poll,
69/// which means collectors are not starting in parallel as intended.
70///
71/// `elapsed_ms` is the wall time between first poll and completion.
72#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default, PartialEq)]
73pub struct CollectorTiming {
74 /// Name of the collector (e.g. "units", "pid1", "dbus_stats")
75 pub name: String,
76 /// Milliseconds from top of the run until the spawned future's first poll.
77 /// Should be small (< a few ms) when collectors are truly running in parallel.
78 pub start_offset_ms: f64,
79 /// Milliseconds from first poll to future completion.
80 pub elapsed_ms: f64,
81 /// Whether the collector returned Ok.
82 pub success: bool,
83}
84
85/// Which API transport served a collector on the last run.
86///
87/// Recorded per enabled collector so operators can watch varlink adoption
88/// climb as the fleet's systemd upgrades past each endpoint's minimum
89/// version: a collector reports `Varlink` when its varlink attempt succeeded
90/// and `Dbus` when it collected the legacy way — either because varlink is
91/// disabled in config or because the varlink attempt failed and fell back.
92/// `Dbus` also covers the file-based networkd fallback: the value answers
93/// "did this collector use varlink", not "which fallback served it".
94/// Collectors with no varlink path (`pid1`, `dbus_stats`) and disabled
95/// collectors stay `None` and emit no gauge, so the present gauges are
96/// exactly the enabled set — no separate enabled-collectors counter needed.
97#[derive(
98 serde_repr::Serialize_repr,
99 serde_repr::Deserialize_repr,
100 Clone,
101 Copy,
102 Debug,
103 Default,
104 PartialEq,
105 Eq,
106)]
107#[repr(u8)]
108pub enum CollectorTransport {
109 #[default]
110 Dbus = 0,
111 Varlink = 1,
112}
113
114impl CollectorTransport {
115 /// Gauge value for flat JSON and metric exporters: 1 when varlink served
116 /// the collector, 0 for the D-Bus/file fallback.
117 ///
118 /// The `repr(u8)` discriminants are the gauge values, so every output
119 /// format (json, json-pretty, json-flat) reports the same integer —
120 /// matching the other stat enums (`SystemdSystemState`, the unit state
121 /// enums) rather than serializing as a string in some formats.
122 pub fn as_u64(self) -> u64 {
123 self as u64
124 }
125}
126
127/// Per-collector transport record for the last collection run.
128///
129/// Every field is `Some` when its collector ran and `None` when it did not
130/// (disabled in config). Absent-when-disabled is what makes the adoption
131/// ratio work: `count()` over the gauges is the enabled set.
132///
133/// NOTE for future collectors: the host `MachineStats` is constructed once
134/// outside the daemon loop, not fresh each iteration — so a collector with
135/// an early-return path that skips its gauge assignment would silently
136/// inherit the previous run's value instead of dropping the gauge. Always
137/// assign on every path, including cache hits and config-disabled fallbacks.
138#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default, PartialEq)]
139pub struct VarlinkUsage {
140 /// Always collected; follows `[system-state] varlink` via the shared
141 /// `Manager.Describe` call. Normally agrees with `system_state` (one
142 /// call serves both), but persists when `[system-state]` is disabled —
143 /// making it the cheapest varlink canary on such hosts.
144 #[serde(skip_serializing_if = "Option::is_none")]
145 pub version: Option<CollectorTransport>,
146 #[serde(skip_serializing_if = "Option::is_none")]
147 pub system_state: Option<CollectorTransport>,
148 /// `Varlink` means the bulk enumeration came from the metrics stream and
149 /// per-unit details from `io.systemd.Unit.List`, on the host and inside
150 /// containers alike.
151 #[serde(skip_serializing_if = "Option::is_none")]
152 pub units: Option<CollectorTransport>,
153 #[serde(skip_serializing_if = "Option::is_none")]
154 pub networkd: Option<CollectorTransport>,
155 /// Host-side machine enumeration: machined's `io.systemd.Machine.List`
156 /// (systemd v257+) or its D-Bus API. Per-container transports land on
157 /// each machine's own `MachineStats` instead.
158 #[serde(skip_serializing_if = "Option::is_none")]
159 pub machines: Option<CollectorTransport>,
160 #[serde(skip_serializing_if = "Option::is_none")]
161 pub boot_blame: Option<CollectorTransport>,
162 #[serde(skip_serializing_if = "Option::is_none")]
163 pub verify: Option<CollectorTransport>,
164}
165
166/// Stats collected for a single systemd-nspawn container or VM managed by systemd-machined
167#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default, PartialEq)]
168pub struct MachineStats {
169 /// systemd-networkd interface states inside the container
170 pub networkd: networkd::NetworkdState,
171 /// PID 1 process stats from procfs (using the container's leader PID)
172 pub pid1: Option<pid1::Pid1Stats>,
173 /// Overall systemd system state (e.g. running, degraded) inside the container
174 pub system_state: system::SystemdSystemState,
175 /// Aggregated systemd unit counts and per-service/timer stats inside the container
176 pub units: units::SystemdUnitStats,
177 /// systemd version running inside the container
178 pub version: system::SystemdVersion,
179 /// D-Bus daemon/broker statistics inside the container
180 pub dbus_stats: Option<dbus_stats::DBusStats>,
181 /// Boot blame statistics: slowest units at boot with activation times in seconds
182 #[serde(skip_serializing_if = "Option::is_none")]
183 pub boot_blame: Option<boot::BootBlameStats>,
184 /// Unit verification error statistics
185 pub verify_stats: Option<verify::VerifyStats>,
186 /// Which transport served each collector on the last run.
187 pub varlink_usage: VarlinkUsage,
188}
189
190/// Root struct containing all enabled monitord metrics for the host system and containers
191#[derive(serde::Serialize, serde::Deserialize, Debug, Default, PartialEq)]
192pub struct MonitordStats {
193 /// systemd-networkd interface states and managed interface count
194 pub networkd: networkd::NetworkdState,
195 /// PID 1 (systemd) process stats from procfs: CPU, memory, FDs, tasks
196 pub pid1: Option<pid1::Pid1Stats>,
197 /// Overall systemd manager state (e.g. running, degraded, initializing)
198 pub system_state: system::SystemdSystemState,
199 /// Aggregated systemd unit counts by type/state and per-service/timer detailed metrics
200 pub units: units::SystemdUnitStats,
201 /// Installed systemd version (major.minor.revision.os)
202 pub version: system::SystemdVersion,
203 /// D-Bus daemon/broker statistics (connections, bus names, match rules, per-peer accounting)
204 pub dbus_stats: Option<dbus_stats::DBusStats>,
205 /// Per-container stats keyed by machine name, collected via systemd-machined
206 pub machines: HashMap<String, MachineStats>,
207 /// Boot blame statistics: slowest units at boot with activation times in seconds
208 #[serde(skip_serializing_if = "Option::is_none")]
209 pub boot_blame: Option<boot::BootBlameStats>,
210 /// Unit verification error statistics
211 pub verify_stats: Option<verify::VerifyStats>,
212 /// End-to-end duration of the last stat collection run in milliseconds.
213 pub stat_collection_run_time_ms: f64,
214 /// Per-collector timings from the last run, sorted slowest first. Empty
215 /// before the first run completes. Callers compute parallelism ratio
216 /// (sum of `elapsed_ms` / `stat_collection_run_time_ms`) and identify the
217 /// gating collector (first entry) directly from this vector.
218 pub collector_timings: Vec<CollectorTiming>,
219 /// Which transport served each collector on the last run.
220 pub varlink_usage: VarlinkUsage,
221 /// Metrics from other systemd-report sources in `/run/systemd/report/`,
222 /// keyed by source. `None` unless `[report] collect = true`.
223 #[serde(skip_serializing_if = "Option::is_none")]
224 pub report: Option<report_collector::ReportStats>,
225}
226
227/// Print statistics in the format set in configuration
228pub fn print_stats(
229 key_prefix: &str,
230 output_format: &config::MonitordOutputFormat,
231 stats: &MonitordStats,
232) {
233 match output_format {
234 config::MonitordOutputFormat::Json => println!(
235 "{}",
236 serde_json::to_string(&stats).expect("Invalid JSON serialization")
237 ),
238 config::MonitordOutputFormat::JsonFlat => println!(
239 "{}",
240 json::flatten(stats, key_prefix).expect("Invalid JSON serialization")
241 ),
242 config::MonitordOutputFormat::JsonPretty => println!(
243 "{}",
244 serde_json::to_string_pretty(&stats).expect("Invalid JSON serialization")
245 ),
246 }
247}
248
249fn set_stat_collection_run_time(stats: &mut MonitordStats, elapsed_runtime: Duration) {
250 stats.stat_collection_run_time_ms = elapsed_runtime.as_secs_f64() * 1000.0;
251}
252
253/// Output produced by every spawned collector future after wrapping with timing.
254type TimedCollectorOutput = (String, anyhow::Result<()>, Duration, Duration);
255
256/// Spawn a collector future onto the join set with timing instrumentation.
257///
258/// The wrapping closure records the moment the future is first polled (relative
259/// to `collect_start`) and the elapsed wall time until it completes. Both
260/// durations and the collector name are returned alongside the original result.
261///
262/// `tokio::task::JoinSet::spawn` runs the future on a new task, and tracing
263/// spans do not cross task boundaries automatically — without explicitly
264/// capturing and re-attaching the caller's span here, every collector (and
265/// anything it spawns in turn, e.g. units.rs's per-unit tasks) would show up
266/// as an unrelated root trace instead of a child of the current collection run.
267fn spawn_timed<F>(
268 join_set: &mut tokio::task::JoinSet<TimedCollectorOutput>,
269 name: &'static str,
270 collect_start: Instant,
271 fut: F,
272) where
273 F: std::future::Future<Output = anyhow::Result<()>> + Send + 'static,
274{
275 let parent_span = tracing::Span::current();
276 let span = tracing::debug_span!(
277 parent: &parent_span,
278 "collector",
279 name,
280 elapsed_ms = tracing::field::Empty,
281 success = tracing::field::Empty,
282 );
283 let recording_span = span.clone();
284 join_set.spawn(
285 async move {
286 let task_first_poll = Instant::now();
287 let start_offset = task_first_poll.duration_since(collect_start);
288 let result = fut.await;
289 let elapsed = task_first_poll.elapsed();
290 recording_span.record("elapsed_ms", elapsed.as_secs_f64() * 1000.0);
291 recording_span.record("success", result.is_ok());
292 (name.to_string(), result, start_offset, elapsed)
293 }
294 .instrument(span),
295 );
296}
297
298/// Lazily-created system bus connection shared by every collector that
299/// needs D-Bus — also passed into collectors that decide their transport
300/// internally (`verify`, `boot_blame`), so those resolve it only on their
301/// D-Bus code paths rather than up front (see finding 1 on #224).
302///
303/// The cell starts empty (or seeded from `maybe_connection` for library
304/// callers) and is only connected on first use, so a run whose enabled
305/// collectors all succeed over varlink/fs/procfs never touches the bus at
306/// all — the prerequisite for the zero-D-Bus claim in #37.
307///
308/// `tokio::sync::OnceCell` serializes initializers behind a semaphore:
309/// concurrent first-users wait for the in-flight attempt and share its
310/// result — there is no race and no spare connection. A failed attempt is
311/// *not* cached (a waiter starts a fresh attempt instead), so a dead bus
312/// costs one connect attempt per D-Bus collector, sequentially. `ENOENT`
313/// fails fast and the run finishes in milliseconds, but `method_timeout`
314/// only bounds method calls, not `Builder::build()` — a socket that
315/// exists and hangs (wedged broker) would serialize one blocking connect
316/// per D-Bus collector per cycle, where the old code blocked exactly once
317/// at startup. Worth knowing when pointing at an unfamiliar bus address.
318pub(crate) type DbusCell = Arc<tokio::sync::OnceCell<zbus::Connection>>;
319
320/// Resolve the shared D-Bus connection, connecting on first use.
321///
322/// Only called on D-Bus code paths (varlink/fs-first collectors reach here
323/// solely through their fallbacks), so a missing bus surfaces as that
324/// collector's ordinary error — logged per-collector, never fatal to the
325/// run. Daemon-mode reuse is preserved: the same connection serves every
326/// cycle until a failed cycle drops it (see below).
327pub(crate) async fn dbus_connection(
328 cell: &DbusCell,
329 dbus_timeout: u64,
330) -> Result<zbus::Connection, MonitordError> {
331 cell.get_or_try_init(|| async {
332 zbus::connection::Builder::system()
333 .method_timeout(std::time::Duration::from_secs(dbus_timeout))
334 .build()
335 .await
336 })
337 .await
338 .cloned()
339 .map_err(MonitordError::ZbusError)
340}
341
342/// Main statistic collection function running what's required by configuration in parallel
343/// Takes an optional locked stats struct to update and to output stats to STDOUT or not.
344/// Takes an optional D-Bus connection. Returns `Some(connection)` if the
345/// collection cycle completed without errors (meaning the connection is reusable),
346/// `None` if errors occurred.
347pub async fn stat_collector(
348 config: config::Config,
349 maybe_locked_stats: Option<Arc<RwLock<MonitordStats>>>,
350 output_stats: bool,
351 maybe_connection: Option<zbus::Connection>,
352) -> Result<Option<zbus::Connection>, MonitordError> {
353 let mut collect_interval_ms: u128 = 0;
354 if config.monitord.daemon {
355 collect_interval_ms = (config.monitord.daemon_stats_refresh_secs * 1000).into();
356 }
357
358 let config = Arc::new(config);
359 let locked_monitord_stats: Arc<RwLock<MonitordStats>> =
360 maybe_locked_stats.unwrap_or(Arc::new(RwLock::new(MonitordStats::default())));
361 let locked_machine_stats: Arc<RwLock<MachineStats>> =
362 Arc::new(RwLock::new(MachineStats::default()));
363 let cached_machine_connections: Arc<tokio::sync::Mutex<machines::MachineConnections>> =
364 Arc::new(tokio::sync::Mutex::new(HashMap::new()));
365
366 std::env::set_var("DBUS_SYSTEM_BUS_ADDRESS", &config.monitord.dbus_address);
367 // Seeded when the library caller passes a connection, otherwise
368 // connected lazily by the first collector that needs the bus. Mutable
369 // so a failed daemon cycle can swap in a fresh cell (see below) rather
370 // than letting the next cycle reuse a bus that may have gone away.
371 let mut dbus_cell: DbusCell = Arc::new(tokio::sync::OnceCell::new());
372 if let Some(conn) = maybe_connection {
373 // Seeding cannot fail: a fresh cell is always empty.
374 let _ = dbus_cell.set(conn);
375 }
376 let dbus_timeout = config.monitord.dbus_timeout;
377 let mut join_set: tokio::task::JoinSet<TimedCollectorOutput> = tokio::task::JoinSet::new();
378 let mut had_error;
379
380 // Counters for the systemd-report server. Kept even when the server is
381 // off: recording a run costs a few integer bumps.
382 let report_state = Arc::new(std::sync::Mutex::new(report::ReportState::default()));
383 if config.monitord.daemon && config.report.enabled {
384 if let Err(e) = report::spawn_server(
385 report::REPORT_DIR.into(),
386 locked_monitord_stats.clone(),
387 report_state.clone(),
388 ) {
389 error!("Unable to start the systemd-report server thread: {:?}", e);
390 }
391 }
392
393 loop {
394 let collect_start_time = Instant::now();
395 // Kept alive for the whole iteration so its reported duration covers
396 // the full run (spawn + drain), not just the synchronous spawn phase
397 // below where `run_guard` is held.
398 let run_span = tracing::info_span!("stat_collector_run");
399 let run_guard = run_span.enter();
400 info!("Starting stat collection run");
401
402 // One Manager.Describe serves both the version and system state
403 // collectors: PID 1 handles varlink requests one at a time, so a second
404 // call would sit behind the units collector's whole metrics stream.
405 //
406 // Which request reaches PID 1 first is still up to the scheduler, so
407 // under CPU pressure this call can land behind that stream anyway. That
408 // is the old cost for one call rather than two, not a new failure mode.
409 // Making it deterministic would mean holding the units collector until
410 // this resolves, which would put the collector that gates the cycle
411 // behind an unrelated socket.
412 let manager_describe = config.use_varlink(&[config.system_state.varlink]).then(|| {
413 crate::varlink_system::shared_describe(
414 crate::varlink_system::MANAGER_SOCKET_PATH.into(),
415 )
416 });
417
418 // Likewise one io.systemd.Metrics.List per cycle: units and verify both
419 // read it, and a second stream would make PID 1 walk every unit again.
420 // Lazy, so a cycle served entirely over D-Bus sends nothing.
421 let manager_metrics =
422 crate::varlink_units::shared_metrics(crate::varlink_units::METRICS_SOCKET_PATH.into());
423
424 // Always collect systemd version
425 {
426 let dbus_cell = Arc::clone(&dbus_cell);
427 let stats_clone = locked_machine_stats.clone();
428 let describe = manager_describe.clone();
429 let no_fallback = config.varlink.no_fallback;
430 spawn_timed(&mut join_set, "version", collect_start_time, async move {
431 if let Some(describe) = describe {
432 match crate::varlink_system::update_version(describe, stats_clone.clone()).await
433 {
434 Ok(()) => {
435 stats_clone.write().await.varlink_usage.version =
436 Some(CollectorTransport::Varlink);
437 return Ok(());
438 }
439 Err(err) => {
440 crate::varlink_fallback::report_varlink_failure(
441 no_fallback,
442 "version",
443 "D-Bus",
444 err,
445 )?;
446 }
447 }
448 }
449 stats_clone.write().await.varlink_usage.version = Some(CollectorTransport::Dbus);
450 let conn = dbus_connection(&dbus_cell, dbus_timeout).await?;
451 crate::system::update_version(conn, stats_clone.clone()).await
452 });
453 }
454
455 // Collect pid1 procfs stats
456 if config.pid1.enabled {
457 spawn_timed(
458 &mut join_set,
459 "pid1",
460 collect_start_time,
461 crate::pid1::update_pid1_stats(1, locked_machine_stats.clone()),
462 );
463 }
464
465 // Run networkd collector if enabled
466 if config.networkd.enabled {
467 let config_clone = Arc::clone(&config);
468 let dbus_cell = Arc::clone(&dbus_cell);
469 let stats_clone = locked_machine_stats.clone();
470 let no_fallback = config.varlink.no_fallback;
471 spawn_timed(&mut join_set, "networkd", collect_start_time, async move {
472 if config_clone.use_varlink(&[config_clone.networkd.varlink]) {
473 let endpoint = crate::varlink_networkd::NETWORK_SOCKET_PATH.into();
474 match crate::varlink_networkd::get_networkd_state(&endpoint).await {
475 Ok(networkd_stats) => {
476 let mut machine_stats = stats_clone.write().await;
477 machine_stats.networkd = networkd_stats;
478 machine_stats.varlink_usage.networkd =
479 Some(CollectorTransport::Varlink);
480 return Ok(());
481 }
482 Err(err) => {
483 crate::varlink_fallback::report_varlink_failure(
484 no_fallback,
485 "networkd",
486 "file-based",
487 err,
488 )?;
489 }
490 }
491 }
492 stats_clone.write().await.varlink_usage.networkd = Some(CollectorTransport::Dbus);
493 // No eager connect: the cell flows into the collector and
494 // is resolved only if sysfs yields no usable map — the
495 // same lazy pattern as boot_blame.
496 crate::networkd::update_networkd_stats(
497 config_clone.networkd.link_state_dir.clone(),
498 None,
499 std::path::PathBuf::from("/sys"),
500 Some((dbus_cell, dbus_timeout)),
501 stats_clone,
502 )
503 .await
504 });
505 }
506
507 // Run system running (SystemState) state collector
508 if config.system_state.enabled {
509 let dbus_cell = Arc::clone(&dbus_cell);
510 let stats_clone = locked_machine_stats.clone();
511 let describe = manager_describe.clone();
512 let no_fallback = config.varlink.no_fallback;
513 spawn_timed(
514 &mut join_set,
515 "system_state",
516 collect_start_time,
517 async move {
518 if let Some(describe) = describe {
519 match crate::varlink_system::update_system_stats(
520 describe,
521 stats_clone.clone(),
522 )
523 .await
524 {
525 Ok(()) => {
526 stats_clone.write().await.varlink_usage.system_state =
527 Some(CollectorTransport::Varlink);
528 return Ok(());
529 }
530 Err(err) => {
531 crate::varlink_fallback::report_varlink_failure(
532 no_fallback,
533 "system state",
534 "D-Bus",
535 err,
536 )?;
537 }
538 }
539 }
540 stats_clone.write().await.varlink_usage.system_state =
541 Some(CollectorTransport::Dbus);
542 let conn = dbus_connection(&dbus_cell, dbus_timeout).await?;
543 crate::system::update_system_stats(conn, stats_clone.clone()).await
544 },
545 );
546 }
547
548 // Run service collectors if there are services listed in config
549 if config.units.enabled {
550 let config_clone = Arc::clone(&config);
551 let dbus_cell = Arc::clone(&dbus_cell);
552 let stats_clone = locked_machine_stats.clone();
553 let metrics = manager_metrics.clone();
554 let no_fallback = config.varlink.no_fallback;
555 spawn_timed(&mut join_set, "units", collect_start_time, async move {
556 if config_clone.use_varlink(&[config_clone.units.varlink]) {
557 match crate::varlink_units::update_unit_stats(
558 Arc::clone(&config_clone),
559 stats_clone.clone(),
560 metrics,
561 )
562 .await
563 {
564 Ok(discovery) => {
565 // Per-service stats, timer properties and service
566 // types all come from io.systemd.Unit.List. If that
567 // socket is unusable the whole units collection is
568 // redone over D-Bus: restoring pieces of it would
569 // leave [services] and timers partially filled from
570 // the metrics, which is worse than either path alone.
571 if let Err(err) = crate::varlink_units::apply_unit_details(
572 &crate::varlink_unit::MANAGER_SOCKET_PATH.into(),
573 &stats_clone,
574 &config_clone,
575 "",
576 &discovery,
577 )
578 .await
579 {
580 crate::varlink_fallback::report_varlink_failure(
581 no_fallback,
582 "unit details",
583 "D-Bus",
584 err,
585 )?;
586 stats_clone.write().await.varlink_usage.units =
587 Some(CollectorTransport::Dbus);
588 let conn = dbus_connection(&dbus_cell, dbus_timeout).await?;
589 return crate::units::update_unit_stats(
590 config_clone,
591 conn,
592 stats_clone,
593 String::new(),
594 )
595 .await;
596 }
597 if config_clone.units.unit_files {
598 let unit_files = crate::units::collect_unit_files_stats("").await;
599 let mut ms = stats_clone.write().await;
600 ms.units.unit_files = unit_files;
601 }
602 stats_clone.write().await.varlink_usage.units =
603 Some(CollectorTransport::Varlink);
604 return Ok(());
605 }
606 Err(err) => {
607 crate::varlink_fallback::report_varlink_failure(
608 no_fallback,
609 "units",
610 "D-Bus",
611 err,
612 )?;
613 }
614 }
615 }
616 stats_clone.write().await.varlink_usage.units = Some(CollectorTransport::Dbus);
617 let conn = dbus_connection(&dbus_cell, dbus_timeout).await?;
618 crate::units::update_unit_stats(config_clone, conn, stats_clone, String::new())
619 .await
620 });
621 }
622
623 if config.machines.enabled {
624 let stats_clone = locked_machine_stats.clone();
625 let config_clone = Arc::clone(&config);
626 let dbus_cell = Arc::clone(&dbus_cell);
627 let monitord_stats_clone = locked_monitord_stats.clone();
628 let connections_clone = cached_machine_connections.clone();
629 spawn_timed(&mut join_set, "machines", collect_start_time, async move {
630 // Enumeration records its transport (varlink or D-Bus) on
631 // the host stats; per-container collection records its own
632 // transports on each machine's stats.
633 crate::machines::update_machines_stats(
634 config_clone,
635 dbus_cell,
636 stats_clone,
637 monitord_stats_clone,
638 connections_clone,
639 )
640 .await
641 });
642 }
643
644 if config.dbus_stats.enabled {
645 let dbus_cell = Arc::clone(&dbus_cell);
646 let config_clone = Arc::clone(&config);
647 let stats_clone = locked_machine_stats.clone();
648 spawn_timed(
649 &mut join_set,
650 "dbus_stats",
651 collect_start_time,
652 async move {
653 let conn = dbus_connection(&dbus_cell, dbus_timeout).await?;
654 crate::dbus_stats::update_dbus_stats(config_clone, conn, stats_clone).await
655 },
656 );
657 }
658
659 // `verify` and `boot_blame` decide their transport internally:
660 // they take the shared cell and resolve it only on a D-Bus code
661 // path, so a varlink success or cache hit never connects.
662 if config.boot_blame.enabled {
663 let dbus_cell = Arc::clone(&dbus_cell);
664 let config_clone = Arc::clone(&config);
665 let stats_clone = locked_machine_stats.clone();
666 spawn_timed(
667 &mut join_set,
668 "boot_blame",
669 collect_start_time,
670 async move {
671 let no_fallback = config_clone.varlink.no_fallback;
672 crate::boot::update_boot_blame_stats(
673 config_clone,
674 dbus_cell,
675 dbus_timeout,
676 stats_clone,
677 no_fallback,
678 )
679 .await
680 },
681 );
682 }
683
684 if config.verify.enabled {
685 let dbus_cell = Arc::clone(&dbus_cell);
686 let config_clone = Arc::clone(&config);
687 let stats_clone = locked_machine_stats.clone();
688 let metrics = config
689 .use_varlink(&[config.verify.varlink])
690 .then(|| manager_metrics.clone());
691 spawn_timed(&mut join_set, "verify", collect_start_time, async move {
692 crate::verify::update_verify_stats(
693 dbus_cell,
694 dbus_timeout,
695 stats_clone,
696 config_clone.verify.allowlist.clone(),
697 config_clone.verify.blocklist.clone(),
698 metrics,
699 config_clone.varlink.no_fallback,
700 )
701 .await
702 });
703 }
704
705 // Always varlink with no D-Bus fallback, so like pid1 it records no
706 // varlink_usage gauge.
707 if config.report.collect {
708 spawn_timed(
709 &mut join_set,
710 "report",
711 collect_start_time,
712 crate::report_collector::update_report_stats(
713 Arc::clone(&config),
714 locked_monitord_stats.clone(),
715 ),
716 );
717 }
718
719 if join_set.len() == 1 {
720 warn!("No collectors except systemd version scheduled to run. Exiting");
721 }
722
723 // All collectors above were spawned with `run_span` captured as their
724 // parent; the guard must be dropped before the first `.await` below
725 // since span guards are not valid to hold across an await point.
726 drop(run_guard);
727
728 // Drain join_set, collect per-collector timings + log per-collector failures
729 had_error = false;
730 let mut timings: Vec<CollectorTiming> = Vec::new();
731 while let Some(res) = join_set.join_next().await {
732 match res {
733 Ok((name, collector_result, start_offset, elapsed)) => {
734 let success = collector_result.is_ok();
735 if let Err(e) = collector_result {
736 had_error = true;
737 error!("Collector '{}' failure: {:?}", name, e);
738 }
739 timings.push(CollectorTiming {
740 name,
741 start_offset_ms: start_offset.as_secs_f64() * 1000.0,
742 elapsed_ms: elapsed.as_secs_f64() * 1000.0,
743 success,
744 });
745 }
746 Err(e) => {
747 had_error = true;
748 error!("Join error: {:?}", e);
749 }
750 }
751 }
752
753 let elapsed_runtime = collect_start_time.elapsed();
754 let elapsed_runtime_ms = elapsed_runtime.as_millis();
755
756 // Sort timings by elapsed desc so the slowest collector is first in the JSON output
757 timings.sort_by(|a, b| {
758 b.elapsed_ms
759 .partial_cmp(&a.elapsed_ms)
760 .unwrap_or(std::cmp::Ordering::Equal)
761 });
762
763 // Per-collector lines log at debug! to keep daemon-mode noise low.
764 // The same data is on MonitordStats::collector_timings for callers that need it.
765 for t in &timings {
766 debug!(
767 "collector '{}' start_offset={:.1}ms elapsed={:.1}ms{}",
768 t.name,
769 t.start_offset_ms,
770 t.elapsed_ms,
771 if t.success { "" } else { " (FAILED)" },
772 );
773 }
774
775 {
776 // Update monitord stats with machine stats
777 let mut monitord_stats = locked_monitord_stats.write().await;
778 let machine_stats = locked_machine_stats.read().await;
779 monitord_stats.pid1 = machine_stats.pid1.clone();
780 monitord_stats.networkd = machine_stats.networkd.clone();
781 monitord_stats.system_state = machine_stats.system_state;
782 monitord_stats.version = machine_stats.version.clone();
783 monitord_stats.units = machine_stats.units.clone();
784 monitord_stats.dbus_stats = machine_stats.dbus_stats.clone();
785 monitord_stats.boot_blame = machine_stats.boot_blame.clone();
786 monitord_stats.verify_stats = machine_stats.verify_stats.clone();
787 monitord_stats.varlink_usage = machine_stats.varlink_usage.clone();
788 set_stat_collection_run_time(&mut monitord_stats, elapsed_runtime);
789 report_state
790 .lock()
791 .unwrap_or_else(|poisoned| poisoned.into_inner())
792 .record_run(&timings, had_error);
793 monitord_stats.collector_timings = timings;
794 }
795
796 info!("stat collection run took {}ms", elapsed_runtime_ms);
797 if output_stats {
798 let monitord_stats = locked_monitord_stats.read().await;
799 print_stats(
800 &config.monitord.key_prefix,
801 &config.monitord.output_format,
802 &monitord_stats,
803 );
804 }
805 if !config.monitord.daemon {
806 break;
807 }
808 if had_error {
809 // Drop the shared connection so the next cycle reconnects
810 // rather than reusing a bus that may have gone away mid-run.
811 // Each iteration clones the cell into its tasks at spawn time,
812 // so reassigning the local is enough for the next cycle's
813 // spawns to pick up the fresh cell.
814 dbus_cell = Arc::new(tokio::sync::OnceCell::new());
815 }
816 let sleep_time_ms = collect_interval_ms - elapsed_runtime_ms;
817 info!("stat collection sleeping for {}s 😴", sleep_time_ms / 1000);
818 tokio::time::sleep(Duration::from_millis(
819 sleep_time_ms
820 .try_into()
821 .expect("Sleep time does not fit into a u64 :O"),
822 ))
823 .await;
824 }
825 // A failed cycle returns no connection so a repeated one-shot caller
826 // reconnects instead of reusing a broken bus; a clean cycle hands the
827 // shared connection back for reuse. (In daemon mode the reset above
828 // already swapped in a fresh cell, so `get()` here is empty by design
829 // and `None` is the only honest answer.)
830 let conn = if had_error {
831 None
832 } else {
833 dbus_cell.get().cloned()
834 };
835 Ok(conn)
836}
837
838#[cfg(test)]
839mod tests {
840 use super::*;
841
842 /// The lazy-connect contract finding 6 on #224 pins down: a failed
843 /// connect is not cached, so consecutive failures each attempt (and
844 /// report) a fresh error rather than inheriting a poisoned cell.
845 #[tokio::test]
846 async fn test_dbus_connection_failure_is_not_cached() {
847 std::env::set_var(
848 "DBUS_SYSTEM_BUS_ADDRESS",
849 "unix:path=/nonexistent/monitord-test-bus-socket",
850 );
851 let cell: DbusCell = Arc::new(tokio::sync::OnceCell::new());
852 assert!(dbus_connection(&cell, 1).await.is_err());
853 assert!(
854 cell.get().is_none(),
855 "failed connect must not populate the cell"
856 );
857 assert!(dbus_connection(&cell, 1).await.is_err());
858 assert!(cell.get().is_none());
859 }
860
861 #[test]
862 fn test_stat_collection_run_time_ms_conversion() {
863 let mut stats = MonitordStats::default();
864 set_stat_collection_run_time(&mut stats, Duration::from_millis(5));
865 assert_eq!(stats.stat_collection_run_time_ms, 5.0);
866
867 set_stat_collection_run_time(&mut stats, Duration::from_micros(500));
868 assert!((stats.stat_collection_run_time_ms - 0.5).abs() < f64::EPSILON);
869 }
870}