-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetrics.go
619 lines (532 loc) · 13.2 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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
package waf
import (
"fmt"
"math"
"sort"
"strings"
"sync"
"time"
"github.com/rs/zerolog"
"gitlab.com/tozd/go/errors"
)
const (
MetricCompress = "c"
MetricJSONMarshal = "j"
MetricTotal = "t"
)
const serverTimingHeader = "Server-Timing"
// DurationMeasurement is a measurement of a duration.
type DurationMeasurement struct {
startTime time.Time
Discarded bool
Duration time.Duration
}
// Start records the start of the duration.
func (d *DurationMeasurement) Start() *DurationMeasurement {
if d == nil || d.Discarded {
return d
}
if !d.startTime.IsZero() {
panic(errors.New("duration measurement already started"))
}
d.startTime = time.Now()
return d
}
// Stop computes the duration.
func (d *DurationMeasurement) Stop() *DurationMeasurement {
if d == nil || d.Discarded {
return d
}
if d.startTime.IsZero() {
panic(errors.New("duration measurement not started"))
}
if d.Duration != 0 {
panic(errors.New("duration measurement already stopped"))
}
d.Duration = time.Since(d.startTime)
return d
}
// Discard discards the measurement.
//
// Any future calls to measurement methods are ignored.
func (d *DurationMeasurement) Discard() *DurationMeasurement {
if d == nil {
return d
}
d.Discarded = true
return d
}
// DurationMetric is a metric of a duration.
type DurationMetric struct {
name string
startTime time.Time
Discarded bool
Duration time.Duration
}
func (d *DurationMetric) Name() string {
if d == nil {
return ""
}
return d.name
}
func (d *DurationMetric) MarshalZerologObject(e *zerolog.Event) {
// We use only really measured durations and not just started
// (it is impossible to both start and end the measurement with 0 duration).
if d == nil || d.Discarded || d.Duration == 0 {
return
}
e.Dur(d.name, d.Duration)
}
func (d *DurationMetric) ServerTimingString() string {
// We use only really measured durations and not just started
// (it is impossible to both start and end the measurement with 0 duration).
if d == nil || d.Discarded || d.Duration == 0 {
return ""
}
// We want only millisecond precision to minimize any side channels.
return fmt.Sprintf("%s;dur=%d", d.name, d.Duration.Milliseconds())
}
// Start records the start of the duration.
//
// Can be called only once per metric.
func (d *DurationMetric) Start() *DurationMetric {
if d == nil || d.Discarded {
return d
}
if !d.startTime.IsZero() {
panic(errors.New("duration metric already started"))
}
d.startTime = time.Now()
return d
}
// Stop computes the duration.
func (d *DurationMetric) Stop() *DurationMetric {
if d == nil || d.Discarded {
return d
}
if d.startTime.IsZero() {
panic(errors.New("duration metric not started"))
}
if d.Duration != 0 {
panic(errors.New("duration metric already stopped"))
}
d.Duration = time.Since(d.startTime)
return d
}
// Discard discards the metric.
//
// Any future calls to metric methods are ignored.
func (d *DurationMetric) Discard() *DurationMetric {
if d == nil {
return d
}
d.Discarded = true
return d
}
// CounterMetric is a counter metric.
type CounterMetric struct {
name string
Discarded bool
Count int64
}
func (c *CounterMetric) Name() string {
if c == nil {
return ""
}
return c.name
}
func (c *CounterMetric) MarshalZerologObject(e *zerolog.Event) {
if c == nil || c.Discarded {
return
}
e.Int64(c.name, c.Count)
}
func (c *CounterMetric) ServerTimingString() string {
// Not supported.
// TODO: Should we use non-standard key name?
return ""
}
// Inc increases the counter by one.
func (c *CounterMetric) Inc() *CounterMetric {
if c == nil || c.Discarded {
return c
}
c.Count++
return c
}
// Add increases the counter by n.
func (c *CounterMetric) Add(n int64) *CounterMetric {
if c == nil || c.Discarded {
return c
}
c.Count += n
return c
}
// Discard discards the metric.
//
// Any future calls to metric methods are ignored.
func (c *CounterMetric) Discard() *CounterMetric {
if c == nil {
return c
}
c.Discarded = true
return c
}
// DurationsMetric is a metric of multiple durations.
type DurationsMetric struct {
name string
Discarded bool
Durations []*DurationMeasurement
// Lock for appending to Durations.
mu sync.Mutex
}
func (d *DurationsMetric) Name() string {
if d == nil {
return ""
}
return d.name
}
func (d *DurationsMetric) MarshalZerologObject(e *zerolog.Event) {
if d == nil || d.Discarded {
return
}
var minDuration time.Duration = math.MaxInt64
var maxDuration time.Duration
var sum time.Duration
var count int
for _, m := range d.Durations {
// We use only really measured durations and not just started
// (it is impossible to both start and end the measurement with 0 duration).
if m.Discarded || m.Duration == 0 {
continue
}
if minDuration > m.Duration {
minDuration = m.Duration
}
if maxDuration < m.Duration {
maxDuration = m.Duration
}
sum += m.Duration
count++
}
if count == 0 {
return
}
dict := zerolog.Dict()
// We add fields in the alphabetical order to match Go JSON marshaling order.
dict.Dur("avg", time.Duration(int64(maxDuration-minDuration)/int64(count)))
dict.Int("count", count)
dict.Dur("dur", sum)
dict.Dur("max", maxDuration)
dict.Dur("min", minDuration)
e.Dict(d.name, dict)
}
func (d *DurationsMetric) ServerTimingString() string {
// Not supported.
// TODO: Should we support non-standard key name? Or use average? Or return multiple durations, one for min, avg, and max?
return ""
}
// Start starts a new duration measurement.
//
// Can be called multiple times per metric with each call returning a new measurement.
func (d *DurationsMetric) Start() *DurationMeasurement {
if d == nil {
return nil
}
m := new(DurationMeasurement)
if d.Discarded {
m.Discarded = true
return m
}
d.mu.Lock()
d.Durations = append(d.Durations, m)
d.mu.Unlock()
// We call Start outside of lock to minimize its impact on measurement.
return m.Start()
}
// Discard discards the metric.
//
// Any future calls to Start return an already discarded duration measurement.
func (d *DurationsMetric) Discard() *DurationsMetric {
if d == nil {
return d
}
d.Discarded = true
return d
}
// DurationCounterMetric is a counter metric with a duration.
type DurationCounterMetric struct {
name string
startTime time.Time
Discarded bool
Duration time.Duration
Count int64
}
func (d *DurationCounterMetric) Name() string {
if d == nil {
return ""
}
return d.name
}
func (d *DurationCounterMetric) MarshalZerologObject(e *zerolog.Event) {
// We use only really measured durations and not just started
// (it is impossible to both start and end the measurement with 0 duration).
if d == nil || d.Discarded || d.Duration == 0 {
return
}
dict := zerolog.Dict()
// We add fields in the alphabetical order to match Go JSON marshaling order.
dict.Int64("count", d.Count)
dict.Dur("dur", d.Duration)
dict.Float64("rate", float64(d.Count)/d.Duration.Seconds())
e.Dict(d.name, dict)
}
func (d *DurationCounterMetric) ServerTimingString() string {
// We use only really measured durations and not just started
// (it is impossible to both start and end the measurement with 0 duration).
if d == nil || d.Discarded || d.Duration == 0 {
return ""
}
// We want only millisecond precision to minimize any side channels.
return fmt.Sprintf("%s;dur=%d", d.name, d.Duration.Milliseconds())
}
// Start records the start of the duration.
//
// Can be called only once per metric.
func (d *DurationCounterMetric) Start() *DurationCounterMetric {
if d == nil || d.Discarded {
return d
}
if !d.startTime.IsZero() {
panic(errors.New("duration counter metric already started"))
}
d.startTime = time.Now()
return d
}
// Stop computes the duration.
func (d *DurationCounterMetric) Stop() *DurationCounterMetric {
if d == nil || d.Discarded {
return d
}
if d.startTime.IsZero() {
panic(errors.New("duration counter metric not started"))
}
if d.Duration != 0 {
panic(errors.New("duration counter metric already stopped"))
}
d.Duration = time.Since(d.startTime)
return d
}
// Inc increases the counter by one.
//
// Only possible after calling Start and before calling Stop.
func (d *DurationCounterMetric) Inc() *DurationCounterMetric {
if d == nil || d.Discarded {
return d
}
if d.startTime.IsZero() {
panic(errors.New("duration counter metric not started"))
}
if d.Duration != 0 {
panic(errors.New("duration counter metric already stopped"))
}
d.Count++
return d
}
// Add increases the counter by n.
//
// Only possible after calling Start and before calling Stop.
func (d *DurationCounterMetric) Add(n int64) *DurationCounterMetric {
if d == nil || d.Discarded {
return d
}
if d.startTime.IsZero() {
panic(errors.New("duration counter metric not started"))
}
if d.Duration != 0 {
panic(errors.New("duration counter metric already stopped"))
}
d.Count += n
return d
}
// Discard discards the metric.
//
// Any future calls to metric methods are ignored.
func (d *DurationCounterMetric) Discard() *DurationCounterMetric {
if d == nil {
return d
}
d.Discarded = true
return d
}
type metric interface {
// All metrics also implement Start() method.
Name() string
zerolog.LogObjectMarshaler
ServerTimingString() string
}
// Metrics is a set of metrics.
//
// Only one metric can exist with a given name.
type Metrics struct {
metrics map[string]metric
mu sync.Mutex
}
// NewMetrics returns new initialized Metrics.
func NewMetrics() *Metrics {
return &Metrics{
metrics: map[string]metric{},
mu: sync.Mutex{},
}
}
// TODO: Return same type as mt type.
// See: https://github.com/golang/go/issues/49085
// Add adds a metric to the set of metrics.
//
// If an existing metric has the same name,
// nothing is added if the existing metric is equal
// to the metric being added. Otherwise Add panics.
func (m *Metrics) Add(mt metric) {
if m == nil {
return
}
m.mu.Lock()
defer m.mu.Unlock()
if t, ok := m.metrics[mt.Name()]; ok {
if t == mt {
return
}
errE := errors.New("duplicate metric")
errors.Details(errE)["name"] = mt.Name()
panic(errE)
}
m.metrics[mt.Name()] = mt
}
// Duration returns a new duration metric.
//
// If called with the name of an existing duration metric,
// that duration metric is returned instead.
func (m *Metrics) Duration(name string) *DurationMetric {
if m == nil {
return nil
}
m.mu.Lock()
defer m.mu.Unlock()
if d, ok := m.metrics[name]; ok {
if dm, ok := d.(*DurationMetric); ok {
return dm
}
errE := errors.New("duplicate metric")
errors.Details(errE)["name"] = name
panic(errE)
}
dm := &DurationMetric{name: name} //nolint:exhaustruct
m.metrics[name] = dm
return dm
}
// Counter returns a new counter metric.
//
// If called with the name of an existing counter metric,
// that counter metric is returned instead.
func (m *Metrics) Counter(name string) *CounterMetric {
if m == nil {
return nil
}
m.mu.Lock()
defer m.mu.Unlock()
if c, ok := m.metrics[name]; ok {
if cm, ok := c.(*CounterMetric); ok {
return cm
}
errE := errors.New("duplicate metric")
errors.Details(errE)["name"] = name
panic(errE)
}
cm := &CounterMetric{name: name} //nolint:exhaustruct
m.metrics[name] = cm
return cm
}
// Durations returns a new durations metric.
//
// If called with the name of an existing durations metric,
// that durations metric is returned instead.
func (m *Metrics) Durations(name string) *DurationsMetric {
if m == nil {
return nil
}
m.mu.Lock()
defer m.mu.Unlock()
if d, ok := m.metrics[name]; ok {
if dm, ok := d.(*DurationsMetric); ok {
return dm
}
errE := errors.New("duplicate metric")
errors.Details(errE)["name"] = name
panic(errE)
}
dm := &DurationsMetric{name: name} //nolint:exhaustruct
m.metrics[name] = dm
return dm
}
// DurationCounter returns a new duration counter metric.
//
// If called with the name of an existing duration counter metric,
// that duration counter metric is returned instead.
func (m *Metrics) DurationCounter(name string) *DurationCounterMetric {
if m == nil {
return nil
}
m.mu.Lock()
defer m.mu.Unlock()
if d, ok := m.metrics[name]; ok {
if dm, ok := d.(*DurationCounterMetric); ok {
return dm
}
errE := errors.New("duplicate metric")
errors.Details(errE)["name"] = name
panic(errE)
}
dm := &DurationCounterMetric{name: name} //nolint:exhaustruct
m.metrics[name] = dm
return dm
}
func (m *Metrics) MarshalZerologObject(e *zerolog.Event) {
if m == nil {
return
}
m.mu.Lock()
defer m.mu.Unlock()
if len(m.metrics) == 0 {
return
}
// We sort names so that we log them always in the same order to make logs reproducible.
metrics := make([]string, 0, len(m.metrics))
for name := range m.metrics {
metrics = append(metrics, name)
}
sort.Strings(metrics)
for _, name := range metrics {
m.metrics[name].MarshalZerologObject(e)
}
}
func (m *Metrics) ServerTimingString() string {
if m == nil {
return ""
}
m.mu.Lock()
defer m.mu.Unlock()
// We sort names so that we log them always in the same order to make headers reproducible.
metrics := make([]string, 0, len(m.metrics))
for name := range m.metrics {
metrics = append(metrics, name)
}
sort.Strings(metrics)
parts := make([]string, 0, len(m.metrics))
for _, name := range metrics {
part := m.metrics[name].ServerTimingString()
if part != "" {
parts = append(parts, part)
}
}
return strings.Join(parts, ",")
}