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        .path(unit.unit_object_path.clone())?
60        .build()
61        .await?;
62    // Get service unit name to check when it last ran to ensure
63    // we are triggers the configured service with times set
64    let service_unit = pt.unit().await?;
65    let mut service_unit_last_state_change_usec: Result<u64, zbus::Error> = Ok(0);
66    let mut service_unit_last_state_change_usec_monotonic: Result<u64, zbus::Error> = Ok(0);
67    if service_unit.is_empty() {
68        error!("{}: No service unit name found for timer.", unit.name);
69    } else {
70        // Get the object path of the service unit
71        let mp = crate::dbus::zbus_systemd::ManagerProxy::new(connection).await?;
72        let service_unit_path = mp.get_unit(&service_unit).await?;
73        // Create a UnitProxy with the unit path to async get the two counters we want
74        let up = crate::dbus::zbus_unit::UnitProxy::builder(connection)
75            .path(service_unit_path)?
76            .build()
77            .await?;
78
79        (
80            service_unit_last_state_change_usec,
81            service_unit_last_state_change_usec_monotonic,
82        ) = tokio::join!(
83            up.state_change_timestamp(),
84            up.state_change_timestamp_monotonic(),
85        );
86    }
87    timer_stats.service_unit_last_state_change_usec = service_unit_last_state_change_usec?;
88    timer_stats.service_unit_last_state_change_usec_monotonic =
89        service_unit_last_state_change_usec_monotonic?;
90
91    // Use tokio::join! without tokio::spawn to avoid per-task allocation overhead.
92    // These all share the same D-Bus connection so spawn adds no parallelism benefit.
93    let (
94        accuracy_usec,
95        fixed_random_delay,
96        last_trigger_usec,
97        last_trigger_usec_monotonic,
98        persistent,
99        next_elapse_usec_monotonic,
100        next_elapse_usec_realtime,
101        randomized_delay_usec,
102        remain_after_elapse,
103    ) = tokio::join!(
104        pt.accuracy_usec(),
105        pt.fixed_random_delay(),
106        pt.last_trigger_usec(),
107        pt.last_trigger_usec_monotonic(),
108        pt.persistent(),
109        pt.next_elapse_usec_monotonic(),
110        pt.next_elapse_usec_realtime(),
111        pt.randomized_delay_usec(),
112        pt.remain_after_elapse(),
113    );
114
115    timer_stats.accuracy_usec = accuracy_usec?;
116    timer_stats.fixed_random_delay = fixed_random_delay?;
117    timer_stats.last_trigger_usec = last_trigger_usec?;
118    timer_stats.last_trigger_usec_monotonic = last_trigger_usec_monotonic?;
119    timer_stats.persistent = persistent?;
120    timer_stats.next_elapse_usec_monotonic = next_elapse_usec_monotonic?;
121    timer_stats.next_elapse_usec_realtime = next_elapse_usec_realtime?;
122    timer_stats.randomized_delay_usec = randomized_delay_usec?;
123    timer_stats.remain_after_elapse = remain_after_elapse?;
124
125    if timer_stats.persistent {
126        stats.timer_persistent_units += 1;
127    }
128
129    if timer_stats.remain_after_elapse {
130        stats.timer_remain_after_elapse += 1;
131    }
132
133    Ok(timer_stats)
134}