Skip to content

Commit 43739e6

Browse files
committed
[metric-config] Add fill metric configuration migration
1 parent ebc41fe commit 43739e6

File tree

2 files changed

+64
-32
lines changed

2 files changed

+64
-32
lines changed

openwisp_monitoring/monitoring/migrations/0014_merge_traffic_metrics.py

Lines changed: 0 additions & 32 deletions
This file was deleted.
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
from django.db import migrations
2+
from swapper import load_model
3+
4+
5+
metric_mapping = {
6+
'reachable': 'ping',
7+
'rx_bytes': 'traffic',
8+
'clients': 'clients',
9+
'used_disk': 'disk',
10+
'percent_used': 'memory',
11+
'cpu_usage': 'cpu',
12+
}
13+
14+
15+
def merge_traffic_metrics(apps, schema_editor):
16+
Metric = load_model('monitoring', 'Metric')
17+
Chart = load_model('monitoring', 'Chart')
18+
rx_metrics = Metric.objects.filter(field_name='rx_bytes')
19+
for rx_metric in rx_metrics:
20+
if rx_metric.name.split()[1] == 'traffic':
21+
return
22+
# Traffic chart is created with tx_bytes metric
23+
tx_metric = Metric.objects.get(name=f'{rx_metric.name.split()[0]} tx_bytes')
24+
if tx_metric.chart_set.count():
25+
chart = Chart.objects.get(metric=tx_metric)
26+
new_name = f'{rx_metric.name.split()[0]} traffic'
27+
print(f'Renamed metric "{rx_metric.name}" to "{new_name}"')
28+
rx_metric.name = new_name
29+
rx_metric.save()
30+
chart.metric = rx_metric
31+
chart.save()
32+
tx_metric.delete()
33+
34+
35+
def find_metric_configuration(field_name):
36+
try:
37+
value = metric_mapping[field_name]
38+
return value
39+
except KeyError:
40+
print(f'No metric configuration found for "{field_name}"')
41+
42+
43+
def fill_configuration(apps, schema_editor):
44+
Metric = apps.get_model('monitoring', 'Metric')
45+
for metric in Metric.objects.all():
46+
metric.configuration = find_metric_configuration(metric.field_name)
47+
metric.full_clean()
48+
metric.save()
49+
50+
51+
class Migration(migrations.Migration):
52+
53+
dependencies = [
54+
('monitoring', '0013_metric_configuration'),
55+
]
56+
57+
operations = [
58+
migrations.RunPython(
59+
merge_traffic_metrics, reverse_code=migrations.RunPython.noop
60+
),
61+
migrations.RunPython(
62+
fill_configuration, reverse_code=migrations.RunPython.noop
63+
),
64+
]

0 commit comments

Comments
 (0)