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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
use std::{fmt::Debug, time::Duration};

use chrono::NaiveDateTime;
use prometheus_client::{
    collector::Collector,
    metrics::{gauge::ConstGauge, info::Info},
    registry::{Registry, Unit},
};
use serde_with::{serde_as, DisplayFromStr};

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


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

    #[tracing::instrument(level = "debug", err)]
    pub async fn get_health(&self) -> anyhow::Result<Vec<HealthRecord>> {
        self.get_all("/rest/system/health").await
    }
}

#[serde_as]
#[derive(serde::Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct Resource {
    pub architecture_name: String, // "arm",
    pub board_name: String,        // "RB4011iGS+",
    pub cpu: String,               // "ARMv7",
    pub platform: String,          // "MikroTik",
    pub factory_software: String,  // "6.44.6",
    pub version: String,           // "7.2.3 (stable)",
    #[serde_as(as = "DisplayFromStr")]
    #[serde(default)]
    pub bad_blocks: f64,

    #[serde_as(as = "DisplayFromStr")]
    pub cpu_count: u8,
    #[serde_as(as = "DisplayFromStr")]
    pub cpu_frequency: u64,
    #[serde_as(as = "DisplayFromStr")]
    /// Percentage of whole router
    pub cpu_load: u16,

    #[serde_as(as = "MikrotikBuildTimeDeserialize")]
    pub build_time: NaiveDateTime,

    #[serde_as(as = "MikrotikUptimeDeserialize")]
    pub uptime: Duration,

    /// Bytes
    #[serde_as(as = "DisplayFromStr")]
    pub total_hdd_space: u64,
    /// Bytes
    #[serde_as(as = "DisplayFromStr")]
    pub free_hdd_space: u64,

    /// Bytes
    #[serde_as(as = "DisplayFromStr")]
    pub total_memory: u64, // "1073741824",
    /// Bytes
    #[serde_as(as = "DisplayFromStr")]
    pub free_memory: u64, // "968822784",

    #[serde_as(as = "Option<DisplayFromStr>")]
    pub write_sect_since_reboot: Option<u64>,
    #[serde_as(as = "Option<DisplayFromStr>")]
    pub write_sect_total: Option<u64>,
}


impl AsMetrics for Resource {
    fn register_as_metrics(self: Box<Self>, registry: &mut Registry) {
        registry
            .sub_registry_with_prefix("resource")
            .register_collector(self);
    }
}

impl Collector for Resource {
    #[allow(clippy::cast_precision_loss, clippy::as_conversions)]
    fn encode(
        &self,
        mut encoder: prometheus_client::encoding::DescriptorEncoder,
    ) -> Result<(), std::fmt::Error> {
        let Resource {
            architecture_name,
            board_name,
            cpu,
            platform,
            factory_software,
            version,
            bad_blocks,
            cpu_count,
            cpu_frequency,
            cpu_load,
            build_time,
            uptime,
            total_hdd_space,
            free_hdd_space,
            total_memory,
            free_memory,
            write_sect_since_reboot,
            write_sect_total,
        } = self;


        Info::new(vec![
            ("architecture_name", architecture_name.as_str()),
            ("board_name", board_name.as_str()),
            ("cpu", cpu.as_str()),
            ("platform", platform.as_str()),
            ("factory_software", factory_software.as_str()),
            ("version", version.as_str()),
            ("build_time", build_time.to_string().as_str()),
        ])
        .encode_e(&mut encoder, "", "")?;

        // Casting from an integer to float will produce the closest possible float *
        for (name, value) in [
            ("bad_blocks", *bad_blocks),
            ("cpu_count", f64::from(*cpu_count)),
            ("cpu_frequency", *cpu_frequency as f64),
            ("cpu_load", f64::from(*cpu_load)),
            ("uptime", uptime.as_secs() as f64),
            ("total_hdd_space", *total_hdd_space as f64),
            ("free_hdd_space", *free_hdd_space as f64),
            ("total_memory", *total_memory as f64),
            ("free_memory", *free_memory as f64),
        ] {
            ConstGauge::new(value).encode_e(&mut encoder, name, "")?;
        }

        if let Some(write_sect_since_reboot) = write_sect_since_reboot {
            ConstGauge::new(*write_sect_since_reboot as f64).encode_e(
                &mut encoder,
                "write_sect_since_reboot",
                "",
            )?;
        }
        if let Some(write_sect_total) = write_sect_total {
            ConstGauge::new(*write_sect_total as f64).encode_e(
                &mut encoder,
                "write_sect_total",
                "",
            )?;
        }


        Ok(())
    }
}

#[serde_as]
#[derive(serde::Deserialize, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
pub struct HealthRecord {
    #[serde(rename = ".id")]
    pub id: String,

    pub name: String,
    #[serde(rename = "type")]
    pub unit: String,
    #[serde_as(as = "DisplayFromStr")]
    pub value: f64,
}


impl AsMetrics for HealthRecord {
    fn register_as_metrics(self: Box<Self>, registry: &mut Registry) {
        registry
            .sub_registry_with_prefix("health")
            .sub_registry_with_label(("name".into(), self.name.clone().into()))
            .register_collector(self);
    }
}
impl Collector for HealthRecord {
    fn encode(
        &self,
        mut encoder: prometheus_client::encoding::DescriptorEncoder,
    ) -> Result<(), std::fmt::Error> {
        let (unit, name) = match self.unit.as_str() {
            "C" => (Unit::Celsius, "temperature"),
            "V" => (Unit::Volts, "voltage"),
            _ => {
                (
                    Unit::Other(self.unit.to_ascii_lowercase()),
                    self.name.rsplit(['-', '_']).next().unwrap_or_default(),
                )
            },
        };

        ConstGauge::new(self.value).encode_e_unit(&mut encoder, name, "", &unit)?;

        Ok(())
    }
}

struct MikrotikBuildTimeDeserialize;

impl<'de> serde_with::DeserializeAs<'de, NaiveDateTime> for MikrotikBuildTimeDeserialize {
    fn deserialize_as<D>(deserializer: D) -> Result<NaiveDateTime, D::Error>
    where
        D: serde::de::Deserializer<'de>,
    {
        let s: &str = serde::de::Deserialize::deserialize(deserializer)?;

        NaiveDateTime::parse_from_str(s, "%b/%d/%Y %H:%M:%S").map_err(serde::de::Error::custom)
    }
}

struct MikrotikUptimeDeserialize;

impl<'de> serde_with::DeserializeAs<'de, Duration>
    for crate::mikrotik_api::resource::MikrotikUptimeDeserialize
{
    fn deserialize_as<D>(deserializer: D) -> Result<Duration, D::Error>
    where
        D: serde::de::Deserializer<'de>,
    {
        let s: &str = serde::de::Deserialize::deserialize(deserializer)?;

        humantime::parse_duration(s).map_err(serde::de::Error::custom)
    }
}