rrdcached-client 0.2.0

A RRDCached (RRDtool) client library
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
use crate::{
    consolidation_function::ConsolidationFunction,
    errors::RRDCachedClientError,
    sanitisation::{check_data_source_name, check_rrd_path},
};

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CreateDataSourceType {
    Gauge,
    Counter,
    DCounter,
    Derive,
    DDerive,
    Absolute,
}

impl CreateDataSourceType {
    pub fn to_str(self) -> &'static str {
        match self {
            CreateDataSourceType::Gauge => "GAUGE",
            CreateDataSourceType::Counter => "COUNTER",
            CreateDataSourceType::DCounter => "DCOUNTER",
            CreateDataSourceType::Derive => "DERIVE",
            CreateDataSourceType::DDerive => "DDERIVE",
            CreateDataSourceType::Absolute => "ABSOLUTE",
        }
    }
}

/// Arguments for a data source (DS).
#[derive(Debug)]
pub struct CreateDataSource {
    /// Name of the data source.
    /// Must be between 1 and 64 characters and only contain alphanumeric characters and underscores
    /// and dashes.
    pub name: String,

    /// Minimum value
    pub minimum: Option<f64>,

    /// Maximum value
    pub maximum: Option<f64>,

    /// Heartbeat, if no data is received for this amount of time,
    /// the value is unknown.
    pub heartbeat: i64,

    /// Type of the data source
    pub serie_type: CreateDataSourceType,
}

impl CreateDataSource {
    /// Check that the content is valid.
    pub fn validate(&self) -> Result<(), RRDCachedClientError> {
        if self.heartbeat <= 0 {
            return Err(RRDCachedClientError::InvalidCreateDataSerie(
                "heartbeat must be greater than 0".to_string(),
            ));
        }
        if let Some(minimum) = self.minimum {
            if let Some(maximum) = self.maximum {
                if maximum <= minimum {
                    return Err(RRDCachedClientError::InvalidCreateDataSerie(
                        "maximum must be greater than to minimum".to_string(),
                    ));
                }
            }
        }

        check_data_source_name(&self.name)?;

        Ok(())
    }

    /// Convert to a string argument parameter.
    pub fn to_str(&self) -> String {
        format!(
            "DS:{}:{}:{}:{}:{}",
            self.name,
            self.serie_type.to_str(),
            self.heartbeat,
            match self.minimum {
                Some(minimum) => minimum.to_string(),
                None => "U".to_string(),
            },
            match self.maximum {
                Some(maximum) => maximum.to_string(),
                None => "U".to_string(),
            }
        )
    }
}

/// Arguments for a round robin archive (RRA).
#[derive(Debug)]
pub struct CreateRoundRobinArchive {
    /// Archive types are AVERAGE, MIN, MAX, LAST.
    pub consolidation_function: ConsolidationFunction,

    /// Number between 0 and 1 to accept unknown data
    /// 0.5 means that if more of 50% of the data points are unknown,
    /// the value is unknown.
    pub xfiles_factor: f64,

    /// Number of steps that are used to calculate the value
    pub steps: i64,

    /// Number of rows in the archive
    pub rows: i64,
}

impl CreateRoundRobinArchive {
    /// Check that the content is valid.
    pub fn validate(&self) -> Result<(), RRDCachedClientError> {
        if self.xfiles_factor < 0.0 || self.xfiles_factor > 1.0 {
            return Err(RRDCachedClientError::InvalidCreateDataSerie(
                "xfiles_factor must be between 0 and 1".to_string(),
            ));
        }
        if self.steps <= 0 {
            return Err(RRDCachedClientError::InvalidCreateDataSerie(
                "steps must be greater than 0".to_string(),
            ));
        }
        if self.rows <= 0 {
            return Err(RRDCachedClientError::InvalidCreateDataSerie(
                "rows must be greater than 0".to_string(),
            ));
        }
        Ok(())
    }

    /// Convert to a string argument parameter.
    pub fn to_str(&self) -> String {
        format!(
            "RRA:{}:{}:{}:{}",
            self.consolidation_function.to_str(),
            self.xfiles_factor,
            self.steps,
            self.rows
        )
    }
}

/// Arguments to create a new RRD file
#[derive(Debug)]
pub struct CreateArguments {
    /// Path to the RRD file
    /// The path must be between 1 and 64 characters and only contain alphanumeric characters and underscores
    ///
    /// Does **not** end with .rrd
    pub path: String,

    /// List of data sources, the order is important
    /// Must be at least one.
    pub data_sources: Vec<CreateDataSource>,

    /// List of round robin archives.
    /// Must be at least one.
    pub round_robin_archives: Vec<CreateRoundRobinArchive>,

    /// Start time of the first data point
    pub start_timestamp: u64,

    /// Number of seconds between two data points
    pub step_seconds: u64,
}

impl CreateArguments {
    /// Check that the content is valid.
    pub fn validate(&self) -> Result<(), RRDCachedClientError> {
        if self.data_sources.is_empty() {
            return Err(RRDCachedClientError::InvalidCreateDataSerie(
                "at least one data serie is required".to_string(),
            ));
        }
        if self.round_robin_archives.is_empty() {
            return Err(RRDCachedClientError::InvalidCreateDataSerie(
                "at least one round robin archive is required".to_string(),
            ));
        }
        for data_serie in &self.data_sources {
            data_serie.validate()?;
        }
        for rr_archive in &self.round_robin_archives {
            rr_archive.validate()?;
        }
        check_rrd_path(&self.path)?;
        Ok(())
    }

    /// Convert to a string argument parameter.
    pub fn to_str(&self) -> String {
        let mut result = format!(
            "{}.rrd -s {} -b {}",
            self.path, self.step_seconds, self.start_timestamp
        );
        for data_serie in &self.data_sources {
            result.push(' ');
            result.push_str(&data_serie.to_str());
        }
        for rr_archive in &self.round_robin_archives {
            result.push(' ');
            result.push_str(&rr_archive.to_str());
        }
        result
    }
}

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

    // Test for CreateDataSourceType to_str method
    #[test]
    fn test_create_data_source_type_to_str() {
        assert_eq!(CreateDataSourceType::Gauge.to_str(), "GAUGE");
        assert_eq!(CreateDataSourceType::Counter.to_str(), "COUNTER");
        assert_eq!(CreateDataSourceType::DCounter.to_str(), "DCOUNTER");
        assert_eq!(CreateDataSourceType::Derive.to_str(), "DERIVE");
        assert_eq!(CreateDataSourceType::DDerive.to_str(), "DDERIVE");
        assert_eq!(CreateDataSourceType::Absolute.to_str(), "ABSOLUTE");
    }

    // Test for CreateDataSource validate method
    #[test]
    fn test_create_data_source_validate() {
        let valid_ds = CreateDataSource {
            name: "valid_name_1".to_string(),
            minimum: Some(0.0),
            maximum: Some(100.0),
            heartbeat: 300,
            serie_type: CreateDataSourceType::Gauge,
        };
        assert!(valid_ds.validate().is_ok());

        let invalid_ds_name = CreateDataSource {
            name: "Invalid Name!".to_string(), // Invalid due to space and exclamation
            ..valid_ds
        };
        assert!(invalid_ds_name.validate().is_err());

        let invalid_ds_heartbeat = CreateDataSource {
            heartbeat: -1, // Invalid heartbeat
            name: "valid_name_2".to_string(),
            ..valid_ds
        };
        assert!(invalid_ds_heartbeat.validate().is_err());

        let invalid_ds_min_max = CreateDataSource {
            minimum: Some(100.0),
            maximum: Some(50.0), // Invalid minimum and maximum
            name: "valid_name_3".to_string(),
            ..valid_ds
        };
        assert!(invalid_ds_min_max.validate().is_err());

        // Maximum below minimum
        let invalid_ds_max = CreateDataSource {
            minimum: Some(100.0),
            maximum: Some(0.0),
            name: "valid_name_5".to_string(),
            ..valid_ds
        };
        assert!(invalid_ds_max.validate().is_err());

        // Maximum but no minimum
        let valid_ds_max = CreateDataSource {
            maximum: Some(100.0),
            name: "valid_name_6".to_string(),
            ..valid_ds
        };
        assert!(valid_ds_max.validate().is_ok());

        // Minimum but no maximum
        let valid_ds_min = CreateDataSource {
            minimum: Some(-100.0),
            name: "valid_name_7".to_string(),
            ..valid_ds
        };
        assert!(valid_ds_min.validate().is_ok());
    }

    // Test for CreateDataSource to_str method
    #[test]
    fn test_create_data_source_to_str() {
        let ds = CreateDataSource {
            name: "test_ds".to_string(),
            minimum: Some(10.0),
            maximum: Some(100.0),
            heartbeat: 600,
            serie_type: CreateDataSourceType::Gauge,
        };
        assert_eq!(ds.to_str(), "DS:test_ds:GAUGE:600:10:100");

        let ds = CreateDataSource {
            name: "test_ds".to_string(),
            minimum: None,
            maximum: None,
            heartbeat: 600,
            serie_type: CreateDataSourceType::Gauge,
        };
        assert_eq!(ds.to_str(), "DS:test_ds:GAUGE:600:U:U");
    }

    // Test for CreateRoundRobinArchive validate method
    #[test]
    fn test_create_round_robin_archive_validate() {
        let valid_rra = CreateRoundRobinArchive {
            consolidation_function: ConsolidationFunction::Average,
            xfiles_factor: 0.5,
            steps: 1,
            rows: 100,
        };
        assert!(valid_rra.validate().is_ok());

        let invalid_rra_xff = CreateRoundRobinArchive {
            xfiles_factor: -0.1, // Invalid xfiles_factor
            ..valid_rra
        };
        assert!(invalid_rra_xff.validate().is_err());

        let invalid_rra_steps = CreateRoundRobinArchive {
            steps: 0, // Invalid steps
            ..valid_rra
        };
        assert!(invalid_rra_steps.validate().is_err());

        let invalid_rra_rows = CreateRoundRobinArchive {
            rows: -100, // Invalid rows
            ..valid_rra
        };
        assert!(invalid_rra_rows.validate().is_err());
    }

    // Test for CreateRoundRobinArchive to_str method
    #[test]
    fn test_create_round_robin_archive_to_str() {
        let rra = CreateRoundRobinArchive {
            consolidation_function: ConsolidationFunction::Max,
            xfiles_factor: 0.5,
            steps: 1,
            rows: 100,
        };
        assert_eq!(rra.to_str(), "RRA:MAX:0.5:1:100");
    }

    // Test for CreateArguments validate method
    #[test]
    fn test_create_arguments_validate() {
        let valid_args = CreateArguments {
            path: "valid_path".to_string(),
            data_sources: vec![CreateDataSource {
                name: "ds1".to_string(),
                minimum: Some(0.0),
                maximum: Some(100.0),
                heartbeat: 300,
                serie_type: CreateDataSourceType::Gauge,
            }],
            round_robin_archives: vec![CreateRoundRobinArchive {
                consolidation_function: ConsolidationFunction::Average,
                xfiles_factor: 0.5,
                steps: 1,
                rows: 100,
            }],
            start_timestamp: 1609459200,
            step_seconds: 300,
        };
        assert!(valid_args.validate().is_ok());

        let invalid_args_no_ds = CreateArguments {
            data_sources: vec![],
            path: "valid_path".to_string(),
            ..valid_args
        };
        assert!(invalid_args_no_ds.validate().is_err());

        let invalid_args_no_rra = CreateArguments {
            round_robin_archives: vec![],
            path: "valid_path".to_string(),
            ..valid_args
        };
        assert!(invalid_args_no_rra.validate().is_err());
    }

    // Test for CreateArguments to_str method
    #[test]
    fn test_create_arguments_to_str() {
        let args = CreateArguments {
            path: "test_path".to_string(),
            data_sources: vec![CreateDataSource {
                name: "ds1".to_string(),
                minimum: Some(0.0),
                maximum: Some(100.0),
                heartbeat: 300,
                serie_type: CreateDataSourceType::Gauge,
            }],
            round_robin_archives: vec![CreateRoundRobinArchive {
                consolidation_function: ConsolidationFunction::Average,
                xfiles_factor: 0.5,
                steps: 1,
                rows: 100,
            }],
            start_timestamp: 1609459200,
            step_seconds: 300,
        };
        let expected_str =
            "test_path.rrd -s 300 -b 1609459200 DS:ds1:GAUGE:300:0:100 RRA:AVERAGE:0.5:1:100";
        assert_eq!(args.to_str(), expected_str);
    }
}