Skip to content

Commit

Permalink
[deco] use DeleteLabelValues properly with a caching solution to remo…
Browse files Browse the repository at this point in the history
…ve defunct metrics
  • Loading branch information
DictumMortuum committed Oct 5, 2024
1 parent abc444c commit ed48ebe
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 11 deletions.
1 change: 0 additions & 1 deletion cmd/file-exporter/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ func readFiles() error {
return nil
}

fmt.Printf("visited file or dir: %q\n", path)
err = processFile(path)
if err != nil {
return err
Expand Down
15 changes: 10 additions & 5 deletions cmd/file-exporter/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (

func Version(c *gin.Context) {
rs := map[string]any{
"version": "v0.0.8",
"version": "v0.0.9",
}
c.AbortWithStatusJSON(200, rs)
}
Expand All @@ -32,7 +32,9 @@ func livenessHandler() http.HandlerFunc {
func Metrics() http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
for key := range global_labels {
global_labels[key] = false
tmp := global_labels[key]
tmp.Valid = false
global_labels[key] = tmp
}

err := readFiles()
Expand All @@ -43,9 +45,12 @@ func Metrics() http.HandlerFunc {
}

for key, val := range global_labels {
log.Println(key, val)
if !val {
global_metrics[key].Reset()
if !val.Valid {
ok := global_metrics[key].DeleteLabelValues(val.Labels...)
if ok {
delete(global_metrics, key)
delete(global_labels, key)
}
}
}

Expand Down
25 changes: 20 additions & 5 deletions cmd/file-exporter/metrics.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
package main

import (
"errors"
"strings"

"github.com/DictumMortuum/servus-extapi/pkg/util"
"github.com/prometheus/client_golang/prometheus"
)

type CachedLabels struct {
Labels []string
Valid bool
}

var (
global_labels = map[string]bool{}
global_labels = map[string]CachedLabels{}
global_metrics = map[string]*prometheus.MetricVec{}
)

Expand Down Expand Up @@ -36,10 +42,19 @@ func toMetric(raw string) error {
)

val := util.Atof(raw_val)
prometheus.Unregister(metric)
prometheus.MustRegister(metric)
global_labels[key_name+"_"+key_namespace] = true
global_metrics[key_name+"_"+key_namespace] = metric.MetricVec
are := &prometheus.AlreadyRegisteredError{}
err := prometheus.Register(metric)
if errors.As(err, are) {
metric = are.ExistingCollector.(*prometheus.GaugeVec)
} else if err != nil {
return err
}
// prometheus.MustRegister(metric)
global_labels[s[0]] = CachedLabels{
Valid: true,
Labels: vals,
}
global_metrics[s[0]] = metric.MetricVec
metric.WithLabelValues(vals...).Set(val)

return nil
Expand Down

0 comments on commit ed48ebe

Please sign in to comment.