Repository navigation
Expand file tree
/
Copy path__init__.py
More file actions
354 lines (292 loc) · 10.1 KB
/
Copy path__init__.py
File metadata and controls
354 lines (292 loc) · 10.1 KB
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
#!/usr/bin/python
from __future__ import unicode_literals
import copy
import re
import os
import time
import threading
from contextlib import contextmanager
try:
from BaseHTTPServer import BaseHTTPRequestHandler
except ImportError:
# Python 3
from http.server import BaseHTTPRequestHandler
from functools import wraps
from threading import Lock
__all__ = ['Counter', 'Gauge', 'Summary', 'CollectorRegistry']
_METRIC_NAME_RE = re.compile(r'^[a-zA-Z_:][a-zA-Z0-9_:]*$')
_METRIC_LABEL_NAME_RE = re.compile(r'^[a-zA-Z_:][a-zA-Z0-9_:]*$')
_RESERVED_METRIC_LABEL_NAME_RE = re.compile(r'^__.*$')
class CollectorRegistry(object):
'''Metric collector registry.
Collectors must have a no-argument method 'collect' that returns a list of
Metric objects. The returned metrics should be consistent with the Prometheus
exposition formats.
'''
def __init__(self):
self._collectors = set()
self._lock = Lock()
def register(self, collector):
'''Add a collector to the registry.'''
with self._lock:
self._collectors.add(collector)
def unregister(self, metric):
'''Remove a collector from the registry.'''
with self._lock:
self._collectors.remove(collector)
def collect(self):
'''Yields metrics from the collectors in the registry.'''
collectors = None
with self._lock:
collectors = copy.copy(self._collectors)
for collector in collectors:
for metric in collector.collect():
yield metric
def get_sample_value(self, name, labels=None):
'''Returns the sample value, or None if not found.
This is inefficient, and intended only for use in unittests.
'''
if labels is None:
labels = {}
for metric in self.collect():
for n, l, value in metric._samples:
if n == name and l == labels:
return value
return None
REGISTRY = CollectorRegistry()
'''The default registry.'''
_METRIC_TYPES = ('counter', 'gauge', 'summary', 'untyped')
class Metric(object):
'''A single metric and it's samples.'''
def __init__(self, name, documentation, typ):
self._name = name
self._documentation = documentation
if typ not in _METRIC_TYPES:
raise ValueError('Invalid metric type: ' + typ)
self._type = typ
self._samples = []
'''Add a sample to the metric'''
def add_sample(self, name, labels, value):
self._samples.append((name, labels, value))
class _LabelWrapper(object):
'''Handles labels for the wrapped metric.'''
def __init__(self, wrappedClass, labelnames):
self._wrappedClass = wrappedClass
self._type = wrappedClass._type
self._labelnames = labelnames
self._lock = Lock()
self._metrics = {}
for l in labelnames:
if l.startswith('__'):
raise InvalidLabelName(l)
def labels(self, *labelvalues):
'''Return the child for the given labelset.'''
if len(labelvalues) != len(self._labelnames):
raise ValueError('Incorrect label count')
labelvalues = tuple(labelvalues)
with self._lock:
if labelvalues not in self._metrics:
self._metrics[labelvalues] = self._wrappedClass()
return self._metrics[labelvalues]
def remove(self, *labelvalues):
'''Remove the given labelset from the metric.'''
if len(labelvalues) != len(self._labelnames):
raise ValueError('Incorrect label count')
labelvalues = tuple(labelvalues)
with self._lock:
del self._metrics[labelvalues]
def _samples(self):
with self._lock:
metrics = self._metrics.copy()
for labels, metric in metrics.items():
for suffix, _, value in metric._samples():
yield (suffix, dict(zip(self._labelnames, labels)), value)
def _MetricWrapper(cls):
'''Provides common functionality for metrics.'''
def init(name, documentation, labelnames=(), namespace='', subsystem='', registry=REGISTRY):
if labelnames:
for l in labelnames:
if not _METRIC_LABEL_NAME_RE.match(l):
raise ValueError('Invalid label metric name: ' + l)
if _RESERVED_METRIC_LABEL_NAME_RE.match(l):
raise ValueError('Reserved label metric name: ' + l)
collector = _LabelWrapper(cls, labelnames)
else:
collector = cls()
full_name = ''
if namespace:
full_name += namespace + '_'
if subsystem:
full_name += subsystem + '_'
full_name += name
if not _METRIC_NAME_RE.match(full_name):
raise ValueError('Invalid metric name: ' + full_name)
def collect():
metric = Metric(full_name, documentation, cls._type)
for suffix, labels, value in collector._samples():
metric.add_sample(full_name + suffix, labels, value)
return [metric]
collector.collect = collect
registry.register(collector)
return collector
return init
@_MetricWrapper
class Counter(object):
_type = 'counter'
def __init__(self):
self._value = 0.0
self._lock = Lock()
def inc(self, amount=1):
'''Increment counter by the given amount.'''
if amount < 0:
raise ValueError('Counters can only be incremented by non-negative amounts.')
with self._lock:
self._value += amount
def count_exceptions(self, exception=Exception):
'''Count exceptions in a block of code or function.
Can be used as a function decorator or context manager.
Increments the counter when an exception of the given
type is raised up out of the code.
'''
class ExceptionCounter(object):
def __init__(self, counter):
self._counter = counter
def __enter__(self): pass
def __exit__(self, typ, value, traceback):
if isinstance(value, exception):
self._counter.inc()
def __call__(self, f):
@wraps(f)
def wrapped(*args, **kwargs):
with self:
return f(*args, **kwargs)
return wrapped
return ExceptionCounter(self)
def _samples(self):
with self._lock:
return (('', {}, self._value), )
@_MetricWrapper
class Gauge(object):
_type = 'gauge'
def __init__(self):
self._value = 0.0
self._lock = Lock()
def inc(self, amount=1):
'''Increment gauge by the given amount.'''
with self._lock:
self._value += amount
def dec(self, amount=1):
'''Decrement gauge by the given amount.'''
with self._lock:
self._value -= amount
def set(self, value):
'''Set gauge to the given value.'''
with self._lock:
self._value = float(value)
def set_to_current_time(self):
'''Set gauge to the current unixtime.'''
self.set(time.time())
def track_inprogress(self):
'''Track inprogress blocks of code or functions.
Can be used as a function decorator or context manager.
Increments the gauge when the code is entered,
and decrements when it is exited.
'''
class InprogressTracker(object):
def __init__(self, gauge):
self._gauge = gauge
def __enter__(self):
self._gauge.inc()
def __exit__(self, typ, value, traceback):
self._gauge.dec()
def __call__(self, f):
@wraps(f)
def wrapped(*args, **kwargs):
with self:
return f(*args, **kwargs)
return wrapped
return InprogressTracker(self)
def _samples(self):
with self._lock:
return (('', {}, self._value), )
@_MetricWrapper
class Summary(object):
_type = 'summary'
def __init__(self):
self._count = 0.0
self._sum = 0.0
self._lock = Lock()
def observe(self, amount):
'''Observe the given amount.'''
with self._lock:
self._count += 1
self._sum += amount
def time(self):
'''Time a block of code or function, and observe the duration in seconds.
Can be used as a function decorator or context manager.
'''
class Timer(object):
def __init__(self, summary):
self._summary = summary
def __enter__(self):
self._start = time.time()
def __exit__(self, typ, value, traceback):
# Time can go backwards.
self._summary.observe(max(time.time() - self._start, 0))
def __call__(self, f):
@wraps(f)
def wrapped(*args, **kwargs):
with self:
return f(*args, **kwargs)
return wrapped
return Timer(self)
def _samples(self):
with self._lock:
return (
('_count', {}, self._count),
('_sum', {}, self._sum))
CONTENT_TYPE_LATEST = 'text/plain; version=0.0.4; charset=utf-8'
'''Content type of the latest text format'''
def generate_latest(registry=REGISTRY):
'''Returns the metrics from the registry in latest text format as a string.'''
output = []
for metric in registry.collect():
output.append('# HELP {0} {1}'.format(
metric._name, metric._documentation.replace('\\', r'\\').replace('\n', r'\n')))
output.append('\n# TYPE {0} {1}\n'.format(metric._name, metric._type))
for name, labels, value in metric._samples:
if labels:
labelstr = '{{{0}}}'.format(','.join(
['{0}="{1}"'.format(
k, v.replace('\\', r'\\').replace('\n', r'\n').replace('\'', r'\''))
for k, v in labels.items()]))
else:
labelstr = ''
output.append('{0}{1} {2}\n'.format(name, labelstr, value))
return ''.join(output).encode('utf-8')
class MetricsHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-Type', CONTENT_TYPE_LATEST)
self.end_headers()
self.wfile.write(generate_latest(REGISTRY))
def write_to_textfile(path, registry):
'''Write metrics to the given path.
This is intended for use with the Node exporter textfile collector.
The path must end in .prom for the textfile collector to process it.'''
tmppath = '%s.%s.%s' % (path, os.getpid(), threading.current_thread().ident)
with open(tmppath, 'wb') as f:
f.write(generate_latest(registry))
# rename(2) is atomic.
os.rename(tmppath, path)
if __name__ == '__main__':
c = Counter('cc', 'A counter')
c.inc()
g = Gauge('gg', 'A gauge')
g.set(17)
s = Summary('ss', 'A summary', ['a', 'b'])
s.labels('c', 'd').observe(17)
from BaseHTTPServer import HTTPServer
server_address = ('', 8000)
httpd = HTTPServer(server_address, MetricsHandler)
httpd.serve_forever()