-
Notifications
You must be signed in to change notification settings - Fork 16
/
trace.go
executable file
·523 lines (469 loc) · 11.4 KB
/
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
package trace
import (
"context"
"fmt"
"os"
"path/filepath"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"unsafe"
"github.com/xhd2015/xgo/runtime/core"
"github.com/xhd2015/xgo/runtime/trap"
)
// hold goroutine stacks, keyed by goroutine ptr
var stackMap sync.Map // uintptr(goroutine) -> *Root
var testInfoMapping sync.Map // uintptr(goroutine) -> *testInfo
// stack trace options:
//
// on: automatically collect when test starts and ends
var xgoStackTrace = os.Getenv("XGO_STACK_TRACE")
// options:
//
// true: stdlib is by default allowed
// TODO: use compiler inserted flag instead of env
var xgoStdlibTrapDefaultAllow = os.Getenv("XGO_STD_LIB_TRAP_DEFAULT_ALLOW")
var skipStdlibTraceByDefault = xgoStdlibTrapDefaultAllow == "true"
type testInfo struct {
name string
onFinish func()
}
func init() {
__xgo_link_on_test_start(func(t *testing.T, fn func(t *testing.T)) {
name := t.Name()
if name == "" {
return
}
key := uintptr(__xgo_link_getcurg())
tInfo := &testInfo{
name: name,
}
testInfoMapping.LoadOrStore(key, tInfo)
if xgoStackTrace == "on" {
tInfo.onFinish = Begin()
}
})
__xgo_link_on_test_end(func(t *testing.T, fn func(t *testing.T)) {
key := uintptr(__xgo_link_getcurg())
val, ok := testInfoMapping.Load(key)
if !ok {
return
}
ttInfo := val.(*testInfo)
if ttInfo.onFinish != nil {
ttInfo.onFinish()
ttInfo.onFinish = nil
}
})
__xgo_link_on_goexit(func() {
key := uintptr(__xgo_link_getcurg())
testInfoMapping.Delete(key)
collectingMap.Delete(key)
})
}
// link by compiler
func __xgo_link_on_test_start(fn func(t *testing.T, fn func(t *testing.T))) {
fmt.Fprintln(os.Stderr, "WARNING: failed to link __xgo_link_on_test_start(requires xgo).")
}
func __xgo_link_on_test_end(fn func(t *testing.T, fn func(t *testing.T))) {
fmt.Fprintln(os.Stderr, "WARNING: failed to link __xgo_link_on_test_end(requires xgo).")
}
// link by compiler
func __xgo_link_getcurg() unsafe.Pointer {
fmt.Fprintln(os.Stderr, "WARNING: failed to link __xgo_link_getcurg(requires xgo).")
return nil
}
func __xgo_link_on_goexit(fn func()) {
fmt.Fprintln(os.Stderr, "WARNING: failed to link __xgo_link_on_goexit(requires xgo).")
}
func __xgo_link_init_finished() bool {
fmt.Fprintln(os.Stderr, "WARNING: failed to link __xgo_link_init_finished(requires xgo).")
return false
}
// linked by compiler
func __xgo_link_peek_panic() interface{} {
fmt.Fprintln(os.Stderr, "WARNING: failed to link __xgo_link_peek_panic(requires xgo).")
return nil
}
// xgo will optimize these two functions to direct call
func timeNow() time.Time {
// to: time.Now_Xgo_Original()
return time.Now()
}
func timeSince(t time.Time) time.Duration {
// to: time.Since_Xgo_Original()
return time.Since(t)
}
var enabledGlobally bool
var interceptorRefCount int32
// Enable setup the trace interceptor
// if called from init, the interceptor is enabled
// globally. Otherwise locally
func Enable() func() {
if __xgo_link_init_finished() {
return enableLocal(nil)
}
enabledGlobally = true
setupInterceptor()
return func() {
panic("global trace cannot be turned off")
}
}
// executes f and collect its trace
// by default trace output will be
// controlled by XGO_TRACE_OUTPUT
func Collect(f func()) {
if !__xgo_link_init_finished() {
panic("Collect cannot be called from init")
}
collect(f, &collectOpts{})
}
func Begin() func() {
if !__xgo_link_init_finished() {
panic("Begin cannot be called from init")
}
return enableLocal(&collectOpts{})
}
type collectOpts struct {
name string
onComplete func(root *Root)
filter []func(stack *Stack) bool
root *Root
exportOptions *ExportOptions
}
func Options() *collectOpts {
return &collectOpts{}
}
func (c *collectOpts) Name(name string) *collectOpts {
c.name = name
return c
}
func (c *collectOpts) OnComplete(f func(root *Root)) *collectOpts {
c.onComplete = f
return c
}
func (c *collectOpts) WithFilter(f func(stack *Stack) bool) *collectOpts {
c.filter = append(c.filter, f)
return c
}
func (c *collectOpts) WithExport(expOpts *ExportOptions) *collectOpts {
c.exportOptions = expOpts
return c
}
func (c *collectOpts) Collect(f func()) {
collect(f, c)
}
func (c *collectOpts) Begin() func() {
return enableLocal(c)
}
func setupInterceptor() func() {
if atomic.AddInt32(&interceptorRefCount, 1) > 1 {
return func() {
atomic.AddInt32(&interceptorRefCount, -1)
}
}
// collect trace
cancel := trap.AddInterceptorHead(&trap.Interceptor{
Pre: handleTracePre,
Post: handleTracePost,
})
return func() {
atomic.AddInt32(&interceptorRefCount, -1)
cancel()
}
}
// returns a value to be passed to post
// if returns err trap.ErrSkip, this interceptor is skipped, handleTracePost is not called, next interceptors will
// be normally executed
// if returns nil error, handleTracePost is called
func handleTracePre(ctx context.Context, f *core.FuncInfo, args core.Object, results core.Object) (interface{}, error) {
if !__xgo_link_init_finished() {
// do not collect trace while init
return nil, trap.ErrSkip
}
if f.Stdlib && skipStdlibTraceByDefault {
return nil, trap.ErrSkip
}
key := uintptr(__xgo_link_getcurg())
localOptStack, ok := collectingMap.Load(key)
var localOpts *collectOpts
if ok {
l := localOptStack.(*optStack)
if len(l.list) > 0 {
localOpts = l.list[len(l.list)-1]
}
} else if !enabledGlobally {
return nil, trap.ErrSkip
}
stack := &Stack{
FuncInfo: f,
Args: args,
Results: results,
}
var globalRoot interface{}
var localRoot *Root
var initial bool
if localOpts == nil {
var globalLoaded bool
globalRoot, globalLoaded = stackMap.Load(key)
if !globalLoaded {
initial = true
}
} else {
if !checkFilter(stack, localOpts.filter) {
// do not collect trace if filtered out
return nil, trap.ErrSkip
}
localRoot = localOpts.root
if localRoot == nil {
initial = true
}
}
if initial {
// initial stack
root := &Root{
Top: stack,
Begin: timeNow(),
Children: []*Stack{
stack,
},
}
stack.Begin = int64(timeSince(root.Begin))
if localOpts == nil {
stackMap.Store(key, root)
} else {
localOpts.root = root
}
// NOTE: for initial stack, the data is nil
// this will signal Post to emit a trace
return nil, nil
}
var root *Root
if localOpts != nil {
root = localRoot
} else {
root = globalRoot.(*Root)
}
stack.Begin = int64(timeSince(root.Begin))
prevTop := root.Top
root.Top.Children = append(root.Top.Children, stack)
root.Top = stack
return prevTop, nil
}
func checkFilter(stack *Stack, filters []func(stack *Stack) bool) bool {
for _, f := range filters {
if !f(stack) {
return false
}
}
return true
}
func handleTracePost(ctx context.Context, f *core.FuncInfo, args core.Object, results core.Object, data interface{}) error {
key := uintptr(__xgo_link_getcurg())
localOptStack, ok := collectingMap.Load(key)
var localOpts *collectOpts
if ok {
l := localOptStack.(*optStack)
if len(l.list) > 0 {
localOpts = l.list[len(l.list)-1]
}
} else if !enabledGlobally {
return nil
}
var root *Root
if localOpts != nil {
if localOpts.root == nil {
panic(fmt.Errorf("unbalanced stack"))
}
root = localOpts.root
} else {
v, ok := stackMap.Load(key)
if !ok {
panic(fmt.Errorf("unbalanced stack"))
}
root = v.(*Root)
}
// detect panic
pe := __xgo_link_peek_panic()
if pe != nil {
root.Top.Panic = true
peErr, ok := pe.(error)
if !ok {
peErr = fmt.Errorf("panic: %v", pe)
}
root.Top.Error = peErr
} else {
if errObj, ok := results.(core.ObjectWithErr); ok {
fnErr := errObj.GetErr().Value()
if fnErr != nil {
root.Top.Error = fnErr.(error)
}
}
}
root.Top.End = int64(timeSince(root.Begin))
if data == nil {
root.Top = nil
// stack finished
if localOpts != nil {
// handled by local options
return nil
}
// global
stackMap.Delete(key)
emitTraceNoErr("", root, nil)
return nil
}
// pop stack
root.Top = data.(*Stack)
return nil
}
var collectingMap sync.Map // <uintptr> -> []*collectOpts
type optStack struct {
list []*collectOpts
}
func collect(f func(), collOpts *collectOpts) {
finish := enableLocal(collOpts)
defer finish()
f()
}
func enableLocal(collOpts *collectOpts) func() {
if collOpts == nil {
collOpts = &collectOpts{}
}
cancel := setupInterceptor()
key := uintptr(__xgo_link_getcurg())
if collOpts.name == "" {
var name string
tinfo, ok := testInfoMapping.Load(key)
if ok {
name = tinfo.(*testInfo).name
}
if name == "" {
name = fmt.Sprintf("g_%x", uint(key))
}
collOpts.name = name
}
if collOpts.root == nil {
collOpts.root = &Root{
Top: &Stack{},
Begin: timeNow(),
}
}
top := collOpts.root.Top
act, _ := collectingMap.LoadOrStore(key, &optStack{})
opts := act.(*optStack)
// push
opts.list = append(opts.list, collOpts)
return func() {
if key != uintptr(__xgo_link_getcurg()) {
panic("finish trace from another goroutine!")
}
cancel()
// pop
opts.list = opts.list[:len(opts.list)-1]
if len(opts.list) == 0 {
collectingMap.Delete(key)
}
root := collOpts.root
root.Children = top.Children
root.Top = nil
// root.Children =
// call complete
if collOpts.onComplete != nil {
collOpts.onComplete(root)
} else {
emitTraceNoErr(collOpts.name, root, collOpts.exportOptions)
}
}
}
var traceOutput = os.Getenv("XGO_TRACE_OUTPUT")
func getTraceOutput() string {
return traceOutput
}
var marshalStack func(root *Root) ([]byte, error)
func SetMarshalStack(fn func(root *Root) ([]byte, error)) {
marshalStack = fn
}
func fmtStack(root *Root, opts *ExportOptions) (data []byte, err error) {
defer func() {
if e := recover(); e != nil {
if pe, ok := e.(error); ok {
err = pe
} else {
err = fmt.Errorf("panic: %v", e)
}
return
}
}()
if marshalStack != nil {
return marshalStack(root)
}
exportRoot := root.Export(opts)
if opts != nil {
if opts.FilterRoot != nil {
exportRoot = opts.FilterRoot(exportRoot)
}
if opts.MarshalRoot != nil {
return opts.MarshalRoot(exportRoot)
}
}
return MarshalAnyJSON(exportRoot)
}
func emitTraceNoErr(name string, root *Root, opts *ExportOptions) {
emitTrace(name, root, opts)
}
func formatTime(t time.Time, layout string) (output string) {
trap.Direct(func() {
output = t.Format(layout)
})
return
}
// this should also be marked as trap.Skip()
// TODO: may add callback for this
func emitTrace(name string, root *Root, opts *ExportOptions) error {
xgoTraceOutput := getTraceOutput()
if xgoTraceOutput == "off" {
return nil
}
useStdout := xgoTraceOutput == "stdout"
subName := name
if name == "" {
traceIDNum := int64(1)
ghex := fmt.Sprintf("g_%x", __xgo_link_getcurg())
traceID := "t_" + strconv.FormatInt(traceIDNum, 10)
if xgoTraceOutput == "" {
traceDir := formatTime(timeNow(), "trace_20060102_150405")
subName = filepath.Join(traceDir, ghex, traceID)
} else if useStdout {
subName = fmt.Sprintf("%s/%s", ghex, traceID)
} else {
subName = filepath.Join(xgoTraceOutput, ghex, traceID)
}
}
if useStdout {
fmt.Printf("%s: ", subName)
}
var traceOut []byte
trace, stackErr := fmtStack(root, opts)
if stackErr != nil {
traceOut = []byte("error:" + stackErr.Error())
} else {
traceOut = trace
}
if useStdout {
fmt.Printf("%s\n", traceOut)
return nil
}
subFile := subName + ".json"
subDir := filepath.Dir(subFile)
err := os.MkdirAll(subDir, 0755)
if err != nil {
return err
}
trap.Direct(func() {
err = WriteFile(subFile, traceOut, 0755)
})
return err
}