include prometheus metrics, refs #200

This commit is contained in:
Jakob Ketterl 2021-02-01 18:43:14 +01:00
parent 998092f377
commit 5e1c4391c6
3 changed files with 28 additions and 3 deletions

View File

@ -1,9 +1,30 @@
from . import Controller from . import Controller
from owrx.metrics import Metrics from owrx.metrics import CounterMetric, DirectMetric, Metrics
import json import json
class MetricsController(Controller): class MetricsController(Controller):
def indexAction(self): def indexAction(self):
data = json.dumps(Metrics.getSharedInstance().getMetrics()) data = json.dumps(Metrics.getSharedInstance().getHierarchicalMetrics())
self.send_response(data, content_type="application/json") self.send_response(data, content_type="application/json")
def prometheusAction(self):
metrics = Metrics.getSharedInstance().getFlatMetrics()
def prometheusFormat(key, metric):
value = metric.getValue()
if isinstance(metric, CounterMetric):
key += "_total"
value = value["count"]
elif isinstance(metric, DirectMetric):
pass
else:
raise ValueError("Unexpected metric type for metric {}".format(repr(metric)))
return "{key} {value}".format(key=key.replace(".", "_"), value=value)
data = ["# https://prometheus.io/docs/instrumenting/exposition_formats/"] + [
prometheusFormat(k, v) for k, v in metrics.items()
]
self.send_response("\n".join(data), content_type="text/plain; version=0.0.4")

View File

@ -98,6 +98,7 @@ class Router(object):
StaticRoute("/features", FeatureController), StaticRoute("/features", FeatureController),
StaticRoute("/api/features", ApiController), StaticRoute("/api/features", ApiController),
StaticRoute("/api/receiverdetails", ApiController, options={"action": "receiverDetails"}), StaticRoute("/api/receiverdetails", ApiController, options={"action": "receiverDetails"}),
StaticRoute("/metrics", MetricsController, options={"action": "prometheusAction"}),
StaticRoute("/metrics.json", MetricsController), StaticRoute("/metrics.json", MetricsController),
StaticRoute("/settings", SettingsController), StaticRoute("/settings", SettingsController),
StaticRoute("/generalsettings", GeneralSettingsController), StaticRoute("/generalsettings", GeneralSettingsController),

View File

@ -52,7 +52,10 @@ class Metrics(object):
return None return None
return self.metrics[name] return self.metrics[name]
def getMetrics(self): def getFlatMetrics(self):
return self.metrics
def getHierarchicalMetrics(self):
result = {} result = {}
for (key, metric) in self.metrics.items(): for (key, metric) in self.metrics.items():