monitord 0.23.0

monitord ... know how happy your systemd is! 😊
Documentation
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! This code is adapted from the code generated by `zlink-codegen` from Varlink IDL.

use serde::{Deserialize, Serialize};
use zlink::{proxy, ReplyError};

/// Proxy trait for calling methods on the interface.
#[proxy("io.systemd.Metrics")]
pub trait Metrics {
    /// A struct representing various metric value types. A metric can be of one type
    /// [Requires 'more' flag]
    #[zlink(more)]
    async fn list(
        &mut self,
    ) -> zlink::Result<
        impl futures_util::Stream<Item = zlink::Result<Result<ListOutput, MetricsError>>>,
    >;
    /// Method to get the metric families
    /// [Requires 'more' flag]
    #[zlink(more)]
    async fn describe(
        &mut self,
    ) -> zlink::Result<
        impl futures_util::Stream<Item = zlink::Result<Result<DescribeOutput, MetricsError>>>,
    >;
}

/// Output parameters for the List method.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ListOutput {
    pub name: String,
    pub value: serde_json::Value,
    pub object: Option<String>,
    pub fields: Option<std::collections::HashMap<String, serde_json::Value>>,
}

impl ListOutput {
    /// Returns the name of the metric
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the name of the metric
    pub fn name_suffix(&self) -> &str {
        self.name
            .rsplit_once('.')
            .map(|(_, suffix)| suffix)
            .unwrap_or(&self.name)
    }

    /// Returns the value of the metric
    pub fn value(&self) -> &serde_json::Value {
        &self.value
    }

    /// Returns the object name if present
    pub fn object(&self) -> Option<&str> {
        self.object.as_deref()
    }

    /// Returns the object name or empty string if not present
    pub fn object_name(&self) -> String {
        self.object.as_deref().unwrap_or("").to_string()
    }

    /// Returns the string value. Caller must validate value is a string first.
    pub fn value_as_string(&self) -> &str {
        self.value
            .as_str()
            .expect("value_as_string called on non-string value; validate metric type first")
    }

    /// Returns the int value. Caller must validate value is an integer first.
    pub fn value_as_int(&self) -> i64 {
        self.value
            .as_i64()
            .expect("value_as_int called on non-integer value; validate metric type first")
    }

    /// Returns the bool value. Caller must validate value is a bool first.
    pub fn value_as_bool(&self) -> bool {
        self.value
            .as_bool()
            .expect("value_as_bool called on non-boolean value; validate metric type first")
    }

    /// Returns the fields map if present
    pub fn fields(&self) -> Option<&std::collections::HashMap<String, serde_json::Value>> {
        self.fields.as_ref()
    }

    /// Extract a string field value from the fields map by field name
    pub fn get_field_as_str(&self, field_name: &str) -> Option<&str> {
        self.fields
            .as_ref()
            .and_then(|f| f.get(field_name))
            .and_then(|v| v.as_str())
    }
}
/// Output parameters for the Describe method.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DescribeOutput {
    pub name: String,
    pub description: String,
    pub r#type: MetricFamilyType,
}
/// An enum representing various metric family types
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum MetricFamilyType {
    /// A counter metric family type which is a monotonically increasing value
    Counter,
    /// A gauge metric family type which is a value that can go up and down
    Gauge,
    /// A string metric family type
    String,
}

/// Errors that can occur in this interface.
#[derive(Debug, Clone, PartialEq, ReplyError)]
#[zlink(interface = "io.systemd.Metrics")]
pub enum MetricsError {
    /// No such metric found
    NoSuchMetric,
}

impl std::fmt::Display for MetricsError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MetricsError::NoSuchMetric => write!(f, "No such metric found"),
        }
    }
}

impl std::error::Error for MetricsError {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_object_name_with_value() {
        let output = ListOutput {
            name: "test.metric".to_string(),
            value: serde_json::Value::Null,
            object: Some("my-service.service".to_string()),
            fields: None,
        };

        assert_eq!(output.object_name(), "my-service.service");
    }

    #[test]
    fn test_object_name_without_value() {
        let output = ListOutput {
            name: "test.metric".to_string(),
            value: serde_json::Value::Null,
            object: None,
            fields: None,
        };

        assert_eq!(output.object_name(), "");
    }

    #[test]
    fn test_object_name_with_empty_string() {
        let output = ListOutput {
            name: "test.metric".to_string(),
            value: serde_json::Value::Null,
            object: Some("".to_string()),
            fields: None,
        };

        assert_eq!(output.object_name(), "");
    }

    #[test]
    fn test_object_returns_option() {
        let output_with_object = ListOutput {
            name: "test.metric".to_string(),
            value: serde_json::Value::Null,
            object: Some("service.service".to_string()),
            fields: None,
        };

        let output_without_object = ListOutput {
            name: "test.metric".to_string(),
            value: serde_json::Value::Null,
            object: None,
            fields: None,
        };

        assert_eq!(output_with_object.object(), Some("service.service"));
        assert_eq!(output_without_object.object(), None);
    }

    #[test]
    fn test_get_field_as_str_existing_field() {
        let mut fields = std::collections::HashMap::new();
        fields.insert("type".to_string(), serde_json::json!("service"));
        fields.insert("state".to_string(), serde_json::json!("active"));

        let output = ListOutput {
            name: "test.metric".to_string(),
            value: serde_json::Value::Null,
            object: None,
            fields: Some(fields),
        };

        assert_eq!(output.get_field_as_str("type"), Some("service"));
        assert_eq!(output.get_field_as_str("state"), Some("active"));
    }

    #[test]
    fn test_get_field_as_str_missing_field() {
        let fields = std::collections::HashMap::new();

        let output = ListOutput {
            name: "test.metric".to_string(),
            value: serde_json::Value::Null,
            object: None,
            fields: Some(fields),
        };

        assert_eq!(output.get_field_as_str("nonexistent"), None);
    }

    #[test]
    fn test_get_field_as_str_no_fields() {
        let output = ListOutput {
            name: "test.metric".to_string(),
            value: serde_json::Value::Null,
            object: None,
            fields: None,
        };

        assert_eq!(output.get_field_as_str("type"), None);
    }

    #[test]
    fn test_get_field_as_str_non_string_value() {
        let mut fields = std::collections::HashMap::new();
        fields.insert("number".to_string(), serde_json::json!(123));
        fields.insert("bool".to_string(), serde_json::json!(true));

        let output = ListOutput {
            name: "test.metric".to_string(),
            value: serde_json::Value::Null,
            object: None,
            fields: Some(fields),
        };

        assert_eq!(output.get_field_as_str("number"), None);
        assert_eq!(output.get_field_as_str("bool"), None);
    }

    #[test]
    fn test_name_suffix() {
        let output = ListOutput {
            name: "io.systemd.unit_active_state".to_string(),
            value: serde_json::Value::Null,
            object: None,
            fields: None,
        };

        assert_eq!(output.name_suffix(), "unit_active_state");
    }

    #[test]
    fn test_name_suffix_no_dots() {
        let output = ListOutput {
            name: "simple_name".to_string(),
            value: serde_json::Value::Null,
            object: None,
            fields: None,
        };

        assert_eq!(output.name_suffix(), "simple_name");
    }

    #[test]
    fn test_name_suffix_empty() {
        let output = ListOutput {
            name: "".to_string(),
            value: serde_json::Value::Null,
            object: None,
            fields: None,
        };

        assert_eq!(output.name_suffix(), "");
    }

    #[test]
    fn test_value_as_string_with_value() {
        let output = ListOutput {
            name: "test.metric".to_string(),
            value: serde_json::json!("active"),
            object: None,
            fields: None,
        };

        assert_eq!(output.value_as_string(), "active");
    }

    #[test]
    fn test_value_as_string_empty_string() {
        let output = ListOutput {
            name: "test.metric".to_string(),
            value: serde_json::json!(""),
            object: None,
            fields: None,
        };

        assert_eq!(output.value_as_string(), "");
    }

    #[test]
    fn test_value_as_int_with_value() {
        let output = ListOutput {
            name: "test.metric".to_string(),
            value: serde_json::json!(42),
            object: None,
            fields: None,
        };

        assert_eq!(output.value_as_int(), 42);
    }

    #[test]
    #[should_panic(expected = "value_as_int called on non-integer value")]
    fn test_value_as_int_without_value() {
        let output = ListOutput {
            name: "test.metric".to_string(),
            value: serde_json::Value::Null,
            object: None,
            fields: None,
        };

        output.value_as_int();
    }

    #[test]
    fn test_value_as_int_zero() {
        let output = ListOutput {
            name: "test.metric".to_string(),
            value: serde_json::json!(0),
            object: None,
            fields: None,
        };

        assert_eq!(output.value_as_int(), 0);
    }

    #[test]
    fn test_value_as_int_negative() {
        let output = ListOutput {
            name: "test.metric".to_string(),
            value: serde_json::json!(-5),
            object: None,
            fields: None,
        };

        assert_eq!(output.value_as_int(), -5);
    }

    #[test]
    fn test_value_as_int_large_number() {
        let output = ListOutput {
            name: "test.metric".to_string(),
            value: serde_json::json!(9999999999_i64),
            object: None,
            fields: None,
        };

        assert_eq!(output.value_as_int(), 9999999999);
    }

    #[test]
    fn test_value_as_bool_true() {
        let output = ListOutput {
            name: "test.metric".to_string(),
            value: serde_json::json!(true),
            object: None,
            fields: None,
        };

        assert_eq!(output.value_as_bool(), true);
    }

    #[test]
    fn test_value_as_bool_false() {
        let output = ListOutput {
            name: "test.metric".to_string(),
            value: serde_json::json!(false),
            object: None,
            fields: None,
        };

        assert_eq!(output.value_as_bool(), false);
    }

    #[test]
    #[should_panic(expected = "value_as_bool called on non-boolean value")]
    fn test_value_as_bool_none() {
        let output = ListOutput {
            name: "test.metric".to_string(),
            value: serde_json::Value::Null,
            object: None,
            fields: None,
        };

        output.value_as_bool();
    }
}