Shad Ansari | 467862f | 2022-02-08 00:40:40 +0000 | [diff] [blame^] | 1 | """network-diag-app exporter""" |
| 2 | |
| 3 | import os |
| 4 | import time |
| 5 | from prometheus_client import start_http_server, Gauge |
| 6 | import requests |
| 7 | import json |
| 8 | |
| 9 | class Metrics: |
| 10 | def __init__(self, app_port=3333, polling_interval_seconds=5): |
| 11 | self.app_port = app_port |
| 12 | self.polling_interval_seconds = polling_interval_seconds |
| 13 | |
| 14 | self.num_configured_devices = Gauge("num_configured_devices", "Number of configured devices") |
| 15 | self.num_configured_devices = Gauge("num_reachable_devices", "Number of reachable devices") |
| 16 | |
| 17 | def run_metrics_loop(self): |
| 18 | while True: |
| 19 | self.fetch() |
| 20 | time.sleep(self.polling_interval_seconds) |
| 21 | |
| 22 | def fetch(self): |
| 23 | resp = requests.get(url=f"http://localhost:{self.app_port}/devices") |
| 24 | self.num_configured_devices = len(json.loads(resp.text)) |
| 25 | |
| 26 | resp = requests.get(url=f"http://localhost:{self.app_port}/devices/reachable") |
| 27 | self.num_configured_devices = len(json.loads(resp.text)) |
| 28 | |
| 29 | def main(): |
| 30 | polling_interval_seconds = int(os.getenv("POLLING_INTERVAL_SECONDS", "5")) |
| 31 | app_port = int(os.getenv("APP_PORT", "3333")) |
| 32 | exporter_port = int(os.getenv("EXPORTER_PORT", "4444")) |
| 33 | |
| 34 | app_metrics = Metrics( |
| 35 | app_port=app_port, |
| 36 | polling_interval_seconds=polling_interval_seconds |
| 37 | ) |
| 38 | start_http_server(exporter_port) |
| 39 | app_metrics.run_metrics_loop() |
| 40 | |
| 41 | if __name__ == "__main__": |
| 42 | main() |