forked from cockroachdb/cockroach
/
leaktest.go
95 lines (88 loc) · 2.66 KB
/
leaktest.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
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package leaktest provides tools to detect leaked goroutines in tests.
// To use it, call "defer leaktest.AfterTest(t)()" at the beginning of each
// test that may use goroutines.
package leaktest
import (
"runtime"
"sort"
"strings"
"testing"
"time"
"github.com/petermattis/goid"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
)
// interestingGoroutines returns all goroutines we care about for the purpose
// of leak checking. It excludes testing or runtime ones.
func interestingGoroutines() map[int64]string {
buf := make([]byte, 2<<20)
buf = buf[:runtime.Stack(buf, true)]
gs := make(map[int64]string)
for _, g := range strings.Split(string(buf), "\n\n") {
sl := strings.SplitN(g, "\n", 2)
if len(sl) != 2 {
continue
}
stack := strings.TrimSpace(sl[1])
if strings.HasPrefix(stack, "testing.RunTests") {
continue
}
if stack == "" ||
strings.Contains(stack, "github.com/cockroachdb/cockroach/pkg/util/log.init") ||
// Below are the stacks ignored by the upstream leaktest code.
strings.Contains(stack, "testing.Main(") ||
strings.Contains(stack, "testing.tRunner(") ||
strings.Contains(stack, "runtime.goexit") ||
strings.Contains(stack, "created by runtime.gc") ||
strings.Contains(stack, "interestingGoroutines") ||
strings.Contains(stack, "runtime.MHeap_Scavenger") ||
strings.Contains(stack, "signal.signal_recv") ||
strings.Contains(stack, "sigterm.handler") ||
strings.Contains(stack, "runtime_mcall") ||
strings.Contains(stack, "goroutine in C code") ||
strings.Contains(stack, "runtime.CPUProfile") {
continue
}
gs[goid.ExtractGID([]byte(g))] = g
}
return gs
}
// AfterTest snapshots the currently-running goroutines and returns a
// function to be run at the end of tests to see whether any
// goroutines leaked.
func AfterTest(t testing.TB) func() {
orig := interestingGoroutines()
return func() {
if t.Failed() {
return
}
if r := recover(); r != nil {
panic(r)
}
// Loop, waiting for goroutines to shut down.
// Wait up to 5 seconds, but finish as quickly as possible.
deadline := timeutil.Now().Add(5 * time.Second)
for {
var leaked []string
for id, stack := range interestingGoroutines() {
if _, ok := orig[id]; !ok {
leaked = append(leaked, stack)
}
}
if len(leaked) == 0 {
return
}
if timeutil.Now().Before(deadline) {
time.Sleep(50 * time.Millisecond)
continue
}
sort.Strings(leaked)
for _, g := range leaked {
t.Errorf("Leaked goroutine: %v", g)
}
return
}
}
}