From e5f7d7fb6fc13eb4181bd304fd6313cd72ba9cc1 Mon Sep 17 00:00:00 2001 From: Vilhelm Prytz Date: Fri, 14 Jul 2023 12:16:30 +0200 Subject: [PATCH] bug: only prometheus.Unregister when labels change/num metric change --- areca_exporter.go | 51 ++++++++++++++++++++++++++++++----------------- 1 file changed, 33 insertions(+), 18 deletions(-) diff --git a/areca_exporter.go b/areca_exporter.go index 3a25d80..1a796c2 100644 --- a/areca_exporter.go +++ b/areca_exporter.go @@ -200,6 +200,20 @@ func getDiskInfo() []map[string]string { return disks } +func regRsfMetric(rsf_info map[string]string) prometheus.Gauge { + raidSet := promauto.NewGauge(prometheus.GaugeOpts{ + Name: "areca_raid_set_state", + Help: "Areca raid set state, 0 for normal, 1 for degraded", + ConstLabels: prometheus.Labels(rsf_info), + }) + if rsf_info["state"] == "Normal" { + raidSet.Set(0) + } else { + raidSet.Set(1) + } + return raidSet +} + func recordMetrics() { arecaSysInfo.Set(1) arecaRsfInfoUp.Set(0) @@ -218,29 +232,30 @@ func recordMetrics() { // get new disk info disk_info := getDiskInfo() - // delete all metrics in raidSetGauges and diskGauges - for _, g := range raidSetGauges { - prometheus.Unregister(g) + // if same amount of raid sets, then just update the labels if changed + if len(raidSetGauges) == len(rsf_info) { + for i, g := range raidSetGauges { + rsf_desc := prometheus.NewDesc("areca_raid_set_state", "Areca raid set state, 0 for normal, 1 for degraded", nil, prometheus.Labels(rsf_info[i])) + if rsf_desc != g.Desc() { + prometheus.Unregister(g) + raidSetGauges[i] = regRsfMetric(rsf_info[i]) + } + } + } else { + // unregister all and re-register all + for _, g := range raidSetGauges { + prometheus.Unregister(g) + } + raidSetGauges = nil + for _, m := range rsf_info { + raidSetGauges = append(raidSetGauges, regRsfMetric(m)) + } } + for _, g := range diskGauges { prometheus.Unregister(g) } - // create new gauges for each rsf - for _, m := range rsf_info { - raidSet := promauto.NewGauge(prometheus.GaugeOpts{ - Name: "areca_raid_set_state", - Help: "Areca raid set state, 0 for normal, 1 for degraded", - ConstLabels: prometheus.Labels(m), - }) - if m["state"] == "Normal" { - raidSet.Set(0) - } else { - raidSet.Set(1) - } - raidSetGauges = append(raidSetGauges, raidSet) - } - for _, m := range disk_info { disk := promauto.NewGauge(prometheus.GaugeOpts{ Name: "areca_disk_info",