|
| 1 | +package pipe |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "errors" |
| 7 | + "io" |
| 8 | + "os" |
| 9 | + "os/exec" |
| 10 | + "sync/atomic" |
| 11 | + "syscall" |
| 12 | + "time" |
| 13 | + |
| 14 | + "golang.org/x/sync/errgroup" |
| 15 | +) |
| 16 | + |
| 17 | +// commandStage is a pipeline `Stage` based on running an external |
| 18 | +// command and piping the data through its stdin and stdout. |
| 19 | +type commandStage struct { |
| 20 | + name string |
| 21 | + stdin io.Closer |
| 22 | + cmd *exec.Cmd |
| 23 | + done chan struct{} |
| 24 | + wg errgroup.Group |
| 25 | + stderr bytes.Buffer |
| 26 | + |
| 27 | + // If the context expired and we attempted to kill the command, |
| 28 | + // `ctx.Err()` is stored here. |
| 29 | + ctxErr atomic.Value |
| 30 | +} |
| 31 | + |
| 32 | +// Command returns a pipeline `Stage` based on the specified external |
| 33 | +// `command`, run with the given command-line `args`. Its stdin and |
| 34 | +// stdout are handled as usual, and its stderr is collected and |
| 35 | +// included in any `*exec.ExitError` that the command might emit. |
| 36 | +func Command(command string, args ...string) Stage { |
| 37 | + if len(command) == 0 { |
| 38 | + panic("attempt to create command with empty command") |
| 39 | + } |
| 40 | + |
| 41 | + cmd := exec.Command(command, args...) |
| 42 | + return CommandStage(command, cmd) |
| 43 | +} |
| 44 | + |
| 45 | +// Command returns a pipeline `Stage` with the name `name`, based on |
| 46 | +// the specified `cmd`. Its stdin and stdout are handled as usual, and |
| 47 | +// its stderr is collected and included in any `*exec.ExitError` that |
| 48 | +// the command might emit. |
| 49 | +func CommandStage(name string, cmd *exec.Cmd) Stage { |
| 50 | + return &commandStage{ |
| 51 | + name: name, |
| 52 | + cmd: cmd, |
| 53 | + done: make(chan struct{}), |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +func (s *commandStage) Name() string { |
| 58 | + return s.name |
| 59 | +} |
| 60 | + |
| 61 | +func (s *commandStage) Start( |
| 62 | + ctx context.Context, env Env, stdin io.ReadCloser, |
| 63 | +) (io.ReadCloser, error) { |
| 64 | + if s.cmd.Dir == "" { |
| 65 | + s.cmd.Dir = env.Dir |
| 66 | + } |
| 67 | + |
| 68 | + if stdin != nil { |
| 69 | + s.cmd.Stdin = stdin |
| 70 | + // Also keep a copy so that we can close it when the command exits: |
| 71 | + s.stdin = stdin |
| 72 | + } |
| 73 | + |
| 74 | + stdout, err := s.cmd.StdoutPipe() |
| 75 | + if err != nil { |
| 76 | + return nil, err |
| 77 | + } |
| 78 | + |
| 79 | + // If the caller hasn't arranged otherwise, read the command's |
| 80 | + // standard error into our `stderr` field: |
| 81 | + if s.cmd.Stderr == nil { |
| 82 | + // We can't just set `s.cmd.Stderr = &s.stderr`, because if we |
| 83 | + // do then `s.cmd.Wait()` doesn't wait to be sure that all |
| 84 | + // error output has been captured. By doing this ourselves, we |
| 85 | + // can be sure. |
| 86 | + p, err := s.cmd.StderrPipe() |
| 87 | + if err != nil { |
| 88 | + return nil, err |
| 89 | + } |
| 90 | + s.wg.Go(func() error { |
| 91 | + _, err := io.Copy(&s.stderr, p) |
| 92 | + // We don't consider `ErrClosed` an error (FIXME: is this |
| 93 | + // correct?): |
| 94 | + if err != nil && !errors.Is(err, os.ErrClosed) { |
| 95 | + return err |
| 96 | + } |
| 97 | + return nil |
| 98 | + }) |
| 99 | + } |
| 100 | + |
| 101 | + // Put the command in its own process group: |
| 102 | + if s.cmd.SysProcAttr == nil { |
| 103 | + s.cmd.SysProcAttr = &syscall.SysProcAttr{} |
| 104 | + } |
| 105 | + s.cmd.SysProcAttr.Setpgid = true |
| 106 | + |
| 107 | + if err := s.cmd.Start(); err != nil { |
| 108 | + return nil, err |
| 109 | + } |
| 110 | + |
| 111 | + // Arrange for the process to be killed (gently) if the context |
| 112 | + // expires before the command exits normally: |
| 113 | + go func() { |
| 114 | + select { |
| 115 | + case <-ctx.Done(): |
| 116 | + s.kill(ctx.Err()) |
| 117 | + case <-s.done: |
| 118 | + // Process already done; no need to kill anything. |
| 119 | + } |
| 120 | + }() |
| 121 | + |
| 122 | + return stdout, nil |
| 123 | +} |
| 124 | + |
| 125 | +// kill is called to kill the process if the context expires. `err` is |
| 126 | +// the corresponding value of `Context.Err()`. |
| 127 | +func (s *commandStage) kill(err error) { |
| 128 | + // I believe that the calls to `syscall.Kill()` in this method are |
| 129 | + // racy. It could be that s.cmd.Wait() succeeds immediately before |
| 130 | + // this call, in which case the process group wouldn't exist |
| 131 | + // anymore. But I don't see any way to avoid this without |
| 132 | + // duplicating a lot of code from `exec.Cmd`. (`os.Cmd.Kill()` and |
| 133 | + // `os.Cmd.Signal()` appear to be race-free, but only because they |
| 134 | + // use internal synchronization. But those methods only kill the |
| 135 | + // process, not the process group, so they are not suitable here. |
| 136 | + |
| 137 | + // We started the process with PGID == PID: |
| 138 | + pid := s.cmd.Process.Pid |
| 139 | + select { |
| 140 | + case <-s.done: |
| 141 | + // Process has ended; no need to kill it again. |
| 142 | + return |
| 143 | + default: |
| 144 | + } |
| 145 | + |
| 146 | + // Record the `ctx.Err()`, which will be used as the error result |
| 147 | + // for this stage. |
| 148 | + s.ctxErr.Store(err) |
| 149 | + |
| 150 | + // First try to kill using a relatively gentle signal so that |
| 151 | + // the processes have a chance to clean up after themselves: |
| 152 | + _ = syscall.Kill(-pid, syscall.SIGTERM) |
| 153 | + |
| 154 | + // Well-behaved processes should commit suicide after the above, |
| 155 | + // but if they don't exit within 2s, murder the whole lot of them: |
| 156 | + go func() { |
| 157 | + // Use an explicit `time.Timer` rather than `time.After()` so |
| 158 | + // that we can stop it (freeing resources) promptly if the |
| 159 | + // command exits before the timer triggers. |
| 160 | + timer := time.NewTimer(2 * time.Second) |
| 161 | + defer timer.Stop() |
| 162 | + |
| 163 | + select { |
| 164 | + case <-s.done: |
| 165 | + // Process has ended; no need to kill it again. |
| 166 | + case <-timer.C: |
| 167 | + _ = syscall.Kill(-pid, syscall.SIGKILL) |
| 168 | + } |
| 169 | + }() |
| 170 | +} |
| 171 | + |
| 172 | +// filterCmdError interprets `err`, which was returned by `Cmd.Wait()` |
| 173 | +// (possibly `nil`), possibly modifying it or ignoring it. It returns |
| 174 | +// the error that should actually be returned to the caller (possibly |
| 175 | +// `nil`). |
| 176 | +func (s *commandStage) filterCmdError(err error) error { |
| 177 | + if err == nil { |
| 178 | + return nil |
| 179 | + } |
| 180 | + |
| 181 | + eErr, ok := err.(*exec.ExitError) |
| 182 | + if !ok { |
| 183 | + return err |
| 184 | + } |
| 185 | + |
| 186 | + ctxErr, ok := s.ctxErr.Load().(error) |
| 187 | + if ok { |
| 188 | + // If the process looks like it was killed by us, substitute |
| 189 | + // `ctxErr` for the process's own exit error. |
| 190 | + ps, ok := eErr.ProcessState.Sys().(syscall.WaitStatus) |
| 191 | + if ok && ps.Signaled() && |
| 192 | + (ps.Signal() == syscall.SIGTERM || ps.Signal() == syscall.SIGKILL) { |
| 193 | + return ctxErr |
| 194 | + } |
| 195 | + } |
| 196 | + |
| 197 | + eErr.Stderr = s.stderr.Bytes() |
| 198 | + return eErr |
| 199 | +} |
| 200 | + |
| 201 | +func (s *commandStage) Wait() error { |
| 202 | + defer close(s.done) |
| 203 | + |
| 204 | + // Make sure that any stderr is copied before `s.cmd.Wait()` |
| 205 | + // closes the read end of the pipe: |
| 206 | + wErr := s.wg.Wait() |
| 207 | + |
| 208 | + err := s.cmd.Wait() |
| 209 | + err = s.filterCmdError(err) |
| 210 | + |
| 211 | + if err == nil && wErr != nil { |
| 212 | + err = wErr |
| 213 | + } |
| 214 | + |
| 215 | + if s.stdin != nil { |
| 216 | + cErr := s.stdin.Close() |
| 217 | + if cErr != nil && err == nil { |
| 218 | + return cErr |
| 219 | + } |
| 220 | + } |
| 221 | + |
| 222 | + return err |
| 223 | +} |
0 commit comments