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
//! A thread-safe, `Future`-aware metrics library.
//!
//! Many programs need to information about runtime performance: the number of requests
//! served, a distribution of request latency, the number of failures, the number of loop
//! iterations, etc. `tacho` allows application code to record runtime information to a
//! central `Aggregator` that merges data into a `Report`.
//!
//! ## Performance
//!
//! We found that the default (cryptographic) `Hash` algorithm adds a significant
//! performance penalty, so the (non-cryptographic) `RandomXxHashBuilder` algorithm is
//! used..
//!
//! Labels are stored in a `BTreeMap` because they are used as hash keys and, therefore,
//! need to implement `Hash`.

// TODO use atomics when we have them.

extern crate hdrsample;
#[macro_use]
extern crate log;
extern crate twox_hash;

use hdrsample::Histogram;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use twox_hash::RandomXxHashBuilder;

pub mod prometheus;
mod report;
mod timing;

pub use report::{Reporter, Report, ReportTake, ReportPeek};
pub use timing::Timing;

type Labels = BTreeMap<String, String>;
type CounterMap = HashMap<Key, u64, RandomXxHashBuilder>;
type GaugeMap = HashMap<Key, u64, RandomXxHashBuilder>;
type StatMap = HashMap<Key, Histogram<u64>, RandomXxHashBuilder>;

/// Creates a metrics registry.
///
/// The returned `Scope` may be you used to instantiate metrics. Labels may be attached to
/// the scope so that all metrics created by this `Scope` are annotated.
///
/// The returned `Reporter` supports consumption of metrics values.
pub fn new() -> (Scope, Reporter) {
    let counters = Arc::new(RwLock::new(CounterMap::default()));
    let gauges = Arc::new(RwLock::new(GaugeMap::default()));
    let stats = Arc::new(RwLock::new(StatMap::default()));

    let scope = Scope {
        labels: Labels::default(),
        counters: counters.clone(),
        gauges: gauges.clone(),
        stats: stats.clone(),
    };

    let reporter = report::new(counters, gauges, stats);

    (scope, reporter)
}

/// Describes a metric.
#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Key {
    name: String,
    labels: Labels,
}
impl Key {
    fn new(name: String, labels: Labels) -> Key {
        Key {
            name: name,
            labels: labels,
        }
    }

    pub fn name(&self) -> &str {
        &self.name
    }
    pub fn labels(&self) -> &Labels {
        &self.labels
    }
}


/// Supports creation of scoped metrics.
///
/// `Scope`s may be cloned without copying the underlying metrics registry.
///
/// Labels may be attached to the scope so that all metrics created by the `Scope` are
/// labeled.
#[derive(Clone)]
pub struct Scope {
    labels: Labels,
    counters: Arc<RwLock<CounterMap>>,
    gauges: Arc<RwLock<GaugeMap>>,
    stats: Arc<RwLock<StatMap>>,
}

impl Scope {
    /// Accesses scoping labels.
    pub fn labels(&self) -> &Labels {
        &self.labels
    }

    /// Adds a label into scope (potentially overwriting).
    pub fn labeled(self, k: String, v: String) -> Scope {
        Scope {
            counters: self.counters,
            gauges: self.gauges,
            stats: self.stats,
            labels: {
                let mut labels = self.labels;
                labels.insert(k, v);
                labels
            },
        }
    }

    /// Creates a Counter with the given name.
    pub fn counter(&self, name: String) -> Counter {
        Counter {
            key: Key::new(name, self.labels.clone()),
            counters: self.counters.clone(),
        }
    }

    /// Creates a Gauge with the given name.
    pub fn gauge(&self, name: String) -> Gauge {
        Gauge {
            key: Key::new(name, self.labels.clone()),
            gauges: self.gauges.clone(),
        }
    }

    /// Creates a Stat with the given name.
    ///
    /// The underlying histogram is automatically resized as values are added.
    pub fn stat(&self, name: String) -> Stat {
        Stat {
            key: Key::new(name, self.labels.clone()),
            stats: self.stats.clone(),
            bounds: None,
        }
    }

    /// Creates a Stat with the given name and histogram paramters.
    pub fn stat_with_bounds(&self, name: String, low: u64, high: u64) -> Stat {
        Stat {
            key: Key::new(name, self.labels.clone()),
            stats: self.stats.clone(),
            bounds: Some((low, high)),
        }
    }
}

/// Counts monotically.
#[derive(Clone)]
pub struct Counter {
    key: Key,
    counters: Arc<RwLock<CounterMap>>,
}
impl Counter {
    pub fn name(&self) -> &str {
        &self.key.name
    }
    pub fn labels(&self) -> &Labels {
        &self.key.labels
    }

    pub fn incr(&mut self, v: u64) {
        let mut counters = self.counters
            .write()
            .expect("failed to obtain write lock for counter");
        if let Some(mut curr) = counters.get_mut(&self.key) {
            *curr += v;
            return;
        }
        counters.insert(self.key.clone(), v);
    }
}

/// Captures an instantaneous value.
#[derive(Clone)]
pub struct Gauge {
    key: Key,
    gauges: Arc<RwLock<GaugeMap>>,
}
impl Gauge {
    pub fn name(&self) -> &str {
        &self.key.name
    }
    pub fn labels(&self) -> &Labels {
        &self.key.labels
    }

    pub fn set(&mut self, v: u64) {
        let mut gauges = self.gauges
            .write()
            .expect("failed to obtain write lock for gauge");
        if let Some(mut curr) = gauges.get_mut(&self.key) {
            *curr = v;
            return;
        }
        gauges.insert(self.key.clone(), v);
    }
}

/// Caputres a distribution of values.
#[derive(Clone)]
pub struct Stat {
    key: Key,
    stats: Arc<RwLock<StatMap>>,
    bounds: Option<(u64, u64)>,
}

const HISTOGRAM_PRECISION: u32 = 4;

impl Stat {
    pub fn name(&self) -> &str {
        &self.key.name
    }
    pub fn labels(&self) -> &Labels {
        &self.key.labels
    }

    pub fn add(&mut self, v: u64) {
        self.add_values(&[v]);
    }

    pub fn add_values(&mut self, vs: &[u64]) {
        trace!("histo record {:?} {:?}", self.key, vs);
        let mut stats = self.stats
            .write()
            .expect("failed to obtain write lock for stat");
        if let Some(mut histo) = stats.get_mut(&self.key) {
            for v in vs {
                if let Err(e) = histo.record(*v) {
                    error!("failed to add value to histogram: {:?}", e);
                }
            }
            return;
        }

        trace!("creating histogram {:?} bounds={:?}", self.key, self.bounds);
        let mut histo = match self.bounds {
            None => Histogram::<u64>::new(HISTOGRAM_PRECISION).expect("failed to build Histogram"),
            Some((low, high)) => {
                Histogram::<u64>::new_with_bounds(low, high, HISTOGRAM_PRECISION)
                    .expect("failed to build Histogram")
            }
        };
        for v in vs {
            if let Err(e) = histo.record(*v) {
                error!("failed to add value to histogram: {:?}", e);
            }
        }
        stats.insert(self.key.clone(), histo);
    }
}

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

    #[test]
    fn test_report_peek() {
        let (metrics, reporter) = super::new();
        let metrics = metrics.labeled("joy".into(), "painting".into());

        metrics.counter("happy_accidents".into()).incr(1);
        metrics.gauge("paint_level".into()).set(2);
        metrics.stat("stroke_len".into()).add_values(&[1, 2, 3]);
        {
            let report = reporter.peek();
            {
                let k = report
                    .counters()
                    .keys()
                    .find(|k| k.name() == "happy_accidents")
                    .expect("expected counter");
                assert_eq!(k.labels.get("joy"), Some(&"painting".to_string()));
                assert_eq!(report.counters().get(&k), Some(&1));
            }
            {
                let k = report
                    .gauges()
                    .keys()
                    .find(|k| k.name() == "paint_level")
                    .expect("expected gauge");
                assert_eq!(k.labels.get("joy"), Some(&"painting".to_string()));
                assert_eq!(report.gauges().get(&k), Some(&2));
            }
            assert_eq!(report
                           .gauges()
                           .keys()
                           .find(|k| k.name() == "brush_width"),
                       None);
            {
                let k = report
                    .stats()
                    .keys()
                    .find(|k| k.name() == "stroke_len")
                    .expect("expected stat");
                assert_eq!(k.labels.get("joy"), Some(&"painting".to_string()));
                assert!(report.stats().contains_key(&k));
            }
            assert_eq!(report.stats().keys().find(|k| k.name() == "tree_len"), None);
        }

        metrics.counter("happy_accidents".into()).incr(2);
        metrics.gauge("brush_width".into()).set(5);
        metrics.stat("stroke_len".into()).add_values(&[1, 2, 3]);
        metrics.stat("tree_len".into()).add_values(&[3, 4, 5]);
        {
            let report = reporter.peek();
            {
                let k = report
                    .counters()
                    .keys()
                    .find(|k| k.name() == "happy_accidents")
                    .expect("expected counter");
                assert_eq!(k.labels.get("joy"), Some(&"painting".to_string()));
                assert_eq!(report.counters().get(&k), Some(&3));
            }
            {
                let k = report
                    .gauges()
                    .keys()
                    .find(|k| k.name() == "paint_level")
                    .expect("expected gauge");
                assert_eq!(k.labels.get("joy"), Some(&"painting".to_string()));
                assert_eq!(report.gauges().get(&k), Some(&2));
            }
            {
                let k = report
                    .gauges()
                    .keys()
                    .find(|k| k.name() == "brush_width")
                    .expect("expected gauge");
                assert_eq!(k.labels.get("joy"), Some(&"painting".to_string()));
                assert_eq!(report.gauges().get(&k), Some(&5));
            }
            {
                let k = report
                    .stats()
                    .keys()
                    .find(|k| k.name() == "stroke_len")
                    .expect("expeced stat");
                assert_eq!(k.labels.get("joy"), Some(&"painting".to_string()));
                assert!(report.stats().contains_key(&k));
            }
            {
                let k = report
                    .stats()
                    .keys()
                    .find(|k| k.name() == "tree_len")
                    .expect("expeced stat");
                assert_eq!(k.labels.get("joy"), Some(&"painting".to_string()));
                assert!(report.stats().contains_key(&k));
            }
        }
    }

    #[test]
    fn test_report_take() {
        let (metrics, mut reporter) = super::new();
        let metrics = metrics.labeled("joy".into(), "painting".into());

        metrics.counter("happy_accidents".into()).incr(1);
        metrics.gauge("paint_level".into()).set(2);
        metrics.stat("stroke_len".into()).add_values(&[1, 2, 3]);
        {
            let report = reporter.take();
            {
                let k = report
                    .counters()
                    .keys()
                    .find(|k| k.name() == "happy_accidents")
                    .expect("expected counter");
                assert_eq!(k.labels.get("joy"), Some(&"painting".to_string()));
                assert_eq!(report.counters().get(&k), Some(&1));
            }
            {
                let k = report
                    .gauges()
                    .keys()
                    .find(|k| k.name() == "paint_level")
                    .expect("expected gauge");
                assert_eq!(k.labels.get("joy"), Some(&"painting".to_string()));
                assert_eq!(report.gauges().get(&k), Some(&2));
            }
            assert_eq!(report
                           .gauges()
                           .keys()
                           .find(|k| k.name() == "brush_width"),
                       None);
            {
                let k = report
                    .stats()
                    .keys()
                    .find(|k| k.name() == "stroke_len")
                    .expect("expected stat");
                assert_eq!(k.labels.get("joy"), Some(&"painting".to_string()));
                assert!(report.stats.contains_key(&k));
            }
            assert_eq!(report.stats.keys().find(|k| k.name() == "tree_len"), None);
        }

        metrics.counter("happy_accidents".into()).incr(2);
        metrics.gauge("brush_width".into()).set(5);
        metrics.stat("tree_len".into()).add_values(&[3, 4, 5]);
        {
            let report = reporter.take();
            {
                let k = report
                    .counters()
                    .keys()
                    .find(|k| k.name() == "happy_accidents")
                    .expect("expected counter");
                assert_eq!(k.labels.get("joy"), Some(&"painting".to_string()));
                assert_eq!(report.counters().get(&k), Some(&3));
            }
            assert_eq!(report
                           .gauges()
                           .keys()
                           .find(|k| k.name() == "paint_level"),
                       None);
            {
                let k = report
                    .gauges()
                    .keys()
                    .find(|k| k.name() == "brush_width")
                    .expect("expected gauge");
                assert_eq!(k.labels.get("joy"), Some(&"painting".to_string()));
                assert_eq!(report.gauges().get(&k), Some(&5));
            }
            assert_eq!(report.stats().keys().find(|k| k.name() == "stroke_len"),
                       None);
            {
                let k = report
                    .stats()
                    .keys()
                    .find(|k| k.name() == "tree_len")
                    .expect("expeced stat");
                assert_eq!(k.labels.get("joy"), Some(&"painting".to_string()));
                assert!(report.stats().contains_key(&k));
            }
        }
    }
}