-
Notifications
You must be signed in to change notification settings - Fork 0
/
metrics.go
318 lines (289 loc) · 11.3 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
package cassette
import (
"context"
"errors"
"net/http"
"net/http/pprof"
"runtime"
"time"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/p2p/net/swarm"
"github.com/mercari/go-circuitbreaker"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/exporters/prometheus"
"go.opentelemetry.io/otel/metric/instrument"
"go.opentelemetry.io/otel/sdk/metric"
)
var (
statusSkipped = attribute.String("status", "skipped")
statusFailed = attribute.String("status", "failed")
statusSucceeded = attribute.String("status", "succeeded")
)
type metrics struct {
c *Cassette
server *http.Server
exporter *prometheus.Exporter
lookupRequestCounter instrument.Int64Counter
lookupResponseTTFPHistogram instrument.Int64Histogram
lookupResponseResultCountHistogram instrument.Int64Histogram
lookupResponseLatencyHistogram instrument.Int64Histogram
cacheSize instrument.Int64ObservableGauge
broadcastInFlightTimeHistogram instrument.Int64Histogram
broadcastBatchSizeHistogram instrument.Int64Histogram
broadcastCidCounter instrument.Int64Counter
broadcastRecipientsUpDownCounter instrument.Int64UpDownCounter
broadcastRecipientsCBStateUpDownCounter instrument.Int64UpDownCounter
broadcastInFlightUpDownCounter instrument.Int64UpDownCounter
receiverErrorCounter instrument.Int64Counter
receiverConnectionUpDownCounter instrument.Int64UpDownCounter
receiverMessageCounter instrument.Int64Counter
}
func newMetrics(c *Cassette) (*metrics, error) {
m := metrics{
c: c,
server: &http.Server{
Addr: c.metricsHttpListenAddr,
// TODO add other metrics server options.
},
}
return &m, nil
}
func (m *metrics) Start(_ context.Context) error {
var err error
if m.exporter, err = prometheus.New(
prometheus.WithoutUnits(),
prometheus.WithoutScopeInfo(),
prometheus.WithoutTargetInfo()); err != nil {
return err
}
provider := metric.NewMeterProvider(metric.WithReader(m.exporter))
meter := provider.Meter("ipni/cassette")
if m.lookupRequestCounter, err = meter.Int64Counter(
"ipni/cassette/lookup_request_count",
instrument.WithUnit("1"),
instrument.WithDescription("The number of lookup requests received."),
); err != nil {
return err
}
if m.lookupResponseTTFPHistogram, err = meter.Int64Histogram(
"ipni/cassette/lookup_response_first_provider_time",
instrument.WithUnit("ms"),
instrument.WithDescription("The elapsed to find the first provider in milliseconds."),
); err != nil {
return err
}
if m.lookupResponseResultCountHistogram, err = meter.Int64Histogram(
"ipni/cassette/lookup_response_result_count",
instrument.WithUnit("1"),
instrument.WithDescription("The number of providers found per lookup."),
); err != nil {
return err
}
if m.lookupResponseLatencyHistogram, err = meter.Int64Histogram(
"ipni/cassette/lookup_response_latency",
instrument.WithUnit("ms"),
instrument.WithDescription("The lookup response latency."),
); err != nil {
return err
}
if m.cacheSize, err = meter.Int64ObservableGauge(
"ipni/cassette/cache_size",
instrument.WithUnit("1"),
instrument.WithDescription("The number cached records."),
instrument.WithInt64Callback(m.reportCacheSize),
); err != nil {
return err
}
if m.broadcastInFlightTimeHistogram, err = meter.Int64Histogram(
"ipni/cassette/broadcast_in_flight_time",
instrument.WithUnit("ms"),
instrument.WithDescription("The elapsed time between broadcast requested and broadcast sent."),
); err != nil {
return err
}
if m.broadcastBatchSizeHistogram, err = meter.Int64Histogram(
"ipni/cassette/broadcast_batch_size",
instrument.WithUnit("1"),
instrument.WithDescription("The histogram of the number of CIDs in each broadcast message."),
); err != nil {
return err
}
if m.broadcastCidCounter, err = meter.Int64Counter(
"ipni/cassette/broadcast_cid_count",
instrument.WithUnit("1"),
instrument.WithDescription("The number of CIDs that are broadcasted tagged by status."),
); err != nil {
return err
}
if m.broadcastRecipientsUpDownCounter, err = meter.Int64UpDownCounter(
"ipni/cassette/broadcast_recipients_count",
instrument.WithUnit("1"),
instrument.WithDescription("The number of broadcast recipients."),
); err != nil {
return err
}
if m.broadcastRecipientsCBStateUpDownCounter, err = meter.Int64UpDownCounter(
"ipni/cassette/broadcast_recipients_cb_state_count",
instrument.WithUnit("1"),
instrument.WithDescription("The broadcast recipients circuit breaker state count."),
); err != nil {
return err
}
if m.broadcastInFlightUpDownCounter, err = meter.Int64UpDownCounter(
"ipni/cassette/broadcast_in_flight_count",
instrument.WithUnit("1"),
instrument.WithDescription("The number of in-flight CIDs awaiting broadcast."),
); err != nil {
return err
}
if m.receiverErrorCounter, err = meter.Int64Counter(
"ipni/cassette/receiver_error_count",
instrument.WithUnit("1"),
instrument.WithDescription("The number of errors observed by BitSwap receiver."),
); err != nil {
return err
}
if m.receiverConnectionUpDownCounter, err = meter.Int64UpDownCounter(
"ipni/cassette/receiver_connection_count",
instrument.WithUnit("1"),
instrument.WithDescription("The number of connections observed by BitSwap receiver."),
); err != nil {
return err
}
if m.receiverMessageCounter, err = meter.Int64Counter(
"ipni/cassette/receiver_message_count",
instrument.WithUnit("1"),
instrument.WithDescription("The number of messages observed by BitSwap receiver."),
); err != nil {
return err
}
m.server.Handler = m.serveMux()
go func() { _ = m.server.ListenAndServe() }()
m.server.RegisterOnShutdown(func() {
// TODO add timeout to exporter shutdown
if err := m.exporter.Shutdown(context.TODO()); err != nil {
logger.Errorw("Failed to shut down Prometheus exporter", "err", err)
}
})
logger.Infow("Metric server started", "addr", m.server.Addr)
return nil
}
func (m *metrics) serveMux() *http.ServeMux {
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
if m.c.metricsEnablePprofDebug {
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
mux.HandleFunc("/debug/pprof/gc",
func(w http.ResponseWriter, req *http.Request) {
runtime.GC()
},
)
}
return mux
}
func (m *metrics) notifyBroadcastSkipped(ctx context.Context, totalCidCount int64, inFlightTime time.Duration) {
m.broadcastInFlightTimeHistogram.Record(ctx, inFlightTime.Milliseconds(), statusSkipped)
m.broadcastCidCounter.Add(ctx, totalCidCount, statusSkipped)
m.broadcastInFlightUpDownCounter.Add(ctx, -totalCidCount)
}
func (m *metrics) notifyBroadcastFailed(ctx context.Context, totalCidCount int64, err error, inFlightTime time.Duration) {
errKindAttr := errKindAttribute(err)
m.broadcastInFlightTimeHistogram.Record(ctx, inFlightTime.Milliseconds(), statusFailed, errKindAttr)
m.broadcastCidCounter.Add(ctx, totalCidCount, errKindAttr, statusFailed)
m.broadcastInFlightUpDownCounter.Add(ctx, -totalCidCount)
}
func (m *metrics) notifyBroadcastSucceeded(ctx context.Context, totalCidCount int64, cancelCidCount int64, wantHave bool, inFlightTime time.Duration) {
m.broadcastInFlightTimeHistogram.Record(ctx, inFlightTime.Milliseconds(), statusSucceeded)
m.broadcastBatchSizeHistogram.Record(ctx, totalCidCount, attribute.Bool("want-have", wantHave))
m.broadcastCidCounter.Add(ctx, totalCidCount-cancelCidCount, statusSucceeded, attribute.Bool("cancel", false))
m.broadcastCidCounter.Add(ctx, cancelCidCount, statusSucceeded, attribute.Bool("cancel", true))
m.broadcastInFlightUpDownCounter.Add(ctx, -totalCidCount)
}
func (m *metrics) notifyBroadcastRequested(ctx context.Context, cidCount int64) {
m.broadcastInFlightUpDownCounter.Add(ctx, cidCount)
}
func (m *metrics) notifyBroadcastRecipientAdded(ctx context.Context) {
m.broadcastRecipientsUpDownCounter.Add(ctx, 1)
}
func (m *metrics) notifyBroadcastRecipientCBStateChanged(ctx context.Context, pid peer.ID, from, to circuitbreaker.State) {
recipient := attribute.String("recipient", pid.String())
m.broadcastRecipientsCBStateUpDownCounter.Add(ctx, -1, attribute.String("state", string(from)), recipient)
m.broadcastRecipientsCBStateUpDownCounter.Add(ctx, 1, attribute.String("state", string(to)), recipient)
}
func (m *metrics) notifyBroadcastRecipientRemoved(ctx context.Context) {
m.broadcastRecipientsUpDownCounter.Add(ctx, -1)
}
func (m *metrics) notifyReceiverErrored(ctx context.Context, err error) {
m.receiverErrorCounter.Add(ctx, 1, errKindAttribute(err))
}
func (m *metrics) notifyReceiverConnected(ctx context.Context) {
m.receiverConnectionUpDownCounter.Add(ctx, 1)
}
func (m *metrics) notifyReceiverDisconnected(ctx context.Context) {
m.receiverConnectionUpDownCounter.Add(ctx, -1)
}
func (m *metrics) notifyReceiverMessageReceived(ctx context.Context, sender peer.ID) {
// TODO: It is OK to use prometheus for counting messages received per sender.
// Because, there is a handful of recipients. Once the number of senders increase beyond
// 10s we should expose a dedicated HTTP api for querying sender rankings.
m.receiverMessageCounter.Add(ctx, 1, attribute.String("sender", sender.String()))
}
func (m *metrics) notifyLookupRequested(ctx context.Context) {
m.lookupRequestCounter.Add(ctx, 1)
}
func (m *metrics) notifyLookupResponded(ctx context.Context, resultCount int64, timeToFirstResult time.Duration, latency time.Duration, cacheHit bool) {
cacheAttr := attribute.Bool("cached", cacheHit)
if resultCount > 0 {
m.lookupResponseTTFPHistogram.Record(ctx, timeToFirstResult.Milliseconds(), cacheAttr)
}
m.lookupResponseResultCountHistogram.Record(ctx, resultCount, cacheAttr)
m.lookupResponseLatencyHistogram.Record(ctx, latency.Milliseconds(), cacheAttr)
}
func (m *metrics) reportCacheSize(_ context.Context, observer instrument.Int64Observer) error {
observer.Observe(int64(m.c.cache.len()))
return nil
}
func errKindAttribute(err error) attribute.KeyValue {
// TODO check logs for other popular error kinds we might care about.
var errKind string
switch {
case errors.Is(err, context.DeadlineExceeded):
errKind = "deadline-exceeded"
case errors.Is(err, context.Canceled):
errKind = "canceled"
case errors.Is(err, network.ErrReset):
errKind = "stream-reset"
case errors.Is(err, network.ErrResourceLimitExceeded):
errKind = "resource-limit"
case errors.Is(err, swarm.ErrDialBackoff):
errKind = "dial-backoff"
case errors.Is(err, circuitbreaker.ErrOpen):
errKind = "cb-open"
default:
// Unwrap for DialError only checks `Cause` which seems to be nil in dial errors.
// Instead, the errors are added to the field DialErrors and those errors are not
// checked in unwrap. Hence the hack below.
switch e := err.(type) {
case *swarm.DialError:
errKind = "dial-error"
for _, de := range e.DialErrors {
if de.Cause.Error() == "dial backoff" {
errKind = "dial-backoff"
break
}
}
default:
errKind = "other"
}
}
return attribute.String("error-kind", errKind)
}
func (m *metrics) Shutdown(ctx context.Context) error {
return m.server.Shutdown(ctx)
}