-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathstorage_prometheus.go
175 lines (141 loc) · 4.53 KB
/
storage_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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// PrometheusConfig describes the YAML-provided configuration for a Prometheus
// pushgateway storage backend
type PrometheusConfig struct {
ListenAddr string `yaml:"listen-addr"`
Namespace string `yaml:"metric-namespace,omitempty"`
}
// PrometheusStorage holds the configuration for a Graphite storage backend
type PrometheusStorage struct {
ListenAddr string
Namespace string
Registry *prometheus.Registry
RegisteredMetrics map[string]*prometheus.GaugeVec
}
// NewPrometheusStorage sets up a new Prometheus storage backend
func NewPrometheusStorage(c ServiceConfig) PrometheusStorage {
p := PrometheusStorage{}
p.RegisteredMetrics = make(map[string]*prometheus.GaugeVec)
p.Namespace = strings.ReplaceAll(c.Storage.Prometheus.Namespace, "-", "_")
p.ListenAddr = c.Storage.Prometheus.ListenAddr
p.Registry = prometheus.NewRegistry()
return p
}
// StartStorageEngine creates a goroutine loop to receive metrics and send
// them off to a Prometheus pushgateway
func (p PrometheusStorage) StartStorageEngine(ctx context.Context, wg *sync.WaitGroup) (chan<- Metric, chan<- Event) {
// We're going to declare eventChan here but not initialize the channel because Prometheus
// storage doesn't support Events, only Metrics. We should never receive an Event on this
// channel and if something mistakenly sends one, the program will panic.
var eventChan chan<- Event
// We *do* support Metrics, so we'll initialize this as a buffered channel
metricChan := make(chan Metric, 10)
// Start processing the metrics we receive
go p.processMetrics(ctx, wg, metricChan)
logger := log.New(os.Stdout, "", log.LstdFlags)
server := &http.Server{
Addr: p.ListenAddr,
ErrorLog: logger,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 15 * time.Second,
}
http.Handle("/metrics", promhttp.HandlerFor(p.Registry, promhttp.HandlerOpts{
ErrorLog: log.New(os.Stdout, "", log.LstdFlags),
}))
// Run our server in a goroutine so that it doesn't block.
go func() {
err := http.ListenAndServe(p.ListenAddr, nil)
if err != nil {
log.Fatalf("unable to start Prometheus listener: %s\n", err)
}
}()
go func(ctx context.Context) {
for {
select {
case <-ctx.Done():
log.Println("Cancellation request received. Cancelling job runner.")
server.Shutdown(ctx)
return
}
}
}(ctx)
return metricChan, eventChan
}
func (p PrometheusStorage) processMetrics(ctx context.Context, wg *sync.WaitGroup, mchan <-chan Metric) {
wg.Add(1)
defer wg.Done()
for {
select {
case m := <-mchan:
err := p.sendMetric(m)
if err != nil {
log.Println(err)
}
case <-ctx.Done():
log.Println("Cancellation request recieved. Cancelling metrics processor.")
return
}
}
}
// sendMetric sends a metric value to Prometheus
func (p PrometheusStorage) sendMetric(m Metric) error {
var metricName string
if p.Namespace == "" {
metricName = fmt.Sprintf("crabby_%v", m.Timing)
} else {
metricName = fmt.Sprintf("%v_%v", p.Namespace, m.Timing)
}
// If we receive a metric with a nil Tags map, we make a map.
if m.Tags == nil {
m.Tags = make(map[string]string)
}
m.Tags["crabby_job"] = m.Job
m.Tags["url"] = m.URL
metricName = strings.ReplaceAll(metricName, ".", "_")
promLabelNames := makePrometheusLabelSliceFromTagsMap(m.Tags)
_, present := p.RegisteredMetrics[metricName]
// If this metric vector is present in our map of metrics, we'll fetch the gauge and set the current value
if present {
metric, err := p.RegisteredMetrics[metricName].GetMetricWith(m.Tags)
if err != nil {
return fmt.Errorf("unable to get metric %v with tags %+v: %v", metricName, m.Tags, err)
}
metric.Set(m.Value)
} else {
// The metric wasn't present in our map, so we'll set up a new gauge vector
p.RegisteredMetrics[metricName] = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: metricName,
Help: "Crabby timing metric, in milliseconds",
},
promLabelNames,
)
p.Registry.MustRegister(p.RegisteredMetrics[metricName])
}
return nil
}
// sendEvent is necessary to implement the StorageEngine interface.
func (p PrometheusStorage) sendEvent(e Event) error {
var err error
return err
}
func makePrometheusLabelSliceFromTagsMap(tags map[string]string) []string {
var promLabels []string
for k := range tags {
promLabels = append(promLabels, k)
}
return promLabels
}