-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
85 lines (72 loc) · 2.49 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"""
Utility functions
"""
from dataclasses import dataclass
from typing import List, Dict, Iterator
from prometheus_client import Metric
@dataclass
class SensorData:
"""
Storage for a single sensor's data
"""
sensor_id: str
last_read: int
meta: Dict[str, str]
metrics: Dict[str, str]
# pylint:disable=too-few-public-methods
class SensorsDataCollector:
"""
Converts SensorData dataclasses into Prometheus Metrics
"""
def __init__(self, sensors_data: List[SensorData], prefix: str):
self.sensors_data = sensors_data
self.prefix = prefix
def collect(self) -> Iterator[Metric]:
"""
Do the conversion
"""
# Metric(name, documentation, typ, unit)
#
# system information metric
metric = Metric(
name=f'{self.prefix}info', documentation='Information about the sensor.', typ='gauge')
for sensor in self.sensors_data:
metric.add_sample(name=f'{self.prefix}info', value=1, labels={
'sensor_id': sensor.sensor_id,
'software': sensor.meta.get('software_version', '')
})
yield metric
# last measurement metric
metric = Metric(
name=f'{self.prefix}last_measurement',
documentation='When was the most recent data received.',
typ='gauge',
unit='timestamp'
)
for sensor in self.sensors_data:
metric.add_sample(
name=f'{self.prefix}last_measurement',
value=sensor.last_read,
labels={
'sensor_id': sensor.sensor_id,
})
yield metric
# sensors data
# iterate through all metrics
sensors_metrics = []
for sensor in self.sensors_data:
sensors_metrics += sensor.metrics.keys()
for metric_name in sorted(set(sensors_metrics)):
metric = Metric(
name=f'{self.prefix}{metric_name}',
documentation=f'{metric_name} metric from airrohr.',
typ='gauge'
)
for sensor in self.sensors_data:
if (value := sensor.metrics.get(metric_name)) is not None:
metric.add_sample(
name=f'{self.prefix}{metric_name}', value=value,
timestamp=sensor.last_read, labels={
'sensor_id': sensor.sensor_id,
})
yield metric