Debian Codegraph @

gopls/internal/test/integration/runner.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 integration
6
7 import (
8 "bytes"
9 "context"
10 "fmt"
11 "io"
12 "net"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "runtime"
17 "runtime/pprof"
18 "strings"
19 "sync"
20 "testing"
21 "time"
22
23 "golang.org/x/tools/gopls/internal/cache"
24 "golang.org/x/tools/gopls/internal/debug"
25 "golang.org/x/tools/gopls/internal/lsprpc"
26 "golang.org/x/tools/gopls/internal/protocol"
27 "golang.org/x/tools/gopls/internal/test/integration/fake"
28 "golang.org/x/tools/gopls/internal/util/memoize"
29 "golang.org/x/tools/internal/jsonrpc2"
30 "golang.org/x/tools/internal/jsonrpc2/servertest"
31 "golang.org/x/tools/internal/testenv"
32 )
33
34 // Mode is a bitmask that defines for which execution modes a test should run.
35 //
36 // Each mode controls several aspects of gopls' configuration:
37 // - Which server options to use for gopls sessions
38 // - Whether to use a shared cache
39 // - Whether to use a shared server
40 // - Whether to run the server in-process or in a separate process
41 //
42 // The behavior of each mode with respect to these aspects is summarized below.
43 // TODO(rfindley, cleanup): rather than using arbitrary names for these modes,
44 // we can compose them explicitly out of the features described here, allowing
45 // individual tests more freedom in constructing problematic execution modes.
46 // For example, a test could assert on a certain behavior when running on a
47 // separate process. Moreover, we could unify 'Modes' with 'Options', and use
48 // RunMultiple rather than a hard-coded loop through modes.
49 //
50 // Mode | Options | Shared Cache? | Shared Server? | In-process?
51 // ---------------------------------------------------------------------------
52 // Default | Default | Y | N | Y
53 // Forwarded | Default | Y | Y | Y
54 // SeparateProcess | Default | Y | Y | N
55 type Mode int
56
57 const (
58 // Default mode runs gopls with the default options, communicating over pipes
59 // to emulate the lsp sidecar execution mode, which communicates over
60 // stdin/stdout.
61 //
62 // It uses separate servers for each test, but a shared cache, to avoid
63 // duplicating work when processing GOROOT.
64 Default Mode = 1 << iota
65
66 // Forwarded uses the default options, but forwards connections to a shared
67 // in-process gopls server.
68 Forwarded
69
70 // SeparateProcess uses the default options, but forwards connection to an
71 // external gopls daemon.
72 //
73 // Only supported on GOOS=linux.
74 SeparateProcess
75 )
76
77 func (m Mode) String() string {
78 switch m {
79 case Default:
80 return "default"
81 case Forwarded:
82 return "forwarded"
83 case SeparateProcess:
84 return "separate process"
85 default:
86 return "unknown mode"
87 }
88 }
89
90 // A Runner runs tests in gopls execution environments, as specified by its
91 // modes. For modes that share state (for example, a shared cache or common
92 // remote), any tests that execute on the same Runner will share the same
93 // state.
94 type Runner struct {
95 // Configuration
96 DefaultModes Mode // modes to run for each test
97 Timeout time.Duration // per-test timeout, if set
98 PrintGoroutinesOnFailure bool // whether to dump goroutines on test failure
99 SkipCleanup bool // if set, don't delete test data directories when the test exits
100
101 // Immutable state shared across test invocations
102 goplsPath string // path to the gopls executable (for SeparateProcess mode)
103 tempDir string // shared parent temp directory
104 store *memoize.Store // shared store
105
106 // Lazily allocated resources
107 tsOnce sync.Once
108 ts *servertest.TCPServer // shared in-process test server ("forwarded" mode)
109
110 startRemoteOnce sync.Once
111 remoteSocket string // unix domain socket for shared daemon ("separate process" mode)
112 remoteErr error
113 cancelRemote func()
114 }
115
116 type TestFunc func(t *testing.T, env *Env)
117
118 // Run executes the test function in the default configured gopls execution
119 // modes. For each a test run, a new workspace is created containing the
120 // un-txtared files specified by filedata.
121 func (r *Runner) Run(t *testing.T, files string, test TestFunc, opts ...RunOption) {
122 // TODO(rfindley): this function has gotten overly complicated, and warrants
123 // refactoring.
124
125 if !runFromMain {
126 // Main performs various setup precondition checks.
127 // While it could theoretically be made OK for a Runner to be used outside
128 // of Main, it is simpler to enforce that we only use the Runner from
129 // integration test suites.
130 t.Fatal("integration.Runner.Run must be run from integration.Main")
131 }
132
133 tests := []struct {
134 name string
135 mode Mode
136 getServer func() jsonrpc2.StreamServer
137 }{
138 {"default", Default, r.defaultServer},
139 {"forwarded", Forwarded, r.forwardedServer},
140 {"separate_process", SeparateProcess, r.separateProcessServer},
141 }
142
143 for _, tc := range tests {
144 config := defaultConfig()
145 for _, opt := range opts {
146 opt.set(&config)
147 }
148 modes := r.DefaultModes
149 if config.modes != 0 {
150 modes = config.modes
151 }
152 if modes&tc.mode == 0 {
153 continue
154 }
155
156 t.Run(tc.name, func(t *testing.T) {
157 // TODO(rfindley): once jsonrpc2 shutdown is fixed, we should not leak
158 // goroutines in this test function.
159 // stacktest.NoLeak(t)
160
161 ctx := context.Background()
162 if r.Timeout != 0 {
163 var cancel context.CancelFunc
164 ctx, cancel = context.WithTimeout(ctx, r.Timeout)
165 defer cancel()
166 } else if d, ok := testenv.Deadline(t); ok {
167 timeout := time.Until(d) * 19 / 20 // Leave an arbitrary 5% for cleanup.
168 var cancel context.CancelFunc
169 ctx, cancel = context.WithTimeout(ctx, timeout)
170 defer cancel()
171 }
172
173 // TODO(rfindley): do we need an instance at all? Can it be removed?
174 ctx = debug.WithInstance(ctx, "")
175
176 rootDir := filepath.Join(r.tempDir, filepath.FromSlash(t.Name()))
177 if err := os.MkdirAll(rootDir, 0755); err != nil {
178 t.Fatal(err)
179 }
180
181 files := fake.UnpackTxt(files)
182 if config.editor.WindowsLineEndings {
183 for name, data := range files {
184 files[name] = bytes.ReplaceAll(data, []byte("\n"), []byte("\r\n"))
185 }
186 }
187 config.sandbox.Files = files
188 config.sandbox.RootDir = rootDir
189 sandbox, err := fake.NewSandbox(&config.sandbox)
190 if err != nil {
191 t.Fatal(err)
192 }
193 defer func() {
194 if !r.SkipCleanup {
195 if err := sandbox.Close(); err != nil {
196 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1) // ignore error
197 t.Errorf("closing the sandbox: %v", err)
198 }
199 }
200 }()
201
202 // Write the go.sum file for the requested directories, before starting the server.
203 var environ []string
204 for k, v := range config.editor.Env {
205 // We must manually resolve $SANDBOX_WORKDIR here because WriteGoSum invokes go list
206 // before fake.Editor is fully initialized (which normally handles this substitution
207 // natively in Env()). Surprisingly, there is no shared helper function for this
208 // string replacement, so we duplicate Editor.Env() substitution logic here.
209 v = strings.ReplaceAll(v, "$SANDBOX_WORKDIR", sandbox.Workdir.RootURI().Path())
210 environ = append(environ, fmt.Sprintf("%s=%s", k, v))
211 }
212 environ = append(environ, "GOWORK=off")
213
214 for _, dir := range config.writeGoSum {
215 if _, err := sandbox.RunGoCommand(context.Background(), dir, "list", []string{"-mod=mod", "./..."}, environ, true); err != nil {
216 t.Fatal(err)
217 }
218 }
219
220 ss := tc.getServer()
221
222 framer := jsonrpc2.NewRawStream
223 ls := &loggingFramer{}
224 framer = ls.framer(jsonrpc2.NewRawStream)
225 ts := servertest.NewPipeServer(ss, framer)
226
227 env := ConnectGoplsEnv(t, ctx, sandbox, config.editor, ts)
228 defer func() {
229 if t.Failed() && r.PrintGoroutinesOnFailure {
230 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1) // ignore error
231 }
232 if (t.Failed() && !config.noLogsOnError) || *printLogs {
233 ls.printBuffers(t.Name(), os.Stderr)
234 }
235 // For tests that failed due to a timeout, don't fail to shutdown
236 // because ctx is done.
237 //
238 // There is little point to setting an arbitrary timeout for closing
239 // the editor: in general we want to clean up before proceeding to the
240 // next test, and if there is a deadlock preventing closing it will
241 // eventually be handled by the `go test` timeout.
242 if err := env.Editor.Close(context.WithoutCancel(ctx)); err != nil {
243 t.Errorf("closing editor: %v", err)
244 }
245 }()
246 // Always await the initial workspace load.
247 env.Await(InitialWorkspaceLoad)
248 test(t, env)
249 })
250 }
251 }
252
253 // ConnectGoplsEnv creates a new Gopls environment for the given sandbox,
254 // editor config, and server connector.
255 //
256 // TODO(rfindley): significantly refactor the way testing environments are
257 // constructed.
258 func ConnectGoplsEnv(t testing.TB, ctx context.Context, sandbox *fake.Sandbox, config fake.EditorConfig, connector servertest.Connector) *Env {
259 awaiter := NewAwaiter(sandbox.Workdir)
260 editor, err := fake.NewEditor(sandbox, config).Connect(ctx, connector, awaiter.Hooks())
261 if err != nil {
262 t.Fatal(err)
263 }
264 env := &Env{
265 TB: t,
266 Ctx: ctx,
267 Sandbox: sandbox,
268 Server: connector,
269 Editor: editor,
270 Awaiter: awaiter,
271 }
272 return env
273 }
274
275 // longBuilders maps builders that are skipped when -short is set to a
276 // (possibly empty) justification.
277 var longBuilders = map[string]string{
278 "x_tools-gotip-openbsd-amd64": "go.dev/issue/72145",
279 "x_tools-go1.24-openbsd-amd64": "go.dev/issue/72145",
280 "x_tools-go1.23-openbsd-amd64": "go.dev/issue/72145",
281
282 "darwin-amd64-10_12": "",
283 "freebsd-amd64-race": "",
284 "illumos-amd64": "",
285 "netbsd-arm-bsiegert": "",
286 "solaris-amd64-oraclerel": "",
287 "windows-arm-zx2c4": "",
288 "linux-ppc64le-power9osu": "go.dev/issue/66748",
289 }
290
291 // TODO(rfindley): inline into Main.
292 func checkBuilder() string {
293 builder := os.Getenv("GO_BUILDER_NAME")
294 if reason, ok := longBuilders[builder]; ok && testing.Short() {
295 if reason != "" {
296 return fmt.Sprintf("skipping %s with -short due to %s", builder, reason)
297 } else {
298 return fmt.Sprintf("skipping %s with -short", builder)
299 }
300 }
301 return ""
302 }
303
304 type loggingFramer struct {
305 mu sync.Mutex
306 buf *safeBuffer
307 }
308
309 // safeBuffer is a threadsafe buffer for logs.
310 type safeBuffer struct {
311 mu sync.Mutex
312 buf bytes.Buffer
313 }
314
315 func (b *safeBuffer) Write(p []byte) (int, error) {
316 b.mu.Lock()
317 defer b.mu.Unlock()
318 return b.buf.Write(p)
319 }
320
321 func (s *loggingFramer) framer(f jsonrpc2.Framer) jsonrpc2.Framer {
322 return func(nc net.Conn) jsonrpc2.Stream {
323 s.mu.Lock()
324 framed := false
325 if s.buf == nil {
326 s.buf = &safeBuffer{buf: bytes.Buffer{}}
327 framed = true
328 }
329 s.mu.Unlock()
330 stream := f(nc)
331 if framed {
332 return protocol.LoggingStream(stream, s.buf)
333 }
334 return stream
335 }
336 }
337
338 func (s *loggingFramer) printBuffers(testname string, w io.Writer) {
339 s.mu.Lock()
340 defer s.mu.Unlock()
341
342 if s.buf == nil {
343 return
344 }
345 fmt.Fprintf(os.Stderr, "#### Start Gopls Test Logs for %q\n", testname)
346 s.buf.mu.Lock()
347 io.Copy(w, &s.buf.buf)
348 s.buf.mu.Unlock()
349 fmt.Fprintf(os.Stderr, "#### End Gopls Test Logs for %q\n", testname)
350 }
351
352 // defaultServer handles the Default execution mode.
353 func (r *Runner) defaultServer() jsonrpc2.StreamServer {
354 return lsprpc.NewStreamServer(cache.New(r.store), false, nil)
355 }
356
357 // forwardedServer handles the Forwarded execution mode.
358 func (r *Runner) forwardedServer() jsonrpc2.StreamServer {
359 r.tsOnce.Do(func() {
360 ctx := context.Background()
361 ctx = debug.WithInstance(ctx, "")
362 ss := lsprpc.NewStreamServer(cache.New(nil), false, nil)
363 r.ts = servertest.NewTCPServer(ctx, ss, nil)
364 })
365 return newForwarder("tcp", r.ts.Addr)
366 }
367
368 // runTestAsGoplsEnvvar triggers TestMain to run gopls instead of running
369 // tests. It's a trick to allow tests to find a binary to use to start a gopls
370 // subprocess.
371 const runTestAsGoplsEnvvar = "_GOPLS_TEST_BINARY_RUN_AS_GOPLS"
372
373 // separateProcessServer handles the SeparateProcess execution mode.
374 func (r *Runner) separateProcessServer() jsonrpc2.StreamServer {
375 if runtime.GOOS != "linux" {
376 panic("separate process execution mode is only supported on linux")
377 }
378
379 r.startRemoteOnce.Do(func() {
380 socketDir, err := os.MkdirTemp(r.tempDir, "gopls-test-socket")
381 if err != nil {
382 r.remoteErr = err
383 return
384 }
385 r.remoteSocket = filepath.Join(socketDir, "gopls-test-daemon")
386
387 // The server should be killed by when the test runner exits, but to be
388 // conservative also set a listen timeout.
389 args := []string{"serve", "-listen", "unix;" + r.remoteSocket, "-listen.timeout", "1m"}
390
391 ctx, cancel := context.WithCancel(context.Background())
392 cmd := exec.CommandContext(ctx, r.goplsPath, args...)
393 cmd.Env = append(os.Environ(), runTestAsGoplsEnvvar+"=true")
394
395 // Start the external gopls process. This is still somewhat racy, as we
396 // don't know when gopls binds to the socket, but the gopls forwarder
397 // client has built-in retry behavior that should mostly mitigate this
398 // problem (and if it doesn't, we probably want to improve the retry
399 // behavior).
400 if err := cmd.Start(); err != nil {
401 cancel()
402 r.remoteSocket = ""
403 r.remoteErr = err
404 } else {
405 r.cancelRemote = cancel
406 // Spin off a goroutine to wait, so that we free up resources when the
407 // server exits.
408 go cmd.Wait()
409 }
410 })
411
412 return newForwarder("unix", r.remoteSocket)
413 }
414
415 func newForwarder(network, address string) jsonrpc2.StreamServer {
416 server, err := lsprpc.NewForwarder(network+";"+address, nil)
417 if err != nil {
418 // This should never happen, as we are passing an explicit address.
419 panic(fmt.Sprintf("internal error: unable to create forwarder: %v", err))
420 }
421 return server
422 }
423
424 // Close cleans up resource that have been allocated to this workspace.
425 func (r *Runner) Close() error {
426 var errmsgs []string
427 if r.ts != nil {
428 if err := r.ts.Close(); err != nil {
429 errmsgs = append(errmsgs, err.Error())
430 }
431 }
432 if r.cancelRemote != nil {
433 r.cancelRemote()
434 }
435 if !r.SkipCleanup {
436 if err := os.RemoveAll(r.tempDir); err != nil {
437 errmsgs = append(errmsgs, err.Error())
438 }
439 }
440 if len(errmsgs) > 0 {
441 return fmt.Errorf("errors closing the test runner:\n\t%s", strings.Join(errmsgs, "\n\t"))
442 }
443 return nil
444 }