git » gofer » main » tree

[main] / nettrace / trace.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
// Package nettrace implements tracing of requests. Traces are created by
// nettrace.New, and can then be viewed over HTTP on /debug/traces.
package nettrace

import (
	"container/ring"
	"fmt"
	"math/rand"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"
)

// IDs are of the form "family!timestamp!unique identifier", which allows for
// sorting them by time much easily, and also some convenient optimizations
// when looking up an id across all the known ones.
// Family is not escaped. It should not contain the separator.
// It is not expected to be stable, for internal use only.
type id string

func newID(family string, ts int64) id {
	return id(
		family + "!" +
			strconv.FormatInt(ts, 10) + "!" +
			strconv.FormatUint(rand.Uint64(), 10))
}

func (id id) Family() string {
	sp := strings.SplitN(string(id), "!", 2)
	if len(sp) != 2 {
		return string(id)
	}
	return sp[0]
}

// Trace represents a single request trace.
type Trace interface {
	// NewChild creates a new trace, that is a child of this one.
	NewChild(family, title string) Trace

	// Link to another trace with the given message.
	Link(other Trace, msg string)

	// SetMaxEvents sets the maximum number of events that will be stored in
	// the trace. It must be called right after initialization.
	SetMaxEvents(n int)

	// SetError marks that the trace was for an error event.
	SetError()

	// Printf adds a message to the trace.
	Printf(format string, a ...interface{})

	// Errorf adds a message to the trace, marks it as an error, and returns
	// an error for it.
	Errorf(format string, a ...interface{}) error

	// Finish marks the trace as complete.
	// The trace should not be used after calling this method.
	Finish()
}

// A single trace. Can be active or inactive.
// Exported fields are allowed to be accessed directly, e.g. by the HTTP
// handler. Private ones are mutex protected.
type trace struct {
	ID id

	Family string
	Title  string

	Parent *trace

	Start time.Time

	// Fields below are mu-protected.
	// We keep them unexported so they're not accidentally accessed in html
	// templates.
	mu sync.Mutex

	end time.Time

	isError   bool
	maxEvents int

	// We keep two separate groups: the first ~1/3rd events in a simple slice,
	// and the last 2/3rd in a ring so we can drop events without losing the
	// first ones.
	cutoff      int
	firstEvents []event
	lastEvents  *evtRing
}

type evtType uint8

const (
	evtLOG = evtType(1 + iota)
	evtCHILD
	evtLINK
	evtDROP
)

func (t evtType) IsLog() bool   { return t == evtLOG }
func (t evtType) IsChild() bool { return t == evtCHILD }
func (t evtType) IsLink() bool  { return t == evtLINK }
func (t evtType) IsDrop() bool  { return t == evtDROP }

type event struct {
	When time.Time
	Type evtType

	Ref *trace
	Msg string
}

const defaultMaxEvents = 30

func newTrace(family, title string) *trace {
	start := time.Now()
	tr := &trace{
		ID:     newID(family, start.UnixNano()),
		Family: family,
		Title:  title,
		Start:  start,

		maxEvents: defaultMaxEvents,
		cutoff:    defaultMaxEvents / 3,
	}

	// Pre-allocate a couple of events to speed things up.
	// Don't allocate lastEvents, that can be expensive and it is not always
	// needed. No need to slow down trace creation just for it.
	tr.firstEvents = make([]event, 0, 4)

	familiesMu.Lock()
	ft, ok := families[family]
	if !ok {
		ft = newFamilyTraces()
		families[family] = ft
	}
	familiesMu.Unlock()

	ft.mu.Lock()
	ft.active[tr.ID] = tr
	ft.mu.Unlock()

	return tr
}

// New creates a new trace with the given family and title.
func New(family, title string) Trace {
	return newTrace(family, title)
}

func (tr *trace) append(evt *event) {
	tr.mu.Lock()
	defer tr.mu.Unlock()

	if len(tr.firstEvents) < tr.cutoff {
		tr.firstEvents = append(tr.firstEvents, *evt)
		return
	}

	if tr.lastEvents == nil {
		// The ring holds the last 2/3rds of the events.
		tr.lastEvents = newEvtRing(tr.maxEvents - tr.cutoff)
	}

	tr.lastEvents.Add(evt)
}

// String is for debugging only.
func (tr *trace) String() string {
	return fmt.Sprintf("trace{%s, %s, %q, %d}",
		tr.Family, tr.Title, tr.ID, len(tr.Events()))
}

func (tr *trace) NewChild(family, title string) Trace {
	c := newTrace(family, title)
	c.Parent = tr

	// Add the event to the parent.
	evt := &event{
		When: time.Now(),
		Type: evtCHILD,
		Ref:  c,
	}
	tr.append(evt)

	return c
}

func (tr *trace) Link(other Trace, msg string) {
	evt := &event{
		When: time.Now(),
		Type: evtLINK,
		Ref:  other.(*trace),
		Msg:  msg,
	}
	tr.append(evt)
}

func (tr *trace) SetMaxEvents(n int) {
	// Set a minimum of 6, so the truncation works without running into
	// issues.
	if n < 6 {
		n = 6
	}
	tr.mu.Lock()
	tr.maxEvents = n
	tr.cutoff = n / 3
	tr.mu.Unlock()
}

func (tr *trace) SetError() {
	tr.mu.Lock()
	tr.isError = true
	tr.mu.Unlock()
}

func (tr *trace) Printf(format string, a ...interface{}) {
	evt := &event{
		When: time.Now(),
		Type: evtLOG,
		Msg:  fmt.Sprintf(format, a...),
	}

	tr.append(evt)
}

func (tr *trace) Errorf(format string, a ...interface{}) error {
	tr.SetError()
	err := fmt.Errorf(format, a...)
	tr.Printf(err.Error())
	return err
}

func (tr *trace) Finish() {
	tr.mu.Lock()
	tr.end = time.Now()
	tr.mu.Unlock()

	familiesMu.Lock()
	ft := families[tr.Family]
	familiesMu.Unlock()
	ft.finalize(tr)
}

// Duration of this trace.
func (tr *trace) Duration() time.Duration {
	tr.mu.Lock()
	start, end := tr.Start, tr.end
	tr.mu.Unlock()

	if end.IsZero() {
		return time.Since(start)
	}
	return end.Sub(start)
}

// Events returns a copy of the trace events.
func (tr *trace) Events() []event {
	tr.mu.Lock()
	defer tr.mu.Unlock()

	evts := make([]event, len(tr.firstEvents))
	copy(evts, tr.firstEvents)

	if tr.lastEvents == nil {
		return evts
	}

	if !tr.lastEvents.firstDrop.IsZero() {
		evts = append(evts, event{
			When: tr.lastEvents.firstDrop,
			Type: evtDROP,
		})
	}

	tr.lastEvents.Do(func(e *event) {
		evts = append(evts, *e)
	})

	return evts
}

func (tr *trace) IsError() bool {
	tr.mu.Lock()
	defer tr.mu.Unlock()
	return tr.isError
}

//
// Trace hierarchy
//
// Each trace belongs to a family. For each family, we have all active traces,
// and then N traces that finished <1s, N that finished <2s, etc.

// We keep this many buckets of finished traces.
const nBuckets = 8

// Buckets to use. Length must match nBuckets.
// "Traces with a latency >= $duration".
var buckets = []time.Duration{
	time.Duration(0),
	5 * time.Millisecond,
	10 * time.Millisecond,
	50 * time.Millisecond,
	100 * time.Millisecond,
	300 * time.Millisecond,
	1 * time.Second,
	10 * time.Second,
}

func findBucket(latency time.Duration) int {
	for i, d := range buckets {
		if latency >= d {
			continue
		}
		return i - 1
	}

	return nBuckets - 1
}

// How many traces we keep per bucket.
const tracesInBucket = 10

type traceRing struct {
	ring *ring.Ring
	max  int
	l    int
}

func newTraceRing(n int) *traceRing {
	return &traceRing{
		ring: ring.New(n),
		max:  n,
	}
}

func (r *traceRing) Add(tr *trace) {
	r.ring.Value = tr
	r.ring = r.ring.Next()
	if r.l < r.max {
		r.l++
	}
}

func (r *traceRing) Len() int {
	return r.l
}

func (r *traceRing) Do(f func(tr *trace)) {
	r.ring.Do(func(x interface{}) {
		if x == nil {
			return
		}
		f(x.(*trace))
	})
}

type familyTraces struct {
	mu sync.Mutex

	// All active ones.
	active map[id]*trace

	// The ones we decided to keep.
	// Each bucket is a ring-buffer, finishedHead keeps the head pointer.
	finished [nBuckets]*traceRing

	// The ones that errored have their own bucket.
	errors *traceRing

	// Histogram of latencies.
	latencies histogram
}

func newFamilyTraces() *familyTraces {
	ft := &familyTraces{}
	ft.active = map[id]*trace{}
	for i := 0; i < nBuckets; i++ {
		ft.finished[i] = newTraceRing(tracesInBucket)
	}
	ft.errors = newTraceRing(tracesInBucket)
	return ft
}

func (ft *familyTraces) LenActive() int {
	ft.mu.Lock()
	defer ft.mu.Unlock()
	return len(ft.active)
}

func (ft *familyTraces) LenErrors() int {
	ft.mu.Lock()
	defer ft.mu.Unlock()
	return ft.errors.Len()
}

func (ft *familyTraces) LenBucket(b int) int {
	ft.mu.Lock()
	defer ft.mu.Unlock()
	return ft.finished[b].Len()
}

func (ft *familyTraces) TracesFor(b int, allgt bool) []*trace {
	ft.mu.Lock()
	defer ft.mu.Unlock()

	trs := []*trace{}
	appendTrace := func(tr *trace) {
		trs = append(trs, tr)
	}
	if b == -2 {
		ft.errors.Do(appendTrace)
	} else if b == -1 {
		for _, tr := range ft.active {
			appendTrace(tr)
		}
	} else if b < nBuckets {
		ft.finished[b].Do(appendTrace)
		if allgt {
			for i := b + 1; i < nBuckets; i++ {
				ft.finished[i].Do(appendTrace)
			}
		}
	}

	// Sort them by start, newer first. This is the order that will be used
	// when displaying them.
	sort.Slice(trs, func(i, j int) bool {
		return trs[i].Start.After(trs[j].Start)
	})
	return trs
}

func (ft *familyTraces) find(id id) *trace {
	ft.mu.Lock()
	defer ft.mu.Unlock()

	if tr, ok := ft.active[id]; ok {
		return tr
	}

	var found *trace
	for _, bs := range ft.finished {
		bs.Do(func(tr *trace) {
			if tr.ID == id {
				found = tr
			}
		})
		if found != nil {
			return found
		}
	}

	ft.errors.Do(func(tr *trace) {
		if tr.ID == id {
			found = tr
		}
	})
	if found != nil {
		return found
	}

	return nil
}

func (ft *familyTraces) finalize(tr *trace) {
	latency := tr.end.Sub(tr.Start)
	b := findBucket(latency)

	ft.mu.Lock()

	// Delete from the active list.
	delete(ft.active, tr.ID)

	// Add it to the corresponding finished bucket, based on the trace
	// latency.
	ft.finished[b].Add(tr)

	// Errors go on their own list, in addition to the above.
	if tr.isError {
		ft.errors.Add(tr)
	}

	ft.latencies.Add(b, latency)

	ft.mu.Unlock()
}

func (ft *familyTraces) Latencies() *histSnapshot {
	ft.mu.Lock()
	defer ft.mu.Unlock()
	return ft.latencies.Snapshot()
}

//
// Global state
//

var (
	familiesMu sync.Mutex
	families   = map[string]*familyTraces{}
)

func copyFamilies() map[string]*familyTraces {
	n := map[string]*familyTraces{}

	familiesMu.Lock()
	for f, trs := range families {
		n[f] = trs
	}
	familiesMu.Unlock()

	return n
}

func findInFamilies(traceID id, refID id) *trace {
	// First, try to find it via the family.
	family := traceID.Family()
	familiesMu.Lock()
	fts, ok := families[family]
	familiesMu.Unlock()

	if ok {
		tr := fts.find(traceID)
		if tr != nil {
			return tr
		}
	}

	// If that fail and we have a reference, try finding via it.
	// The reference can be a parent or a child.
	if refID != id("") {
		ref := findInFamilies(refID, "")
		if ref == nil {
			return nil
		}

		// Is the reference's parent the one we're looking for?
		if ref.Parent != nil && ref.Parent.ID == traceID {
			return ref.Parent
		}

		// Try to find it in the ref's events.
		for _, e := range ref.Events() {
			if e.Ref != nil && e.Ref.ID == traceID {
				return e.Ref
			}
		}
	}
	return nil
}