/
impatient_debug_dumper.go
242 lines (218 loc) · 6.55 KB
/
impatient_debug_dumper.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
package libkbfs
import (
"bytes"
"compress/gzip"
"context"
"encoding/base64"
"fmt"
"runtime/pprof"
"sync"
"sync/atomic"
"time"
"github.com/adamwalz/keybase-client/go/logger"
"golang.org/x/time/rate"
)
type ctxTimeTracker struct {
ctx context.Context
expiresAt time.Time
done int32
}
func (c *ctxTimeTracker) markDone() {
atomic.StoreInt32(&c.done, 1)
}
func (c *ctxTimeTracker) isDone() bool {
return atomic.LoadInt32(&c.done) == 1
}
func (c *ctxTimeTracker) isExpired(clock Clock) bool {
return clock.Now().After(c.expiresAt)
}
type ctxTimeTrackerListNode struct {
tracker *ctxTimeTracker
next *ctxTimeTrackerListNode
}
type ctxTimeTrackerList struct {
front *ctxTimeTrackerListNode
tail *ctxTimeTrackerListNode
}
func (c *ctxTimeTrackerList) peekFront() (t *ctxTimeTracker) {
if c.front == nil {
return nil
}
return c.front.tracker
}
func (c *ctxTimeTrackerList) popFront() (t *ctxTimeTracker) {
if c.front == nil {
return nil
}
t = c.front.tracker
c.front = c.front.next
if c.front == nil {
// last one!
c.tail = nil
}
return t
}
func (c *ctxTimeTrackerList) append(t *ctxTimeTracker) {
newNode := &ctxTimeTrackerListNode{
tracker: t,
}
if c.tail != nil {
c.tail.next = newNode
}
c.tail = newNode
if c.front == nil {
c.front = newNode
}
}
// ImpatientDebugDumper dumps all running goroutines if an operation takes
// longer than a preset value. User of this type should call Begin() with a
// context associated with an operation, and call the returned function when
// the operation is done. If the operation finishes within the preset duration,
// nothing is dumped into log. Despite being impatient, it tries not to pollute
// the log too much by rate limit goroutine dumping based on
// impatientDebugDumperDumpMinInterval (at most 1 per minute).
type ImpatientDebugDumper struct {
config Config
log logger.Logger
dumpIn time.Duration
ticker *time.Ticker
limiter *rate.Limiter
shutdownFunc func()
shutdownDoneCh chan struct{}
lock sync.Mutex
chronologicalTimeTrackerList *ctxTimeTrackerList
}
const impatientDebugDumperCheckInterval = time.Second
const impatientDebugDumperDumpMinInterval = time.Minute // 1 dump per min max
// NewImpatientDebugDumper creates a new *ImpatientDebugDumper, which logs with
// a logger made by config.MakeLogger("IGD"), and dumps goroutines if an
// operation takes longer than dumpIn.
func NewImpatientDebugDumper(config Config, dumpIn time.Duration) *ImpatientDebugDumper {
ctx, cancel := context.WithCancel(context.Background())
d := &ImpatientDebugDumper{
config: config,
log: config.MakeLogger("IGD"),
dumpIn: dumpIn,
ticker: time.NewTicker(impatientDebugDumperCheckInterval),
limiter: rate.NewLimiter(
rate.Every(impatientDebugDumperDumpMinInterval), 1),
shutdownFunc: cancel,
shutdownDoneCh: make(chan struct{}),
chronologicalTimeTrackerList: &ctxTimeTrackerList{},
}
go d.dumpLoop(ctx.Done())
return d
}
// NewImpatientDebugDumperForForcedDumps creates a new
// *ImpatientDebugDumper, just as above, though without launching any
// background goroutines or allowing the user to begin any
// time-tracked tasks. `ForceDump` is the only way to obtain a dump
// from a dumper constructed with this function.
func NewImpatientDebugDumperForForcedDumps(config Config) *ImpatientDebugDumper {
return &ImpatientDebugDumper{
config: config,
log: config.MakeLogger("IGD"),
limiter: rate.NewLimiter(
rate.Every(impatientDebugDumperDumpMinInterval), 1),
}
}
func (d *ImpatientDebugDumper) dump(ctx context.Context) {
if !d.limiter.Allow() {
// Use a limiter to avoid dumping too much into log accidently.
return
}
buf := &bytes.Buffer{}
base64er := base64.NewEncoder(base64.StdEncoding, buf)
gzipper := gzip.NewWriter(base64er)
for _, p := range pprof.Profiles() {
fmt.Fprintf(gzipper,
"\n======== START Profile: %s ========\n\n", p.Name())
_ = p.WriteTo(gzipper, 2)
fmt.Fprintf(gzipper,
"\n======== END Profile: %s ========\n\n", p.Name())
}
gzipper.Close()
base64er.Close()
d.log.CDebugf(ctx,
"Operation exceeded max wait time. dump>gzip>base64: %q "+
"Pipe the quoted content into ` | base64 -d | gzip -d ` "+
"to read as a Homosapien.", buf.String())
}
// ForceDump dumps all debug info to the log, if it hasn't done so
// recently according to the rate-limiter.
func (d *ImpatientDebugDumper) ForceDump(ctx context.Context) {
d.dump(ctx)
}
func (d *ImpatientDebugDumper) dumpTick() {
d.lock.Lock()
defer d.lock.Unlock()
for {
// In each iteration we deal with the front of list:
// 1) If list is empty, we just return and wait for the next tick;
// 2) If front is done, pop front from the list, and continue into
// next iteration to check next one;
// 3) If front is not done but expired, dump routines (if rate limiter
// permits), pop front from the list, and continue into next
// iteration to check next one;
// 4) If front is not done yet nor expired, just return and wait for
// next tick when we check again.
//
// Since we either move on or return, there's no risk of infinite
// looping here.
t := d.chronologicalTimeTrackerList.peekFront()
if t == nil {
return
}
if t.isDone() {
// This operation is done, so just move on.
d.chronologicalTimeTrackerList.popFront()
continue
}
if t.isExpired(d.config.Clock()) {
// This operation isn't done, and it has expired. So dump debug
// information and move on.
d.dump(t.ctx)
d.chronologicalTimeTrackerList.popFront()
continue
}
// This operation isn't done yet, but it also hasn't expired. So
// just return and wait for next tick and check again.
return
}
}
func (d *ImpatientDebugDumper) dumpLoop(shutdownCh <-chan struct{}) {
defer close(d.shutdownDoneCh)
for {
select {
case <-d.ticker.C:
d.dumpTick()
case <-shutdownCh:
d.ticker.Stop()
d.log.Debug("shutdown")
return
}
}
}
// Begin causes d to start tracking time for ctx. The returned function should
// be called once the associated operation is done, likely in a defer
// statement.
func (d *ImpatientDebugDumper) Begin(ctx context.Context) (done func()) {
if d.chronologicalTimeTrackerList == nil {
return nil
}
tracker := &ctxTimeTracker{
ctx: ctx,
expiresAt: d.config.Clock().Now().Add(d.dumpIn),
}
d.lock.Lock()
defer d.lock.Unlock()
d.chronologicalTimeTrackerList.append(tracker)
return tracker.markDone
}
// Shutdown shuts down d idempotently.
func (d *ImpatientDebugDumper) Shutdown() {
if d.shutdownFunc != nil {
d.shutdownFunc()
<-d.shutdownDoneCh
}
}