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
454
455
456
457
458
459
460
461
462
463
464
465
466
use std::collections::btree_map::Entry as BEntry;
use std::collections::hash_map::Entry as HEntry;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::iter::FromIterator;
use std::sync::Arc;
use spin::RwLock;
use errors::{Error, Result};
use metrics::Collector;
use proto;
struct RegistryCore {
pub colloctors_by_id: HashMap<u64, Box<Collector>>,
pub dim_hashes_by_name: HashMap<String, u64>,
pub desc_ids: HashSet<u64>,
}
impl RegistryCore {
fn register(&mut self, c: Box<Collector>) -> Result<()> {
let mut desc_id_set = HashSet::new();
let mut collector_id: u64 = 0;
for desc in c.desc() {
if self.desc_ids.contains(&desc.id) {
return Err(Error::Msg(format!(
"descriptor {:?} already exists with the same \
fully-qualified name and const label values",
desc
)));
}
if let Some(hash) = self.dim_hashes_by_name.get(&desc.fq_name) {
if *hash != desc.dim_hash {
return Err(Error::Msg(format!(
"a previously registered descriptor with the \
same fully-qualified name as {:?} has \
different label names or a different help \
string",
desc
)));
}
}
self.dim_hashes_by_name
.insert(desc.fq_name.clone(), desc.dim_hash);
if desc_id_set.insert(desc.id) {
collector_id = collector_id.wrapping_add(desc.id);
} else {
return Err(Error::Msg(format!(
"a duplicate descriptor within the same \
collector the same fully-qualified name: {:?}",
desc.fq_name
)));
}
}
match self.colloctors_by_id.entry(collector_id) {
HEntry::Vacant(vc) => {
self.desc_ids.extend(desc_id_set);
vc.insert(c);
Ok(())
}
HEntry::Occupied(_) => Err(Error::AlreadyReg),
}
}
fn unregister(&mut self, c: Box<Collector>) -> Result<()> {
let mut id_set = Vec::new();
let mut collector_id = 0;
for desc in c.desc() {
if id_set.iter().find(|id| **id == desc.id).is_none() {
id_set.push(desc.id);
collector_id += desc.id;
}
}
if self.colloctors_by_id.remove(&collector_id).is_none() {
return Err(Error::Msg(format!(
"collector {:?} is not registered",
c.desc()
)));
}
Ok(())
}
fn gather(&self) -> Vec<proto::MetricFamily> {
let mut mf_by_name = BTreeMap::new();
for c in self.colloctors_by_id.values() {
let mfs = c.collect();
for mut mf in mfs {
if mf.get_metric().is_empty() {
continue;
}
let name = mf.get_name().to_owned();
match mf_by_name.entry(name) {
BEntry::Vacant(entry) => {
entry.insert(mf);
}
BEntry::Occupied(mut entry) => {
let existent_mf = entry.get_mut();
let existent_metrics = existent_mf.mut_metric();
for metric in mf.take_metric().into_iter() {
existent_metrics.push(metric);
}
}
}
}
}
for mf in mf_by_name.values_mut() {
mf.mut_metric().sort_by(|m1, m2| {
let lps1 = m1.get_label();
let lps2 = m2.get_label();
if lps1.len() != lps2.len() {
return lps1.len().cmp(&lps2.len());
}
for (lp1, lp2) in lps1.iter().zip(lps2.iter()) {
if lp1.get_value() != lp2.get_value() {
return lp1.get_value().cmp(lp2.get_value());
}
}
m1.get_timestamp_ms().cmp(&m2.get_timestamp_ms())
});
}
let kvs = Vec::from_iter(mf_by_name.into_iter());
kvs.into_iter().map(|(_, m)| m).collect()
}
}
#[derive(Clone)]
pub struct Registry {
r: Arc<RwLock<RegistryCore>>,
}
impl Default for Registry {
fn default() -> Registry {
let r = RegistryCore {
colloctors_by_id: HashMap::new(),
dim_hashes_by_name: HashMap::new(),
desc_ids: HashSet::new(),
};
Registry {
r: Arc::new(RwLock::new(r)),
}
}
}
impl Registry {
pub fn new() -> Registry {
Registry::default()
}
pub fn register(&self, c: Box<Collector>) -> Result<()> {
self.r.write().register(c)
}
pub fn unregister(&self, c: Box<Collector>) -> Result<()> {
self.r.write().unregister(c)
}
pub fn gather(&self) -> Vec<proto::MetricFamily> {
self.r.read().gather()
}
}
cfg_if! {
if #[cfg(all(feature = "process", target_os="linux"))] {
fn register_default_process_collector(reg: &Registry) -> Result<()> {
use process_collector::ProcessCollector;
let pc = ProcessCollector::for_self();
reg.register(Box::new(pc))
}
} else {
fn register_default_process_collector(_: &Registry) -> Result<()> {
Ok(())
}
}
}
lazy_static! {
static ref DEFAULT_REGISTRY: Registry = {
let reg = Registry::default();
register_default_process_collector(®).unwrap();
reg
};
}
pub fn register(c: Box<Collector>) -> Result<()> {
DEFAULT_REGISTRY.register(c)
}
pub fn unregister(c: Box<Collector>) -> Result<()> {
DEFAULT_REGISTRY.unregister(c)
}
pub fn gather() -> Vec<proto::MetricFamily> {
DEFAULT_REGISTRY.gather()
}
#[cfg(test)]
mod tests {
use super::*;
use counter::{Counter, CounterVec};
use desc::Desc;
use metrics::{Collector, Opts};
use proto;
use std::collections::HashMap;
use std::thread;
#[test]
fn test_registry() {
let r = Registry::new();
let counter = Counter::new("test", "test help").unwrap();
r.register(Box::new(counter.clone())).unwrap();
counter.inc();
let r1 = r.clone();
let handler = thread::spawn(move || {
let metric_familys = r1.gather();
assert_eq!(metric_familys.len(), 1);
});
assert!(handler.join().is_ok());
assert!(r.register(Box::new(counter.clone())).is_err());
assert!(r.unregister(Box::new(counter.clone())).is_ok());
assert!(r.unregister(Box::new(counter.clone())).is_err());
let counter_vec =
CounterVec::new(Opts::new("test_vec", "test vec help"), &["a", "b"]).unwrap();
r.register(Box::new(counter_vec.clone())).unwrap();
counter_vec.with_label_values(&["1", "2"]).inc();
}
#[test]
fn test_default_registry() {
let counter = Counter::new("test", "test help").unwrap();
assert!(register(Box::new(counter.clone())).is_ok());
assert_ne!(gather().len(), 0);
assert!(unregister(Box::new(counter.clone())).is_ok());
assert!(unregister(Box::new(counter.clone())).is_err());
}
#[test]
fn test_gather_order() {
let r = Registry::new();
let counter_a = Counter::new("test_a_counter", "test help").unwrap();
let counter_b = Counter::new("test_b_counter", "test help").unwrap();
let counter_2 = Counter::new("test_2_counter", "test help").unwrap();
r.register(Box::new(counter_b.clone())).unwrap();
r.register(Box::new(counter_2.clone())).unwrap();
r.register(Box::new(counter_a.clone())).unwrap();
let mfs = r.gather();
assert_eq!(mfs.len(), 3);
assert_eq!(mfs[0].get_name(), "test_2_counter");
assert_eq!(mfs[1].get_name(), "test_a_counter");
assert_eq!(mfs[2].get_name(), "test_b_counter");
let r = Registry::new();
let opts = Opts::new("test", "test help")
.const_label("a", "1")
.const_label("b", "2");
let counter_vec = CounterVec::new(opts, &["cc", "c1", "a2", "c0"]).unwrap();
r.register(Box::new(counter_vec.clone())).unwrap();
let mut map1 = HashMap::new();
map1.insert("cc", "12");
map1.insert("c1", "a1");
map1.insert("a2", "0");
map1.insert("c0", "hello");
counter_vec.with(&map1).inc();
let mut map2 = HashMap::new();
map2.insert("cc", "12");
map2.insert("c1", "0");
map2.insert("a2", "0");
map2.insert("c0", "hello");
counter_vec.with(&map2).inc();
counter_vec.with(&map2).inc();
let mut map3 = HashMap::new();
map3.insert("cc", "12");
map3.insert("c1", "0");
map3.insert("a2", "da");
map3.insert("c0", "hello");
counter_vec.with(&map3).inc();
counter_vec.with(&map3).inc();
counter_vec.with(&map3).inc();
let mut map4 = HashMap::new();
map4.insert("cc", "12");
map4.insert("c1", "0");
map4.insert("a2", "da");
map4.insert("c0", "你好");
counter_vec.with(&map4).inc();
counter_vec.with(&map4).inc();
counter_vec.with(&map4).inc();
counter_vec.with(&map4).inc();
let mfs = r.gather();
assert_eq!(mfs.len(), 1);
let ms = mfs[0].get_metric();
assert_eq!(ms.len(), 4);
assert_eq!(ms[0].get_counter().get_value() as u64, 2);
assert_eq!(ms[1].get_counter().get_value() as u64, 1);
assert_eq!(ms[2].get_counter().get_value() as u64, 3);
assert_eq!(ms[3].get_counter().get_value() as u64, 4);
}
struct MultipleCollector {
descs: Vec<Desc>,
counters: Vec<Counter>,
}
impl Collector for MultipleCollector {
fn desc(&self) -> Vec<&Desc> {
self.descs.iter().collect()
}
fn collect(&self) -> Vec<proto::MetricFamily> {
self.counters
.iter()
.inspect(|c| c.inc())
.map(|c| c.collect())
.fold(Vec::new(), |mut acc, mfs| {
acc.extend(mfs);
acc
})
}
}
#[test]
fn test_register_multiplecollector() {
let counters = vec![
Counter::new("c1", "c1 is a counter").unwrap(),
Counter::new("c2", "c2 is a counter").unwrap(),
];
let descs = counters.iter().map(|c| c.desc().into_iter().cloned()).fold(
Vec::new(),
|mut acc, ds| {
acc.extend(ds);
acc
},
);
let mc = MultipleCollector { descs, counters };
let r = Registry::new();
r.register(Box::new(mc)).unwrap();
}
#[test]
fn test_prune_empty_metric_family() {
let counter_vec =
CounterVec::new(Opts::new("test_vec", "test vec help"), &["a", "b"]).unwrap();
let r = Registry::new();
r.register(Box::new(counter_vec.clone())).unwrap();
assert!(r.gather().is_empty());
counter_vec.with_label_values(&["1", "2"]).inc();
assert!(!r.gather().is_empty());
}
}