forked from raystack/optimus
-
Notifications
You must be signed in to change notification settings - Fork 1
/
prometheus.go
80 lines (65 loc) · 1.93 KB
/
prometheus.go
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
package telemetry
import (
"sort"
"sync"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/push"
"github.com/prometheus/common/expfmt"
)
var (
counterMetricMap = map[string]prometheus.Counter{}
counterMetricMutex = sync.Mutex{}
gaugeMetricMap = map[string]prometheus.Gauge{}
gaugeMetricMutex = sync.Mutex{}
MetricServer string
)
const metricsPushJob = "optimus_push"
func getKey(metric string, labels map[string]string) string {
eventMetricKey := metric
keys := make([]string, 0, len(labels))
for k := range labels {
keys = append(keys, k)
}
sort.Strings(keys)
for _, key := range keys {
eventMetricKey += "/" + key + ":" + labels[key]
}
return eventMetricKey
}
func NewCounter(metric string, labels map[string]string) prometheus.Counter {
metricKey := getKey(metric, labels)
counterMetricMutex.Lock()
defer counterMetricMutex.Unlock()
if existingMetric, ok := counterMetricMap[metricKey]; ok {
return existingMetric
}
newMetric := promauto.NewCounter(prometheus.CounterOpts{Name: metric, ConstLabels: labels})
counterMetricMap[metricKey] = newMetric
return newMetric
}
func SetGaugeViaPush(name string, labels map[string]string, val float64) error {
if MetricServer == "" {
return nil
}
metric := prometheus.NewGauge(prometheus.GaugeOpts{
Name: name,
ConstLabels: labels,
})
metric.Set(val)
return push.New(MetricServer, metricsPushJob).
Format(expfmt.FmtText).
Collector(metric).
Push()
}
func NewGauge(metric string, labels map[string]string) prometheus.Gauge {
metricKey := getKey(metric, labels)
gaugeMetricMutex.Lock()
defer gaugeMetricMutex.Unlock()
if existingMetric, ok := gaugeMetricMap[metricKey]; ok {
return existingMetric
}
newMetric := promauto.NewGauge(prometheus.GaugeOpts{Name: metric, ConstLabels: labels})
gaugeMetricMap[metricKey] = newMetric
return newMetric
}