-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
354 lines (308 loc) · 8.32 KB
/
middleware.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
package prometheusfiber
import (
"github.com/gofiber/adaptor/v2"
"github.com/gofiber/fiber/v2"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/valyala/fasthttp"
"log"
"strconv"
"time"
)
var defaultMetricPath = "/metrics"
var defaultSubSystem = "fiber"
const (
_ = iota
KB float64 = 1 << (10 * iota)
MB
)
// reqDurBuckets is the buckets for request duration.
var reqDurBuckets = prometheus.DefBuckets
// reqSizeBuckets is the buckets for request size.
var reqSizeBuckets = []float64{1.0 * KB, 2.0 * KB, 5.0 * KB, 10.0 * KB, 100 * KB, 500 * KB, 1.0 * MB, 2.5 * MB, 5.0 * MB, 10.0 * MB}
// resSizeBuckets is the buckets for response size.
var resSizeBuckets = []float64{1.0 * KB, 2.0 * KB, 5.0 * KB, 10.0 * KB, 100 * KB, 500 * KB, 1.0 * MB, 2.5 * MB, 5.0 * MB, 10.0 * MB}
// Metric defines an individual metric collection.
type Metric struct {
Collector prometheus.Collector
ID string
Name string
Description string
Type string
Args []string
Buckets []float64
}
// reqCount collects request metrics.
var reqCount = Metric{
ID: "reqCount",
Name: "requests_total",
Description: "Total number of requests by status code and HTTP method",
Type: "counter_vec",
Args: []string{"code", "method", "host", "url"},
}
// reqDur collects request latency metrics.
var reqDur = Metric{
ID: "reqDur",
Name: "request_duration_seconds",
Description: "The HTTP request latencies in seconds.",
Args: []string{"code", "method", "url"},
Type: "histogram_vec",
Buckets: reqDurBuckets,
}
// respSize collects response size metrics.
var respSize = Metric{
ID: "respSize",
Name: "response_size_bytes",
Description: "The HTTP response sizes in bytes.",
Args: []string{"code", "method", "url"},
Type: "histogram_vec",
Buckets: resSizeBuckets,
}
// reqSize collects request size metrics.
var reqSize = Metric{
ID: "reqSize",
Name: "request_size_bytes",
Description: "The HTTP request sizes in bytes.",
Args: []string{"code", "method", "url"},
Type: "histogram_vec",
Buckets: reqSizeBuckets,
}
// defaultMetrics consists of default metrics.
var defaultMetrics = []*Metric{
&reqCount,
&reqDur,
&respSize,
&reqSize,
}
// Prometheus contains metric collection instruments.
type Prometheus struct {
reqCount *prometheus.CounterVec
reqDur *prometheus.HistogramVec
respSize *prometheus.HistogramVec
reqSize *prometheus.HistogramVec
router *fiber.App
listenAddress string
metricsList []*Metric
metricsPath string
subsystem string
skip []string
}
// Options defines
type Options struct {
SubSystem string
MetricPath string
Skip []string
}
type Option func(o *Options)
// WithSubSystem defines subsystem.
func WithSubSystem(subsystem string) Option {
return func(o *Options) {
o.SubSystem = subsystem
}
}
// WithMetricPath define path where metric will be published.
func WithMetricPath(path string) Option {
return func(o *Options) {
o.MetricPath = path
}
}
// WithSkipURL will skip urls
func WithSkipURL(urls ...string) Option {
return func(o *Options) {
o.Skip = urls
}
}
// NewOptions is a factory function to generate Options.
func NewOptions(opts ...Option) Options {
options := Options{
SubSystem: defaultSubSystem,
MetricPath: defaultMetricPath,
Skip: make([]string, 0),
}
for _, o := range opts {
o(&options)
}
return options
}
// NewPrometheus is a factory function for prometheus.
func NewPrometheus(opts ...Option) *Prometheus {
options := NewOptions(opts...)
metricsList := make([]*Metric, 0, len(defaultMetrics))
metricsList = append(metricsList, defaultMetrics...)
p := &Prometheus{
metricsList: metricsList,
metricsPath: options.MetricPath,
subsystem: options.SubSystem,
skip: options.Skip,
}
p.registerMetrics()
return p
}
// NewMetric is a factory function to create an individual metric.
func NewMetric(m *Metric, subsystem string) prometheus.Collector {
var metric prometheus.Collector
switch m.Type {
case "counter_vec":
metric = prometheus.NewCounterVec(
prometheus.CounterOpts{
Subsystem: subsystem,
Name: m.Name,
Help: m.Description,
},
m.Args,
)
case "counter":
metric = prometheus.NewCounter(
prometheus.CounterOpts{
Subsystem: subsystem,
Name: m.Name,
Help: m.Description,
},
)
case "gauge_vec":
metric = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Subsystem: subsystem,
Name: m.Name,
Help: m.Description,
},
m.Args,
)
case "gauge":
metric = prometheus.NewGauge(
prometheus.GaugeOpts{
Subsystem: subsystem,
Name: m.Name,
Help: m.Description,
},
)
case "histogram_vec":
metric = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Subsystem: subsystem,
Name: m.Name,
Help: m.Description,
Buckets: m.Buckets,
},
m.Args,
)
case "histogram":
metric = prometheus.NewHistogram(
prometheus.HistogramOpts{
Subsystem: subsystem,
Name: m.Name,
Help: m.Description,
Buckets: m.Buckets,
},
)
case "summary_vec":
metric = prometheus.NewSummaryVec(
prometheus.SummaryOpts{
Subsystem: subsystem,
Name: m.Name,
Help: m.Description,
},
m.Args,
)
case "summary":
metric = prometheus.NewSummary(
prometheus.SummaryOpts{
Subsystem: subsystem,
Name: m.Name,
Help: m.Description,
},
)
}
return metric
}
// Middleware is the prometheus middleware.
func (ps *Prometheus) Middleware(ctx *fiber.Ctx) error {
if ctx.Path() == ps.metricsPath {
return ctx.Next()
}
for _, skip := range ps.skip {
if ctx.Path() == skip {
return ctx.Next()
}
}
start := time.Now()
reqSize := computeApproximateRequestSize(ctx.Request())
method := ctx.Route().Method
err := ctx.Next()
status := fiber.StatusInternalServerError
if err != nil {
if e, ok := err.(*fiber.Error); ok {
status = e.Code
}
} else {
status = ctx.Response().StatusCode()
}
elapsed := float64(time.Since(start)) / float64(time.Second)
url := ctx.Route().Path
statusStr := strconv.Itoa(status)
ps.reqDur.WithLabelValues(statusStr, method, url).Observe(elapsed)
ps.reqCount.WithLabelValues(statusStr, method, ctx.Hostname(), url).Inc()
ps.reqSize.WithLabelValues(statusStr, method, url).Observe(float64(reqSize))
ps.respSize.WithLabelValues(statusStr, method, url).Observe(float64(computeApproximateResponseSize(ctx.Response())))
return err
}
// SetMetricsPath sets metric path.
func (ps *Prometheus) SetMetricsPath(app *fiber.App) {
if ps.listenAddress != "" {
ps.router.Get(ps.metricsPath, adaptor.HTTPHandler(promhttp.Handler()))
ps.runServer()
} else {
app.Get(ps.metricsPath, adaptor.HTTPHandler(promhttp.Handler()))
}
}
// runServer publish metrics in a different server.
func (ps *Prometheus) runServer() {
if ps.listenAddress != "" {
go func() {
if err := ps.router.Listen(ps.listenAddress); err != nil {
log.Fatalln(err)
}
}()
}
}
// Use registers a prometheus middleware on a fiber app.
func (ps *Prometheus) Use(app *fiber.App) {
app.Use(ps.Middleware)
ps.SetMetricsPath(app)
}
// registerMetrics register metrics on prometheus.
func (ps *Prometheus) registerMetrics() {
for _, metricDef := range ps.metricsList {
metric := NewMetric(metricDef, ps.subsystem)
if err := prometheus.Register(metric); err != nil {
return
}
switch metricDef {
case &reqCount:
ps.reqCount = metric.(*prometheus.CounterVec)
case &reqDur:
ps.reqDur = metric.(*prometheus.HistogramVec)
case &respSize:
ps.respSize = metric.(*prometheus.HistogramVec)
case &reqSize:
ps.reqSize = metric.(*prometheus.HistogramVec)
}
metricDef.Collector = metric
}
}
// computeApproximateRequestSize calculates size of the request body.
func computeApproximateRequestSize(r *fasthttp.Request) int {
size := len(r.Body()) + 2
r.Header.VisitAll(func(key, value []byte) {
size += len(key) + len(value) + 2
})
return size
}
// computeApproximateResponseSize calculates size of the response body.
func computeApproximateResponseSize(r *fasthttp.Response) int {
size := len(r.Body()) + 2
r.Header.VisitAll(func(key, value []byte) {
size += len(key) + len(value) + 2
})
return size
}