Debian Codegraph @

internal/xtools-internal/gocommand/invoke.go

raw
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 gocommand is a helper for calling the go command.
6 package gocommand
7
8 import (
9 "bytes"
10 "context"
11 "encoding/json"
12 "errors"
13 "fmt"
14 "io"
15 "log"
16 "os"
17 "os/exec"
18 "path/filepath"
19 "regexp"
20 "runtime"
21 "strconv"
22 "strings"
23 "sync"
24 "time"
25 )
26
27 // A Runner will run go command invocations and serialize
28 // them if it sees a concurrency error.
29 type Runner struct {
30 // once guards the runner initialization.
31 once sync.Once
32
33 // inFlight tracks available workers.
34 inFlight chan struct{}
35
36 // serialized guards the ability to run a go command serially,
37 // to avoid deadlocks when claiming workers.
38 serialized chan struct{}
39 }
40
41 const maxInFlight = 10
42
43 func (runner *Runner) initialize() {
44 runner.once.Do(func() {
45 runner.inFlight = make(chan struct{}, maxInFlight)
46 runner.serialized = make(chan struct{}, 1)
47 })
48 }
49
50 // 1.13: go: updates to go.mod needed, but contents have changed
51 // 1.14: go: updating go.mod: existing contents have changed since last read
52 var modConcurrencyError = regexp.MustCompile(`go:.*go.mod.*contents have changed`)
53
54 // Run is a convenience wrapper around RunRaw.
55 // It returns only stdout and a "friendly" error.
56 func (runner *Runner) Run(ctx context.Context, inv Invocation) (*bytes.Buffer, error) {
57 stdout, _, friendly, _ := runner.RunRaw(ctx, inv)
58 return stdout, friendly
59 }
60
61 // RunPiped runs the invocation serially, always waiting for any concurrent
62 // invocations to complete first.
63 func (runner *Runner) RunPiped(ctx context.Context, inv Invocation, stdout, stderr io.Writer) error {
64 _, err := runner.runPiped(ctx, inv, stdout, stderr)
65 return err
66 }
67
68 // RunRaw runs the invocation, serializing requests only if they fight over
69 // go.mod changes.
70 // Postcondition: both error results have same nilness.
71 func (runner *Runner) RunRaw(ctx context.Context, inv Invocation) (*bytes.Buffer, *bytes.Buffer, error, error) {
72 // Make sure the runner is always initialized.
73 runner.initialize()
74
75 // First, try to run the go command concurrently.
76 stdout, stderr, friendlyErr, err := runner.runConcurrent(ctx, inv)
77
78 // If we encounter a load concurrency error, we need to retry serially.
79 if friendlyErr != nil && modConcurrencyError.MatchString(friendlyErr.Error()) {
80 // Run serially by calling runPiped.
81 stdout.Reset()
82 stderr.Reset()
83 friendlyErr, err = runner.runPiped(ctx, inv, stdout, stderr)
84 }
85
86 return stdout, stderr, friendlyErr, err
87 }
88
89 // Postcondition: both error results have same nilness.
90 func (runner *Runner) runConcurrent(ctx context.Context, inv Invocation) (*bytes.Buffer, *bytes.Buffer, error, error) {
91 // Wait for 1 worker to become available.
92 select {
93 case <-ctx.Done():
94 return nil, nil, ctx.Err(), ctx.Err()
95 case runner.inFlight <- struct{}{}:
96 defer func() { <-runner.inFlight }()
97 }
98
99 stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{}
100 friendlyErr, err := inv.runWithFriendlyError(ctx, stdout, stderr)
101 return stdout, stderr, friendlyErr, err
102 }
103
104 // Postcondition: both error results have same nilness.
105 func (runner *Runner) runPiped(ctx context.Context, inv Invocation, stdout, stderr io.Writer) (error, error) {
106 // Make sure the runner is always initialized.
107 runner.initialize()
108
109 // Acquire the serialization lock. This avoids deadlocks between two
110 // runPiped commands.
111 select {
112 case <-ctx.Done():
113 return ctx.Err(), ctx.Err()
114 case runner.serialized <- struct{}{}:
115 defer func() { <-runner.serialized }()
116 }
117
118 // Wait for all in-progress go commands to return before proceeding,
119 // to avoid load concurrency errors.
120 for range maxInFlight {
121 select {
122 case <-ctx.Done():
123 return ctx.Err(), ctx.Err()
124 case runner.inFlight <- struct{}{}:
125 // Make sure we always "return" any workers we took.
126 defer func() { <-runner.inFlight }()
127 }
128 }
129
130 return inv.runWithFriendlyError(ctx, stdout, stderr)
131 }
132
133 // An Invocation represents a call to the go command.
134 type Invocation struct {
135 Verb string
136 Args []string
137 BuildFlags []string
138
139 // If ModFlag is set, the go command is invoked with -mod=ModFlag.
140 // TODO(rfindley): remove, in favor of Args.
141 ModFlag string
142
143 // If ModFile is set, the go command is invoked with -modfile=ModFile.
144 // TODO(rfindley): remove, in favor of Args.
145 ModFile string
146
147 // Overlay is the name of the JSON overlay file that describes
148 // unsaved editor buffers; see [WriteOverlays].
149 // If set, the go command is invoked with -overlay=Overlay.
150 // TODO(rfindley): remove, in favor of Args.
151 Overlay string
152
153 // If CleanEnv is set, the invocation will run only with the environment
154 // in Env, not starting with os.Environ.
155 CleanEnv bool
156 Env []string
157 WorkingDir string
158 Logf func(format string, args ...any)
159 }
160
161 // Postcondition: both error results have same nilness.
162 func (i *Invocation) runWithFriendlyError(ctx context.Context, stdout, stderr io.Writer) (friendlyError error, rawError error) {
163 rawError = i.run(ctx, stdout, stderr)
164 if rawError != nil {
165 friendlyError = rawError
166 // Check for 'go' executable not being found.
167 if ee, ok := rawError.(*exec.Error); ok && ee.Err == exec.ErrNotFound {
168 friendlyError = fmt.Errorf("go command required, not found: %v", ee)
169 }
170 if ctx.Err() != nil {
171 friendlyError = ctx.Err()
172 }
173 friendlyError = fmt.Errorf("err: %v: stderr: %s", friendlyError, stderr)
174 }
175 return
176 }
177
178 // logf logs if i.Logf is non-nil.
179 func (i *Invocation) logf(format string, args ...any) {
180 if i.Logf != nil {
181 i.Logf(format, args...)
182 }
183 }
184
185 func (i *Invocation) run(ctx context.Context, stdout, stderr io.Writer) error {
186 goArgs := []string{i.Verb}
187
188 appendModFile := func() {
189 if i.ModFile != "" {
190 goArgs = append(goArgs, "-modfile="+i.ModFile)
191 }
192 }
193 appendModFlag := func() {
194 if i.ModFlag != "" {
195 goArgs = append(goArgs, "-mod="+i.ModFlag)
196 }
197 }
198 appendOverlayFlag := func() {
199 if i.Overlay != "" {
200 goArgs = append(goArgs, "-overlay="+i.Overlay)
201 }
202 }
203
204 switch i.Verb {
205 case "env", "version":
206 goArgs = append(goArgs, i.Args...)
207 case "mod":
208 // mod needs the sub-verb before flags.
209 goArgs = append(goArgs, i.Args[0])
210 appendModFile()
211 goArgs = append(goArgs, i.Args[1:]...)
212 case "get":
213 goArgs = append(goArgs, i.BuildFlags...)
214 appendModFile()
215 goArgs = append(goArgs, i.Args...)
216
217 default: // notably list and build.
218 goArgs = append(goArgs, i.BuildFlags...)
219 appendModFile()
220 appendModFlag()
221 appendOverlayFlag()
222 goArgs = append(goArgs, i.Args...)
223 }
224 cmd := exec.Command("go", goArgs...)
225 cmd.Stdout = stdout
226 cmd.Stderr = stderr
227
228 // https://go.dev/issue/59541: don't wait forever copying stderr
229 // after the command has exited.
230 // After CL 484741 we copy stdout manually, so we we'll stop reading that as
231 // soon as ctx is done. However, we also don't want to wait around forever
232 // for stderr. Give a much-longer-than-reasonable delay and then assume that
233 // something has wedged in the kernel or runtime.
234 cmd.WaitDelay = 30 * time.Second
235
236 // The cwd gets resolved to the real path. On Darwin, where
237 // /tmp is a symlink, this breaks anything that expects the
238 // working directory to keep the original path, including the
239 // go command when dealing with modules.
240 //
241 // os.Getwd has a special feature where if the cwd and the PWD
242 // are the same node then it trusts the PWD, so by setting it
243 // in the env for the child process we fix up all the paths
244 // returned by the go command.
245 if !i.CleanEnv {
246 cmd.Env = os.Environ()
247 }
248 cmd.Env = append(cmd.Env, i.Env...)
249 if i.WorkingDir != "" {
250 cmd.Env = append(cmd.Env, "PWD="+i.WorkingDir)
251 cmd.Dir = i.WorkingDir
252 }
253
254 debugStr := cmdDebugStr(cmd)
255 i.logf("starting %v", debugStr)
256 start := time.Now()
257 defer func() {
258 i.logf("%s for %v", time.Since(start), debugStr)
259 }()
260
261 return runCmdContext(ctx, cmd)
262 }
263
264 // DebugHangingGoCommands may be set by tests to enable additional
265 // instrumentation (including panics) for debugging hanging Go commands.
266 //
267 // See golang/go#54461 for details.
268 var DebugHangingGoCommands = false
269
270 // runCmdContext is like exec.CommandContext except it sends os.Interrupt
271 // before os.Kill.
272 func runCmdContext(ctx context.Context, cmd *exec.Cmd) (err error) {
273 // If cmd.Stdout is not an *os.File, the exec package will create a pipe and
274 // copy it to the Writer in a goroutine until the process has finished and
275 // either the pipe reaches EOF or command's WaitDelay expires.
276 //
277 // However, the output from 'go list' can be quite large, and we don't want to
278 // keep reading (and allocating buffers) if we've already decided we don't
279 // care about the output. We don't want to wait for the process to finish, and
280 // we don't wait to wait for the WaitDelay to expire either.
281 //
282 // Instead, if cmd.Stdout requires a copying goroutine we explicitly replace
283 // it with a pipe (which is an *os.File), which we can close in order to stop
284 // copying output as soon as we realize we don't care about it.
285 var stdoutW *os.File
286 if cmd.Stdout != nil {
287 if _, ok := cmd.Stdout.(*os.File); !ok {
288 var stdoutR *os.File
289 stdoutR, stdoutW, err = os.Pipe()
290 if err != nil {
291 return err
292 }
293 prevStdout := cmd.Stdout
294 cmd.Stdout = stdoutW
295
296 stdoutErr := make(chan error, 1)
297 go func() {
298 _, err := io.Copy(prevStdout, stdoutR)
299 if err != nil {
300 err = fmt.Errorf("copying stdout: %w", err)
301 }
302 stdoutErr <- err
303 }()
304 defer func() {
305 // We started a goroutine to copy a stdout pipe.
306 // Wait for it to finish, or terminate it if need be.
307 var err2 error
308 select {
309 case err2 = <-stdoutErr:
310 stdoutR.Close()
311 case <-ctx.Done():
312 stdoutR.Close()
313 // Per https://pkg.go.dev/os#File.Close, the call to stdoutR.Close
314 // should cause the Read call in io.Copy to unblock and return
315 // immediately, but we still need to receive from stdoutErr to confirm
316 // that it has happened.
317 <-stdoutErr
318 err2 = ctx.Err()
319 }
320 if err == nil {
321 err = err2
322 }
323 }()
324
325 // Per https://pkg.go.dev/os/exec#Cmd, “If Stdout and Stderr are the
326 // same writer, and have a type that can be compared with ==, at most
327 // one goroutine at a time will call Write.”
328 //
329 // Since we're starting a goroutine that writes to cmd.Stdout, we must
330 // also update cmd.Stderr so that it still holds.
331 func() {
332 defer func() { recover() }()
333 if cmd.Stderr == prevStdout {
334 cmd.Stderr = cmd.Stdout
335 }
336 }()
337 }
338 }
339
340 startTime := time.Now()
341 err = cmd.Start()
342 if stdoutW != nil {
343 // The child process has inherited the pipe file,
344 // so close the copy held in this process.
345 stdoutW.Close()
346 stdoutW = nil
347 }
348 if err != nil {
349 return err
350 }
351
352 resChan := make(chan error, 1)
353 go func() {
354 resChan <- cmd.Wait()
355 }()
356
357 // If we're interested in debugging hanging Go commands, stop waiting after a
358 // minute and panic with interesting information.
359 debug := DebugHangingGoCommands
360 if debug {
361 timer := time.NewTimer(1 * time.Minute)
362 defer timer.Stop()
363 select {
364 case err := <-resChan:
365 return err
366 case <-timer.C:
367 // HandleHangingGoCommand terminates this process.
368 // Pass off resChan in case we can collect the command error.
369 handleHangingGoCommand(startTime, cmd, resChan)
370 case <-ctx.Done():
371 }
372 } else {
373 select {
374 case err := <-resChan:
375 return err
376 case <-ctx.Done():
377 }
378 }
379
380 // Cancelled. Interrupt and see if it ends voluntarily.
381 if err := cmd.Process.Signal(os.Interrupt); err == nil {
382 // (We used to wait only 1s but this proved
383 // fragile on loaded builder machines.)
384 timer := time.NewTimer(5 * time.Second)
385 defer timer.Stop()
386 select {
387 case err := <-resChan:
388 return err
389 case <-timer.C:
390 }
391 }
392
393 // Didn't shut down in response to interrupt. Kill it hard.
394 if err := cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) && debug {
395 log.Printf("error killing the Go command: %v", err)
396 }
397
398 return <-resChan
399 }
400
401 // handleHangingGoCommand outputs debugging information to help diagnose the
402 // cause of a hanging Go command, and then exits with log.Fatalf.
403 func handleHangingGoCommand(start time.Time, cmd *exec.Cmd, resChan chan error) {
404 switch runtime.GOOS {
405 case "linux", "darwin", "freebsd", "netbsd", "openbsd":
406 fmt.Fprintln(os.Stderr, `DETECTED A HANGING GO COMMAND
407
408 The gopls test runner has detected a hanging go command. In order to debug
409 this, the output of ps and lsof/fstat is printed below.
410
411 See golang/go#54461 for more details.`)
412
413 fmt.Fprintln(os.Stderr, "\nps axo ppid,pid,command:")
414 fmt.Fprintln(os.Stderr, "-------------------------")
415 psCmd := exec.Command("ps", "axo", "ppid,pid,command")
416 psCmd.Stdout = os.Stderr
417 psCmd.Stderr = os.Stderr
418 if err := psCmd.Run(); err != nil {
419 log.Printf("Handling hanging Go command: running ps: %v", err)
420 }
421
422 listFiles := "lsof"
423 if runtime.GOOS == "freebsd" || runtime.GOOS == "netbsd" {
424 listFiles = "fstat"
425 }
426
427 fmt.Fprintln(os.Stderr, "\n"+listFiles+":")
428 fmt.Fprintln(os.Stderr, "-----")
429 listFilesCmd := exec.Command(listFiles)
430 listFilesCmd.Stdout = os.Stderr
431 listFilesCmd.Stderr = os.Stderr
432 if err := listFilesCmd.Run(); err != nil {
433 log.Printf("Handling hanging Go command: running %s: %v", listFiles, err)
434 }
435 // Try to extract information about the slow go process by issuing a SIGQUIT.
436 if err := cmd.Process.Signal(sigStuckProcess); err == nil {
437 select {
438 case err := <-resChan:
439 stderr := "not a bytes.Buffer"
440 if buf, _ := cmd.Stderr.(*bytes.Buffer); buf != nil {
441 stderr = buf.String()
442 }
443 log.Printf("Quit hanging go command:\n\terr:%v\n\tstderr:\n%v\n\n", err, stderr)
444 case <-time.After(5 * time.Second):
445 }
446 } else {
447 log.Printf("Sending signal %d to hanging go command: %v", sigStuckProcess, err)
448 }
449 }
450 log.Fatalf("detected hanging go command (golang/go#54461); waited %s\n\tcommand:%s\n\tpid:%d", time.Since(start), cmd, cmd.Process.Pid)
451 }
452
453 func cmdDebugStr(cmd *exec.Cmd) string {
454 env := make(map[string]string)
455 for _, kv := range cmd.Env {
456 split := strings.SplitN(kv, "=", 2)
457 if len(split) == 2 {
458 k, v := split[0], split[1]
459 env[k] = v
460 }
461 }
462
463 var args []string
464 for _, arg := range cmd.Args {
465 quoted := strconv.Quote(arg)
466 if quoted[1:len(quoted)-1] != arg || strings.Contains(arg, " ") {
467 args = append(args, quoted)
468 } else {
469 args = append(args, arg)
470 }
471 }
472 return fmt.Sprintf("GOROOT=%v GOPATH=%v GO111MODULE=%v GOPROXY=%v PWD=%v %v", env["GOROOT"], env["GOPATH"], env["GO111MODULE"], env["GOPROXY"], env["PWD"], strings.Join(args, " "))
473 }
474
475 // WriteOverlays writes each value in the overlay (see the Overlay
476 // field of go/packages.Config) to a temporary file and returns the name
477 // of a JSON file describing the mapping that is suitable for the "go
478 // list -overlay" flag.
479 //
480 // On success, the caller must call the cleanup function exactly once
481 // when the files are no longer needed.
482 func WriteOverlays(overlay map[string][]byte) (filename string, cleanup func(), err error) {
483 // Do nothing if there are no overlays in the config.
484 if len(overlay) == 0 {
485 return "", func() {}, nil
486 }
487
488 dir, err := os.MkdirTemp("", "gocommand-*")
489 if err != nil {
490 return "", nil, err
491 }
492
493 // The caller must clean up this directory,
494 // unless this function returns an error.
495 // (The cleanup operand of each return
496 // statement below is ignored.)
497 defer func() {
498 cleanup = func() {
499 os.RemoveAll(dir)
500 }
501 if err != nil {
502 cleanup()
503 cleanup = nil
504 }
505 }()
506
507 // Write each map entry to a temporary file.
508 overlays := make(map[string]string)
509 for k, v := range overlay {
510 // Use a unique basename for each file (001-foo.go),
511 // to avoid creating nested directories.
512 base := fmt.Sprintf("%d-%s", 1+len(overlays), filepath.Base(k))
513 filename := filepath.Join(dir, base)
514 err := os.WriteFile(filename, v, 0o666)
515 if err != nil {
516 return "", nil, err
517 }
518 overlays[k] = filename
519 }
520
521 // Write the JSON overlay file that maps logical file names to temp files.
522 //
523 // OverlayJSON is the format overlay files are expected to be in.
524 // The Replace map maps from overlaid paths to replacement paths:
525 // the Go command will forward all reads trying to open
526 // each overlaid path to its replacement path, or consider the overlaid
527 // path not to exist if the replacement path is empty.
528 //
529 // From golang/go#39958.
530 type OverlayJSON struct {
531 Replace map[string]string `json:"replace,omitempty"`
532 }
533 b, err := json.Marshal(OverlayJSON{Replace: overlays})
534 if err != nil {
535 return "", nil, err
536 }
537 filename = filepath.Join(dir, "overlay.json")
538 if err := os.WriteFile(filename, b, 0o666); err != nil {
539 return "", nil, err
540 }
541
542 return filename, nil, nil
543 }