Skip to main content

monitord/
report.rs

1//! # report module
2//!
3//! Serve monitord's own health as an `io.systemd.Metrics` source so
4//! `systemd-report` (systemd ≥ 260) includes monitord in its report.
5//!
6//! `systemd-report` calls `io.systemd.Metrics.List` / `Describe` on every
7//! socket in `/run/systemd/report/`. A source's socket must be named as a
8//! varlink interface name, and every metric it returns must be prefixed with
9//! that name followed by a dot. Metrics without the prefix are dropped as
10//! invalid. So the socket is always [`REPORT_SOCKET_NAME`] and every family
11//! in [`FAMILIES`] starts with it.
12//!
13//! These metrics cover monitord itself: whether its last collection run
14//! was clean, how long each collector took, and failure counters. They do
15//! not re-export the stats monitord collects, which systemd's own report
16//! sources already publish.
17
18use std::collections::BTreeMap;
19use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
20use std::os::unix::fs::{FileTypeExt, PermissionsExt};
21use std::path::{Path, PathBuf};
22use std::sync::{Arc, Mutex};
23use std::time::{SystemTime, UNIX_EPOCH};
24
25use futures_util::stream;
26use serde::{Deserialize, Serialize};
27use tokio::sync::RwLock;
28use tracing::{debug, error, info, warn};
29use zlink::introspect;
30
31use crate::{CollectorTiming, MonitordStats};
32
33/// Socket filename, which is also the prefix of every metric name.
34pub const REPORT_SOCKET_NAME: &str = "io.monitord";
35/// Directory `systemd-report` scans for system-scope sources.
36pub const REPORT_DIR: &str = "/run/systemd/report";
37
38/// First fd systemd passes in socket activation (`SD_LISTEN_FDS_START`).
39const SD_LISTEN_FDS_START: i32 = 3;
40
41/// Metric family type, as in systemd's `io.systemd.Metrics` IDL.
42#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, introspect::Type)]
43#[serde(rename_all = "snake_case")]
44#[zlink(rename_all = "snake_case")]
45pub enum MetricFamilyType {
46    Counter,
47    Gauge,
48    String,
49    /// Arbitrary JSON object. monitord exports none; listed so our
50    /// introspected IDL matches systemd's.
51    Object,
52}
53
54/// A metric value: any JSON value, `any` in systemd's IDL (a systemd
55/// extension zlink can describe but not derive for `serde_json::Value`).
56#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
57#[serde(transparent)]
58pub struct MetricValue(pub serde_json::Value);
59
60impl introspect::Type for MetricValue {
61    const TYPE: &'static zlink::idl::Type<'static> = &zlink::idl::Type::Any;
62}
63
64/// One metric family: (name suffix after `io.monitord.`, description, type).
65pub const FAMILIES: &[(&str, &str, MetricFamilyType)] = &[
66    (
67        "collectionErrorsTotal",
68        "Collection runs where at least one collector failed",
69        MetricFamilyType::Counter,
70    ),
71    (
72        "collectionRunTimeMs",
73        "Wall time of the last collection run in milliseconds",
74        MetricFamilyType::Gauge,
75    ),
76    (
77        "collectionRunsTotal",
78        "Collection runs completed since monitord started",
79        MetricFamilyType::Counter,
80    ),
81    (
82        "collectorElapsedMs",
83        "Wall time of each collector in the last run in milliseconds",
84        MetricFamilyType::Gauge,
85    ),
86    (
87        "collectorFailuresTotal",
88        "Failed runs of each collector since monitord started",
89        MetricFamilyType::Counter,
90    ),
91    (
92        "collectorSuccess",
93        "1 if the collector succeeded in the last run, else 0",
94        MetricFamilyType::Gauge,
95    ),
96    (
97        "healthy",
98        "1 if the last collection run had no collector failures, else 0",
99        MetricFamilyType::Gauge,
100    ),
101    (
102        "lastCollectionTimestamp",
103        "Unix time in seconds when the last collection run finished",
104        MetricFamilyType::Gauge,
105    ),
106    (
107        "varlinkUsage",
108        "1 if varlink served the collector in the last run, 0 for D-Bus",
109        MetricFamilyType::Gauge,
110    ),
111    ("version", "monitord version", MetricFamilyType::String),
112];
113
114/// Counters kept across collection runs. Not part of `MonitordStats` so the
115/// JSON output is unchanged; only the report server reads them.
116#[derive(Clone, Debug, Default, PartialEq)]
117pub struct ReportState {
118    pub collection_runs_total: u64,
119    pub collection_errors_total: u64,
120    /// Failure count per collector name. Every collector seen gets an
121    /// entry, so a counter is present at 0 before its first failure.
122    pub collector_failures_total: BTreeMap<String, u64>,
123    /// `None` until the first run finishes.
124    pub last_collection_timestamp: Option<u64>,
125    pub last_run_healthy: bool,
126}
127
128impl ReportState {
129    /// Record a finished collection run.
130    pub fn record_run(&mut self, timings: &[CollectorTiming], had_error: bool) {
131        self.collection_runs_total += 1;
132        if had_error {
133            self.collection_errors_total += 1;
134        }
135        for timing in timings {
136            let failures = self
137                .collector_failures_total
138                .entry(timing.name.clone())
139                .or_default();
140            if !timing.success {
141                *failures += 1;
142            }
143        }
144        self.last_run_healthy = !had_error;
145        self.last_collection_timestamp = SystemTime::now()
146            .duration_since(UNIX_EPOCH)
147            .ok()
148            .map(|d| d.as_secs());
149    }
150}
151
152/// `io.systemd.Metrics.List` reply.
153#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, introspect::Type)]
154pub struct MetricReply {
155    pub name: String,
156    #[serde(skip_serializing_if = "Option::is_none")]
157    pub object: Option<String>,
158    pub value: MetricValue,
159}
160
161/// `io.systemd.Metrics.Describe` reply.
162#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, introspect::Type)]
163pub struct DescribeReply {
164    pub name: String,
165    pub description: String,
166    pub r#type: MetricFamilyType,
167}
168
169/// Errors this source sends back, named as systemd names them.
170#[derive(Debug, Clone, PartialEq, zlink::ReplyError)]
171#[zlink(interface = "org.varlink.service")]
172pub enum ReportError {
173    /// `List`/`Describe` called without the `more` flag.
174    ExpectedMore,
175}
176
177/// `ExpectedMore` is a standard `org.varlink.service` error, so it is kept
178/// out of the `io.systemd.Metrics` IDL we introspect as.
179impl introspect::ReplyError for ReportError {
180    const VARIANTS: &'static [&'static zlink::idl::Error<'static>] = &[];
181}
182
183fn full_name(suffix: &str) -> String {
184    format!("{REPORT_SOCKET_NAME}.{suffix}")
185}
186
187fn metric(suffix: &str, object: Option<&str>, value: impl Into<serde_json::Value>) -> MetricReply {
188    MetricReply {
189        name: full_name(suffix),
190        object: object.map(str::to_string),
191        value: MetricValue(value.into()),
192    }
193}
194
195/// Build every `List` reply from the latest stats and counters.
196///
197/// Before the first run there are no timings and no timestamp, so only
198/// the version, the run counters and `healthy` = 0 are returned.
199pub fn build_metrics(stats: &MonitordStats, state: &ReportState) -> Vec<MetricReply> {
200    let mut metrics = vec![
201        metric("version", None, env!("CARGO_PKG_VERSION")),
202        metric("healthy", None, u64::from(state.last_run_healthy)),
203        metric("collectionRunsTotal", None, state.collection_runs_total),
204        metric("collectionErrorsTotal", None, state.collection_errors_total),
205    ];
206    if let Some(ts) = state.last_collection_timestamp {
207        metrics.push(metric("lastCollectionTimestamp", None, ts));
208        metrics.push(metric(
209            "collectionRunTimeMs",
210            None,
211            stats.stat_collection_run_time_ms,
212        ));
213    }
214    for timing in &stats.collector_timings {
215        let object = Some(timing.name.as_str());
216        metrics.push(metric("collectorElapsedMs", object, timing.elapsed_ms));
217        metrics.push(metric(
218            "collectorSuccess",
219            object,
220            u64::from(timing.success),
221        ));
222    }
223    for (name, failures) in &state.collector_failures_total {
224        metrics.push(metric("collectorFailuresTotal", Some(name), *failures));
225    }
226    let usage = serde_json::to_value(&stats.varlink_usage).unwrap_or_default();
227    if let serde_json::Value::Object(usage) = usage {
228        for (collector, transport) in usage {
229            if transport.is_null() {
230                continue;
231            }
232            metrics.push(metric("varlinkUsage", Some(&collector), transport));
233        }
234    }
235    metrics
236}
237
238/// Mark every reply but the last as continued, as a streamed reply needs.
239fn into_stream<T>(
240    items: Vec<T>,
241) -> impl futures_util::Stream<Item = Result<zlink::Reply<T>, ReportError>> + Unpin {
242    let last = items.len().saturating_sub(1);
243    stream::iter(
244        items
245            .into_iter()
246            .enumerate()
247            .map(move |(i, item)| Ok(zlink::Reply::new(Some(item)).set_continues(Some(i < last)))),
248    )
249}
250
251fn expected_more<T>(
252) -> impl futures_util::Stream<Item = Result<zlink::Reply<T>, ReportError>> + Unpin {
253    stream::iter(vec![Err(ReportError::ExpectedMore)])
254}
255
256/// The `io.systemd.Metrics` service.
257pub struct MetricsService {
258    stats: Arc<RwLock<MonitordStats>>,
259    state: Arc<Mutex<ReportState>>,
260}
261
262impl MetricsService {
263    pub fn new(stats: Arc<RwLock<MonitordStats>>, state: Arc<Mutex<ReportState>>) -> Self {
264        Self { stats, state }
265    }
266
267    /// Every `List` reply, built from one consistent run.
268    ///
269    /// Same lock order as the writer in `stat_collector`, which records a
270    /// run in `ReportState` while it holds the stats write lock: take the
271    /// stats read lock first, then copy the state under it. Copying the state
272    /// first would let a run finish in between, and the reply would mix the
273    /// old run's `healthy`/counters with the new run's timings.
274    async fn snapshot(&self) -> Vec<MetricReply> {
275        let stats = self.stats.read().await;
276        let state = self
277            .state
278            .lock()
279            .unwrap_or_else(|poisoned| poisoned.into_inner())
280            .clone();
281        build_metrics(&stats, &state)
282    }
283}
284
285#[zlink::service(
286    interface = "io.systemd.Metrics",
287    vendor = "monitord",
288    product = "monitord",
289    version = env!("CARGO_PKG_VERSION"),
290    url = "https://github.com/cooperlees/monitord"
291)]
292impl MetricsService {
293    #[zlink(more)]
294    async fn list(
295        &self,
296        more: bool,
297    ) -> impl futures_util::Stream<Item = Result<zlink::Reply<MetricReply>, ReportError>> + Unpin
298    {
299        if !more {
300            return futures_util::future::Either::Left(expected_more());
301        }
302        let metrics = self.snapshot().await;
303        futures_util::future::Either::Right(into_stream(metrics))
304    }
305
306    #[zlink(more)]
307    async fn describe(
308        &self,
309        more: bool,
310    ) -> impl futures_util::Stream<Item = Result<zlink::Reply<DescribeReply>, ReportError>> + Unpin
311    {
312        if !more {
313            return futures_util::future::Either::Left(expected_more());
314        }
315        let families = FAMILIES
316            .iter()
317            .map(|(suffix, description, kind)| DescribeReply {
318                name: full_name(suffix),
319                description: description.to_string(),
320                r#type: *kind,
321            })
322            .collect();
323        futures_util::future::Either::Right(into_stream(families))
324    }
325}
326
327/// Take the listening socket systemd passed, if it passed one to us.
328///
329/// Follows `sd_listen_fds(3)`: only when `LISTEN_PID` is our pid, using the
330/// first fd. The env vars are then cleared, and the fd is set close-on-exec
331/// so the machine helpers monitord re-execs don't inherit it.
332///
333/// Call it before starting anything that may spawn a process, as
334/// [`spawn_server`] does: close-on-exec only protects later spawns, and a
335/// helper started earlier keeps its copy of the listener.
336pub fn take_activation_fd() -> Option<OwnedFd> {
337    let pid = std::env::var("LISTEN_PID").ok()?.parse::<u32>().ok()?;
338    if pid != std::process::id() {
339        return None;
340    }
341    let fds = std::env::var("LISTEN_FDS").ok()?.parse::<i32>().ok()?;
342    std::env::remove_var("LISTEN_PID");
343    std::env::remove_var("LISTEN_FDS");
344    std::env::remove_var("LISTEN_FDNAMES");
345    if fds < 1 {
346        return None;
347    }
348    if fds > 1 {
349        warn!("Socket activation passed {fds} fds; using only the first for {REPORT_SOCKET_NAME}");
350    }
351    // SAFETY: systemd hands this fd to us and nothing else in monitord
352    // uses it; taking ownership once is how sd_listen_fds consumers work.
353    let fd = unsafe { OwnedFd::from_raw_fd(SD_LISTEN_FDS_START) };
354    if unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC) } != 0 {
355        warn!(
356            "Unable to mark the socket-activated fd close-on-exec: {}",
357            std::io::Error::last_os_error()
358        );
359    }
360    Some(fd)
361}
362
363/// Bind `path`, replacing a socket file only if nobody is serving on it.
364///
365/// Binding first means a live listener's file is never unlinked: only on
366/// `AddrInUse` is the existing file probed. A refused connection means it
367/// is stale (its owner died without removing it) and it is replaced; a
368/// connection that succeeds means another monitord, or
369/// `monitord-report.socket`, is serving there and this one backs off.
370/// Anything that isn't a socket is left alone.
371fn bind_unless_served(path: &Path) -> anyhow::Result<zlink::tokio::unix::Listener> {
372    match zlink::tokio::unix::bind(path) {
373        Ok(listener) => return Ok(listener),
374        Err(zlink::Error::Io(e)) if e.kind() == std::io::ErrorKind::AddrInUse => {}
375        Err(e) => return Err(e.into()),
376    }
377    let file_type = std::fs::symlink_metadata(path)?.file_type();
378    if !file_type.is_socket() {
379        anyhow::bail!(
380            "{} exists and is not a socket; not replacing it",
381            path.display()
382        );
383    }
384    match std::os::unix::net::UnixStream::connect(path) {
385        Ok(_) => anyhow::bail!(
386            "{} is already being served (another monitord or monitord-report.socket)",
387            path.display()
388        ),
389        Err(e) if e.kind() == std::io::ErrorKind::ConnectionRefused => {
390            debug!("Replacing stale {}", path.display());
391            std::fs::remove_file(path)?;
392            Ok(zlink::tokio::unix::bind(path)?)
393        }
394        Err(e) => Err(anyhow::anyhow!(
395            "Unable to tell whether {} is in use: {e}",
396            path.display()
397        )),
398    }
399}
400
401/// Listener for the report server: `activation_fd` (from
402/// [`take_activation_fd`]) if systemd passed one, otherwise a socket
403/// monitord binds in `dir` itself.
404///
405/// Must run inside the runtime that will serve it, as the listener
406/// registers with that runtime's reactor. `dir` is never created: a
407/// missing `/run/systemd/report` means systemd predates the report
408/// framework, and the directory belongs to systemd.
409pub fn listener(
410    dir: &Path,
411    activation_fd: Option<OwnedFd>,
412) -> anyhow::Result<zlink::tokio::unix::Listener> {
413    if let Some(fd) = activation_fd {
414        info!("Serving {REPORT_SOCKET_NAME} metrics on the socket-activated fd");
415        return Ok(zlink::tokio::unix::Listener::try_from(fd)?);
416    }
417    if !dir.is_dir() {
418        anyhow::bail!(
419            "{} does not exist; systemd-report needs systemd 260 or newer",
420            dir.display()
421        );
422    }
423    let path = dir.join(REPORT_SOCKET_NAME);
424    let listener = bind_unless_served(&path)?;
425    // Read-only health data, so let unprivileged systemd-report read it,
426    // as systemd's own report sockets do (SocketMode=0666).
427    std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o666))?;
428    info!("Serving {REPORT_SOCKET_NAME} metrics on {}", path.display());
429    Ok(listener)
430}
431
432/// Serve `io.systemd.Metrics` on `listener` until an error ends it.
433///
434/// The future is not `Send` (a zlink limitation, rust-lang/rust#100013), so
435/// it can't go to `tokio::spawn` on a multi-threaded runtime. Run it with
436/// `tokio::select!`, on a `LocalSet`, or use [`spawn_server`].
437pub async fn serve(
438    listener: zlink::tokio::unix::Listener,
439    stats: Arc<RwLock<MonitordStats>>,
440    state: Arc<Mutex<ReportState>>,
441) -> anyhow::Result<()> {
442    zlink::Server::new(listener, MetricsService::new(stats, state))
443        .run()
444        .await?;
445    Ok(())
446}
447
448/// Run the report server on its own thread with a current-thread runtime.
449///
450/// Public so library users with their own collection loop (e.g.
451/// monitord-exporter) can serve their stats and state too. A failure is
452/// logged and ends only the server thread, never collection.
453///
454/// The socket-activated fd is claimed and marked close-on-exec here, on
455/// the calling thread before this returns, so no process spawned after the
456/// call can inherit it. Call it before starting collection.
457pub fn spawn_server(
458    dir: PathBuf,
459    stats: Arc<RwLock<MonitordStats>>,
460    state: Arc<Mutex<ReportState>>,
461) -> std::io::Result<std::thread::JoinHandle<()>> {
462    let activation_fd = take_activation_fd();
463    std::thread::Builder::new()
464        .name("monitord-report".to_string())
465        .spawn(move || {
466            let runtime = match tokio::runtime::Builder::new_current_thread()
467                .enable_all()
468                .build()
469            {
470                Ok(runtime) => runtime,
471                Err(e) => {
472                    error!("Unable to start the systemd-report runtime: {e:?}");
473                    return;
474                }
475            };
476            runtime.block_on(async move {
477                // The listener registers with the reactor, so it has to be
478                // made inside this runtime rather than the caller's.
479                let listener = match listener(&dir, activation_fd) {
480                    Ok(listener) => listener,
481                    Err(e) => {
482                        warn!("Not serving systemd-report metrics: {e:?}");
483                        return;
484                    }
485                };
486                if let Err(e) = serve(listener, stats, state).await {
487                    error!("systemd-report server stopped: {e:?}");
488                }
489            });
490        })
491}
492
493#[cfg(test)]
494mod tests {
495    use super::*;
496    use crate::varlink::metrics::{Metrics, MetricsError};
497    use futures_util::StreamExt;
498
499    /// Port of systemd's `varlink_idl_interface_name_is_valid`: dot
500    /// separated labels of ASCII letters, digits and `-`, each starting
501    /// with a letter, at least two labels.
502    fn interface_name_is_valid(name: &str) -> bool {
503        let labels: Vec<&str> = name.split('.').collect();
504        labels.len() >= 2
505            && labels.iter().all(|label| {
506                label
507                    .chars()
508                    .next()
509                    .is_some_and(|c| c.is_ascii_alphabetic())
510                    && label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
511                    && !label.ends_with('-')
512            })
513    }
514
515    /// Port of systemd's `varlink_idl_field_name_is_valid`.
516    fn field_name_is_valid(name: &str) -> bool {
517        name.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
518            && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
519            && !name.ends_with('_')
520    }
521
522    /// What `systemd-report` checks before it accepts a metric from the
523    /// `io.monitord` source (`metrics_name_valid` + the source prefix).
524    fn systemd_report_accepts(name: &str) -> bool {
525        let Some((interface, field)) = name.rsplit_once('.') else {
526            return false;
527        };
528        interface_name_is_valid(interface)
529            && field_name_is_valid(field)
530            && name
531                .strip_prefix(REPORT_SOCKET_NAME)
532                .is_some_and(|rest| rest.starts_with('.'))
533    }
534
535    fn timing(name: &str, success: bool) -> CollectorTiming {
536        CollectorTiming {
537            name: name.to_string(),
538            start_offset_ms: 0.0,
539            elapsed_ms: 1.5,
540            success,
541        }
542    }
543
544    #[test]
545    fn test_socket_name_is_a_valid_source() {
546        assert!(interface_name_is_valid(REPORT_SOCKET_NAME));
547    }
548
549    #[test]
550    fn test_every_family_name_passes_systemd_report_checks() {
551        for (suffix, _, _) in FAMILIES {
552            assert!(systemd_report_accepts(&full_name(suffix)), "{suffix}");
553        }
554        assert!(!systemd_report_accepts("io.monitordfoo.bar"));
555        assert!(!systemd_report_accepts("io.systemd.Manager.foo"));
556    }
557
558    #[test]
559    fn test_families_are_sorted_and_unique() {
560        let names: Vec<&str> = FAMILIES.iter().map(|(n, _, _)| *n).collect();
561        let mut sorted = names.clone();
562        sorted.sort();
563        sorted.dedup();
564        assert_eq!(names, sorted);
565    }
566
567    #[test]
568    fn test_record_run_counts() {
569        let mut state = ReportState::default();
570        state.record_run(&[timing("units", true), timing("pid1", true)], false);
571        assert_eq!(state.collection_runs_total, 1);
572        assert_eq!(state.collection_errors_total, 0);
573        assert!(state.last_run_healthy);
574        assert_eq!(state.collector_failures_total["units"], 0);
575        assert!(state.last_collection_timestamp.is_some());
576
577        state.record_run(&[timing("units", false), timing("pid1", true)], true);
578        assert_eq!(state.collection_runs_total, 2);
579        assert_eq!(state.collection_errors_total, 1);
580        assert!(!state.last_run_healthy);
581        assert_eq!(state.collector_failures_total["units"], 1);
582        assert_eq!(state.collector_failures_total["pid1"], 0);
583
584        // A clean run after a failure clears healthy but keeps the counter.
585        state.record_run(&[timing("units", true)], false);
586        assert!(state.last_run_healthy);
587        assert_eq!(state.collector_failures_total["units"], 1);
588    }
589
590    #[test]
591    fn test_build_metrics_before_first_run() {
592        let metrics = build_metrics(&MonitordStats::default(), &ReportState::default());
593        let names: Vec<&str> = metrics.iter().map(|m| m.name.as_str()).collect();
594        assert!(names.contains(&"io.monitord.version"));
595        assert!(names.contains(&"io.monitord.healthy"));
596        assert!(!names.contains(&"io.monitord.lastCollectionTimestamp"));
597        let healthy = metrics
598            .iter()
599            .find(|m| m.name == "io.monitord.healthy")
600            .unwrap();
601        assert_eq!(healthy.value.0, serde_json::json!(0));
602    }
603
604    #[test]
605    fn test_build_metrics_after_run() {
606        let stats = MonitordStats {
607            stat_collection_run_time_ms: 12.5,
608            collector_timings: vec![timing("units", false)],
609            ..Default::default()
610        };
611        let mut state = ReportState::default();
612        state.record_run(&stats.collector_timings, true);
613
614        let metrics = build_metrics(&stats, &state);
615        for m in &metrics {
616            assert!(systemd_report_accepts(&m.name), "{}", m.name);
617        }
618        let find = |name: &str, object: Option<&str>| {
619            metrics
620                .iter()
621                .find(|m| m.name == name && m.object.as_deref() == object)
622                .unwrap_or_else(|| panic!("missing {name} {object:?}"))
623                .value
624                .0
625                .clone()
626        };
627        assert_eq!(find("io.monitord.healthy", None), serde_json::json!(0));
628        assert_eq!(
629            find("io.monitord.collectionRunTimeMs", None),
630            serde_json::json!(12.5)
631        );
632        assert_eq!(
633            find("io.monitord.collectorSuccess", Some("units")),
634            serde_json::json!(0)
635        );
636        assert_eq!(
637            find("io.monitord.collectorFailuresTotal", Some("units")),
638            serde_json::json!(1)
639        );
640        // Disabled collectors have no transport and so no gauge.
641        assert!(!metrics.iter().any(|m| m.name == "io.monitord.varlinkUsage"));
642    }
643
644    #[tokio::test]
645    async fn test_snapshot_never_mixes_two_runs() {
646        // A clean run is on record when a List arrives mid-collection...
647        let stats = Arc::new(RwLock::new(MonitordStats {
648            collector_timings: vec![timing("units", true)],
649            ..Default::default()
650        }));
651        let state = Arc::new(Mutex::new(ReportState::default()));
652        state
653            .lock()
654            .unwrap()
655            .record_run(&[timing("units", true)], false);
656        let service = MetricsService::new(stats.clone(), state.clone());
657
658        // ...while the writer holds the stats lock to publish a failed run.
659        let mut writer = stats.write().await;
660        let mut reply = std::pin::pin!(service.snapshot());
661        assert!(futures_util::poll!(reply.as_mut()).is_pending());
662        writer.collector_timings = vec![timing("units", false)];
663        state
664            .lock()
665            .unwrap()
666            .record_run(&writer.collector_timings, true);
667        drop(writer);
668
669        // The reply must describe the failed run throughout, not the old
670        // run's healthy=1 next to the new run's failed collector.
671        let metrics = reply.await;
672        let value = |name: &str| {
673            metrics
674                .iter()
675                .find(|m| m.name == name)
676                .unwrap_or_else(|| panic!("missing {name}"))
677                .value
678                .0
679                .clone()
680        };
681        assert_eq!(value("io.monitord.healthy"), serde_json::json!(0));
682        assert_eq!(value("io.monitord.collectorSuccess"), serde_json::json!(0));
683        assert_eq!(
684            value("io.monitord.collectionErrorsTotal"),
685            serde_json::json!(1)
686        );
687    }
688
689    #[tokio::test]
690    async fn test_self_bind_refuses_a_served_socket() {
691        let dir = tempfile::tempdir().expect("tempdir");
692        let _serving = listener(dir.path(), None).expect("first listener");
693        let err = listener(dir.path(), None).expect_err("second listener must back off");
694        assert!(err.to_string().contains("already being served"), "{err}");
695        // The first listener's socket file is still there and still answers.
696        std::os::unix::net::UnixStream::connect(dir.path().join(REPORT_SOCKET_NAME))
697            .expect("original listener still reachable");
698    }
699
700    #[tokio::test]
701    async fn test_self_bind_reclaims_a_stale_socket() {
702        let dir = tempfile::tempdir().expect("tempdir");
703        let path = dir.path().join(REPORT_SOCKET_NAME);
704        // A dead owner: the socket file stays behind after its listener closes.
705        drop(std::os::unix::net::UnixListener::bind(&path).expect("bind"));
706        assert!(path.exists());
707        let _listener = listener(dir.path(), None).expect("stale socket replaced");
708        std::os::unix::net::UnixStream::connect(&path).expect("new listener reachable");
709    }
710
711    #[tokio::test]
712    async fn test_self_bind_leaves_non_sockets_alone() {
713        let dir = tempfile::tempdir().expect("tempdir");
714        let path = dir.path().join(REPORT_SOCKET_NAME);
715        std::fs::write(&path, "not a socket").expect("write");
716        let err = listener(dir.path(), None).expect_err("must not replace a file");
717        assert!(err.to_string().contains("not a socket"), "{err}");
718        assert_eq!(std::fs::read_to_string(&path).unwrap(), "not a socket");
719    }
720
721    #[tokio::test]
722    async fn test_server_round_trip() {
723        let dir = tempfile::tempdir().expect("tempdir");
724        let listener = listener(dir.path(), None).expect("listener");
725        let socket = dir.path().join(REPORT_SOCKET_NAME);
726        let mode = std::fs::metadata(&socket).unwrap().permissions().mode();
727        assert_eq!(mode & 0o777, 0o666);
728
729        let timings = vec![timing("pid1", true)];
730        let mut report_state = ReportState::default();
731        report_state.record_run(&timings, false);
732        let stats = Arc::new(RwLock::new(MonitordStats {
733            collector_timings: timings,
734            ..Default::default()
735        }));
736        let state = Arc::new(Mutex::new(report_state));
737        tokio::select! {
738            res = serve(listener, stats, state) => panic!("server exited: {res:?}"),
739            () = round_trip_client(&socket) => {}
740        }
741    }
742
743    async fn round_trip_client(socket: &Path) {
744        let mut conn = zlink::tokio::unix::connect(socket).await.expect("connect");
745        let listed: Vec<_> = conn
746            .list()
747            .await
748            .expect("list")
749            .map(|r| r.expect("reply").expect("no error"))
750            .collect()
751            .await;
752        assert!(listed.iter().any(
753            |m| m.name == "io.monitord.collectorSuccess" && m.object.as_deref() == Some("pid1")
754        ));
755        assert!(listed
756            .iter()
757            .any(|m| m.name == "io.monitord.healthy" && m.value == serde_json::json!(1)));
758
759        let described: Vec<Result<_, MetricsError>> = conn
760            .describe()
761            .await
762            .expect("describe")
763            .map(|r| r.expect("reply"))
764            .collect()
765            .await;
766        assert_eq!(described.len(), FAMILIES.len());
767        assert!(described.iter().all(Result::is_ok));
768    }
769}