Debian Codegraph @

gopls/internal/test/integration/bench/bench_test.go

raw symbols SCIP
1 // Copyright 2020 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 bench
6
7 import (
8 "bytes"
9 "compress/gzip"
10 "context"
11 "flag"
12 "fmt"
13 "io"
14 "log"
15 "os"
16 "os/exec"
17 "path/filepath"
18 "strings"
19 "sync"
20 "testing"
21 "time"
22
23 "golang.org/x/tools/gopls/internal/cmd"
24 "golang.org/x/tools/gopls/internal/protocol/command"
25 "golang.org/x/tools/gopls/internal/test/integration"
26 "golang.org/x/tools/gopls/internal/test/integration/fake"
27 "golang.org/x/tools/gopls/internal/tool"
28 "golang.org/x/tools/gopls/internal/util/bug"
29 "golang.org/x/tools/gopls/internal/util/fakenet"
30 "golang.org/x/tools/internal/event"
31 "golang.org/x/tools/internal/jsonrpc2"
32 "golang.org/x/tools/internal/jsonrpc2/servertest"
33 "golang.org/x/tools/internal/pprof"
34 )
35
36 var (
37 goplsPath = flag.String("gopls_path", "", "if set, use this gopls for testing; incompatible with -gopls_commit")
38
39 installGoplsOnce sync.Once // guards installing gopls at -gopls_commit
40 goplsCommit = flag.String("gopls_commit", "", "if set, install and use gopls at this commit for testing; incompatible with -gopls_path")
41
42 cpuProfile = flag.String("gopls_cpuprofile", "", "if set, the cpu profile file suffix; see \"Profiling\" in the package doc")
43 memProfile = flag.String("gopls_memprofile", "", "if set, the mem profile file suffix; see \"Profiling\" in the package doc")
44 allocProfile = flag.String("gopls_allocprofile", "", "if set, the alloc profile file suffix; see \"Profiling\" in the package doc")
45 blockProfile = flag.String("gopls_blockprofile", "", "if set, the block profile file suffix; see \"Profiling\" in the package doc")
46 trace = flag.String("gopls_trace", "", "if set, the trace file suffix; see \"Profiling\" in the package doc")
47
48 // If non-empty, tempDir is a temporary working dir that was created by this
49 // test suite.
50 makeTempDirOnce sync.Once // guards creation of the temp dir
51 tempDir string
52 )
53
54 // if runAsGopls is "true", run the gopls command instead of the testing.M.
55 const runAsGopls = "_GOPLS_BENCH_RUN_AS_GOPLS"
56
57 func TestMain(m *testing.M) {
58 bug.PanicOnBugs = true
59 if os.Getenv(runAsGopls) == "true" {
60 tool.Main(context.Background(), cmd.New(), os.Args[1:])
61 os.Exit(0)
62 }
63 event.SetExporter(nil) // don't log to stderr
64 code := m.Run()
65 if err := cleanup(); err != nil {
66 fmt.Fprintf(os.Stderr, "cleaning up after benchmarks: %v\n", err)
67 if code == 0 {
68 code = 1
69 }
70 }
71 os.Exit(code)
72 }
73
74 // getTempDir returns the temporary directory to use for benchmark files,
75 // creating it if necessary.
76 func getTempDir() string {
77 makeTempDirOnce.Do(func() {
78 var err error
79 tempDir, err = os.MkdirTemp("", "gopls-bench")
80 if err != nil {
81 log.Fatal(err)
82 }
83 })
84 return tempDir
85 }
86
87 // shallowClone performs a shallow clone of repo into dir at the given
88 // 'commitish' ref (any commit reference understood by git).
89 //
90 // The directory dir must not already exist.
91 func shallowClone(dir, repo, commitish string) error {
92 if err := os.Mkdir(dir, 0750); err != nil {
93 return fmt.Errorf("creating dir for %s: %v", repo, err)
94 }
95
96 // Set a timeout for git fetch. If this proves flaky, it can be removed.
97 ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
98 defer cancel()
99
100 // Use a shallow fetch to download just the relevant commit.
101 shInit := fmt.Sprintf("git init && git fetch --depth=1 %q %q && git checkout FETCH_HEAD", repo, commitish)
102 initCmd := exec.CommandContext(ctx, "/bin/sh", "-c", shInit)
103 initCmd.Dir = dir
104 if output, err := initCmd.CombinedOutput(); err != nil {
105 return fmt.Errorf("checking out %s: %v\n%s", repo, err, output)
106 }
107 return nil
108 }
109
110 // connectEditor connects a fake editor session in the given dir, using the
111 // given editor config.
112 func connectEditor(dir string, config fake.EditorConfig, ts servertest.Connector) (*fake.Sandbox, *fake.Editor, *integration.Awaiter, error) {
113 s, err := fake.NewSandbox(&fake.SandboxConfig{
114 Workdir: dir,
115 GOPROXY: "https://proxy.golang.org",
116 })
117 if err != nil {
118 return nil, nil, nil, err
119 }
120
121 a := integration.NewAwaiter(s.Workdir)
122 editor, err := fake.NewEditor(s, config).Connect(context.Background(), ts, a.Hooks())
123 if err != nil {
124 return nil, nil, nil, err
125 }
126
127 return s, editor, a, nil
128 }
129
130 // newGoplsConnector returns a connector that connects to a new gopls process,
131 // executed with the provided arguments.
132 func newGoplsConnector(args []string) (servertest.Connector, error) {
133 if *goplsPath != "" && *goplsCommit != "" {
134 panic("can't set both -gopls_path and -gopls_commit")
135 }
136 var (
137 goplsPath = *goplsPath
138 env []string
139 )
140 if *goplsCommit != "" {
141 goplsPath = getInstalledGopls()
142 }
143 if goplsPath == "" {
144 var err error
145 goplsPath, err = os.Executable()
146 if err != nil {
147 return nil, err
148 }
149 env = []string{fmt.Sprintf("%s=true", runAsGopls)}
150 }
151 return &SidecarServer{
152 goplsPath: goplsPath,
153 env: env,
154 args: args,
155 }, nil
156 }
157
158 // profileArgs returns additional command-line arguments to use when invoking
159 // gopls, to enable the user-requested profiles.
160 //
161 // If wantCPU is set, CPU profiling is enabled as well. Some tests may want to
162 // instrument profiling around specific critical sections of the benchmark,
163 // rather than the entire process.
164 //
165 // TODO(rfindley): like CPU, all of these would be better served by a custom
166 // command. Very rarely do we care about memory usage as the process exits: we
167 // care about specific points in time during the benchmark. mem and alloc
168 // should be snapshotted, and tracing should be bracketed around critical
169 // sections.
170 func profileArgs(name string, wantCPU bool) []string {
171 var args []string
172 if wantCPU && *cpuProfile != "" {
173 args = append(args, fmt.Sprintf("-profile.cpu=%s", qualifiedName(name, *cpuProfile)))
174 }
175 if *memProfile != "" {
176 args = append(args, fmt.Sprintf("-profile.mem=%s", qualifiedName(name, *memProfile)))
177 }
178 if *allocProfile != "" {
179 args = append(args, fmt.Sprintf("-profile.alloc=%s", qualifiedName(name, *allocProfile)))
180 }
181 if *blockProfile != "" {
182 args = append(args, fmt.Sprintf("-profile.block=%s", qualifiedName(name, *blockProfile)))
183 }
184 if *trace != "" {
185 args = append(args, fmt.Sprintf("-profile.trace=%s", qualifiedName(name, *trace)))
186 }
187 return args
188 }
189
190 func qualifiedName(args ...string) string {
191 return strings.Join(args, ".")
192 }
193
194 // getInstalledGopls builds gopls at the given -gopls_commit, returning the
195 // path to the gopls binary.
196 func getInstalledGopls() string {
197 if *goplsCommit == "" {
198 panic("must provide -gopls_commit")
199 }
200 toolsDir := filepath.Join(getTempDir(), "gopls_build")
201 goplsPath := filepath.Join(toolsDir, "gopls", "gopls")
202
203 installGoplsOnce.Do(func() {
204 log.Printf("installing gopls: checking out x/tools@%s into %s\n", *goplsCommit, toolsDir)
205 if err := shallowClone(toolsDir, "https://go.googlesource.com/tools", *goplsCommit); err != nil {
206 log.Fatal(err)
207 }
208
209 log.Println("installing gopls: building...")
210 bld := exec.Command("go", "build", ".")
211 bld.Dir = filepath.Join(toolsDir, "gopls")
212 if output, err := bld.CombinedOutput(); err != nil {
213 log.Fatalf("building gopls: %v\n%s", err, output)
214 }
215
216 // Confirm that the resulting path now exists.
217 if _, err := os.Stat(goplsPath); err != nil {
218 log.Fatalf("os.Stat(%s): %v", goplsPath, err)
219 }
220 })
221 return goplsPath
222 }
223
224 // A SidecarServer starts (and connects to) a separate gopls process at the
225 // given path.
226 type SidecarServer struct {
227 goplsPath string
228 env []string // additional environment bindings
229 args []string // command-line arguments
230 }
231
232 // Connect creates new io.Pipes and binds them to the underlying StreamServer.
233 //
234 // It implements the servertest.Connector interface.
235 func (s *SidecarServer) Connect(ctx context.Context) jsonrpc2.Conn {
236 // Note: don't use CommandContext here, as we want gopls to exit gracefully
237 // in order to write out profile data.
238 //
239 // We close the connection on context cancellation below.
240 cmd := exec.Command(s.goplsPath, s.args...)
241
242 stdin, err := cmd.StdinPipe()
243 if err != nil {
244 log.Fatal(err)
245 }
246 stdout, err := cmd.StdoutPipe()
247 if err != nil {
248 log.Fatal(err)
249 }
250 cmd.Stderr = os.Stderr
251 cmd.Env = append(os.Environ(), s.env...)
252 if err := cmd.Start(); err != nil {
253 log.Fatalf("starting gopls: %v", err)
254 }
255
256 go func() {
257 // If we don't log.Fatal here, benchmarks may hang indefinitely if gopls
258 // exits abnormally.
259 //
260 // TODO(rfindley): ideally we would shut down the connection gracefully,
261 // but that doesn't currently work.
262 if err := cmd.Wait(); err != nil {
263 log.Fatalf("gopls invocation failed with error: %v", err)
264 }
265 }()
266
267 clientStream := jsonrpc2.NewHeaderStream(fakenet.NewConn("stdio", stdout, stdin))
268 clientConn := jsonrpc2.NewConn(clientStream)
269
270 go func() {
271 select {
272 case <-ctx.Done():
273 clientConn.Close() // ignore error
274 clientStream.Close() // ignore error
275 case <-clientConn.Done():
276 }
277 }()
278
279 return clientConn
280 }
281
282 // startProfileIfSupported checks to see if the remote gopls instance supports
283 // the start/stop profiling commands. If so, it starts profiling and returns a
284 // function that stops profiling and records the total CPU seconds sampled in the
285 // cpu_seconds benchmark metric.
286 //
287 // If the remote gopls instance does not support profiling commands, this
288 // function returns nil.
289 //
290 // If the supplied userSuffix is non-empty, the profile is written to
291 // <repo>.<userSuffix>, and not deleted when the benchmark exits. Otherwise,
292 // the profile is written to a temp file that is deleted after the cpu_seconds
293 // metric has been computed.
294 func startProfileIfSupported(b *testing.B, env *integration.Env, name string) func() {
295 if !env.Editor.HasCommand(command.StartProfile) {
296 return nil
297 }
298 b.StopTimer()
299 stopProfile := env.StartProfile()
300 b.StartTimer()
301 return func() {
302 b.StopTimer()
303 profFile := stopProfile()
304 totalCPU, err := totalCPUForProfile(profFile)
305 if err != nil {
306 b.Fatalf("reading profile: %v", err)
307 }
308 b.ReportMetric(totalCPU.Seconds()/float64(b.N), "cpu_seconds/op")
309 if *cpuProfile != "" {
310 // Read+write to avoid exdev errors.
311 data, err := os.ReadFile(profFile)
312 if err != nil {
313 b.Fatalf("reading profile: %v", err)
314 }
315 name := qualifiedName(name, *cpuProfile)
316 if err := os.WriteFile(name, data, 0666); err != nil {
317 b.Fatalf("writing profile: %v", err)
318 }
319 }
320 if err := os.Remove(profFile); err != nil {
321 b.Errorf("removing profile file: %v", err)
322 }
323 }
324 }
325
326 // totalCPUForProfile reads the pprof profile with the given file name, parses,
327 // and aggregates the total CPU sampled during the profile.
328 func totalCPUForProfile(filename string) (time.Duration, error) {
329 protoGz, err := os.ReadFile(filename)
330 if err != nil {
331 return 0, err
332 }
333 rd, err := gzip.NewReader(bytes.NewReader(protoGz))
334 if err != nil {
335 return 0, fmt.Errorf("creating gzip reader for %s: %v", filename, err)
336 }
337 data, err := io.ReadAll(rd)
338 if err != nil {
339 return 0, fmt.Errorf("reading %s: %v", filename, err)
340 }
341 return pprof.TotalTime(data)
342 }
343
344 // closeBuffer stops the benchmark timer and closes the buffer with the given
345 // name.
346 //
347 // It may be used to clean up files opened in the shared environment during
348 // benchmarking.
349 func closeBuffer(b *testing.B, env *integration.Env, name string) {
350 b.StopTimer()
351 env.CloseBuffer(name)
352 env.AfterChange()
353 b.StartTimer()
354 }