-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
middleware.go
68 lines (60 loc) · 1.78 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
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package metrics
import (
"net/http"
"strconv"
"strings"
"github.com/cilium/cilium/pkg/metrics/metric"
"github.com/cilium/cilium/pkg/spanstat"
)
// APIEventTSHelper is intended to be a global middleware to track metrics
// around API calls.
// It records the timestamp of an API call in the provided gauge.
type APIEventTSHelper struct {
Next http.Handler
TSGauge metric.Vec[metric.Gauge]
Histogram metric.Vec[metric.Observer]
}
type ResponderWrapper struct {
http.ResponseWriter
code int
}
func (rw *ResponderWrapper) WriteHeader(code int) {
rw.code = code
rw.ResponseWriter.WriteHeader(code)
}
// getShortPath returns the API path trimmed after the 3rd slash.
// examples:
//
// "/v1/config" -> "/v1/config"
// "/v1/endpoint/cilium-local:0" -> "/v1/endpoint"
// "/v1/endpoint/container-id:597.." -> "/v1/endpoint"
func getShortPath(s string) string {
var idxSum int
for nThSlash := 0; nThSlash < 3; nThSlash++ {
idx := strings.IndexByte(s[idxSum:], '/')
if idx == -1 {
return s
}
idxSum += idx + 1
}
return s[:idxSum-1]
}
// ServeHTTP implements the http.Handler interface. It records the timestamp
// this API call began at, then chains to the next handler.
func (m *APIEventTSHelper) ServeHTTP(r http.ResponseWriter, req *http.Request) {
reqOk := req != nil && req.URL != nil && req.URL.Path != ""
var path string
if reqOk {
path = getShortPath(req.URL.Path)
m.TSGauge.WithLabelValues(LabelEventSourceAPI, path, req.Method).SetToCurrentTime()
}
duration := spanstat.Start()
rw := &ResponderWrapper{ResponseWriter: r}
m.Next.ServeHTTP(rw, req)
if reqOk {
took := float64(duration.End(true).Total().Seconds())
m.Histogram.WithLabelValues(path, req.Method, strconv.Itoa(rw.code)).Observe(took)
}
}