forked from buildkite/buildkite-agent-metrics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprometheus.go
More file actions
92 lines (78 loc) · 2.11 KB
/
Copy pathprometheus.go
File metadata and controls
92 lines (78 loc) · 2.11 KB
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
package backend
import (
"fmt"
"log"
"net/http"
"regexp"
"strings"
"github.com/buildkite/buildkite-agent-metrics/collector"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
camel = regexp.MustCompile("(^[^A-Z0-9]*|[A-Z0-9]*)([A-Z0-9][^A-Z]+|$)")
)
type Prometheus struct {
totals map[string]prometheus.Gauge
queues map[string]*prometheus.GaugeVec
pipelines map[string]*prometheus.GaugeVec
}
func NewPrometheusBackend(path, addr string) *Prometheus {
go func() {
http.Handle(path, promhttp.Handler())
log.Fatal(http.ListenAndServe(addr, nil))
}()
return newPrometheus()
}
func newPrometheus() *Prometheus {
return &Prometheus{
totals: make(map[string]prometheus.Gauge),
queues: make(map[string]*prometheus.GaugeVec),
pipelines: make(map[string]*prometheus.GaugeVec),
}
}
func (p *Prometheus) Collect(r *collector.Result) error {
// Clear the gauges to prevent stale values from persisting forever.
for _, gauge := range p.queues {
gauge.Reset()
}
for name, value := range r.Totals {
gauge, ok := p.totals[name]
if !ok {
gauge = prometheus.NewGauge(prometheus.GaugeOpts{
Name: fmt.Sprintf("buildkite_total_%s", camelToUnderscore(name)),
Help: fmt.Sprintf("Buildkite Total: %s", name),
})
prometheus.MustRegister(gauge)
p.totals[name] = gauge
}
gauge.Set(float64(value))
}
for queue, counts := range r.Queues {
for name, value := range counts {
gauge, ok := p.queues[name]
if !ok {
gauge = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: fmt.Sprintf("buildkite_queues_%s", camelToUnderscore(name)),
Help: fmt.Sprintf("Buildkite Queues: %s", name),
}, []string{"queue"})
prometheus.MustRegister(gauge)
p.queues[name] = gauge
}
gauge.WithLabelValues(queue).Set(float64(value))
}
}
return nil
}
func camelToUnderscore(s string) string {
var a []string
for _, sub := range camel.FindAllStringSubmatch(s, -1) {
if sub[1] != "" {
a = append(a, sub[1])
}
if sub[2] != "" {
a = append(a, sub[2])
}
}
return strings.ToLower(strings.Join(a, "_"))
}