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
use desc::Desc;
use errors::{Error, Result};
use metrics::{Collector, Metric, Opts};
use proto;
use std::sync::Arc;
use value::{Value, ValueType};
use vec::{MetricVec, MetricVecBuilder};
#[derive(Clone)]
pub struct Counter {
v: Arc<Value>,
}
impl Counter {
pub fn new<S: Into<String>>(name: S, help: S) -> Result<Counter> {
let opts = Opts::new(name, help);
Counter::with_opts(opts)
}
pub fn with_opts(opts: Opts) -> Result<Counter> {
Counter::with_opts_and_label_values(&opts, &[])
}
fn with_opts_and_label_values(opts: &Opts, label_values: &[&str]) -> Result<Counter> {
let v = Value::new(opts, ValueType::Counter, 0.0, label_values)?;
Ok(Counter { v: Arc::new(v) })
}
#[inline]
pub fn inc_by(&self, v: f64) -> Result<()> {
if v < 0.0 {
return Err(Error::DecreaseCounter(v));
}
Ok(self.v.inc_by(v))
}
#[inline]
pub fn inc(&self) {
self.inc_by(1.0).unwrap()
}
#[inline]
pub fn get(&self) -> f64 {
self.v.get()
}
pub fn local(&self) -> LocalCounter {
LocalCounter::new(self.clone())
}
}
impl Collector for Counter {
fn desc(&self) -> Vec<&Desc> {
vec![&self.v.desc]
}
fn collect(&self) -> Vec<proto::MetricFamily> {
vec![self.v.collect()]
}
}
impl Metric for Counter {
fn metric(&self) -> proto::Metric {
self.v.metric()
}
}
#[derive(Clone)]
pub struct CounterVecBuilder {}
impl MetricVecBuilder for CounterVecBuilder {
type M = Counter;
type P = Opts;
fn build(&self, opts: &Opts, vals: &[&str]) -> Result<Counter> {
Counter::with_opts_and_label_values(opts, vals)
}
}
pub type CounterVec = MetricVec<CounterVecBuilder>;
impl CounterVec {
pub fn new(opts: Opts, label_names: &[&str]) -> Result<CounterVec> {
let variable_names = label_names.iter().map(|s| (*s).to_owned()).collect();
let opts = opts.variable_labels(variable_names);
let metric_vec = MetricVec::create(proto::MetricType::COUNTER, CounterVecBuilder {}, opts)?;
Ok(metric_vec as CounterVec)
}
}
pub struct LocalCounter {
counter: Counter,
val: f64,
}
impl LocalCounter {
pub fn new(counter: Counter) -> LocalCounter {
LocalCounter {
counter: counter,
val: 0.0,
}
}
#[inline]
pub fn inc_by(&mut self, v: f64) -> Result<()> {
if v < 0.0 {
return Err(Error::DecreaseCounter(v));
}
self.val += v;
Ok(())
}
#[inline]
pub fn inc(&mut self) {
self.val += 1.0;
}
#[inline]
pub fn get(&self) -> f64 {
self.val
}
#[inline]
pub fn flush(&mut self) {
if self.val == 0.0 {
return;
}
self.counter.inc_by(self.val).unwrap();
self.val = 0.0;
}
}
#[cfg(test)]
mod tests {
use super::*;
use metrics::{Collector, Opts};
use std::collections::HashMap;
#[test]
fn test_counter() {
let opts = Opts::new("test", "test help")
.const_label("a", "1")
.const_label("b", "2");
let counter = Counter::with_opts(opts).unwrap();
counter.inc();
assert_eq!(counter.get() as u64, 1);
counter.inc_by(42.0).unwrap();
assert_eq!(counter.get() as u64, 43);
let mut mfs = counter.collect();
assert_eq!(mfs.len(), 1);
let mf = mfs.pop().unwrap();
let m = mf.get_metric().get(0).unwrap();
assert_eq!(m.get_label().len(), 2);
assert_eq!(m.get_counter().get_value() as u64, 43);
}
#[test]
fn test_local_counter() {
let counter = Counter::new("counter", "counter helper").unwrap();
let mut local_counter1 = counter.local();
let mut local_counter2 = counter.local();
local_counter1.inc();
local_counter2.inc();
assert_eq!(local_counter1.get() as u64, 1);
assert_eq!(local_counter2.get() as u64, 1);
assert_eq!(counter.get() as u64, 0);
local_counter1.flush();
assert_eq!(counter.get() as u64, 1);
local_counter2.flush();
assert_eq!(counter.get() as u64, 2);
}
#[test]
fn test_counter_vec_with_labels() {
let vec = CounterVec::new(
Opts::new("test_couter_vec", "test counter vec help"),
&["l1", "l2"],
).unwrap();
let mut labels = HashMap::new();
labels.insert("l1", "v1");
labels.insert("l2", "v2");
assert!(vec.remove(&labels).is_err());
vec.with(&labels).inc();
assert!(vec.remove(&labels).is_ok());
assert!(vec.remove(&labels).is_err());
let mut labels2 = HashMap::new();
labels2.insert("l1", "v2");
labels2.insert("l2", "v1");
vec.with(&labels).inc();
assert!(vec.remove(&labels2).is_err());
vec.with(&labels).inc();
let mut labels3 = HashMap::new();
labels3.insert("l1", "v1");
assert!(vec.remove(&labels3).is_err());
}
#[test]
fn test_counter_vec_with_label_values() {
let vec = CounterVec::new(
Opts::new("test_vec", "test counter vec help"),
&["l1", "l2"],
).unwrap();
assert!(vec.remove_label_values(&["v1", "v2"]).is_err());
vec.with_label_values(&["v1", "v2"]).inc();
assert!(vec.remove_label_values(&["v1", "v2"]).is_ok());
vec.with_label_values(&["v1", "v2"]).inc();
assert!(vec.remove_label_values(&["v1"]).is_err());
assert!(vec.remove_label_values(&["v1", "v3"]).is_err());
}
}