summaryrefslogtreecommitdiffstats
path: root/crates/core/tedge_mapper/src/collectd_mapper/collectd.rs
blob: 9d387314abad34a90cf28a484ef152d57f24c622 (plain)
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
use batcher::Batchable;
use chrono::{DateTime, NaiveDateTime, Utc};
use mqtt_client::Message;
use thin_edge_json::measurement::MeasurementVisitor;

#[derive(Debug)]
pub struct CollectdMessage {
    pub metric_group_key: String,
    pub metric_key: String,
    pub timestamp: DateTime<Utc>,
    pub metric_value: f64,
}

#[derive(thiserror::Error, Debug)]
pub enum CollectdError {
    #[error(
        "Message received on invalid collectd topic: {0}. \
        Collectd message topics must be in the format collectd/<hostname>/<metric-plugin-name>/<metric-key>"
    )]
    InvalidMeasurementTopic(String),

    #[error("Invalid payload received on topic: {0}. Error: {1}")]
    InvalidMeasurementPayload(String, CollectdPayloadError),

    #[error("Non UTF-8 payload: {0:?}")]
    NonUTF8MeasurementPayload(Vec<u8>),
}

impl CollectdMessage {
    pub fn accept<T>(&self, visitor: &mut T) -> Result<(), T::Error>
    where
        T: MeasurementVisitor,
    {
        visitor.visit_grouped_measurement(
            &self.metric_group_key,
            &self.metric_key,
            self.metric_value,
        )
    }

    #[cfg(test)]
    pub fn new(
        metric_group_key: &str,
        metric_key: &str,
        metric_value: f64,
        timestamp: DateTime<Utc>,
    ) -> Self {
        Self {
            metric_group_key: metric_group_key.to_string(),
            metric_key: metric_key.to_string(),
            timestamp,
            metric_value,
        }
    }

    pub fn parse_from(mqtt_message: &Message) -> Result<Self, CollectdError> {
        let topic = mqtt_message.topic.name.as_str();
        let collectd_topic = match CollectdTopic::from_str(topic) {
            Ok(collectd_topic) => collectd_topic,
            Err(_) => {
                return Err(CollectdError::InvalidMeasurementTopic(topic.into()));
            }
        };

        let payload = mqtt_message.payload_str().map_err(|_err| {
            CollectdError::NonUTF8MeasurementPayload(mqtt_message.payload_raw().into())
        })?;

        let collectd_payload = CollectdPayload::parse_from(payload)
            .map_err(|err| CollectdError::InvalidMeasurementPayload(topic.into(), err))?;

        Ok(CollectdMessage {
            metric_group_key: collectd_topic.metric_group_key.to_string(),
            metric_key: collectd_topic.metric_key.to_string(),
            timestamp: collectd_payload.timestamp(),
            metric_value: collectd_payload.metric_value,
        })
    }
}

#[derive(Debug, Eq, PartialEq, Hash)]
pub struct CollectdTopic<'a> {
    metric_group_key: &'a str,
    metric_key: &'a str,
}

#[derive(Debug)]
struct InvalidCollectdTopicName;

impl<'a> CollectdTopic<'a> {
    fn from_str(topic_name: &'a str) -> Result<Self, InvalidCollectdTopicName> {
        let mut iter = topic_name.split('/');
        let _collectd_prefix = iter.next().ok_or(InvalidCollectdTopicName)?;
        let _hostname = iter.next().ok_or(InvalidCollectdTopicName)?;
        let metric_group_key = iter.next().ok_or(InvalidCollectdTopicName)?;
        let metric_key = iter.next().ok_or(InvalidCollectdTopicName)?;

        match iter.next() {
            None => Ok(CollectdTopic {
                metric_group_key,
                metric_key,
            }),
            Some(_) => Err(InvalidCollectdTopicName),
        }
    }
}

#[derive(Debug)]
struct CollectdPayload {
    timestamp: f64,
    metric_value: f64,
}

#[derive(thiserror::Error, Debug)]
pub enum CollectdPayloadError {
    #[error("Invalid payload: {0}. Expected payload format: <timestamp>:<value>")]
    InvalidMeasurementPayloadFormat(String),

    #[error("Invalid measurement timestamp: {0}. Epoch time value expected")]
    InvalidMeasurementTimestamp(String),

    #[error("Invalid measurement value: {0}. Must be a number")]
    InvalidMeasurementValue(String),
}

impl CollectdPayload {
    fn parse_from(payload: &str) -> Result<Self, CollectdPayloadError> {
        let mut iter = payload.split(':');

        let timestamp = iter.next().ok_or_else(|| {
            CollectdPayloadError::InvalidMeasurementPayloadFormat(payload.to_string())
        })?;

        let timestamp = timestamp.parse::<f64>().map_err(|_err| {
            CollectdPayloadError::InvalidMeasurementTimestamp(timestamp.to_string())
        })?;

        let metric_value = iter.next().ok_or_else(|| {
            CollectdPayloadError::InvalidMeasurementPayloadFormat(payload.to_string())
        })?;

        let metric_value = metric_value.parse::<f64>().map_err(|_err| {
            CollectdPayloadError::InvalidMeasurementValue(metric_value.to_string())
        })?;

        match iter.next() {
            None => Ok(CollectdPayload {
                timestamp,
                metric_value,
            }),
            Some(_) => Err(CollectdPayloadError::InvalidMeasurementPayloadFormat(
                payload.to_string(),
            )),
        }
    }

    pub fn timestamp(&self) -> DateTime<Utc> {
        let timestamp = self.timestamp.trunc() as i64;
        let nanoseconds = (self.timestamp.fract() * 1.0e9) as u32;
        DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(timestamp, nanoseconds), Utc)
    }
}

impl Batchable for CollectdMessage {
    type Key = String;

    fn key(&self) -> Self::Key {
        format!("{}/{}", &self.metric_group_key, &self.metric_key)
    }

    fn event_time(&self) -> DateTime<Utc> {
        self.timestamp
    }
}

#[cfg(test)]
mod tests {
    use assert_matches::assert_matches;
    use chrono::TimeZone;
    use mqtt_client::Topic;

    use super::*;

    #[test]
    fn collectd_message_parsing() {
        let topic = Topic::new("collectd/localhost/temperature/value").unwrap();
        let mqtt_message = Message::new(&topic, "123456789:32.5");

        let collectd_message = CollectdMessage::parse_from(&mqtt_message).unwrap();

        let CollectdMessage {
            metric_group_key,
            metric_key,
            timestamp,
            metric_value,
        } = collectd_message;

        assert_eq!(metric_group_key, "temperature");
        assert_eq!(metric_key, "value");
        assert_eq!(
            timestamp,
            Utc.ymd(1973, 11, 29).and_hms_milli(21, 33, 09, 0)
        );
        assert_eq!(metric_value, 32.5);
    }

    #[test]
    fn collectd_null_terminated_message_parsing() {
        let topic = Topic::new("collectd/localhost/temperature/value").unwrap();
        let mqtt_message = Message::new(&topic, "123456789.125:32.5\u{0}");

        let collectd_message = CollectdMessage::parse_from(&mqtt_message).unwrap();

        let CollectdMessage {
            metric_group_key,
            metric_key,
            timestamp,
            metric_value,
        } = collectd_message;

        assert_eq!(metric_group_key, "temperature");
        assert_eq!(metric_key, "value");
        assert_eq!(
            timestamp,
            Utc.ymd(1973, 11, 29).and_hms_milli(21, 33, 09, 125)
        );
        assert_eq!(metric_value, 32.5);
    }

    #[test]
    fn invalid_collectd_message_topic() {
        let topic = Topic::new("collectd/less/level").unwrap();
        let mqtt_message = Message::new(&topic, "123456789:32.5");

        let result = CollectdMessage::parse_from(&mqtt_message);

        assert_matches!(result, Err(CollectdError::InvalidMeasurementTopic(_)));
    }

    #[test]
    fn invalid_collectd_message_payload() {
        let topic