| 46 | |
| 47 | |
| 48 | class GraphiteBridge: |
| 49 | def __init__(self, |
| 50 | address: Tuple[str, int], |
| 51 | registry: Collector = 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() |