blob: 5256b0042c0580b2e19a305cbcbacf326829637f [file] [log] [blame]
Shad Ansari7e28dc62022-06-07 13:43:22 -07001"""
2SPDX-FileCopyrightText: 2020-present Intel Corporation
3SPDX-FileCopyrightText: 2020-present Open Networking Foundation <info@opennetworking.org>
4SPDX-License-Identifier: LicenseRef-ONF-Member-1.01
5"""
Shad Ansari467862f2022-02-08 00:40:40 +00006
7import os
8import time
Shad Ansari0a905032022-02-10 19:37:15 +00009from prometheus_client import start_http_server, Gauge, REGISTRY, PROCESS_COLLECTOR, PLATFORM_COLLECTOR
Shad Ansari467862f2022-02-08 00:40:40 +000010import requests
11import json
12
Shad Ansari0a905032022-02-10 19:37:15 +000013REGISTRY.unregister(PROCESS_COLLECTOR)
14REGISTRY.unregister(PLATFORM_COLLECTOR)
15# Unlike process and platform_collector gc_collector registers itself as three different collectors that have no corresponding public named variable.
16REGISTRY.unregister(REGISTRY._names_to_collectors['python_gc_objects_collected_total'])
17#REGISTRY.unregister(REGISTRY._names_to_collectors['python_gc_uncollectable_objects_sum'])
18#REGISTRY.unregister(REGISTRY._names_to_collectors['python_gc_collected_objects_sum'])
19
Shad Ansari467862f2022-02-08 00:40:40 +000020class Metrics:
21 def __init__(self, app_port=3333, polling_interval_seconds=5):
22 self.app_port = app_port
23 self.polling_interval_seconds = polling_interval_seconds
24
25 self.num_configured_devices = Gauge("num_configured_devices", "Number of configured devices")
Shad Ansari6292c452022-02-08 17:39:06 +000026 self.num_reachable_devices = Gauge("num_reachable_devices", "Number of reachable devices")
Shad Ansari467862f2022-02-08 00:40:40 +000027
28 def run_metrics_loop(self):
29 while True:
30 self.fetch()
31 time.sleep(self.polling_interval_seconds)
32
33 def fetch(self):
34 resp = requests.get(url=f"http://localhost:{self.app_port}/devices")
Shad Ansari6292c452022-02-08 17:39:06 +000035 self.num_configured_devices.set(len(json.loads(resp.text)))
Shad Ansari467862f2022-02-08 00:40:40 +000036
37 resp = requests.get(url=f"http://localhost:{self.app_port}/devices/reachable")
Shad Ansari6292c452022-02-08 17:39:06 +000038 self.num_reachable_devices.set(len(json.loads(resp.text)))
Shad Ansari467862f2022-02-08 00:40:40 +000039
40def main():
41 polling_interval_seconds = int(os.getenv("POLLING_INTERVAL_SECONDS", "5"))
42 app_port = int(os.getenv("APP_PORT", "3333"))
43 exporter_port = int(os.getenv("EXPORTER_PORT", "4444"))
44
45 app_metrics = Metrics(
46 app_port=app_port,
47 polling_interval_seconds=polling_interval_seconds
48 )
49 start_http_server(exporter_port)
50 app_metrics.run_metrics_loop()
51
52if __name__ == "__main__":
53 main()