/
collector.go
99 lines (81 loc) · 2.28 KB
/
collector.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package operatormetrics
import (
"fmt"
"strings"
"github.com/prometheus/client_golang/prometheus"
)
// Collector registers a prometheus.Collector with a set of metrics in the
// Prometheus registry. The metrics are collected by calling the CollectCallback
// function.
type Collector struct {
// Metrics is a list of metrics to be collected by the collector.
Metrics []Metric
// CollectCallback is a function that returns a list of CollectionResults.
// The CollectionResults are used to populate the metrics in the collector.
CollectCallback func() []CollectorResult
}
type CollectorResult struct {
Metric Metric
Labels []string
ConstLabels map[string]string
Value float64
}
func (c Collector) hash() string {
var sb strings.Builder
for _, cm := range c.Metrics {
sb.WriteString(cm.GetOpts().Name)
}
return sb.String()
}
func (c Collector) Describe(ch chan<- *prometheus.Desc) {
for _, cm := range c.Metrics {
cm.getCollector().Describe(ch)
}
}
func (c Collector) Collect(ch chan<- prometheus.Metric) {
collectedMetrics := c.CollectCallback()
for _, cr := range collectedMetrics {
metric, ok := operatorRegistry.registeredCollectorMetrics[cr.Metric.GetOpts().Name]
if !ok {
fmt.Printf("metric %s not found in registry", cr.Metric.GetOpts().Name)
continue
}
if err := collectValue(ch, metric, cr); err != nil {
fmt.Printf("error collecting metric %s: %v", cr.Metric.GetOpts().Name, err)
}
}
}
func collectValue(ch chan<- prometheus.Metric, metric Metric, cr CollectorResult) error {
var mType prometheus.ValueType
switch metric.GetType() {
case CounterType:
mType = prometheus.CounterValue
case GaugeType:
mType = prometheus.GaugeValue
case CounterVecType:
mType = prometheus.CounterValue
case GaugeVecType:
mType = prometheus.GaugeValue
default:
return fmt.Errorf("encountered unsupported type for collector %v", metric.GetType())
}
labels := map[string]string{}
for k, v := range cr.ConstLabels {
labels[k] = v
}
for k, v := range metric.GetOpts().ConstLabels {
labels[k] = v
}
desc := prometheus.NewDesc(
metric.GetOpts().Name,
metric.GetOpts().Help,
metric.GetOpts().labels,
labels,
)
cm, err := prometheus.NewConstMetric(desc, mType, cr.Value, cr.Labels...)
if err != nil {
return err
}
ch <- cm
return nil
}