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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
use bindings::{data_set_t, hostname_g, plugin_dispatch_values, plugin_log, value_list_t, value_t,
ARR_LENGTH, DS_TYPE_ABSOLUTE, DS_TYPE_COUNTER, DS_TYPE_DERIVE, DS_TYPE_GAUGE,
LOG_DEBUG, LOG_ERR, LOG_INFO, LOG_NOTICE, LOG_WARNING};
use std::os::raw::c_char;
use std::ptr;
use std::slice;
use chrono::prelude::*;
use chrono::Duration;
use std::ffi::{CStr, CString};
use failure::{Error, ResultExt};
use errors::{ArrayError, SubmitError};
use std::fmt;
use std::str::Utf8Error;
use memchr::memchr;
pub use self::cdtime::{nanos_to_collectd, CdTime};
pub use self::oconfig::{ConfigItem, ConfigValue};
mod cdtime;
mod oconfig;
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[repr(u32)]
pub enum LogLevel {
Error = LOG_ERR,
Warning = LOG_WARNING,
Notice = LOG_NOTICE,
Info = LOG_INFO,
Debug = LOG_DEBUG,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[repr(u32)]
#[allow(dead_code)]
enum ValueType {
Counter = DS_TYPE_COUNTER,
Gauge = DS_TYPE_GAUGE,
Derive = DS_TYPE_DERIVE,
Absolute = DS_TYPE_ABSOLUTE,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Value {
Counter(u64),
Gauge(f64),
Derive(i64),
Absolute(u64),
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Value::Counter(x) | Value::Absolute(x) => write!(f, "{}", x),
Value::Gauge(x) => write!(f, "{}", x),
Value::Derive(x) => write!(f, "{}", x),
}
}
}
impl Into<value_t> for Value {
fn into(self) -> value_t {
match self {
Value::Counter(x) => value_t { counter: x },
Value::Gauge(x) => value_t { gauge: x },
Value::Derive(x) => value_t { derive: x },
Value::Absolute(x) => value_t { absolute: x },
}
}
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct ValueReport<'a> {
pub name: &'a str,
pub value: Value,
pub min: f64,
pub max: f64,
}
#[derive(Debug, PartialEq, Clone)]
pub struct ValueList<'a> {
pub values: Vec<ValueReport<'a>>,
pub plugin: &'a str,
pub plugin_instance: Option<&'a str>,
pub type_: &'a str,
pub type_instance: Option<&'a str>,
pub host: &'a str,
pub time: DateTime<Utc>,
pub interval: Duration,
}
impl<'a> ValueList<'a> {
pub fn from<'b>(set: &'b data_set_t, list: &'b value_list_t) -> Result<ValueList<'b>, Error> {
let p = from_array(&list.plugin).context("Plugin could not be parsed")?;
let ds_len = length(set.ds_num);
let list_len = length(list.values_len);
let values: Result<Vec<ValueReport>, Error> = unsafe {
slice::from_raw_parts(list.values, list_len)
}.iter()
.zip(unsafe { slice::from_raw_parts(set.ds, ds_len) })
.map(|(val, source)| unsafe {
let v = match ::std::mem::transmute(source.type_) {
ValueType::Gauge => Value::Gauge(val.gauge),
ValueType::Counter => Value::Counter(val.counter),
ValueType::Derive => Value::Derive(val.derive),
ValueType::Absolute => Value::Absolute(val.absolute),
};
let name = from_array(&source.name).with_context(|_e| {
format!("For plugin: {}, data source name could not be decoded", p)
})?;
Ok(ValueReport {
name,
value: v,
min: source.min,
max: source.max,
})
})
.collect();
assert!(list.time > 0);
assert!(list.interval > 0);
Ok(ValueList {
values: values?,
plugin_instance: empty_to_none(from_array(&list.plugin_instance).with_context(|_e| {
format!("For plugin: {}, plugin instance could not be decoded", p)
})?),
plugin: p,
type_: from_array(&list.type_)
.with_context(|_e| format!("For plugin: {}, type could not be decoded", p))?,
type_instance: empty_to_none(from_array(&list.type_instance).with_context(|_e| {
format!("For plugin: {}, type instance could not be decoded", p)
})?),
host: from_array(&list.host)
.with_context(|_e| format!("For plugin: {}, host could not be decoded", p))?,
time: CdTime::from(list.time).into(),
interval: CdTime::from(list.interval).into(),
})
}
}
#[derive(Debug, PartialEq, Clone)]
struct SubmitValueList<'a> {
values: &'a [Value],
plugin_instance: Option<&'a str>,
plugin: &'a str,
type_: &'a str,
type_instance: Option<&'a str>,
host: Option<&'a str>,
time: Option<DateTime<Utc>>,
interval: Option<Duration>,
}
#[derive(Debug, PartialEq, Clone)]
pub struct ValueListBuilder<'a> {
list: SubmitValueList<'a>,
}
impl<'a> ValueListBuilder<'a> {
pub fn new<T: Into<&'a str>, U: Into<&'a str>>(plugin: T, type_: U) -> ValueListBuilder<'a> {
ValueListBuilder {
list: SubmitValueList {
values: &[],
plugin_instance: None,
plugin: plugin.into(),
type_: type_.into(),
type_instance: None,
host: None,
time: None,
interval: None,
},
}
}
pub fn values(mut self, values: &'a [Value]) -> ValueListBuilder<'a> {
self.list.values = values;
self
}
pub fn plugin_instance<T: Into<&'a str>>(mut self, plugin_instance: T) -> ValueListBuilder<'a> {
self.list.plugin_instance = Some(plugin_instance.into());
self
}
pub fn type_instance<T: Into<&'a str>>(mut self, type_instance: T) -> ValueListBuilder<'a> {
self.list.type_instance = Some(type_instance.into());
self
}
pub fn host<T: Into<&'a str>>(mut self, host: T) -> ValueListBuilder<'a> {
self.list.host = Some(host.into());
self
}
pub fn time(mut self, dt: DateTime<Utc>) -> ValueListBuilder<'a> {
self.list.time = Some(dt);
self
}
pub fn interval(mut self, interval: Duration) -> ValueListBuilder<'a> {
self.list.interval = Some(interval);
self
}
pub fn submit(self) -> Result<(), Error> {
let mut v: Vec<value_t> = self.list.values.into_iter().map(|&x| x.into()).collect();
let plugin_instance = self.list
.plugin_instance
.map(|x| to_array_res(x).context("plugin_instance"))
.unwrap_or_else(|| Ok([0i8; ARR_LENGTH]))?;
let type_instance = self.list
.type_instance
.map(|x| to_array_res(x).context("type_instance"))
.unwrap_or_else(|| Ok([0i8; ARR_LENGTH]))?;
let host = self.list
.host
.map(|x| to_array_res(x).context("host"))
.unwrap_or_else(|| unsafe { Ok(hostname_g) })?;
#[cfg(feature = "collectd-57")]
let len = v.len();
#[cfg(not(feature = "collectd-57"))]
let len = v.len() as i32;
let list = value_list_t {
values: v.as_mut_ptr(),
values_len: len,
plugin_instance,
plugin: to_array_res(self.list.plugin)?,
type_: to_array_res(self.list.type_)?,
type_instance,
host,
time: self.list.time.map(CdTime::from).unwrap_or(CdTime(0)).into(),
interval: self.list
.interval
.map(CdTime::from)
.unwrap_or(CdTime(0))
.into(),
meta: ptr::null_mut(),
};
match unsafe { plugin_dispatch_values(&list) } {
0 => Ok(()),
i => Err(SubmitError::DispatchError(i).into()),
}
}
}
fn to_array_res(s: &str) -> Result<[c_char; ARR_LENGTH], ArrayError> {
if s.len() >= ARR_LENGTH {
return Err(ArrayError::TooLong(s.len()));
}
let bytes = s.as_bytes();
if let Some(ind) = memchr(0, bytes) {
return Err(ArrayError::NullPresent(ind, s.to_string()));
}
let mut arr = [0; ARR_LENGTH];
arr[0..bytes.len()].copy_from_slice(bytes);
Ok(unsafe { ::std::mem::transmute(arr) })
}
pub fn from_array(s: &[c_char; ARR_LENGTH]) -> Result<&str, Utf8Error> {
unsafe {
let a = s as *const [i8; ARR_LENGTH] as *const i8;
CStr::from_ptr(a).to_str()
}
}
pub fn empty_to_none(s: &str) -> Option<&str> {
if s.is_empty() {
None
} else {
Some(s)
}
}
pub fn collectd_log(lvl: LogLevel, message: &str) {
let cs = CString::new(message).expect("Collectd log to not contain nulls");
unsafe {
plugin_log(lvl as i32, cs.as_ptr());
}
}
#[cfg(feature = "collectd-57")]
pub fn length(len: usize) -> usize {
len
}
#[cfg(not(feature = "collectd-57"))]
pub fn length(len: i32) -> usize {
len as usize
}
#[cfg(feature = "collectd-57")]
pub fn get_default_interval() -> u64 {
0
}
#[cfg(not(feature = "collectd-57"))]
pub fn get_default_interval<T>() -> *const T {
use std::ptr;
ptr::null()
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::raw::c_char;
use bindings::data_source_t;
use self::cdtime::nanos_to_collectd;
#[test]
fn test_to_array() {
let actual = to_array_res("Hi");
assert!(actual.is_ok());
assert_eq!(&actual.unwrap()[..2], &[b'H' as c_char, b'i' as c_char]);
}
#[test]
fn test_to_array_res_nul() {
let actual = to_array_res("hi\0");
assert!(actual.is_err());
}
#[test]
fn test_to_array_res_too_long() {
let actual = to_array_res(
"Hello check this out, I am a long string and there is no signs of stopping; well, maybe one day I will stop when I get too longggggggggggggggggggggggggggggggggggg",
);
assert!(actual.is_err());
}
#[test]
fn test_submit() {
let values = vec![Value::Gauge(15.0), Value::Gauge(10.0), Value::Gauge(12.0)];
let result = ValueListBuilder::new("my-plugin", "load")
.values(&values)
.submit();
assert_eq!(result.unwrap(), ());
}
#[test]
fn test_recv_value_list_conversion() {
let empty: [c_char; ARR_LENGTH] = [0; ARR_LENGTH];
let mut metric: [c_char; ARR_LENGTH] = [0; ARR_LENGTH];
metric[0] = b'h' as c_char;
metric[1] = b'o' as c_char;
let mut name: [c_char; ARR_LENGTH] = [0; ARR_LENGTH];
name[0] = b'h' as c_char;
name[1] = b'i' as c_char;
let val = data_source_t {
name: name,
type_: DS_TYPE_GAUGE as i32,
min: 10.0,
max: 11.0,
};
let mut v = vec![val];
let conv = data_set_t {
type_: metric,
ds_num: 1,
ds: v.as_mut_ptr(),
};
let mut vs = vec![value_t { gauge: 3.0 }];
let list_t = value_list_t {
values: vs.as_mut_ptr(),
values_len: 1,
time: nanos_to_collectd(1_000_000_000),
interval: nanos_to_collectd(1_000_000_000),
host: metric,
plugin: name,
plugin_instance: metric,
type_: metric,
type_instance: empty,
meta: ptr::null_mut(),
};
let actual = ValueList::from(&conv, &list_t).unwrap();
assert_eq!(
actual,
ValueList {
values: vec![
ValueReport {
name: "hi",
value: Value::Gauge(3.0),
min: 10.0,
max: 11.0,
},
],
plugin_instance: Some("ho"),
plugin: "hi",
type_: "ho",
type_instance: None,
host: "ho",
time: Utc.ymd(1970, 1, 1).and_hms(0, 0, 1),
interval: Duration::seconds(1),
}
);
}
}