/
collector.go
67 lines (58 loc) · 1.96 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
package prometheus
import (
"fmt"
"time"
gocache "github.com/patrickmn/go-cache"
"github.com/prometheus/client_golang/prometheus"
"github.com/torilabs/mqtt-prometheus-exporter/config"
"github.com/torilabs/mqtt-prometheus-exporter/log"
"go.uber.org/zap"
)
// Collector is an extended interface of prometheus.Collector.
type Collector interface {
prometheus.Collector
Observe(metric config.Metric, topic string, v float64, labelValues ...string)
}
type memoryCachedCollector struct {
cache *gocache.Cache
descriptions []*prometheus.Desc
}
type collectorEntry struct {
m prometheus.Metric
ts time.Time
}
// NewCollector constructs collector for incoming prometheus metrics.
func NewCollector(expiration time.Duration, possibleMetrics []config.Metric) Collector {
if len(possibleMetrics) == 0 {
log.Logger.Warn("No metrics are configured.")
}
var descs []*prometheus.Desc
for _, m := range possibleMetrics {
descs = append(descs, m.PrometheusDescription())
}
return &memoryCachedCollector{
cache: gocache.New(expiration, expiration*10),
descriptions: descs,
}
}
func (c *memoryCachedCollector) Observe(metric config.Metric, topic string, v float64, labelValues ...string) {
m, err := prometheus.NewConstMetric(metric.PrometheusDescription(), metric.PrometheusValueType(), v, labelValues...)
if err != nil {
log.Logger.With(zap.Error(err)).Warnf("Creation of prometheus metric failed.")
return
}
key := fmt.Sprintf("%s|%s", metric.PrometheusName, topic)
c.cache.SetDefault(key, &collectorEntry{m: m, ts: time.Now()})
}
func (c *memoryCachedCollector) Describe(ch chan<- *prometheus.Desc) {
for i := range c.descriptions {
ch <- c.descriptions[i]
}
}
func (c *memoryCachedCollector) Collect(mc chan<- prometheus.Metric) {
log.Logger.Debugf("Collecting. Returned '%d' metrics.", c.cache.ItemCount())
for _, rawItem := range c.cache.Items() {
item := rawItem.Object.(*collectorEntry)
mc <- prometheus.NewMetricWithTimestamp(item.ts, item.m)
}
}