-
Notifications
You must be signed in to change notification settings - Fork 38
/
prom.go
401 lines (341 loc) · 10.9 KB
/
prom.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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
// Package ginprom is a library to instrument a gin server and expose a
// /metrics endpoint for Prometheus to scrape, keeping a low cardinality by
// preserving the path parameters name in the prometheus label
package ginprom
import (
"errors"
"fmt"
"net/http"
"strconv"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var defaultPath = "/metrics"
var defaultNs = "gin"
var defaultSys = "gonic"
var defaultHandlerNameFunc = (*gin.Context).HandlerName
var defaultRequestPathFunc = (*gin.Context).FullPath
var defaultReqCntMetricName = "requests_total"
var defaultReqDurMetricName = "request_duration"
var defaultReqSzMetricName = "request_size_bytes"
var defaultResSzMetricName = "response_size_bytes"
// ErrInvalidToken is returned when the provided token is invalid or missing.
var ErrInvalidToken = errors.New("invalid or missing token")
// ErrCustomGauge is returned when the custom gauge can't be found.
var ErrCustomGauge = errors.New("error finding custom gauge")
// ErrCustomCounter is returned when the custom counter can't be found.
var ErrCustomCounter = errors.New("error finding custom counter")
type pmapb struct {
sync.RWMutex
values map[string]bool
}
type pmapGauge struct {
sync.RWMutex
values map[string]prometheus.GaugeVec
}
type pmapCounter struct {
sync.RWMutex
values map[string]prometheus.CounterVec
}
type pmapHistogram struct {
sync.RWMutex
values map[string]prometheus.HistogramVec
}
// Prometheus contains the metrics gathered by the instance and its path.
type Prometheus struct {
reqCnt *prometheus.CounterVec
reqDur *prometheus.HistogramVec
reqSz, resSz prometheus.Summary
customGauges pmapGauge
customCounters pmapCounter
customCounterLabelsProvider func(c *gin.Context) map[string]string
customCounterLabels []string
customHistograms pmapHistogram
MetricsPath string
Namespace string
Subsystem string
Token string
Ignored pmapb
Engine *gin.Engine
BucketsSize []float64
Registry *prometheus.Registry
HandlerNameFunc func(c *gin.Context) string
RequestPathFunc func(c *gin.Context) string
HandlerOpts promhttp.HandlerOpts
RequestCounterMetricName string
RequestDurationMetricName string
RequestSizeMetricName string
ResponseSizeMetricName string
}
// IncrementGaugeValue increments a custom gauge.
func (p *Prometheus) IncrementGaugeValue(name string, labelValues []string) error {
p.customGauges.RLock()
defer p.customGauges.RUnlock()
if g, ok := p.customGauges.values[name]; ok {
g.WithLabelValues(labelValues...).Inc()
} else {
return ErrCustomGauge
}
return nil
}
// SetGaugeValue sets gauge to value.
func (p *Prometheus) SetGaugeValue(name string, labelValues []string, value float64) error {
p.customGauges.RLock()
defer p.customGauges.RUnlock()
if g, ok := p.customGauges.values[name]; ok {
g.WithLabelValues(labelValues...).Set(value)
} else {
return ErrCustomGauge
}
return nil
}
// AddGaugeValue adds value to custom gauge.
func (p *Prometheus) AddGaugeValue(name string, labelValues []string, value float64) error {
p.customGauges.RLock()
defer p.customGauges.RUnlock()
if g, ok := p.customGauges.values[name]; ok {
g.WithLabelValues(labelValues...).Add(value)
} else {
return ErrCustomGauge
}
return nil
}
// DecrementGaugeValue decrements a custom gauge.
func (p *Prometheus) DecrementGaugeValue(name string, labelValues []string) error {
p.customGauges.RLock()
defer p.customGauges.RUnlock()
if g, ok := p.customGauges.values[name]; ok {
g.WithLabelValues(labelValues...).Dec()
} else {
return ErrCustomGauge
}
return nil
}
// SubGaugeValue adds gauge to value.
func (p *Prometheus) SubGaugeValue(name string, labelValues []string, value float64) error {
p.customGauges.RLock()
defer p.customGauges.RUnlock()
if g, ok := p.customGauges.values[name]; ok {
g.WithLabelValues(labelValues...).Sub(value)
} else {
return ErrCustomGauge
}
return nil
}
// AddCustomGauge adds a custom gauge and registers it.
func (p *Prometheus) AddCustomGauge(name, help string, labels []string) {
p.customGauges.Lock()
defer p.customGauges.Unlock()
g := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: p.Namespace,
Subsystem: p.Subsystem,
Name: name,
Help: help,
},
labels)
p.customGauges.values[name] = *g
p.mustRegister(g)
}
// IncrementCounterValue increments a custom counter.
func (p *Prometheus) IncrementCounterValue(name string, labelValues []string) error {
p.customCounters.RLock()
defer p.customCounters.RUnlock()
if g, ok := p.customCounters.values[name]; ok {
g.WithLabelValues(labelValues...).Inc()
} else {
return ErrCustomCounter
}
return nil
}
// AddCounterValue adds value to custom counter.
func (p *Prometheus) AddCounterValue(name string, labelValues []string, value float64) error {
p.customCounters.RLock()
defer p.customCounters.RUnlock()
if g, ok := p.customCounters.values[name]; ok {
g.WithLabelValues(labelValues...).Add(value)
} else {
return ErrCustomCounter
}
return nil
}
// AddCustomCounter adds a custom counter and registers it.
func (p *Prometheus) AddCustomCounter(name, help string, labels []string) {
p.customCounters.Lock()
defer p.customCounters.Unlock()
g := prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: p.Namespace,
Subsystem: p.Subsystem,
Name: name,
Help: help,
}, labels)
p.customCounters.values[name] = *g
p.mustRegister(g)
}
// AddCustomHistogramValue adds value to custom counter.
func (p *Prometheus) AddCustomHistogramValue(name string, labelValues []string, value float64) error {
p.customHistograms.RLock()
defer p.customHistograms.RUnlock()
if g, ok := p.customHistograms.values[name]; ok {
g.WithLabelValues(labelValues...).Observe(value)
} else {
return ErrCustomCounter
}
return nil
}
// AddCustomCounter adds a custom counter and registers it.
func (p *Prometheus) AddCustomHistogram(name, help string, labels []string) {
p.customHistograms.Lock()
defer p.customHistograms.Unlock()
g := prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: p.Namespace,
Subsystem: p.Subsystem,
Name: name,
Help: help,
}, labels)
p.customHistograms.values[name] = *g
p.mustRegister(g)
}
func (p *Prometheus) mustRegister(c ...prometheus.Collector) {
registerer, _ := p.getRegistererAndGatherer()
registerer.MustRegister(c...)
}
// New will initialize a new Prometheus instance with the given options.
// If no options are passed, sane defaults are used.
// If a router is passed using the Engine() option, this instance will
// automatically bind to it.
func New(options ...PrometheusOption) *Prometheus {
p := &Prometheus{
MetricsPath: defaultPath,
Namespace: defaultNs,
Subsystem: defaultSys,
HandlerNameFunc: defaultHandlerNameFunc,
RequestPathFunc: defaultRequestPathFunc,
RequestCounterMetricName: defaultReqCntMetricName,
RequestDurationMetricName: defaultReqDurMetricName,
RequestSizeMetricName: defaultReqSzMetricName,
ResponseSizeMetricName: defaultResSzMetricName,
}
p.customGauges.values = make(map[string]prometheus.GaugeVec)
p.customCounters.values = make(map[string]prometheus.CounterVec)
p.customCounterLabels = make([]string, 0)
p.customHistograms.values = make(map[string]prometheus.HistogramVec)
p.Ignored.values = make(map[string]bool)
for _, option := range options {
option(p)
}
p.register()
if p.Engine != nil {
p.Engine.GET(p.MetricsPath, p.prometheusHandler(p.Token))
}
return p
}
func (p *Prometheus) getRegistererAndGatherer() (prometheus.Registerer, prometheus.Gatherer) {
if p.Registry == nil {
return prometheus.DefaultRegisterer, prometheus.DefaultGatherer
}
return p.Registry, p.Registry
}
func (p *Prometheus) register() {
p.reqCnt = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: p.Namespace,
Subsystem: p.Subsystem,
Name: p.RequestCounterMetricName,
Help: "How many HTTP requests processed, partitioned by status code and HTTP method.",
},
append([]string{"code", "method", "handler", "host", "path"}, p.customCounterLabels...),
)
p.mustRegister(p.reqCnt)
p.reqDur = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: p.Namespace,
Subsystem: p.Subsystem,
Buckets: p.BucketsSize,
Name: p.RequestDurationMetricName,
Help: "The HTTP request latency bucket.",
}, []string{"method", "path", "host"})
p.mustRegister(p.reqDur)
p.reqSz = prometheus.NewSummary(
prometheus.SummaryOpts{
Namespace: p.Namespace,
Subsystem: p.Subsystem,
Name: p.RequestSizeMetricName,
Help: "The HTTP request sizes in bytes.",
},
)
p.mustRegister(p.reqSz)
p.resSz = prometheus.NewSummary(
prometheus.SummaryOpts{
Namespace: p.Namespace,
Subsystem: p.Subsystem,
Name: p.ResponseSizeMetricName,
Help: "The HTTP response sizes in bytes.",
},
)
p.mustRegister(p.resSz)
}
func (p *Prometheus) isIgnored(path string) bool {
p.Ignored.RLock()
defer p.Ignored.RUnlock()
_, ok := p.Ignored.values[path]
return ok
}
// Instrument is a gin middleware that can be used to generate metrics for a
// single handler
func (p *Prometheus) Instrument() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
path := p.RequestPathFunc(c)
if path == "" || p.isIgnored(path) {
c.Next()
return
}
reqSz := computeApproximateRequestSize(c.Request)
c.Next()
status := strconv.Itoa(c.Writer.Status())
elapsed := float64(time.Since(start)) / float64(time.Second)
resSz := float64(c.Writer.Size())
labels := []string{status, c.Request.Method, p.HandlerNameFunc(c), c.Request.Host, path}
if p.customCounterLabelsProvider != nil {
extraLabels := p.customCounterLabelsProvider(c)
for _, label := range p.customCounterLabels {
labels = append(labels, extraLabels[label])
}
}
p.reqCnt.WithLabelValues(labels...).Inc()
p.reqDur.WithLabelValues(c.Request.Method, path, c.Request.Host).Observe(elapsed)
p.reqSz.Observe(float64(reqSz))
p.resSz.Observe(resSz)
}
}
// Use is a method that should be used if the engine is set after middleware
// initialization.
func (p *Prometheus) Use(e *gin.Engine) {
e.GET(p.MetricsPath, p.prometheusHandler(p.Token))
p.Engine = e
}
func (p *Prometheus) prometheusHandler(token string) gin.HandlerFunc {
registerer, gatherer := p.getRegistererAndGatherer()
h := promhttp.InstrumentMetricHandler(
registerer, promhttp.HandlerFor(gatherer, p.HandlerOpts),
)
return func(c *gin.Context) {
if token == "" {
h.ServeHTTP(c.Writer, c.Request)
return
}
header := c.Request.Header.Get("Authorization")
if header == "" {
c.String(http.StatusUnauthorized, ErrInvalidToken.Error())
return
}
bearer := fmt.Sprintf("Bearer %s", token)
if header != bearer {
c.String(http.StatusUnauthorized, ErrInvalidToken.Error())
return
}
h.ServeHTTP(c.Writer, c.Request)
}
}