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
pub use metrics_lib::metrics::{Metric, Counter, StdCounter};

use std::collections::HashMap;

use ::json;

use ::iron::prelude::{IronResult, Response};
use ::iron::status;

pub struct MetricsService {

    metrics: HashMap<String, Metric>,
    reporter_name: String,

}

impl MetricsService {

    pub fn get_name(&self) -> &str {
        &(*self.reporter_name)
    }

    pub fn add<S: Into<String>>(&mut self, name: S, metric: Metric) -> Result<(), String> {
        let n = name.into();
        match self.metrics.insert(n.clone(), metric) {
            Some(_) => Ok(()),
            None => Err(format!("Unable to attach metric reporter {}, {:?}", n, self.metrics.len())),
        }
    }

    pub fn new<S: Into<String>>(reporter_name: S) -> Self {
        MetricsService {
            metrics: HashMap::new(),
            reporter_name: reporter_name.into(),
        }
    }

    pub fn report(&self) -> IronResult<Response> {
        let mut report: HashMap<&String,i64> = HashMap::new();
        for (name, metric) in &self.metrics {
            let snapshot = match *metric {
                Metric::Meter(ref x) => {
                    x.snapshot().count as i64
                }
                Metric::Gauge(ref x ) => {
                    x.snapshot().value as i64
                }
                Metric::Counter(ref x) => {
                    x.snapshot().value as i64
                }
                Metric::Histogram(_) => {
                   -1 as i64
                }
            };
            report.insert(name, snapshot);
        }
        match json::to_string(&report) {
            Ok(r) => {
                Ok(Response::with((status::Ok, r)))
            },
            Err(e) => Ok(Response::with((status::InternalServerError, format!("{:?}", e))))
        }

    }
}