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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
|
# Copyright (c) 2022 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Metric library.
Time measurements are done by time.time().
Although time.time() is susceptible to big (or even negative) jumps
when a system is badly synchronized, it is still better
than time.monotonic(), as that value has no relation to epoch time.
"""
from collections import namedtuple
from threading import Lock
from time import time
import re
class Value:
"""
A value storage protected by a mutex.
"""
def __init__(self):
"""
Initialize value to default and create a lock.
"""
self._value = 0.0
self._lock = Lock()
self._timestamp = None
def inc(self, amount):
"""
Increment value by amount under mutex.
Add a timestamp of capturing value.
:param amount: Amount of increment.
:type amount: int or float
"""
with self._lock:
self._value += amount
self._timestamp = time()
def set(self, value):
"""
Set to a specific value under mutex.
Add a timestamp of capturing value.
:param value: Amount of increment.
:type value: int or float
"""
with self._lock:
self._value = value
self._timestamp = time()
def get(self):
"""
Get a value under mutex.
:returns: Stored value.
:rtype: int or float
"""
with self._lock:
return self._value
def get_timestamp(self):
"""
Get a timestamp under mutex.
:returns: Stored timestamp.
:rtype: str
"""
with self._lock:
return self._timestamp
class Metric:
"""
A single metric parent and its samples.
"""
def __init__(self, name, documentation, typ):
"""
Initialize class and do basic sanitize.
:param name: Full metric name.
:param documentation: Metric HELP string.
:param typ: Metric type [counter|gauge|info].
:type name: str
:type documentation: str
:type typ: str
"""
self.metric_types = (
u"counter", u"gauge", u"info"
)
self.metric_sample = namedtuple(
u"Sample", [u"name", u"labels", u"value", u"timestamp"]
)
if not re.compile(r"^[a-zA-Z._:][a-zA-Z0-9._:]*$").match(name):
raise ValueError(f"Invalid metric name: {name}!")
if typ not in self.metric_types:
raise ValueError(f"Invalid metric type: {typ}!")
self.name = name
self.documentation = documentation
self.type = typ
self.samples = []
def add_sample(self, name, labels, value, timestamp):
"""
Add a sample (entry) to the metric.
:param name: Full metric name.
:param labels: Metric labels.
:param value: Metric value.
:param timestamp: Timestamp. Default to be when accessed.
:type name: str
:type lables: tuple
:type value: int or float
:type timestamp: float
"""
self.samples.append(
self.metric_sample(name, labels, value, timestamp)
)
def __eq__(self, other):
"""
Check equality of added metric.
:param other: Metric to compare.
:type other: Metric
"""
return (isinstance(other, Metric)
and self.name == other.name
and self.documentation == other.documentation
and self.type == other.type
and self.samples == other.samples)
def __repr__(self):
"""
Represantation as a string for a debug print.
"""
return (
f"Metric({self.name}, "
f"{self.documentation}, "
f"{self.type}, "
f"{self.samples})"
)
class MetricBase:
"""
Abstract class for Metric implementation.
"""
_type = None
def __init__(
self, name, documentation, labelnames=(), namespace="",
subsystem="", labelvalues=None,
):
"""
Metric initialization.
:param name: Metric name.
:param documentation: Metric HELP string.
:param labelnames: Metric label list.
:param namespace: Metric namespace (will be added as prefix).
:param subsystem: Metric susbsystem (will be added as prefix).
:param labelvalues: Metric label values.
:type name: str
:type documentation: str
:type labelnames: list
:type namespace: str
:type subsystem: str
:type labelvalues: list
"""
self._name = self.validate_name(name, namespace, subsystem)
self._labelnames = self.validate_labelnames(labelnames)
self._labelvalues = tuple(labelvalues or ())
self._documentation = documentation
if self._is_parent():
self._lock = Lock()
self._metrics = {}
if self._is_observable():
self._metric_init()
@staticmethod
def validate_name(name, namespace, subsystem):
"""
Construct metric full name and validate naming convention.
:param name: Metric name.
:param namespace: Metric namespace (will be added as prefix).
:param subsystem: Metric susbsystem (will be added as prefix).
:type name: str
:type namespace: str
:type subsystem: str
:returns: Metric full name.
:rtype: str
:rasies ValueError: If name does not conform with naming conventions.
"""
full_name = u""
full_name += f"{namespace}." if namespace else u""
full_name += f"{subsystem}." if subsystem else u""
full_name += name
if not re.compile(r"^[a-zA-Z._:][a-zA-Z0-9._:]*$").match(full_name):
raise ValueError(
f"Invalid metric name: {full_name}!"
)
return full_name
@staticmethod
def validate_labelnames(labelnames):
"""
Create label tuple and validate naming convention.
:param labelnames: Metric label list.
:type labelnames: list
:returns: Label names.
:rtype: tuple
:rasies ValueError: If name does not conform with naming conventions.
"""
labelnames = tuple(labelnames)
for label in labelnames:
if not re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$").match(label):
raise ValueError(f"Invalid label metric name: {label}!")
if re.compile(r"^__.*$").match(label):
raise ValueError(f"Reserved label metric name: {label}!")
return labelnames
def _is_observable(self):
"""
Check whether this metric is observable, i.e.
* a metric without label names and values, or
* the child of a labelled metric.
:return: Observable
:rtype: bool
"""
return not self._labelnames or (self._labelnames and self._labelvalues)
def _is_parent(self):
"""
Check whether metric is parent, i.e.
* a metric with label names but not its values.
:return: Parent
:rtype: bool
"""
return self._labelnames and not self._labelvalues
def _get_metric(self):
"""
Returns metric that will handle samples.
:returns: Metric object.
:rtype: Metric
"""
return Metric(self._name, self._documentation, self._type)
def describe(self):
"""
Returns metric that will handle samples.
:returns: List of metric objects.
:rtype: list
"""
return [self._get_metric()]
def collect(self):
"""
Returns metric with samples.
:returns: List with metric object.
:rtype: list
"""
metric = self._get_metric()
for suffix, labels, value, timestamp in self.samples():
metric.add_sample(self._name + suffix, labels, value, timestamp)
return [metric]
def labels(self, *labelvalues, **labelkwargs):
"""
Return the child for the given labelset.
:param labelvalues: Label values.
:param labelkwargs: Dictionary with label names and values.
:type labelvalues: list
:type labelkwargs: dict
:returns: Metric with labels and values.
:rtype: Metric
:raises ValueError: If labels were not initialized.
:raises ValueError: If labels are already set (chaining).
:raises ValueError: If both parameters are passed.
:raises ValueError: If label values are not matching label names.
"""
if not self._labelnames:
raise ValueError(
f"No label names were set when constructing {self}!"
)
if self._labelvalues:
raise ValueError(
f"{self} already has labels set; can not chain .labels() calls!"
)
if labelvalues and labelkwargs:
raise ValueError(
u"Can't pass both *args and **kwargs!"
)
if labelkwargs:
if sorted(labelkwargs) != sorted(self._labelnames):
raise ValueError(u"Incorrect label names!")
labelvalues = tuple(labelkwargs[l] for l in self._labelnames)
else:
if len(labelvalues) != len(self._labelnames):
raise ValueError(u"Incorrect label count!")
labelvalues = tuple(l for l in labelvalues)
with self._lock:
if labelvalues not in self._metrics:
self._metrics[labelvalues] = self.__class__(
self._name,
documentation=self._documentation,
labelnames=self._labelnames,
labelvalues=labelvalues
)
return self._metrics[labelvalues]
def samples(self):
"""
Returns samples whether an object is parent or child.
:returns: List of Metric objects with values.
:rtype: list
"""
if self._is_parent():
return self._multi_samples()
return self._child_samples()
def _multi_samples(self):
"""
Returns parent and its childs with its values.
:returns: List of Metric objects with values.
:rtype: list
"""
with self._lock:
metrics = self._metrics.copy()
for labels, metric in metrics.items():
series_labels = list(zip(self._labelnames, labels))
for suffix, sample_labels, value, timestamp in metric.samples():
yield (
suffix, dict(series_labels + list(sample_labels.items())),
value, timestamp
)
def _child_samples(self):
"""
Returns child with its values. Should be implemented by child class.
:raises NotImplementedError: If implementation in not in subclass.
"""
raise NotImplementedError(
f"_child_samples() must be implemented by {self}!"
)
def _metric_init(self):
"""
Initialize the metric object as a child.
:raises NotImplementedError: If implementation in not in subclass.
"""
raise NotImplementedError(
f"_metric_init() must be implemented by {self}!"
)
def __str__(self):
"""
String for a debug print.
"""
return f"{self._type}:{self._name}"
def __repr__(self):
"""
Represantation as a string for a debug print.
"""
metric_type = type(self)
return f"{metric_type.__module__}.{metric_type.__name__}({self._name})"
class Counter(MetricBase):
"""
A Counter tracks counts of events or running totals.
"""
_type = u"counter"
def __init__(self,
name,
documentation,
labelnames=(),
namespace=u"",
subsystem=u"",
labelvalues=None
):
"""
Initialize the Counter metric object.
:param name: Metric name.
:param documentation: Metric HELP string.
:param labelnames: Metric label list.
:param namespace: Metric namespace (will be added as prefix).
:param subsystem: Metric susbsystem (will be added as prefix).
:param labelvalues: Metric label values.
:type name: str
:type documentation: str
:type labelnames: list
:type namespace: str
:type subsystem: str
:type labelvalues: list
"""
super(Counter, self).__init__(
name=name,
documentation=documentation,
labelnames=labelnames,
namespace=namespace,
subsystem=subsystem,
labelvalues=labelvalues,
)
def _metric_init(self):
"""
Initialize counter value.
"""
self._value = Value()
def inc(self, amount=1):
"""
Increment counter by the given amount.
:param amount: Amount to increment.
:type amount: int or float
:raises ValueError: If amout is not positive.
"""
if amount < 0:
raise ValueError(
u"Counters can only be incremented by non-negative amounts."
)
self._value.inc(amount)
def _child_samples(self):
"""
Returns list of child samples.
:returns: List of child samples.
:rtype: tuple
"""
return ((u"", {}, self._value.get(), self._value.get_timestamp()),)
class Gauge(MetricBase):
"""
Gauge metric, to report instantaneous values.
"""
_type = u"gauge"
def __init__(self,
name,
documentation,
labelnames=(),
namespace=u"",
subsystem=u"",
labelvalues=None
):
"""
Initialize the Gauge metric object.
:param name: Metric name.
:param documentation: Metric HELP string.
:param labelnames: Metric label list.
:param namespace: Metric namespace (will be added as prefix).
:param subsystem: Metric susbsystem (will be added as prefix).
:param labelvalues: Metric label values.
:type name: str
:type documentation: str
:type labelnames: list
:type namespace: str
:type subsystem: str
:type labelvalues: list
"""
super(Gauge, self).__init__(
name=name,
documentation=documentation,
labelnames=labelnames,
namespace=namespace,
subsystem=subsystem,
labelvalues=labelvalues,
)
def _metric_init(self):
"""
Initialize gauge value.
"""
self._value = Value()
def inc(self, amount=1):
"""
Increment gauge by the given amount.
:param amount: Amount to increment.
:type amount: int or float
"""
self._value.inc(amount)
def dec(self, amount=1):
"""
Decrement gauge by the given amount.
:param amount: Amount to decrement.
:type amount: int or float
"""
self._value.inc(-amount)
def set(self, value):
"""
Set gauge to the given value.
:param amount: Value to set.
:type amount: int or float
"""
self._value.set(float(value))
def _child_samples(self):
"""
Returns list of child samples.
:returns: List of child samples.
:rtype: tuple
"""
return ((u"", {}, self._value.get(), self._value.get_timestamp()),)
class Info(MetricBase):
"""
Info metric, key-value pairs.
"""
_type = u"info"
def __init__(self,
name,
documentation,
labelnames=(),
namespace=u"",
subsystem=u"",
labelvalues=None
):
"""
Initialize the Info metric object.
:param name: Metric name.
:param documentation: Metric HELP string.
:param labelnames: Metric label list.
:param namespace: Metric namespace (will be added as prefix).
:param subsystem: Metric susbsystem (will be added as prefix).
:param labelvalues: Metric label values.
:type name: str
:type documentation: str
:type labelnames: list
:type namespace: str
:type subsystem: str
:type labelvalues: list
"""
super(Info, self).__init__(
name=name,
documentation=documentation,
labelnames=labelnames,
namespace=namespace,
subsystem=subsystem,
labelvalues=labelvalues,
)
def _metric_init(self):
"""
Initialize gauge value and time it was created.
"""
self._labelname_set = set(self._labelnames)
self._lock = Lock()
self._value = {}
def info(self, value):
"""
Set info to the given value.
:param value: Value to set.
:type value: int or float
:raises ValueError: If labels are overlapping.
"""
if self._labelname_set.intersection(value.keys()):
raise ValueError(
u"Overlapping labels for Info metric, "
f"metric: {self._labelnames} child: {value}!"
)
with self._lock:
self._value = dict(value)
def _child_samples(self):
"""
Returns list of child samples.
:returns: List of child samples.
:rtype: tuple
"""
with self._lock:
return ((u"_info", self._value, 1.0, time()),)
|