forked from DataDog/gostackparse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gostackparse_test.go
448 lines (406 loc) · 11 KB
/
gostackparse_test.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2021 Datadog, Inc.
package gostackparse
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/stretchr/testify/require"
)
var update = flag.Bool("update", false, "update golden files")
// TestParse_GoldenFiles verifies the output of the parser for a set of input
// files in the test-fixtures. If you want to test a new behavior or bug fix,
// this is the best place to do it.
func TestParse_GoldenFiles(t *testing.T) {
inputs, err := filepath.Glob(filepath.Join("test-fixtures", "*.txt"))
require.NoError(t, err)
for _, input := range inputs {
inputData, err := ioutil.ReadFile(input)
require.NoError(t, err)
golden := strings.TrimSuffix(input, filepath.Ext(input)) + ".golden.json"
goroutines, errs := Parse(bytes.NewReader(inputData))
var errS []string
for _, err := range errs {
errS = append(errS, err.Error())
}
actual, err := json.MarshalIndent(struct {
Errors []string
Goroutines []*Goroutine
}{errS, goroutines}, "", " ")
actual = append(actual, '\n')
require.NoError(t, err)
if *update {
ioutil.WriteFile(golden, actual, 0644)
}
expected, _ := ioutil.ReadFile(golden)
require.True(t, bytes.Equal(actual, expected), golden)
}
}
// TestParse_PropertyBased does an exhaustive property based test against all
// possible permutations of a few interesting line fragements defined below,
// making sure the parser always does the right thing and never panics. This
// test is complex and shouldn't be extended unless there is a good reason for
// doing so. It's essentially just a very agressive smoke test.
func TestParse_PropertyBased(t *testing.T) {
seen := map[string]bool{}
tests := fixtures.Permutations()
for i := 0; i < tests; i++ {
dump := fixtures.Generate(i)
dumpS := dump.String()
msg := fmt.Sprintf("permutation %d:\n%s", i, dumpS)
require.False(t, seen[dumpS], msg)
seen[dumpS] = true
goroutines, errs := Parse(strings.NewReader(dumpS))
wantErr := dump.header.WantErr
for _, f := range dump.stack {
if wantErr != "" {
break
} else if f.fn.WantErr != "" {
wantErr = f.fn.WantErr
} else if f.file.WantErr != "" {
wantErr = f.file.WantErr
}
}
if wantErr == "" {
wantErr = dump.createdBy.fn.WantErr
}
if wantErr == "" && dump.createdBy.fn.WantFrame != nil {
wantErr = dump.createdBy.file.WantErr
}
if wantErr != "" {
require.NotNil(t, errs, msg)
require.Contains(t, errs[0].Error(), wantErr, msg)
require.Equal(t, 0, len(goroutines), msg)
continue
}
require.Nil(t, errs, msg)
require.Equal(t, 1, len(goroutines), msg)
g := goroutines[0]
require.Equal(t, dump.header.WantG.ID, g.ID, msg)
require.Equal(t, dump.header.WantG.State, g.State, msg)
require.Equal(t, dump.header.WantG.Wait, g.Wait, msg)
require.Equal(t, dump.header.WantG.LockedToThread, g.LockedToThread, msg)
require.Equal(t, len(dump.stack), len(g.Stack), msg)
for i, dumpFrame := range dump.stack {
gFrame := g.Stack[i]
require.Equal(t, dumpFrame.fn.WantFrame.Func, gFrame.Func, msg)
require.Equal(t, dumpFrame.file.WantFrame.File, gFrame.File, msg)
require.Equal(t, dumpFrame.file.WantFrame.Line, gFrame.Line, msg)
}
if dump.createdBy.fn.WantFrame == nil {
require.Nil(t, g.CreatedBy, msg)
} else {
require.Equal(t, dump.createdBy.fn.WantFrame.Func, g.CreatedBy.Func, msg)
require.Equal(t, dump.createdBy.file.WantFrame.File, g.CreatedBy.File, msg)
require.Equal(t, dump.createdBy.file.WantFrame.Line, g.CreatedBy.Line, msg)
}
}
t.Logf("executed %d tests", tests)
}
type dump struct {
header headerLine
stack []frameLines
createdBy frameLines
}
func (d *dump) String() string {
s := d.header.String()
for _, f := range d.stack {
s += f.String()
}
s += d.createdBy.String()
return s
}
type headerLine struct {
Line string
WantG *Goroutine
WantErr string
}
func (h *headerLine) String() string {
return h.Line + "\n"
}
type frameLines struct {
fn frameLine
file frameLine
}
func (f *frameLines) String() string {
return f.fn.Line + "\n" + f.file.Line + "\n"
}
type frameLine struct {
Line string
WantFrame *Frame
WantErr string
}
// generator generates all possible goroutine stack trace permutations based on
// the given stack depths and line fragements.
type generator struct {
minStack int
maxStack int
headers []headerLine
funcs []frameLine
files []frameLine
createdBy []frameLine
}
func (g *generator) Generate(n int) *dump {
// keep going around in circles
n = n % g.Permutations()
header := n % len(g.headers)
n = n / len(g.headers)
cFn := n % len(g.createdBy)
n = n / len(g.createdBy)
cFile := n % len(g.files)
n = n / len(g.files)
var stack []frameLines
for d := 0; d < g.maxStack && (n > 0 || d < g.minStack); d++ {
fn := n % len(g.funcs)
n = n / len(g.funcs)
file := n % len(g.files)
n = n / len(g.files)
frame := frameLines{
fn: g.funcs[fn],
file: g.files[file],
}
stack = append(stack, frame)
}
d := &dump{
header: g.headers[header],
stack: stack,
createdBy: frameLines{
fn: g.createdBy[cFn],
file: g.files[cFile],
},
}
return d
}
func (g *generator) Permutations() int {
p := 0
for d := g.minStack; d <= g.maxStack; d++ {
pp := 1
for frame := 0; frame < d; frame++ {
pp = pp * len(g.files) * len(g.funcs)
}
p += len(g.headers) * pp * len(g.createdBy) * len(g.files)
}
return p
}
var fixtures = generator{
// Testing larger stack depths greatly increases the number of permutations
// but is unlikely to shake out more bugs, so a depth of 1 to 2 seems like
// the sweet spot.
minStack: 1,
maxStack: 2,
headers: []headerLine{
{
Line: "goroutine 1 [chan receive]:",
WantG: &Goroutine{ID: 1, State: "chan receive", Wait: 0},
},
{
Line: "goroutine 2 [IO Wait, locked to thread]:",
WantG: &Goroutine{ID: 2, State: "IO Wait", Wait: 0, LockedToThread: true},
},
{
Line: "goroutine 23 [select, 5 minutes]:",
WantG: &Goroutine{ID: 23, State: "select", Wait: 5 * time.Minute},
},
{
Line: "goroutine 42 [select, 5 minutes, locked to thread]:",
WantG: &Goroutine{ID: 42, State: "select", Wait: 5 * time.Minute, LockedToThread: true},
},
{
Line: "goroutine 23 []:",
WantErr: "invalid goroutine header",
},
{
Line: "goroutine ",
WantErr: "invalid goroutine header",
},
{
Line: "goroutine 1 [chan receive]:\n",
WantErr: "invalid function call",
},
},
funcs: []frameLine{
{
Line: "main.main()",
WantFrame: &Frame{Func: "main.main"},
},
{
Line: "runtime.goparkunlock(...)",
WantFrame: &Frame{Func: "runtime.goparkunlock"},
},
{
Line: "net/http.(*persistConn).writeLoop(0xc0001a5c20)",
WantFrame: &Frame{Func: "net/http.(*persistConn).writeLoop"},
},
{
Line: "foo.bar",
WantErr: "invalid function call",
},
{
Line: "foo.bar(",
WantErr: "invalid function call",
},
{
Line: "net/http.(*persistConn).writeLoop(0xc0",
WantErr: "invalid function call",
},
{
Line: "net/http.(*persist",
WantErr: "invalid function call",
},
{
Line: "net/http.*persist)(",
WantErr: "invalid function call",
},
{
Line: "net/http.(*persist))",
WantErr: "invalid function call",
},
{
Line: "net/http.((*persist)",
WantErr: "invalid function call",
},
{
Line: "()",
WantErr: "invalid function call",
},
},
files: []frameLine{
{
Line: "\t/go/src/example.org/example/main.go:231 +0x1187",
WantFrame: &Frame{File: "/go/src/example.org/example/main.go", Line: 231},
},
{
Line: "\t/root/go1.15.6.linux.amd64/src/runtime/proc.go:312",
WantFrame: &Frame{File: "/root/go1.15.6.linux.amd64/src/runtime/proc.go", Line: 312},
},
{
Line: "/root/go1.15.6.linux.amd64/src/runtime/proc.go:312",
WantErr: "invalid file:line ref",
},
{
Line: "",
WantErr: "invalid file:line ref",
},
},
createdBy: []frameLine{
{
Line: "created by net/http.(*Server).Serve",
WantFrame: &Frame{Func: "net/http.(*Server).Serve"},
},
{
Line: "created by github.com/example.org/example/k8s.io/klog.init.0",
WantFrame: &Frame{Func: "github.com/example.org/example/k8s.io/klog.init.0"},
},
},
}
func BenchmarkGostackparse(b *testing.B) {
data, err := ioutil.ReadFile(filepath.Join("test-fixtures", "waitsince.txt"))
require.NoError(b, err)
b.ResetTimer()
b.ReportAllocs()
start := time.Now()
parsedBytes := 0
for i := 0; i < b.N; i++ {
parsedBytes += len(data)
gs, err := Parse(bytes.NewReader(data))
if err != nil {
b.Fatal(err)
} else if l := len(gs); l != 9 {
b.Fatal(l)
}
}
mbPerSec := float64(parsedBytes) / time.Since(start).Seconds() / 1024 / 1024
b.ReportMetric(mbPerSec, "MiB/s")
}
func TestFuzzCorupus(t *testing.T) {
if os.Getenv("FUZZ_CORPUS") == "" {
t.Skip("set FUZZ_CORPUS=true to generate fuzz corpus")
}
dir := "corpus"
tests := fixtures.Permutations()
require.NoError(t, os.MkdirAll(dir, 0755))
for i := 0; i < tests; i++ {
dump := fixtures.Generate(i)
name := filepath.Join(dir, fmt.Sprintf("%d.txt", i))
require.NoError(t, ioutil.WriteFile(name, []byte(dump.String()), 0666))
}
}
func Test_parseFile(t *testing.T) {
tests := []struct {
name string
line string
wantFrame Frame
wantReturn bool
}{
{
name: "empty",
line: "",
wantFrame: Frame{},
wantReturn: false,
},
{
name: "simple",
line: "\t/root/go1.15.6.linux.amd64/src/net/http/server.go:2969 +0x36c",
wantFrame: Frame{
File: "/root/go1.15.6.linux.amd64/src/net/http/server.go",
Line: 2969,
},
wantReturn: true,
},
{
name: "simple+space",
line: "\t/root/go1.15.6.linux.amd64/src/net/http/cool server.go:2969 +0x36c",
wantFrame: Frame{
File: "/root/go1.15.6.linux.amd64/src/net/http/cool server.go",
Line: 2969,
},
wantReturn: true,
},
{
name: "no-relative-pc",
line: "\t/root/go1.15.6.linux.amd64/src/net/http/server.go:2969",
wantFrame: Frame{
File: "/root/go1.15.6.linux.amd64/src/net/http/server.go",
Line: 2969,
},
wantReturn: true,
},
{
name: "no-relative-pc+space",
line: "\t/root/go1.15.6.linux.amd64/src/net/http/cool server.go:2969",
wantFrame: Frame{
File: "/root/go1.15.6.linux.amd64/src/net/http/cool server.go",
Line: 2969,
},
wantReturn: true,
},
}
for _, tt := range tests {
if len(tt.line) > 1 {
tt.name = "windows+" + tt.name
tt.line = "\tC:" + tt.line[1:]
tt.wantFrame.File = "C:" + tt.wantFrame.File
tests = append(tests, tt)
}
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var f Frame
got := parseFile([]byte(tt.line), &f)
if got != tt.wantReturn {
t.Fatalf("got=%v want=%v", got, tt.wantReturn)
} else if f != tt.wantFrame {
t.Fatalf("got=%+v want=%+v", f, tt.wantFrame)
}
})
}
}