Skip to content

Commit fc126e6

Browse files
committed
replace map in prometheus with sync.Map
1 parent bee3061 commit fc126e6

File tree

1 file changed

+10
-7
lines changed

1 file changed

+10
-7
lines changed

dnstap_prometheus_output.go

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ package dtap
1919
import (
2020
"context"
2121
"strings"
22+
"sync"
2223
"time"
2324

2425
log "github.com/sirupsen/logrus"
@@ -42,7 +43,7 @@ type DnstapPrometheusOutputMetrics struct {
4243
Name string
4344
Vec *prometheus.CounterVec
4445
LabelKeys []string
45-
LabelValues map[string]*DnstapPrometheusOutputMetricsValues
46+
LabelValues sync.Map // map[string]*DnstapPrometheusOutputMetricsValues
4647
Interval int
4748
Expire int
4849
CancelFunc context.CancelFunc
@@ -75,18 +76,18 @@ func NewDnstapPrometheusOutputMetrics(counterConfig OutputPrometheusMetrics) *Dn
7576
Help: counterConfig.GetHelp(),
7677
}, counterConfig.GetLabels()),
7778
LabelKeys: counterConfig.GetLabels(),
78-
LabelValues: map[string]*DnstapPrometheusOutputMetricsValues{},
79+
LabelValues: sync.Map{},
7980
Expire: counterConfig.GetExpireSec(),
8081
Interval: counterConfig.GetExpireInterval(),
8182
}
8283
}
8384

8485
func (d *DnstapPrometheusOutputMetrics) Inc(values []string) {
8586
d.Vec.WithLabelValues(values...).Inc()
86-
d.LabelValues[strings.Join(values, ",")] = &DnstapPrometheusOutputMetricsValues{
87+
d.LabelValues.Store(strings.Join(values, ","), &DnstapPrometheusOutputMetricsValues{
8788
Values: values,
8889
LastUpdate: time.Now(),
89-
}
90+
})
9091
}
9192

9293
func (d *DnstapPrometheusOutputMetrics) Flush(ctx context.Context) {
@@ -96,12 +97,14 @@ func (d *DnstapPrometheusOutputMetrics) Flush(ctx context.Context) {
9697
case <-ctx.Done():
9798
return
9899
case <-ticker.C:
99-
for k, value := range d.LabelValues {
100+
d.LabelValues.Range(func(k, val interface{}) bool {
101+
value := val.(*DnstapPrometheusOutputMetricsValues)
100102
if time.Now().Sub(value.LastUpdate) > time.Second*time.Duration(d.Expire) {
101103
d.Vec.DeleteLabelValues(value.Values...)
102-
delete(d.LabelValues, k)
104+
d.LabelValues.Delete(k)
103105
}
104-
}
106+
return true
107+
})
105108
}
106109
}
107110
}

0 commit comments

Comments
 (0)