1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
14 "internal/goexperiment"
15 traceparser "internal/trace"
26 var saveTraces = flag.Bool("savetraces", false, "save traces collected by tests")
28 func TestOverlappingDuration(t *testing.T) {
30 start0, end0, start1, end1 int64
37 1, 10, 5, 20, 5 * time.Nanosecond,
40 1, 10, 2, 8, 6 * time.Nanosecond,
44 for _, tc := range cases {
45 s0, e0, s1, e1 := tc.start0, tc.end0, tc.start1, tc.end1
46 if got := overlappingDuration(s0, e0, s1, e1); got != tc.want {
47 t.Errorf("overlappingDuration(%d, %d, %d, %d)=%v; want %v", s0, e0, s1, e1, got, tc.want)
49 if got := overlappingDuration(s1, e1, s0, e0); got != tc.want {
50 t.Errorf("overlappingDuration(%d, %d, %d, %d)=%v; want %v", s1, e1, s0, e0, got, tc.want)
55 // prog0 starts three goroutines.
57 // goroutine 1: taskless region
58 // goroutine 2: starts task0, do work in task0.region0, starts task1 which ends immediately.
59 // goroutine 3: do work in task0.region1 and task0.region2, ends task0
61 ctx := context.Background()
66 go func() { // goroutine 1
68 trace.WithRegion(ctx, "taskless.region", func() {
69 trace.Log(ctx, "key0", "val0")
74 go func() { // goroutine 2
76 ctx, task := trace.NewTask(ctx, "task0")
77 trace.WithRegion(ctx, "task0.region0", func() {
79 go func() { // goroutine 3
82 trace.WithRegion(ctx, "task0.region1", func() {
83 trace.WithRegion(ctx, "task0.region2", func() {
84 trace.Log(ctx, "key2", "val2")
86 trace.Log(ctx, "key1", "val1")
90 ctx2, task2 := trace.NewTask(ctx, "task1")
91 trace.Log(ctx2, "key3", "val3")
97 func TestAnalyzeAnnotations(t *testing.T) {
98 // TODO: classify taskless regions
100 // Run prog0 and capture the execution trace.
101 if err := traceProgram(t, prog0, "TestAnalyzeAnnotations"); err != nil {
102 t.Fatalf("failed to trace the program: %v", err)
105 res, err := analyzeAnnotations()
107 t.Fatalf("failed to analyzeAnnotations: %v", err)
110 // For prog0, we expect
111 // - task with name = "task0", with three regions.
112 // - task with name = "task1", with no region.
113 wantTasks := map[string]struct {
121 regions: []string{"task0.region0", "", "task0.region1", "task0.region2"},
129 for _, task := range res.tasks {
130 want, ok := wantTasks[task.name]
132 t.Errorf("unexpected task: %s", task)
135 if task.complete() != want.complete || len(task.goroutines) != want.goroutines || !reflect.DeepEqual(regionNames(task), want.regions) {
136 t.Errorf("got task %v; want %+v", task, want)
139 delete(wantTasks, task.name)
141 if len(wantTasks) > 0 {
142 t.Errorf("no more tasks; want %+v", wantTasks)
145 wantRegions := []string{
146 "", // an auto-created region for the goroutine 3
152 var gotRegions []string
153 for regionID := range res.regions {
154 gotRegions = append(gotRegions, regionID.Type)
157 sort.Strings(wantRegions)
158 sort.Strings(gotRegions)
159 if !reflect.DeepEqual(gotRegions, wantRegions) {
160 t.Errorf("got regions %q, want regions %q", gotRegions, wantRegions)
164 // prog1 creates a task hierarchy consisting of three tasks.
166 ctx := context.Background()
167 ctx1, task1 := trace.NewTask(ctx, "task1")
169 trace.WithRegion(ctx1, "task1.region", func() {
170 ctx2, task2 := trace.NewTask(ctx1, "task2")
172 trace.WithRegion(ctx2, "task2.region", func() {
173 ctx3, task3 := trace.NewTask(ctx2, "task3")
175 trace.WithRegion(ctx3, "task3.region", func() {
181 func TestAnalyzeAnnotationTaskTree(t *testing.T) {
182 // Run prog1 and capture the execution trace.
183 if err := traceProgram(t, prog1, "TestAnalyzeAnnotationTaskTree"); err != nil {
184 t.Fatalf("failed to trace the program: %v", err)
187 res, err := analyzeAnnotations()
189 t.Fatalf("failed to analyzeAnnotations: %v", err)
193 // For prog0, we expect
194 // - task with name = "", with taskless.region in regions.
195 // - task with name = "task0", with three regions.
196 wantTasks := map[string]struct {
203 children: []string{"task2"},
204 regions: []string{"task1.region"},
208 children: []string{"task3"},
209 regions: []string{"task2.region"},
214 regions: []string{"task3.region"},
218 for _, task := range tasks {
219 want, ok := wantTasks[task.name]
221 t.Errorf("unexpected task: %s", task)
224 delete(wantTasks, task.name)
226 if parentName(task) != want.parent ||
227 !reflect.DeepEqual(childrenNames(task), want.children) ||
228 !reflect.DeepEqual(regionNames(task), want.regions) {
229 t.Errorf("got %v; want %+v", task, want)
233 if len(wantTasks) > 0 {
234 t.Errorf("no more tasks; want %+v", wantTasks)
238 // prog2 starts two tasks; "taskWithGC" that overlaps with GC
239 // and "taskWithoutGC" that doesn't. In order to run this reliably,
240 // the caller needs to set up to prevent GC from running automatically.
241 // prog2 returns the upper-bound gc time that overlaps with the first task.
242 func prog2() (gcTime time.Duration) {
243 ch := make(chan bool)
244 ctx1, task := trace.NewTask(context.Background(), "taskWithGC")
245 trace.WithRegion(ctx1, "taskWithGC.region1", func() {
247 defer trace.StartRegion(ctx1, "taskWithGC.region2").End()
251 debug.FreeOSMemory() // task1 affected by gc
252 gcTime = time.Since(s)
257 ctx2, task2 := trace.NewTask(context.Background(), "taskWithoutGC")
258 trace.WithRegion(ctx2, "taskWithoutGC.region1", func() {
265 func TestAnalyzeAnnotationGC(t *testing.T) {
266 err := traceProgram(t, func() {
267 oldGC := debug.SetGCPercent(10000) // gc, and effectively disable GC
268 defer debug.SetGCPercent(oldGC)
270 }, "TestAnalyzeAnnotationGC")
272 t.Fatalf("failed to trace the program: %v", err)
275 res, err := analyzeAnnotations()
277 t.Fatalf("failed to analyzeAnnotations: %v", err)
280 // Check collected GC Start events are all sorted and non-overlapping.
282 for i, ev := range res.gcEvents {
283 if ev.Type != traceparser.EvGCStart {
284 t.Errorf("unwanted event in gcEvents: %v", ev)
286 if i > 0 && lastTS > ev.Ts {
287 t.Errorf("overlapping GC events:\n%d: %v\n%d: %v", i-1, res.gcEvents[i-1], i, res.gcEvents[i])
294 // Check whether only taskWithGC reports overlapping duration.
295 for _, task := range res.tasks {
296 got := task.overlappingGCDuration(res.gcEvents)
298 case "taskWithoutGC":
300 t.Errorf("%s reported %v as overlapping GC time; want 0: %v", task.name, got, task)
303 upperBound := task.duration()
304 // TODO(hyangah): a tighter upper bound is gcTime, but
305 // use of it will make the test flaky due to the issue
306 // described in golang.org/issue/16755. Tighten the upper
307 // bound when the issue with the timestamp computed
308 // based on clockticks is resolved.
309 if got <= 0 || got > upperBound {
310 t.Errorf("%s reported %v as overlapping GC time; want (0, %v):\n%v", task.name, got, upperBound, task)
311 buf := new(bytes.Buffer)
312 fmt.Fprintln(buf, "GC Events")
313 for _, ev := range res.gcEvents {
314 fmt.Fprintf(buf, " %s -> %s\n", ev, ev.Link)
316 fmt.Fprintln(buf, "Events in Task")
317 for i, ev := range task.events {
318 fmt.Fprintf(buf, " %d: %s\n", i, ev)
327 // traceProgram runs the provided function while tracing is enabled,
328 // parses the captured trace, and sets the global trace loader to
329 // point to the parsed trace.
331 // If savetraces flag is set, the captured trace will be saved in the named file.
332 func traceProgram(t *testing.T, f func(), name string) error {
334 if goexperiment.ExecTracer2 {
335 t.Skip("skipping because test programs are covered elsewhere for the new tracer")
337 buf := new(bytes.Buffer)
338 if err := trace.Start(buf); err != nil {
345 res, err := traceparser.Parse(buf, name+".faketrace")
346 if err == traceparser.ErrTimeOrder {
347 t.Skipf("skipping due to golang.org/issue/16755: %v", err)
348 } else if err != nil {
352 swapLoaderData(res, err)
356 func regionNames(task *taskDesc) (ret []string) {
357 for _, s := range task.regions {
358 ret = append(ret, s.Name)
363 func parentName(task *taskDesc) string {
364 if task.parent != nil {
365 return task.parent.name
370 func childrenNames(task *taskDesc) (ret []string) {
371 for _, s := range task.children {
372 ret = append(ret, s.name)
377 func swapLoaderData(res traceparser.ParseResult, err error) {
378 // swap loader's data.
379 parseTrace() // fool loader.once.
384 analyzeGoroutines(nil) // fool gsInit once.
385 gs = traceparser.GoroutineStats(res.Events)
389 func saveTrace(buf *bytes.Buffer, name string) {
393 if err := os.WriteFile(name+".trace", buf.Bytes(), 0600); err != nil {
394 panic(fmt.Errorf("failed to write trace file: %v", err))