forked from zalando/skipper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
metrics.go
293 lines (244 loc) · 7.9 KB
/
metrics.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
package metrics
import (
"encoding/json"
"fmt"
"net/http"
"net/http/pprof"
"strings"
"time"
log "github.com/Sirupsen/logrus"
"github.com/rcrowley/go-metrics"
)
type skipperMetrics map[string]interface{}
// Options for initializing metrics collection.
type Options struct {
// Network address where the current metrics values
// can be pulled from. If not set, the collection of
// the metrics is disabled.
Listener string
// Common prefix for the keys of the different
// collected metrics.
Prefix string
// If set, garbage collector metrics are collected
// in addition to the http traffic metrics.
EnableDebugGcMetrics bool
// If set, Go runtime metrics are collected in
// addition to the http traffic metrics.
EnableRuntimeMetrics bool
// If set, detailed total response time metrics will be collected
// for each route, additionally grouped by status and method.
EnableServeRouteMetrics bool
// If set, detailed total response time metrics will be collected
// for each host, additionally grouped by status and method.
EnableServeHostMetrics bool
// If set, detailed response time metrics will be collected
// for each backend host
EnableBackendHostMetrics bool
// EnableProfile exposes profiling information on /pprof of the
// metrics listener.
EnableProfile bool
}
const (
KeyRouteLookup = "routelookup"
KeyRouteFailure = "routefailure"
KeyFilterRequest = "filter.%s.request"
KeyFiltersRequest = "allfilters.request.%s"
KeyProxyBackend = "backend.%s"
KeyProxyBackendHost = "backendhost.%s"
KeyFilterResponse = "filter.%s.response"
KeyFiltersResponse = "allfilters.response.%s"
KeyResponse = "response.%d.%s.skipper.%s"
KeyServeRoute = "serveroute.%s.%s.%d"
KeyServeHost = "servehost.%s.%s.%d"
KeyErrorsBackend = "errors.backend.%s"
KeyErrorsStreaming = "errors.streaming.%s"
statsRefreshDuration = time.Duration(5 * time.Second)
defaultReservoirSize = 1024
)
type Metrics struct {
reg metrics.Registry
createTimer func() metrics.Timer
createCounter func() metrics.Counter
options Options
}
var (
Default *Metrics
Void *Metrics
)
func New(o Options) *Metrics {
m := &Metrics{}
m.reg = metrics.NewRegistry()
m.createTimer = createTimer
m.createCounter = metrics.NewCounter
m.options = o
if o.EnableDebugGcMetrics {
metrics.RegisterDebugGCStats(m.reg)
go metrics.CaptureDebugGCStats(m.reg, statsRefreshDuration)
}
if o.EnableRuntimeMetrics {
metrics.RegisterRuntimeMemStats(m.reg)
go metrics.CaptureRuntimeMemStats(m.reg, statsRefreshDuration)
}
return m
}
func NewVoid() *Metrics {
m := &Metrics{}
m.reg = metrics.NewRegistry()
m.createTimer = func() metrics.Timer { return metrics.NilTimer{} }
m.createCounter = func() metrics.Counter { return metrics.NilCounter{} }
return m
}
func init() {
Void = NewVoid()
Default = Void
}
// Initializes the collection of metrics.
func Init(o Options) {
if o.Listener == "" {
log.Infoln("Metrics are disabled")
return
}
Default = New(o)
handler := &metricsHandler{registry: Default.reg, options: o}
if o.EnableProfile {
mux := http.NewServeMux()
mux.Handle("/debug/pprof/", http.HandlerFunc(pprof.Index))
mux.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
mux.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
mux.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
mux.Handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace))
handler.profile = mux
}
log.Infof("metrics listener on %s/metrics", o.Listener)
go http.ListenAndServe(o.Listener, handler)
}
func createTimer() metrics.Timer {
return metrics.NewCustomTimer(metrics.NewHistogram(metrics.NewUniformSample(defaultReservoirSize)), metrics.NewMeter())
}
func (m *Metrics) getTimer(key string) metrics.Timer {
return m.reg.GetOrRegister(key, m.createTimer).(metrics.Timer)
}
func (m *Metrics) updateTimer(key string, d time.Duration) {
if t := m.getTimer(key); t != nil {
t.Update(d)
}
}
func (m *Metrics) measureSince(key string, start time.Time) {
d := time.Since(start)
go m.updateTimer(key, d)
}
func (m *Metrics) MeasureRouteLookup(start time.Time) {
m.measureSince(KeyRouteLookup, start)
}
func (m *Metrics) MeasureFilterRequest(filterName string, start time.Time) {
m.measureSince(fmt.Sprintf(KeyFilterRequest, filterName), start)
}
func (m *Metrics) MeasureAllFiltersRequest(routeId string, start time.Time) {
m.measureSince(fmt.Sprintf(KeyFiltersRequest, routeId), start)
}
func (m *Metrics) MeasureBackend(routeId string, start time.Time) {
m.measureSince(fmt.Sprintf(KeyProxyBackend, routeId), start)
}
func (m *Metrics) MeasureBackendHost(routeBackendHost string, start time.Time) {
if m.options.EnableBackendHostMetrics {
m.measureSince(fmt.Sprintf(KeyProxyBackendHost, hostForKey(routeBackendHost)), start)
}
}
func (m *Metrics) MeasureFilterResponse(filterName string, start time.Time) {
m.measureSince(fmt.Sprintf(KeyFilterResponse, filterName), start)
}
func (m *Metrics) MeasureAllFiltersResponse(routeId string, start time.Time) {
m.measureSince(fmt.Sprintf(KeyFiltersResponse, routeId), start)
}
func (m *Metrics) MeasureResponse(code int, method string, routeId string, start time.Time) {
m.measureSince(fmt.Sprintf(KeyResponse, code, method, routeId), start)
}
func hostForKey(h string) string {
h = strings.Replace(h, ".", "_", -1)
h = strings.Replace(h, ":", "__", -1)
return h
}
func (m *Metrics) MeasureServe(routeId, host, method string, code int, start time.Time) {
if m.options.EnableServeRouteMetrics {
m.measureSince(fmt.Sprintf(KeyServeRoute, routeId, method, code), start)
}
if m.options.EnableServeHostMetrics {
m.measureSince(fmt.Sprintf(KeyServeHost, hostForKey(host), method, code), start)
}
}
func (m *Metrics) getCounter(key string) metrics.Counter {
return m.reg.GetOrRegister(key, m.createCounter).(metrics.Counter)
}
func (m *Metrics) incCounter(key string) {
go func() {
if c := m.getCounter(key); c != nil {
c.Inc(1)
}
}()
}
func (m *Metrics) IncRoutingFailures() {
m.incCounter(KeyRouteFailure)
}
func (m *Metrics) IncErrorsBackend(routeId string) {
m.incCounter(fmt.Sprintf(KeyErrorsBackend, routeId))
}
func (m *Metrics) IncErrorsStreaming(routeId string) {
m.incCounter(fmt.Sprintf(KeyErrorsStreaming, routeId))
}
// This listener is used to expose the collected metrics.
func (sm skipperMetrics) MarshalJSON() ([]byte, error) {
data := make(map[string]map[string]interface{})
for name, metric := range sm {
values := make(map[string]interface{})
var metricsFamily string
switch m := metric.(type) {
case metrics.Gauge:
metricsFamily = "gauges"
values["value"] = m.Value()
case metrics.Histogram:
metricsFamily = "histograms"
h := m.Snapshot()
ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
values["count"] = h.Count()
values["min"] = h.Min()
values["max"] = h.Max()
values["mean"] = h.Mean()
values["stddev"] = h.StdDev()
values["median"] = ps[0]
values["75%"] = ps[1]
values["95%"] = ps[2]
values["99%"] = ps[3]
values["99.9%"] = ps[4]
case metrics.Timer:
metricsFamily = "timers"
t := m.Snapshot()
ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
values["count"] = t.Count()
values["min"] = t.Min()
values["max"] = t.Max()
values["mean"] = t.Mean()
values["stddev"] = t.StdDev()
values["median"] = ps[0]
values["75%"] = ps[1]
values["95%"] = ps[2]
values["99%"] = ps[3]
values["99.9%"] = ps[4]
values["1m.rate"] = t.Rate1()
values["5m.rate"] = t.Rate5()
values["15m.rate"] = t.Rate15()
values["mean.rate"] = t.RateMean()
case metrics.Counter:
metricsFamily = "counters"
t := m.Snapshot()
values["count"] = t.Count()
default:
metricsFamily = "unknown"
values["error"] = fmt.Sprintf("unknown metrics type %T", m)
}
if data[metricsFamily] == nil {
data[metricsFamily] = make(map[string]interface{})
}
data[metricsFamily][name] = values
}
return json.Marshal(data)
}