-
Notifications
You must be signed in to change notification settings - Fork 19
/
goroutine.go
426 lines (381 loc) · 9.54 KB
/
goroutine.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
package main
import (
"bytes"
"crypto/md5"
"errors"
"fmt"
"hash"
"io"
"regexp"
"sort"
"strconv"
"strings"
"os"
"github.com/Knetic/govaluate"
"github.com/foize/go.sgr"
)
type MetaType int
var (
MetaState MetaType = 0
MetaDuration MetaType = 1
durationPattern = regexp.MustCompile(`^\d+ minutes$`)
functions = map[string]govaluate.ExpressionFunction{
"contains": func(args ...interface{}) (interface{}, error) {
if len(args) != 2 {
return nil, fmt.Errorf("contains() accepts exactly two arguments")
}
idx := strings.Index(args[0].(string), args[1].(string))
return bool(idx > -1), nil
},
"lower": func(args ...interface{}) (interface{}, error) {
if len(args) != 1 {
return nil, fmt.Errorf("lower() accepts exactly one arguments")
}
lowered := strings.ToLower(args[0].(string))
return string(lowered), nil
},
"upper": func(args ...interface{}) (interface{}, error) {
if len(args) != 1 {
return nil, fmt.Errorf("upper() accepts exactly one arguments")
}
uppered := strings.ToUpper(args[0].(string))
return string(uppered), nil
},
}
)
// Goroutine contains a goroutine info.
type Goroutine struct {
id int
header string
trace string
lines int
duration int // In minutes.
metas map[MetaType]string
lineMd5 []string
fullMd5 string
fullHasher hash.Hash
duplicates []int
frozen bool
buf *bytes.Buffer
}
// AddLine appends a line to the goroutine info.
func (g *Goroutine) AddLine(l string) {
if !g.frozen {
g.lines++
g.buf.WriteString(l)
g.buf.WriteString("\n")
if strings.HasPrefix(l, "\t") {
parts := strings.Split(l, " ")
fl := strings.TrimSpace(parts[0])
h := md5.New()
io.WriteString(h, fl)
g.lineMd5 = append(g.lineMd5, string(h.Sum(nil)))
io.WriteString(g.fullHasher, fl)
}
}
}
// Freeze freezes the goroutine info.
func (g *Goroutine) Freeze() {
if !g.frozen {
g.frozen = true
g.trace = g.buf.String()
g.buf = nil
g.fullMd5 = string(g.fullHasher.Sum(nil))
}
}
// Print outputs the goroutine details to w.
func (g Goroutine) Print(w io.Writer) error {
if _, err := fmt.Fprint(w, g.header); err != nil {
return err
}
if len(g.duplicates) > 0 {
if _, err := fmt.Fprintf(w, " %d times: [[", len(g.duplicates)); err != nil {
return err
}
for i, id := range g.duplicates {
if i > 0 {
if _, err := fmt.Fprint(w, ", "); err != nil {
return err
}
}
if _, err := fmt.Fprint(w, id); err != nil {
return err
}
}
if _, err := fmt.Fprint(w, "]"); err != nil {
return err
}
}
if _, err := fmt.Fprintln(w); err != nil {
return err
}
if _, err := fmt.Fprintln(w, g.trace); err != nil {
return err
}
return nil
}
// PrintWithColor outputs the goroutine details to stdout with color.
func (g Goroutine) PrintWithColor() {
sgr.Printf("[fg-blue]%s[reset]", g.header)
if len(g.duplicates) > 0 {
sgr.Printf(" [fg-red]%d[reset] times: [[", len(g.duplicates))
for i, id := range g.duplicates {
if i > 0 {
sgr.Printf(", ")
}
sgr.Printf("[fg-green]%d[reset]", id)
}
sgr.Print("]")
}
sgr.Println()
fmt.Println(g.trace)
}
// NewGoroutine creates and returns a new Goroutine.
func NewGoroutine(metaline string) (*Goroutine, error) {
idx := strings.Index(metaline, "[")
parts := strings.Split(metaline[idx+1:len(metaline)-2], ",")
metas := map[MetaType]string{
MetaState: strings.TrimSpace(parts[0]),
}
duration := 0
if len(parts) > 1 {
value := strings.TrimSpace(parts[1])
metas[MetaDuration] = value
if durationPattern.MatchString(value) {
if d, err := strconv.Atoi(value[:len(value)-8]); err == nil {
duration = d
}
}
}
idstr := strings.TrimSpace(metaline[9:idx])
id, err := strconv.Atoi(idstr)
if err != nil {
return nil, err
}
return &Goroutine{
id: id,
lines: 1,
header: metaline,
buf: &bytes.Buffer{},
duration: duration,
metas: metas,
fullHasher: md5.New(),
duplicates: []int{},
}, nil
}
// GoroutineDump defines a goroutine dump.
type GoroutineDump struct {
goroutines []*Goroutine
}
// Add appends a goroutine info to the list.
func (gd *GoroutineDump) Add(g *Goroutine) {
gd.goroutines = append(gd.goroutines, g)
}
// Copy duplicates and returns the GoroutineDump.
func (gd GoroutineDump) Copy(cond string) *GoroutineDump {
dump := GoroutineDump{
goroutines: []*Goroutine{},
}
if cond == "" {
// Copy all.
for _, d := range gd.goroutines {
dump.goroutines = append(dump.goroutines, d)
}
} else {
goroutines, err := gd.withCondition(cond, func(i int, g *Goroutine, passed bool) *Goroutine {
if passed {
return g
}
return nil
})
if err != nil {
fmt.Println(err)
return nil
}
dump.goroutines = goroutines
}
return &dump
}
// Dedup finds goroutines with duplicated stack traces and keeps only one copy
// of them.
func (gd *GoroutineDump) Dedup() {
m := map[string][]int{}
for _, g := range gd.goroutines {
if _, ok := m[g.fullMd5]; ok {
m[g.fullMd5] = append(m[g.fullMd5], g.id)
} else {
m[g.fullMd5] = []int{g.id}
}
}
kept := make([]*Goroutine, 0, len(gd.goroutines))
outter:
for digest, ids := range m {
for _, g := range gd.goroutines {
if g.fullMd5 == digest {
g.duplicates = ids
kept = append(kept, g)
continue outter
}
}
}
if len(gd.goroutines) != len(kept) {
fmt.Printf("Dedupped %d, kept %d\n", len(gd.goroutines), len(kept))
gd.goroutines = kept
}
}
// Delete deletes by the condition.
func (gd *GoroutineDump) Delete(cond string) error {
goroutines, err := gd.withCondition(cond, func(i int, g *Goroutine, passed bool) *Goroutine {
if !passed {
return g
}
return nil
})
if err != nil {
return err
}
gd.goroutines = goroutines
return nil
}
// Diff shows the difference between two dumps.
func (gd *GoroutineDump) Diff(another *GoroutineDump) (*GoroutineDump, *GoroutineDump, *GoroutineDump) {
lonly := map[int]*Goroutine{}
ronly := map[int]*Goroutine{}
common := map[int]*Goroutine{}
for _, v := range gd.goroutines {
lonly[v.id] = v
}
for _, v := range another.goroutines {
if _, ok := lonly[v.id]; ok {
delete(lonly, v.id)
common[v.id] = v
} else {
ronly[v.id] = v
}
}
return NewGoroutineDumpFromMap(lonly), NewGoroutineDumpFromMap(common), NewGoroutineDumpFromMap(ronly)
}
// Keep keeps by the condition.
func (gd *GoroutineDump) Keep(cond string) error {
goroutines, err := gd.withCondition(cond, func(i int, g *Goroutine, passed bool) *Goroutine {
if passed {
return g
}
return nil
})
if err != nil {
return err
}
gd.goroutines = goroutines
return nil
}
// Save saves the goroutine dump to the given file.
func (gd GoroutineDump) Save(fn string) error {
f, err := os.Create(fn)
if err != nil {
return err
}
defer f.Close()
for _, g := range gd.goroutines {
if err := g.Print(f); err != nil {
return err
}
}
return nil
}
// Search displays the goroutines with the offset and limit.
func (gd GoroutineDump) Search(cond string, offset, limit int) {
sgr.Printf("[fg-green]Search with offset %d and limit %d.[reset]\n\n", offset, limit)
count := 0
_, err := gd.withCondition(cond, func(i int, g *Goroutine, passed bool) *Goroutine {
if passed {
if count >= offset && count < offset+limit {
g.PrintWithColor()
}
count++
}
return nil
})
if err != nil {
fmt.Println(err)
}
}
// Show displays the goroutines with the offset and limit.
func (gd GoroutineDump) Show(offset, limit int) {
for i := offset; i < offset+limit && i < len(gd.goroutines); i++ {
gd.goroutines[offset+i].PrintWithColor()
}
}
// Sort sorts the goroutine entries.
func (gd *GoroutineDump) Sort() {
fmt.Printf("# of goroutines: %d\n", len(gd.goroutines))
}
// Summary prints the summary of the goroutine dump.
func (gd GoroutineDump) Summary() {
fmt.Printf("# of goroutines: %d\n", len(gd.goroutines))
stats := map[string]int{}
if len(gd.goroutines) > 0 {
for _, g := range gd.goroutines {
stats[g.metas[MetaState]]++
}
fmt.Println()
}
if len(stats) > 0 {
states := make([]string, 0, 10)
for k := range stats {
states = append(states, k)
}
sort.Sort(sort.StringSlice(states))
for _, k := range states {
fmt.Printf("%15s: %d\n", k, stats[k])
}
fmt.Println()
}
}
// NewGoroutineDump creates and returns a new GoroutineDump.
func NewGoroutineDump() *GoroutineDump {
return &GoroutineDump{
goroutines: []*Goroutine{},
}
}
// NewGoroutineDumpFromMap creates and returns a new GoroutineDump from a map.
func NewGoroutineDumpFromMap(gs map[int]*Goroutine) *GoroutineDump {
gd := &GoroutineDump{
goroutines: []*Goroutine{},
}
for _, v := range gs {
gd.goroutines = append(gd.goroutines, v)
}
return gd
}
func (gd *GoroutineDump) withCondition(cond string, callback func(int, *Goroutine, bool) *Goroutine) ([]*Goroutine, error) {
cond = strings.Trim(cond, "\"")
expression, err := govaluate.NewEvaluableExpressionWithFunctions(cond, functions)
if err != nil {
return nil, err
}
goroutines := make([]*Goroutine, 0, len(gd.goroutines))
for i, g := range gd.goroutines {
params := map[string]interface{}{
"id": g.id,
"dups": len(g.duplicates),
"duration": g.duration,
"lines": g.lines,
"state": g.metas[MetaState],
"trace": g.trace,
}
res, err := expression.Evaluate(params)
if err != nil {
return nil, err
}
if val, ok := res.(bool); ok {
if gor := callback(i, g, val); gor != nil {
goroutines = append(goroutines, gor)
}
} else {
return nil, errors.New("argument expression should return a boolean")
}
}
fmt.Printf("Deleted %d goroutines, kept %d.\n", len(gd.goroutines)-len(goroutines), len(goroutines))
return goroutines, nil
}