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
use failure::Error;
use errors::NotImplemented;
use api::{ConfigItem, LogLevel, ValueList};
use chrono::Duration;

bitflags! {
    /// Bitflags of capabilities that a plugin advertises to collectd.
    #[derive(Default)]
    pub struct PluginCapabilities: u32 {
        const READ =   0b0000_0001;
        const LOG =    0b0000_0010;
        const WRITE =  0b0000_0100;
        const FLUSH =  0b0000_1000;
    }
}

bitflags! {
    /// Bitflags of capabilities that a plugin manager advertises to collectd
    #[derive(Default)]
    pub struct PluginManagerCapabilities: u32 {
        const INIT = 0b0000_0001;
    }
}

/// How many instances of the plugin will be registered
pub enum PluginRegistration {
    /// Our module will only register a single plugin
    Single(Box<Plugin>),

    /// Our module registers several modules. The String in the tuple must be unique identifier
    Multiple(Vec<(String, Box<Plugin>)>),
}

impl PluginCapabilities {
    pub fn has_read(&self) -> bool {
        self.intersects(PluginCapabilities::READ)
    }

    pub fn has_log(&self) -> bool {
        self.intersects(PluginCapabilities::LOG)
    }

    pub fn has_write(&self) -> bool {
        self.intersects(PluginCapabilities::WRITE)
    }

    pub fn has_flush(&self) -> bool {
        self.intersects(PluginCapabilities::FLUSH)
    }
}

/// Defines the entry point for a collectd plugin. Based on collectd's configuration, a
/// `PluginManager` will register any number of plugins (or return an error)
pub trait PluginManager {
    /// Name of the plugin.
    fn name() -> &'static str;

    /// Defines the capabilities of the plugin manager.
    fn capabilities() -> PluginManagerCapabilities {
        PluginManagerCapabilities::default()
    }

    /// Returns one or many instances of a plugin that is configured from collectd's configuration
    /// file. If parameter is `None`, a configuration section for the plugin was not found, so
    /// default values should be used.
    fn plugins(_config: Option<&[ConfigItem]>) -> Result<PluginRegistration, Error>;

    /// Initialize any socket, files, or expensive resources that may have been parsed from the
    /// configuration. If an error is reported, all hooks registered will be unregistered. This is
    /// really only useful for `PluginRegistration::Single` modules who want global data.
    fn initialize() -> Result<(), Error> {
        Err(Error::from(NotImplemented))
    }
}

/// An individual plugin that is capable of reporting values to collectd, receiving values from
/// other plugins, or logging messages. A plugin must implement `Sync` as collectd could be sending
/// values to be written or logged concurrently. The Rust compiler will now ensure that everything
/// not thread safe is wrapped in a Mutex (or another compatible datastructure)
pub trait Plugin: Sync {
    /// A plugin's capabilities. By default a plugin does nothing, but can advertise that it can
    /// configure itself and / or report values.
    fn capabilities(&self) -> PluginCapabilities {
        PluginCapabilities::default()
    }

    /// Customizes how a message of a given level is logged. If the message isn't valid UTF-8, an
    /// allocation is done to replace all invalid characters with the UTF-8 replacement character
    fn log(&mut self, _lvl: LogLevel, _msg: &str) -> Result<(), Error> {
        Err(Error::from(NotImplemented))
    }

    /// This function is called when collectd expects the plugin to report values, which will occur
    /// at the `Interval` defined in the global config (but can be overridden). Implementations
    /// that expect to report values need to have at least have a capability of `READ`. An error in
    /// reporting values will cause collectd to backoff exponentially until a delay of a day is
    /// reached.
    fn read_values(&mut self) -> Result<(), Error> {
        Err(Error::from(NotImplemented))
    }

    /// Collectd is giving you reported values, do with them as you please. If writing values is
    /// expensive, prefer to buffer them in some way and register a `flush` callback to write.
    fn write_values<'a>(&mut self, _list: ValueList<'a>) -> Result<(), Error> {
        Err(Error::from(NotImplemented))
    }

    /// Flush values to be written that are older than given duration. If an identifier is given,
    /// then only those buffered values should be flushed.
    fn flush(
        &mut self,
        _timeout: Option<Duration>,
        _identifier: Option<&str>,
    ) -> Result<(), Error> {
        Err(Error::from(NotImplemented))
    }
}

/// Sets up all the ffi entry points that collectd expects when given a `PluginManager`.
#[macro_export]
macro_rules! collectd_plugin {
    ($type: ty) => {

        // Let's us know if we've seen our config section before
        static mut CONFIG_SEEN: bool = false;

        // This is the main entry point that collectd looks for. Our plugin manager will register
        // callbacks for configuration related to our name. It also registers a callback for
        // initialization for when configuratio is absent or a single plugin wants to hold global
        // data
        #[no_mangle]
        pub extern "C" fn module_register() {
            use std::ffi::CString;
            use $crate::bindings::{plugin_register_init, plugin_register_complex_config};

            let s = CString::new(<$type as PluginManager>::name())
                .expect("Plugin name to not contain nulls");

            unsafe {
                plugin_register_complex_config(
                    s.as_ptr(),
                    Some(collectd_plugin_complex_config)
                );

                plugin_register_init(s.as_ptr(), Some(collectd_plugin_init));
            }

        }

        // Logs an error with a description and all the causes
        fn collectd_log_err(desc: &str, err: &Error) {
            // We join all the causes into a single string. Some thoughts
            //  - This is not the most efficient way (that would belong to itertool crate), but
            //    collecting into a vector then joining is not terribly more expensive.
            //  - When an error occurs, one should expect there is some performance price to pay
            //    for additional, and much needed, context
            //  - Adding a new dependency to this library for a single function to save one line
            //    seems to be a heavy handed solution
            //  - While nearly all languages will display each cause on a separate line for a
            //    stacktrace, I'm not aware of any collectd plugin doing the same. So to keep
            //    convention, all causes are logged on the same line, semicolon delimited.
            let joined = err.causes()
                .map(|x| format!("{}", x))
                .collect::<Vec<String>>()
                .join("; ");

            $crate::collectd_log(
                $crate::LogLevel::Error,
                &format!("{} error: {}", desc, joined)
            );
        }

        unsafe extern "C" fn collectd_plugin_read(dt: *mut $crate::bindings::user_data_t) -> std::os::raw::c_int {
            let ptr: *mut Box<$crate::Plugin>  = std::mem::transmute((*dt).data);
            let mut plugin = Box::from_raw(ptr);
            let result = if let Err(ref e) = plugin.read_values() {
                collectd_log_err("read", e);
                -1
            } else {
                0
            };

            std::mem::forget(plugin);
            result
        }

        unsafe extern "C" fn collectd_plugin_free_user_data(raw: *mut ::std::os::raw::c_void) {
            let ptr: *mut Box<$crate::Plugin> = std::mem::transmute(raw);
            Box::from_raw(ptr);
        }

        unsafe extern "C" fn collectd_plugin_log(
            severity: ::std::os::raw::c_int,
            message: *const std::os::raw::c_char,
            dt: *mut $crate::bindings::user_data_t
        ) {
            use std::ffi::CStr;
            let ptr: *mut Box<$crate::Plugin> = std::mem::transmute((*dt).data);
            let mut plugin = Box::from_raw(ptr);
            let msg = CStr::from_ptr(message).to_string_lossy();
            let lvl: $crate::LogLevel = std::mem::transmute(severity as u32);
            if let Err(ref e) = plugin.log(lvl, std::ops::Deref::deref(&msg)) {
                collectd_log_err("logging", e);
            }
            std::mem::forget(plugin);
        }

        unsafe extern "C" fn collectd_plugin_write(
           ds: *const $crate::bindings::data_set_t,
           vl: *const $crate::bindings::value_list_t,
           dt: *mut $crate::bindings::user_data_t
        ) -> std::os::raw::c_int {
            let ptr: *mut Box<$crate::Plugin> = std::mem::transmute((*dt).data);
            let mut plugin = Box::from_raw(ptr);
            let list = $crate::ValueList::from(&*ds, &*vl);
            if let Err(ref e) = list {
                collectd_log_err("unable to decode collectd data", e);
                std::mem::forget(plugin);
                return -1;
            }

            let result =
                if let Err(ref e) = plugin.write_values(list.unwrap()) {
                    collectd_log_err("writing", e);
                    -1
                } else {
                    0
                };
            std::mem::forget(plugin);
            result
        }

        unsafe extern "C" fn collectd_plugin_init() -> std::os::raw::c_int {
            let mut result = if !CONFIG_SEEN {
                collectd_register_all_plugins(None)
            } else {
                0
            };

            let capabilities = <$type as PluginManager>::capabilities();
            if capabilities.intersects($crate::PluginManagerCapabilities::INIT) {
                if let Err(ref e) = <$type as PluginManager>::initialize() {
                    result = -1;
                    collectd_log_err("init", e);
                }
            }

            result
        }

        unsafe extern "C" fn collectd_plugin_flush(
            timeout: $crate::bindings::cdtime_t,
            identifier: *const std::os::raw::c_char,
            dt: *mut $crate::bindings::user_data_t
        ) -> std::os::raw::c_int {
            use std::ffi::CStr;

            let ptr: *mut Box<$crate::Plugin> = std::mem::transmute((*dt).data);
            let mut plugin = Box::from_raw(ptr);

            let dur = if timeout == 0 { None } else { Some($crate::CdTime::from(timeout).into()) };
            let result =
                if let Ok(ident) = CStr::from_ptr(identifier).to_str() {
                    if let Err(ref e) = plugin.flush(dur, $crate::empty_to_none(ident)) {
                        collectd_log_err("flush", e);
                        -1
                    } else {
                        0
                    }
                } else {
                    -1
                };

            std::mem::forget(plugin);
            result
        }

        unsafe extern "C" fn collectd_plugin_complex_config(
            config: *mut $crate::bindings::oconfig_item_t
        ) -> std::os::raw::c_int {
            // If we've already seen the config, let's error out as one shouldn't use multiple
            // sections of configuration (group them under nodes like write_graphite)
            if CONFIG_SEEN {
                $crate::collectd_log(
                    $crate::LogLevel::Error,
                    &format!("already seen a config section for {}", <$type as PluginManager>::name())
                );
                return -1;
            }

            CONFIG_SEEN = true;
            match $crate::ConfigItem::from(&*config) {
                Ok(config) => collectd_register_all_plugins(Some(&config.children)),
                Err(ref e) => {
                    collectd_log_err("collectd config conversion", e);
                    -1
                }
            }
        }

        fn collectd_register_all_plugins(
            config: Option<&[$crate::ConfigItem]>
        ) -> std::os::raw::c_int {
            match <$type as PluginManager>::plugins(config) {
                Ok(registration) => {
                    match registration {
                        $crate::PluginRegistration::Single(pl) => {
                            collectd_plugin_registration(
                                <$type as $crate::PluginManager>::name(),
                                pl
                            );
                        }
                        $crate::PluginRegistration::Multiple(v) => {
                            for (id, pl) in v {
                                let name = format!("{}/{}",
                                    <$type as $crate::PluginManager>::name(),
                                    id
                                );

                                collectd_plugin_registration(name.as_str(), pl);
                            }
                        }
                    }
                    0
                },
                Err(ref e) => {
                    collectd_log_err("collectd config", e);
                    -1
                }
            }
        }

        fn collectd_plugin_registration(name: &str, plugin: Box<$crate::Plugin>) {
            use std::os::raw::c_void;
            use std::ptr;
            use std::ffi::CString;
            use $crate::bindings::{plugin_register_write, plugin_register_complex_read, plugin_register_log, plugin_register_flush};

            let pl: Box<Box<$crate::Plugin>> = Box::new(plugin);

            // Grab all the properties we need until `into_raw` away
            let should_read = pl.capabilities().has_read();
            let should_log = pl.capabilities().has_log();
            let should_write = pl.capabilities().has_write();
            let should_flush = pl.capabilities().has_flush();

            let s = CString::new(name).expect("Plugin name to not contain nulls");
            unsafe {
                let plugin_ptr: *mut c_void = std::mem::transmute(Box::into_raw(pl));

                // Plugin registration differs only a tiny bit between collectd-57 and older
                // versions. The one difference is that user_data_t went from mutable to not
                // mutable. The code duplication is annoying, but it's better to have it
                // encapsulated in a single crate instead of many others.
                #[cfg(not(feature = "collectd-57"))]
                {
                    // The user data that is passed to read, writes, logs, etc. It is not passed to
                    // config or init. Since user_data_t implements copy, we don't need to forget about
                    // it. See clippy suggestion (forget_copy)
                    let mut data = $crate::bindings::user_data_t {
                        data: plugin_ptr,
                        free_func: Some(collectd_plugin_free_user_data),
                    };

                    if should_read {
                        plugin_register_complex_read(
                            ptr::null(),
                            s.as_ptr(),
                            Some(collectd_plugin_read),
                            $crate::get_default_interval(),
                            &mut data
                        );
                    }

                    if should_write {
                        plugin_register_write(
                            s.as_ptr(),
                            Some(collectd_plugin_write),
                            &mut data
                        );
                    }

                    if should_log {
                        plugin_register_log(s.as_ptr(), Some(collectd_plugin_log), &mut data);
                    }

                    if should_flush {
                        plugin_register_flush(s.as_ptr(), Some(collectd_plugin_flush), &mut data);
                    }
                }

                #[cfg(feature = "collectd-57")]
                {
                    // The user data that is passed to read, writes, logs, etc. It is not passed to
                    // config or init. Since user_data_t implements copy, we don't need to forget about
                    // it. See clippy suggestion (forget_copy)
                    let data = $crate::bindings::user_data_t {
                        data: plugin_ptr,
                        free_func: Some(collectd_plugin_free_user_data),
                    };

                    if should_read {
                        plugin_register_complex_read(
                            ptr::null(),
                            s.as_ptr(),
                            Some(collectd_plugin_read),
                            $crate::get_default_interval(),
                            &data
                        );
                    }

                    if should_write {
                        plugin_register_write(
                            s.as_ptr(),
                            Some(collectd_plugin_write),
                            &data
                        );
                    }

                    if should_log {
                        plugin_register_log(s.as_ptr(), Some(collectd_plugin_log), &data);
                    }

                    if should_flush {
                        plugin_register_flush(s.as_ptr(), Some(collectd_plugin_flush), &data);
                    }
                }
            }
        }
    };
}

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

    #[test]
    fn test_plugin_capabilities() {
        let capabilities = PluginCapabilities::READ | PluginCapabilities::WRITE;
        assert_eq!(capabilities.has_read(), true);
        assert_eq!(capabilities.has_write(), true);

        let capabilities = PluginCapabilities::READ;
        assert_eq!(capabilities.has_read(), true);
        assert_eq!(capabilities.has_write(), false);
    }
}