forked from xmidt-org/talaria
-
Notifications
You must be signed in to change notification settings - Fork 0
/
metrics.go
385 lines (346 loc) · 12.6 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
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
// SPDX-FileCopyrightText: 2017 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0
package main
import (
"net/http"
"strconv"
"time"
"github.com/go-kit/kit/metrics"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/xmidt-org/webpa-common/v2/xhttp"
// nolint:staticcheck
"github.com/xmidt-org/webpa-common/v2/xmetrics"
)
// Metric names
const (
OutboundInFlightGauge = "outbound_inflight"
OutboundRequestDuration = "outbound_request_duration_seconds"
OutboundRequestCounter = "outbound_requests"
OutboundRequestSizeBytes = "outbound_request_size"
TotalOutboundEvents = "total_outbound_events"
OutboundQueueSize = "outbound_queue_size"
OutboundDroppedMessageCounter = "outbound_dropped_messages"
OutboundRetries = "outbound_retries"
OutboundAckSuccessCounter = "outbound_ack_success"
OutboundAckFailureCounter = "outbound_ack_failure"
OutboundAckSuccessLatencyHistogram = "outbound_ack_success_latency_seconds"
OutboundAckFailureLatencyHistogram = "outbound_ack_failure_latency_seconds"
GateStatus = "gate_status"
DrainStatus = "drain_status"
DrainCounter = "drain_count"
InboundWRPMessageCounter = "inbound_wrp_messages"
)
// Metric label names
const (
outcomeLabel = "outcome"
reasonLabel = "reason"
qosLevelLabel = "qos_level"
partnerIDLabel = "partner_id"
messageType = "message_type"
urlLabel = "url"
codeLabel = "code"
eventLabel = "event"
)
// label values
const (
accepted = "accepted"
rejected = "rejected"
unknown = "unknown"
deviceNotFound = "device_not_found"
invalidWRPDest = "invalid_wrp_dest"
missingDeviceCredential = "missing_device_cred"
// nolint:gosec
missingWRPCredential = "missing_wrp_cred"
incompleteCheck = "incomplete_check"
denied = "denied"
authorized = "authorized"
// dropped message & outbound event reasons
unroutableDestinationReason = "unroutable_destination"
encodeErrReason = "encoding_err"
fullQueueReason = "full outbound queue"
genericDoReason = "do_error"
deadlineExceededReason = "context_deadline_exceeded"
contextCanceledReason = "context_canceled"
addressErrReason = "address_error"
parseAddrErrReason = "parse_address_error"
invalidAddrReason = "invalid_address"
dnsErrReason = "dns_error"
hostNotFoundReason = "host_not_found"
connClosedReason = "connection_closed"
opErrReason = "op_error"
networkErrReason = "unknown_network_err"
notSupportedEventReason = "unsupported event"
noEndpointConfiguredForEventReason = "no_endpoint_configured_for_event"
urlSchemeNotAllowedReason = "url_scheme_not_allowed"
malformedHTTPRequestReason = "malformed_http_request"
panicReason = "panic"
connectionUnexpectedlyClosedEOFReason = "connection_unexpectedly_closed_eof"
noErrReason = "no_err"
expectedCodeReason = "expected_code"
non202CodeReason = "non202"
// dropped message codes
messageDroppedCode = "message_dropped"
// outbound event delivery outcomes
successOutcome = "success"
failureOutcome = "failure"
)
func Metrics() []xmetrics.Metric {
return []xmetrics.Metric{
{
Name: OutboundInFlightGauge,
Type: xmetrics.GaugeType,
Help: "The number of active, in-flight requests from devices",
},
{
Name: OutboundRequestDuration,
Type: "histogram",
Help: "The durations of outbound requests from devices",
LabelNames: []string{eventLabel, codeLabel, reasonLabel, urlLabel},
Buckets: []float64{.25, .5, 1, 2.5, 5, 10},
},
{
Name: OutboundRequestCounter,
Type: xmetrics.CounterType,
Help: "The count of outbound requests",
LabelNames: []string{eventLabel, codeLabel, reasonLabel, urlLabel},
},
{
Name: OutboundRequestSizeBytes,
Type: xmetrics.HistogramType,
Help: "A histogram of request sizes for outbound requests",
LabelNames: []string{eventLabel, codeLabel},
Buckets: []float64{200, 500, 900, 1500, 3000, 6000, 12000, 24000, 48000, 96000, 192000},
},
{
Name: TotalOutboundEvents,
Type: xmetrics.CounterType,
Help: "Total count of outbound events",
LabelNames: []string{eventLabel, reasonLabel, urlLabel, outcomeLabel},
},
{
Name: OutboundQueueSize,
Type: xmetrics.GaugeType,
Help: "The current number of requests waiting to be sent outbound",
},
{
Name: OutboundDroppedMessageCounter,
Type: xmetrics.CounterType,
Help: "The total count of messages dropped",
LabelNames: []string{eventLabel, codeLabel, reasonLabel, urlLabel},
},
{
Name: OutboundRetries,
Type: xmetrics.CounterType,
Help: "The total count of outbound HTTP retries",
},
{
Name: OutboundAckSuccessCounter,
Type: xmetrics.CounterType,
Help: "Number of outbound WRP acks",
LabelNames: []string{qosLevelLabel, partnerIDLabel, messageType},
},
{
Name: OutboundAckFailureCounter,
Type: xmetrics.CounterType,
Help: "Number of outbound WRP ack failures",
LabelNames: []string{qosLevelLabel, partnerIDLabel, messageType},
},
{
Name: OutboundAckSuccessLatencyHistogram,
Type: xmetrics.HistogramType,
Help: "A histogram of latencies for successful outbound WRP acks",
LabelNames: []string{qosLevelLabel, partnerIDLabel, messageType},
Buckets: []float64{0.0625, 0.125, .25, .5, 1, 5, 10, 20, 40, 80, 160},
},
{
Name: OutboundAckFailureLatencyHistogram,
Type: xmetrics.HistogramType,
Help: "A histogram of latencies for failed outbound WRP acks",
LabelNames: []string{qosLevelLabel, partnerIDLabel, messageType},
Buckets: []float64{0.0625, 0.125, .25, .5, 1, 5, 10, 20, 40, 80, 160},
},
{
Name: GateStatus,
Type: xmetrics.GaugeType,
Help: "Indicates whether the device gate is open (1.0) or closed (0.0)",
},
{
Name: DrainStatus,
Type: xmetrics.GaugeType,
Help: "Indicates whether a device drain operation is currently running",
},
{
Name: DrainCounter,
Type: xmetrics.CounterType,
Help: "The total count of devices disconnected due to a drain since the server started",
},
{
Name: InboundWRPMessageCounter,
Type: xmetrics.CounterType,
Help: "Number of inbound WRP Messages successfully decoded and ready to route to device",
LabelNames: []string{outcomeLabel, reasonLabel},
},
}
}
type HistogramVec interface {
prometheus.Collector
With(prometheus.Labels) prometheus.Observer
CurryWith(prometheus.Labels) (prometheus.ObserverVec, error)
GetMetricWith(prometheus.Labels) (prometheus.Observer, error)
GetMetricWithLabelValues(...string) (prometheus.Observer, error)
MustCurryWith(labels prometheus.Labels) (o prometheus.ObserverVec)
WithLabelValues(lvs ...string) (o prometheus.Observer)
}
type CounterVec interface {
prometheus.Collector
With(prometheus.Labels) prometheus.Counter
}
type OutboundMeasures struct {
InFlight prometheus.Gauge
RequestDuration HistogramVec
RequestCounter CounterVec
RequestSize HistogramVec
OutboundEvents CounterVec
QueueSize metrics.Gauge
Retries metrics.Counter
DroppedMessages CounterVec
AckSuccess CounterVec
AckFailure CounterVec
AckSuccessLatency HistogramVec
AckFailureLatency HistogramVec
}
func NewOutboundMeasures(r xmetrics.Registry) OutboundMeasures {
return OutboundMeasures{
InFlight: r.NewGaugeVec(OutboundInFlightGauge).WithLabelValues(),
RequestDuration: r.NewHistogramVec(OutboundRequestDuration),
RequestCounter: r.NewCounterVec(OutboundRequestCounter),
RequestSize: r.NewHistogramVec(OutboundRequestSizeBytes),
OutboundEvents: r.NewCounterVec(TotalOutboundEvents),
QueueSize: r.NewGauge(OutboundQueueSize),
Retries: r.NewCounter(OutboundRetries),
DroppedMessages: r.NewCounterVec(OutboundDroppedMessageCounter),
AckSuccess: r.NewCounterVec(OutboundAckSuccessCounter),
AckFailure: r.NewCounterVec(OutboundAckFailureCounter),
// 0 is for the unused `buckets` argument in xmetrics.Registry.NewHistogram
AckSuccessLatency: r.NewHistogramVec(OutboundAckSuccessLatencyHistogram),
// 0 is for the unused `buckets` argument in xmetrics.Registry.NewHistogram
AckFailureLatency: r.NewHistogramVec(OutboundAckFailureLatencyHistogram),
}
}
func InstrumentOutboundSize(obs HistogramVec, next http.RoundTripper) promhttp.RoundTripperFunc {
return promhttp.RoundTripperFunc(func(request *http.Request) (*http.Response, error) {
eventType, ok := request.Context().Value(eventTypeContextKey{}).(string)
if !ok {
eventType = unknown
}
response, err := next.RoundTrip(request)
size := computeApproximateRequestSize(request)
var labels prometheus.Labels
if err != nil {
code := messageDroppedCode
if response != nil {
code = strconv.Itoa(response.StatusCode)
}
labels = prometheus.Labels{eventLabel: eventType, codeLabel: code}
} else {
labels = prometheus.Labels{eventLabel: eventType, codeLabel: strconv.Itoa(response.StatusCode)}
}
obs.With(labels).Observe(float64(size))
return response, err
})
}
func InstrumentOutboundDuration(obs HistogramVec, next http.RoundTripper) promhttp.RoundTripperFunc {
return promhttp.RoundTripperFunc(func(request *http.Request) (*http.Response, error) {
eventType, ok := request.Context().Value(eventTypeContextKey{}).(string)
if !ok {
eventType = unknown
}
start := time.Now()
response, err := next.RoundTrip(request)
delta := time.Since(start).Seconds()
var labels prometheus.Labels
if err != nil {
code := messageDroppedCode
if response != nil {
code = strconv.Itoa(response.StatusCode)
}
labels = prometheus.Labels{eventLabel: eventType, codeLabel: code, reasonLabel: getDoErrReason(err), urlLabel: request.URL.String()}
} else {
labels = prometheus.Labels{eventLabel: eventType, codeLabel: strconv.Itoa(response.StatusCode), reasonLabel: expectedCodeReason, urlLabel: request.URL.String()}
if response.StatusCode != http.StatusAccepted {
labels[reasonLabel] = non202CodeReason
}
}
obs.With(labels).Observe(delta)
return response, err
})
}
func InstrumentOutboundCounter(counter CounterVec, next http.RoundTripper) promhttp.RoundTripperFunc {
return promhttp.RoundTripperFunc(func(request *http.Request) (*http.Response, error) {
eventType, ok := request.Context().Value(eventTypeContextKey{}).(string)
if !ok {
eventType = unknown
}
response, err := next.RoundTrip(request)
var labels prometheus.Labels
if err != nil {
code := messageDroppedCode
if response != nil {
code = strconv.Itoa(response.StatusCode)
}
labels = prometheus.Labels{eventLabel: eventType, codeLabel: code, reasonLabel: getDoErrReason(err), urlLabel: request.URL.String()}
} else {
labels = prometheus.Labels{eventLabel: eventType, codeLabel: strconv.Itoa(response.StatusCode), reasonLabel: noErrReason, urlLabel: request.URL.String()}
if response.StatusCode != http.StatusAccepted {
labels[reasonLabel] = non202CodeReason
}
}
counter.With(labels).Inc()
return response, err
})
}
// NewOutboundRoundTripper produces an http.RoundTripper from the configured Outbounder
// that is also decorated with appropriate metrics.
func NewOutboundRoundTripper(om OutboundMeasures, o *Outbounder) http.RoundTripper {
// TODO add tests for NewOutboundRoundTripper
// nolint:bodyclose
return promhttp.RoundTripperFunc(xhttp.RetryTransactor(
// use the default should retry predicate ...
xhttp.RetryOptions{
Logger: o.logger(),
Retries: o.retries(),
Counter: om.Retries,
},
InstrumentOutboundCounter(
om.RequestCounter,
InstrumentOutboundSize(
om.RequestSize,
InstrumentOutboundDuration(
om.RequestDuration,
promhttp.InstrumentRoundTripperInFlight(om.InFlight, o.transport()),
),
),
),
))
}
func computeApproximateRequestSize(r *http.Request) int {
s := 0
if r.URL != nil {
s += len(r.URL.String())
}
s += len(r.Method)
s += len(r.Proto)
for name, values := range r.Header {
s += len(name)
for _, value := range values {
s += len(value)
}
}
s += len(r.Host)
// N.B. r.Form and r.MultipartForm are assumed to be included in r.URL.
if r.ContentLength != -1 {
s += int(r.ContentLength)
}
return s
}