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
use std::collections::HashMap;
use std::env;
use std::fmt;
use std::io;
use std::convert::From;

#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
extern crate time;

/// Metric units
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
pub enum Unit {
    #[serde(rename = "float")]
    Float,
    #[serde(rename = "integer")]
    Integer,
    #[serde(rename = "percentage")]
    Percentage,
    #[serde(rename = "bytes")]
    Bytes,
    #[serde(rename = "bytes/sec")]
    BytesPerSecond,
    #[serde(rename = "iops")]
    IOPS,
}

impl fmt::Display for Unit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Unit::Float => write!(f, "float"),
            Unit::Integer => write!(f, "integer"),
            Unit::Percentage => write!(f, "percentage"),
            Unit::Bytes => write!(f, "bytes"),
            Unit::BytesPerSecond => write!(f, "bytes/sec"),
            Unit::IOPS => write!(f, "iops"),
        }
    }
}

impl<'a> From<&'a str> for Unit {
    fn from(src: &str) -> Unit {
        match src {
            "float" => Unit::Float,
            "integer" => Unit::Integer,
            "percentage" => Unit::Percentage,
            "bytes" => Unit::Bytes,
            "bytes/sec" => Unit::BytesPerSecond,
            "iops" => Unit::IOPS,
            x => panic!(
                "invalid unit: {} (should be one of float, integer, percentage, bytes, bytes/sec or iops)",
                x
            ),
        }
    }
}

/// A Metric
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
pub struct Metric {
    name: String,
    label: String,
    stacked: bool,
    #[serde(skip_serializing)]
    diff: bool,
}

// Compile time validation?
macro_rules! name_validation {
    ($type:expr, $name:expr) => {
        if !$name.chars().all(|c| {
            'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' || c == '-' || c == '_' || c == '.'
        }) {
            panic!("invalid {} name: {}", $type, $name);
        }
    }
}

impl Metric {
    pub fn new(name: String, label: String, stacked: bool, diff: bool) -> Metric {
        name_validation!("metric", name);
        Metric {
            name: name,
            label: label,
            stacked: stacked,
            diff: diff,
        }
    }
}

/// Construct a Metric.
///
/// ```rust
/// # #[macro_use]
/// # extern crate mackerel_plugin;
/// #
/// # fn main() {
/// let metric = metric! {
///     name: "foo",
///     label: "Foo metric"
/// };
/// # }
/// ```
///
/// Additionally you can specify `stacked` and `diff` options.
///
/// ```rust
/// # #[macro_use]
/// # extern crate mackerel_plugin;
/// #
/// # fn main() {
/// let metric = metric! {
///     name: "foo",
///     label: "Foo metric",
///     stacked: true,
///     diff: true
/// };
/// # }
/// ```
#[macro_export]
macro_rules! metric {
    (name: $name:expr, label: $label:expr) => {
        $crate::Metric::new($name.into(), $label.into(), false, false)
    };

    (name: $name:expr, label: $label:expr, stacked: $stacked:expr) => {
        $crate::Metric::new($name.into(), $label.into(), $stacked, false)
    };

    (name: $name:expr, label: $label:expr, diff: $diff:expr) => {
        $crate::Metric::new($name.into(), $label.into(), false, $diff)
    };

    (name: $name:expr, label: $label:expr, stacked: $stacked:expr, diff: $diff:expr) => {
        $crate::Metric::new($name.into(), $label.into(), $stacked, $diff)
    };

    ($($token:tt)*) => {
        compile_error!("name and label are required for a metric");
    };
}

#[macro_export]
#[doc(hidden)]
macro_rules! metrics {
    ($({$($token:tt)+},)*) => {
        vec![$(metric! {$($token)+},)*]
    };

    ($({$($token:tt)+}),*) => {
        vec![$(metric! {$($token)+}),*]
    };
}

/// A Graph
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
pub struct Graph {
    #[serde(skip_serializing)]
    name: String,
    label: String,
    unit: Unit,
    metrics: Vec<Metric>,
}

impl Graph {
    pub fn new(name: String, label: String, unit: Unit, metrics: Vec<Metric>) -> Graph {
        name_validation!("graph", name);
        Graph {
            name: name,
            label: label,
            unit: unit,
            metrics: metrics,
        }
    }
}

/// Construct a Graph.
///
/// ```rust
/// # #[macro_use]
/// # extern crate mackerel_plugin;
/// #
/// # fn main() {
/// let graph = graph! {
///     name: "linux.swap",
///     label: "Linux Swap Usage",
///     unit: "integer",
///     metrics: [
///         { name: "pswpin", label: "Swap In", diff: true },
///         { name: "pswpout", label: "Swap Out", diff: true },
///     ]
/// };
/// # }
/// ```
#[macro_export]
macro_rules! graph {
    (name: $name:expr, label: $label:expr, unit: $unit:expr, metrics: [$($metrics:tt)+]) => {
        $crate::Graph::new($name.into(), $label.into(), $unit.into(), metrics!($($metrics)+))
    };

    ($($token:tt)*) => {
        compile_error!("name, label, unit and metrics are required for a graph");
    };
}

/// A trait which represents a Plugin.
///
/// You can create a plugin by implementing `fetch_metrics` and `graph_definition`.
pub trait Plugin {
    fn fetch_metrics(&self) -> Result<HashMap<String, f64>, String>;

    fn graph_definition(&self) -> Vec<Graph>;

    #[doc(hidden)]
    fn print_value(&self, out: &mut io::Write, metric_name: String, value: f64, now: time::Timespec) {
        if !value.is_nan() && value.is_finite() {
            let _ = writeln!(out, "{}\t{}\t{}", metric_name, value, now.sec);
        }
    }

    #[doc(hidden)]
    fn output_values(&self, out: &mut io::Write) -> Result<(), String> {
        let now = time::now().to_timespec();
        let results = self.fetch_metrics()?;
        for graph in self.graph_definition() {
            for metric in graph.metrics {
                self.format_values(out, &graph.name, metric, &results, now);
            }
        }
        Ok(())
    }

    #[doc(hidden)]
    fn format_values(&self, out: &mut io::Write, graph_name: &str, metric: Metric, results: &HashMap<String, f64>, now: time::Timespec) {
        let metric_name = format!("{}.{}", graph_name, &metric.name);
        results.get(&metric_name).map(|value| self.print_value(out, metric_name, *value, now));
    }

    #[doc(hidden)]
    fn output_definitions(&self, out: &mut io::Write) -> Result<(), String> {
        writeln!(out, "# mackerel-agent-plugin").map_err(|e| format!("{}", e))?;
        let json = json!({"graphs": self.graph_definition().iter().map(|graph| (&graph.name, graph)).collect::<HashMap<_, _>>()});
        writeln!(out, "{}", json.to_string()).map_err(|e| format!("{}", e))?;
        Ok(())
    }

    #[doc(hidden)]
    fn env_plugin_meta(&self) -> Option<String> {
        env::vars()
            .filter_map(|(key, value)| if key == "MACKEREL_AGENT_PLUGIN_META" {
                Some(value)
            } else {
                None
            })
            .next()
    }

    fn run(&self) -> Result<(), String> {
        let mut stdout = io::stdout();
        if self.env_plugin_meta().map_or(false, |value| value != "") {
            self.output_definitions(&mut stdout)
        } else {
            self.output_values(&mut stdout)
        }
    }
}