-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcollector.go
70 lines (57 loc) · 1.69 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
package ristretto_prometheus
import (
"errors"
"github.com/dgraph-io/ristretto/v2"
"github.com/prometheus/client_golang/prometheus"
)
var ErrDuplicateMetricName = errors.New("duplicate metric name")
// Collector implements the prometheus.Collector interface.
var _ prometheus.Collector = (*Collector)(nil)
type Collector struct {
source *ristretto.Metrics
// metrics contains all descriptions to be registered on a
// Prometheus metrics registry for the Ristretto cache.
metrics []metric
}
type metric struct {
desc *prometheus.Desc
valueType prometheus.ValueType
extractor MetricValueExtractor
}
// NewMetricsCollector returns a Prometheus metrics collector using metrics from the
// given provider.
func NewMetricsCollector(source *ristretto.Metrics, opts ...Option) (*Collector, error) {
var conf config
conf.apply(opts)
uniqFQNames := make(map[string]struct{})
metrics := make([]metric, 0, len(conf.metrics))
for _, c := range conf.metrics {
fqName := prometheus.BuildFQName(conf.namespace, conf.subsystem, c.Name)
if _, ok := uniqFQNames[fqName]; ok {
return nil, ErrDuplicateMetricName
}
uniqFQNames[fqName] = struct{}{}
metrics = append(metrics, metric{
desc: prometheus.NewDesc(fqName, c.Help, nil, conf.constLabels),
valueType: c.ValueType,
extractor: c.Extractor,
})
}
return &Collector{
source: source,
metrics: metrics,
}, nil
}
func (c Collector) Describe(ch chan<- *prometheus.Desc) {
for _, m := range c.metrics {
ch <- m.desc
}
}
func (c Collector) Collect(ch chan<- prometheus.Metric) {
if c.source == nil {
return
}
for _, m := range c.metrics {
ch <- prometheus.MustNewConstMetric(m.desc, m.valueType, m.extractor(c.source))
}
}