Debian Codegraph @

gopls/internal/debug/flight.go

raw symbols SCIP
1 // Copyright 2024 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.
4
5 package debug
6
7 import (
8 "bufio"
9 "fmt"
10 "log"
11 "net/http"
12 "os"
13 "os/exec"
14 "path/filepath"
15 "runtime/trace"
16 "strings"
17 "sync"
18 "syscall"
19 "time"
20 )
21
22 var (
23 traceviewersMu sync.Mutex
24 traceviewers []*os.Process
25
26 kill = (*os.Process).Kill // windows, plan9; UNIX impl kills whole process group
27 sysProcAttr syscall.SysProcAttr // UNIX configuration to create process group
28 )
29
30 // KillTraceViewers kills all "go tool trace" processes started by
31 // /flightrecorder requests, for use in tests (see #74668).
32 func KillTraceViewers() {
33 traceviewersMu.Lock()
34 for _, p := range traceviewers {
35 kill(p) // ignore error
36 }
37 traceviewers = nil
38 traceviewersMu.Unlock()
39 }
40
41 // The FlightRecorder is a global resource, so create at most one per process.
42 var getRecorder = sync.OnceValues(func() (*trace.FlightRecorder, error) {
43 fr := trace.NewFlightRecorder(trace.FlightRecorderConfig{
44 // half a minute is usually enough to know "what just happened?"
45 MinAge: 30 * time.Second,
46 })
47 if err := fr.Start(); err != nil {
48 return nil, err
49 }
50 return fr, nil
51 })
52
53 func startFlightRecorder() (http.HandlerFunc, error) {
54 fr, err := getRecorder()
55 if err != nil {
56 return nil, err
57 }
58
59 // Return a handler that writes the most recent flight record,
60 // starts a trace viewer server, and redirects to it.
61 return func(w http.ResponseWriter, r *http.Request) {
62 errorf := func(format string, args ...any) {
63 msg := fmt.Sprintf(format, args...)
64 http.Error(w, msg, http.StatusInternalServerError)
65 }
66
67 // Write the most recent flight record into a temp file.
68 f, err := os.CreateTemp("", "flightrecord")
69 if err != nil {
70 errorf("can't create temp file for flight record: %v", err)
71 return
72 }
73 if _, err := fr.WriteTo(f); err != nil {
74 f.Close() // ignore error
75 errorf("failed to write flight record: %s", err)
76 return
77 }
78 if err := f.Close(); err != nil {
79 errorf("failed to close flight record: %s", err)
80 return
81 }
82 tracefile, err := filepath.Abs(f.Name())
83 if err != nil {
84 errorf("can't absolutize name of trace file: %v", err)
85 return
86 }
87
88 // Run 'go tool trace' to start a new trace-viewer
89 // web server process. It will run until gopls terminates.
90 // (It would be nicer if we could just link it in; see #66843.)
91 cmd := exec.Command("go", "tool", "trace", tracefile)
92 cmd.SysProcAttr = &sysProcAttr
93
94 // Don't connect trace's std{out,err} to our os.Stderr directly,
95 // otherwise the child may outlive the parent in tests,
96 // and 'go test' will complain about unclosed pipes.
97 // Instead, interpose a pipe that will close when gopls exits.
98 // See CL 677262 for a better solution (a cmd/trace flag).
99 // (#66843 is of course better still.)
100 // Also, this notifies us of the server's readiness and URL.
101 urlC := make(chan string)
102 {
103 r, w, err := os.Pipe()
104 if err != nil {
105 errorf("can't create pipe: %v", err)
106 return
107 }
108 go func() {
109 // Copy from the pipe to stderr,
110 // keeping an eye out for the "listening on URL" string.
111 scan := bufio.NewScanner(r)
112 for scan.Scan() {
113 line := scan.Text()
114 if _, url, ok := strings.Cut(line, "Trace viewer is listening on "); ok {
115 urlC <- url
116 }
117 fmt.Fprintln(os.Stderr, line)
118 }
119 if err := scan.Err(); err != nil {
120 log.Printf("reading from pipe to cmd/trace: %v", err)
121 }
122 }()
123 cmd.Stderr = w
124 cmd.Stdout = w
125 }
126
127 // Suppress the usual cmd/trace behavior of opening a new
128 // browser tab by setting BROWSER to /usr/bin/true (a no-op).
129 cmd.Env = append(os.Environ(), "BROWSER=true")
130 if err := cmd.Start(); err != nil {
131 errorf("failed to start trace server: %s", err)
132 return
133 }
134
135 // Save the process so we can kill it when tests finish.
136 traceviewersMu.Lock()
137 traceviewers = append(traceviewers, cmd.Process)
138 traceviewersMu.Unlock()
139
140 // Some of the CI builders can be quite heavily loaded.
141 // Give them an extra grace period.
142 timeout := 10 * time.Second
143 if os.Getenv("GO_BUILDER_NAME") != "" {
144 timeout = 1 * time.Minute
145 }
146
147 select {
148 case addr := <-urlC:
149 // Success! Send a redirect to the new location.
150 // (This URL bypasses the help screen at /.)
151 http.Redirect(w, r, addr+"/trace?view=proc", 302)
152
153 case <-r.Context().Done():
154 errorf("canceled")
155
156 case <-time.After(timeout):
157 errorf("trace viewer failed to start within %v", timeout)
158 }
159 }, nil
160 }