Shad Ansari | 467862f | 2022-02-08 00:40:40 +0000 | [diff] [blame] | 1 | """network-diag-app exporter""" |
| 2 | |
| 3 | import os |
| 4 | import time |
Shad Ansari | 0a90503 | 2022-02-10 19:37:15 +0000 | [diff] [blame] | 5 | from prometheus_client import start_http_server, Gauge, REGISTRY, PROCESS_COLLECTOR, PLATFORM_COLLECTOR |
Shad Ansari | 467862f | 2022-02-08 00:40:40 +0000 | [diff] [blame] | 6 | import requests |
| 7 | import json |
| 8 | |
Shad Ansari | 0a90503 | 2022-02-10 19:37:15 +0000 | [diff] [blame] | 9 | REGISTRY.unregister(PROCESS_COLLECTOR) |
| 10 | REGISTRY.unregister(PLATFORM_COLLECTOR) |
| 11 | # Unlike process and platform_collector gc_collector registers itself as three different collectors that have no corresponding public named variable. |
| 12 | REGISTRY.unregister(REGISTRY._names_to_collectors['python_gc_objects_collected_total']) |
| 13 | #REGISTRY.unregister(REGISTRY._names_to_collectors['python_gc_uncollectable_objects_sum']) |
| 14 | #REGISTRY.unregister(REGISTRY._names_to_collectors['python_gc_collected_objects_sum']) |
| 15 | |
Shad Ansari | 467862f | 2022-02-08 00:40:40 +0000 | [diff] [blame] | 16 | class Metrics: |
| 17 | def __init__(self, app_port=3333, polling_interval_seconds=5): |
| 18 | self.app_port = app_port |
| 19 | self.polling_interval_seconds = polling_interval_seconds |
| 20 | |
| 21 | self.num_configured_devices = Gauge("num_configured_devices", "Number of configured devices") |
Shad Ansari | 6292c45 | 2022-02-08 17:39:06 +0000 | [diff] [blame] | 22 | self.num_reachable_devices = Gauge("num_reachable_devices", "Number of reachable devices") |
Shad Ansari | 467862f | 2022-02-08 00:40:40 +0000 | [diff] [blame] | 23 | |
| 24 | def run_metrics_loop(self): |
| 25 | while True: |
| 26 | self.fetch() |
| 27 | time.sleep(self.polling_interval_seconds) |
| 28 | |
| 29 | def fetch(self): |
| 30 | resp = requests.get(url=f"http://localhost:{self.app_port}/devices") |
Shad Ansari | 6292c45 | 2022-02-08 17:39:06 +0000 | [diff] [blame] | 31 | self.num_configured_devices.set(len(json.loads(resp.text))) |
Shad Ansari | 467862f | 2022-02-08 00:40:40 +0000 | [diff] [blame] | 32 | |
| 33 | resp = requests.get(url=f"http://localhost:{self.app_port}/devices/reachable") |
Shad Ansari | 6292c45 | 2022-02-08 17:39:06 +0000 | [diff] [blame] | 34 | self.num_reachable_devices.set(len(json.loads(resp.text))) |
Shad Ansari | 467862f | 2022-02-08 00:40:40 +0000 | [diff] [blame] | 35 | |
| 36 | def main(): |
| 37 | polling_interval_seconds = int(os.getenv("POLLING_INTERVAL_SECONDS", "5")) |
| 38 | app_port = int(os.getenv("APP_PORT", "3333")) |
| 39 | exporter_port = int(os.getenv("EXPORTER_PORT", "4444")) |
| 40 | |
| 41 | app_metrics = Metrics( |
| 42 | app_port=app_port, |
| 43 | polling_interval_seconds=polling_interval_seconds |
| 44 | ) |
| 45 | start_http_server(exporter_port) |
| 46 | app_metrics.run_metrics_loop() |
| 47 | |
| 48 | if __name__ == "__main__": |
| 49 | main() |