1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use chrono::{FixedOffset, NaiveDate, NaiveTime};
use prometheus_client::{
    collector::Collector,
    encoding::DescriptorEncoder,
    metrics::{gauge::ConstGauge, info::Info},
    registry::{Registry, Unit},
};
use serde_with::{serde_as, DisplayFromStr};

use super::deserialize_bool;
use crate::{
    prometheus_ext::{AsMetrics, EncodeExt},
    MikrotikClient,
};

impl MikrotikClient {
    #[tracing::instrument(level = "debug", err)]
    pub async fn get_clock(&self) -> anyhow::Result<Clock> {
        self.get_all("/rest/system/clock").await
    }
}

#[serde_as]
#[derive(serde::Deserialize, Debug, Clone)]
#[serde(rename_all = "kebab-case")]
pub struct Clock {
    pub date: NaiveDate,
    #[serde(deserialize_with = "deserialize_bool")]
    pub dst_active: bool,
    #[serde_as(as = "DisplayFromStr")]
    pub gmt_offset: FixedOffset,
    pub time: NaiveTime,
    #[serde(deserialize_with = "deserialize_bool")]
    pub time_zone_autodetect: bool,
    pub time_zone_name: String,
}

impl AsMetrics for Clock {
    fn register_as_metrics(self: Box<Self>, registry: &mut Registry) {
        registry
            .sub_registry_with_prefix("clock")
            .register_collector(self);
    }
}
impl Collector for Clock {
    fn encode(&self, mut encoder: DescriptorEncoder) -> Result<(), std::fmt::Error> {
        if let Some(datetime) = self
            .date
            .and_time(self.time)
            .and_local_timezone(self.gmt_offset)
            .single()
        {
            ConstGauge::new(datetime.timestamp()).encode_e(
                &mut encoder,
                "datetime",
                "Internal mikrotik time normalized to UTC as unix timestamp",
            )?;
        };

        ConstGauge::new(i64::from(self.gmt_offset.local_minus_utc())).encode_e_unit(
            &mut encoder,
            "time_zone_offset",
            "Current TimeZone offset from UTC",
            &Unit::Seconds,
        )?;

        ConstGauge::new(i64::from(self.time_zone_autodetect)).encode_e(
            &mut encoder,
            "time_zone_autodetect",
            "Is time zone autodetect enabled",
        )?;

        ConstGauge::new(i64::from(self.dst_active)).encode_e(
            &mut encoder,
            "dst_active",
            "Is daylight-savings time enabled",
        )?;

        Info::new(&[("time_zone_name", self.time_zone_name.clone())][..]).encode_e(
            &mut encoder,
            "time_zone_name",
            "Current timezone name",
        )?;

        Ok(())
    }
}