monitord/
timer.rs

1//! # timers module
2//!
3//! All timer related logic goes here. This will be hitting timer specific
4//! dbus / varlink etc.
5
6use struct_field_names_as_array::FieldNamesAsArray;
7use thiserror::Error;
8use tracing::error;
9
10use crate::units::SystemdUnitStats;
11
12#[derive(Error, Debug)]
13pub enum MonitordTimerError {
14    #[error("Timer D-Bus error: {0}")]
15    ZbusError(#[from] zbus::Error),
16}
17
18#[derive(
19    serde::Serialize, serde::Deserialize, Clone, Debug, Default, Eq, FieldNamesAsArray, PartialEq,
20)]
21
22/// Per-timer unit metrics from the org.freedesktop.systemd1.Timer D-Bus interface.
23/// Ref: <https://www.freedesktop.org/software/systemd/man/org.freedesktop.systemd1.html>
24pub struct TimerStats {
25    /// AccuracySec timer property in microseconds; systemd may coalesce timer firings within this window to save wakeups
26    pub accuracy_usec: u64,
27    /// Whether FixedRandomDelay= is set; when true, the random delay is stable across reboots for this timer
28    pub fixed_random_delay: bool,
29    /// Realtime timestamp (usec since epoch) when this timer last triggered its service unit
30    pub last_trigger_usec: u64,
31    /// Monotonic timestamp (usec since boot) when this timer last triggered its service unit
32    pub last_trigger_usec_monotonic: u64,
33    /// Monotonic timestamp (usec since boot) when this timer will next elapse
34    pub next_elapse_usec_monotonic: u64,
35    /// Realtime timestamp (usec since epoch) when this timer will next elapse
36    pub next_elapse_usec_realtime: u64,
37    /// Whether Persistent= is set; when true, missed timer runs (e.g. during downtime) are triggered on next boot
38    pub persistent: bool,
39    /// RandomizedDelaySec property in microseconds; a random delay up to this value is added before each trigger
40    pub randomized_delay_usec: u64,
41    /// Whether RemainAfterElapse= is set; when true, the timer stays loaded after all triggers have elapsed
42    pub remain_after_elapse: bool,
43    /// Realtime timestamp (usec since epoch) of the most recent state change of the triggered service unit
44    pub service_unit_last_state_change_usec: u64,
45    /// Monotonic timestamp (usec since boot) of the most recent state change of the triggered service unit
46    pub service_unit_last_state_change_usec_monotonic: u64,
47}
48
49pub const TIMER_STATS_FIELD_NAMES: &[&str] = &TimerStats::FIELD_NAMES_AS_ARRAY;
50
51pub async fn collect_timer_stats(
52    connection: &zbus::Connection,
53    stats: &mut SystemdUnitStats,
54    unit: &crate::units::ListedUnit,
55) -> Result<TimerStats, MonitordTimerError> {
56    let mut timer_stats = TimerStats::default();
57
58    let pt = crate::dbus::zbus_timer::TimerProxy::builder(connection)
59        .cache_properties(zbus::proxy::CacheProperties::No)
60        .path(unit.unit_object_path.clone())?
61        .build()
62        .await?;
63    // Get service unit name to check when it last ran to ensure
64    // we are triggers the configured service with times set
65    let service_unit = pt.unit().await?;
66    let mut service_unit_last_state_change_usec: Result<u64, zbus::Error> = Ok(0);
67    let mut service_unit_last_state_change_usec_monotonic: Result<u64, zbus::Error> = Ok(0);
68    if service_unit.is_empty() {
69        error!("{}: No service unit name found for timer.", unit.name);
70    } else {
71        // Get the object path of the service unit
72        let mp = crate::dbus::zbus_systemd::ManagerProxy::builder(connection)
73            .cache_properties(zbus::proxy::CacheProperties::No)
74            .build()
75            .await?;
76        let service_unit_path = mp.get_unit(&service_unit).await?;
77        // Create a UnitProxy with the unit path to async get the two counters we want
78        let up = crate::dbus::zbus_unit::UnitProxy::builder(connection)
79            .cache_properties(zbus::proxy::CacheProperties::No)
80            .path(service_unit_path)?
81            .build()
82            .await?;
83
84        (
85            service_unit_last_state_change_usec,
86            service_unit_last_state_change_usec_monotonic,
87        ) = tokio::join!(
88            up.state_change_timestamp(),
89            up.state_change_timestamp_monotonic(),
90        );
91    }
92    timer_stats.service_unit_last_state_change_usec = service_unit_last_state_change_usec?;
93    timer_stats.service_unit_last_state_change_usec_monotonic =
94        service_unit_last_state_change_usec_monotonic?;
95
96    // Use tokio::join! without tokio::spawn to avoid per-task allocation overhead.
97    // These all share the same D-Bus connection so spawn adds no parallelism benefit.
98    let (
99        accuracy_usec,
100        fixed_random_delay,
101        last_trigger_usec,
102        last_trigger_usec_monotonic,
103        persistent,
104        next_elapse_usec_monotonic,
105        next_elapse_usec_realtime,
106        randomized_delay_usec,
107        remain_after_elapse,
108    ) = tokio::join!(
109        pt.accuracy_usec(),
110        pt.fixed_random_delay(),
111        pt.last_trigger_usec(),
112        pt.last_trigger_usec_monotonic(),
113        pt.persistent(),
114        pt.next_elapse_usec_monotonic(),
115        pt.next_elapse_usec_realtime(),
116        pt.randomized_delay_usec(),
117        pt.remain_after_elapse(),
118    );
119
120    timer_stats.accuracy_usec = accuracy_usec?;
121    timer_stats.fixed_random_delay = fixed_random_delay?;
122    timer_stats.last_trigger_usec = last_trigger_usec?;
123    timer_stats.last_trigger_usec_monotonic = last_trigger_usec_monotonic?;
124    timer_stats.persistent = persistent?;
125    timer_stats.next_elapse_usec_monotonic = next_elapse_usec_monotonic?;
126    timer_stats.next_elapse_usec_realtime = next_elapse_usec_realtime?;
127    timer_stats.randomized_delay_usec = randomized_delay_usec?;
128    timer_stats.remain_after_elapse = remain_after_elapse?;
129
130    if timer_stats.persistent {
131        stats.timer_persistent_units += 1;
132    }
133
134    if timer_stats.remain_after_elapse {
135        stats.timer_remain_after_elapse += 1;
136    }
137
138    Ok(timer_stats)
139}