Debian Codegraph @

prometheus_client/bridge/graphite.py

raw symbols SCIP
1 #!/usr/bin/env python
2
3 import logging
4 import re
5 import socket
6 import threading
7 import time
8 from timeit import default_timer
9 from typing import Callable, Tuple
10
11 from ..registry import CollectorRegistry, REGISTRY
12
13 # Roughly, have to keep to what works as a file name.
14 # We also remove periods, so labels can be distinguished.
15
16 _INVALID_GRAPHITE_CHARS = re.compile(r"[^a-zA-Z0-9_-]")
17
18
19 def _sanitize(s):
20 return _INVALID_GRAPHITE_CHARS.sub('_', s)
21
22
23 class _RegularPush(threading.Thread):
24 def __init__(self, pusher, interval, prefix):
25 super().__init__()
26 self._pusher = pusher
27 self._interval = interval
28 self._prefix = prefix
29
30 def run(self):
31 wait_until = default_timer()
32 while True:
33 while True:
34 now = default_timer()
35 if now >= wait_until:
36 # May need to skip some pushes.
37 while wait_until < now:
38 wait_until += self._interval
39 break
40 # time.sleep can return early.
41 time.sleep(wait_until - now)
42 try:
43 self._pusher.push(prefix=self._prefix)
44 except OSError:
45 logging.exception("Push failed")
46
47
48 class GraphiteBridge:
49 def __init__(self,
50 address: Tuple[str, int],
51 registry: CollectorRegistry = REGISTRY,
52 timeout_seconds: float = 30,
53 _timer: Callable[[], float] = time.time,
54 tags: bool = False,
55 ):
56 self._address = address
57 self._registry = registry
58 self._tags = tags
59 self._timeout = timeout_seconds
60 self._timer = _timer
61
62 def push(self, prefix: str = '') -> None:
63 now = int(self._timer())
64 output = []
65
66 prefixstr = ''
67 if prefix:
68 prefixstr = prefix + '.'
69
70 for metric in self._registry.collect():
71 for s in metric.samples:
72 if s.labels:
73 if self._tags:
74 sep = ';'
75 fmt = '{0}={1}'
76 else:
77 sep = '.'
78 fmt = '{0}.{1}'
79 labelstr = sep + sep.join(
80 [fmt.format(
81 _sanitize(k), _sanitize(v))
82 for k, v in sorted(s.labels.items())])
83 else:
84 labelstr = ''
85 output.append(f'{prefixstr}{_sanitize(s.name)}{labelstr} {float(s.value)} {now}\n')
86
87 conn = socket.create_connection(self._address, self._timeout)
88 conn.sendall(''.join(output).encode('ascii'))
89 conn.close()
90
91 def start(self, interval: float = 60.0, prefix: str = '') -> None:
92 t = _RegularPush(self, interval, prefix)
93 t.daemon = True
94 t.start()