Debian Codegraph @

exec/exec.go

raw
1 /*
2 Copyright 2017 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package exec
18
19 import (
20 "context"
21 "errors"
22 "io"
23 "io/fs"
24 osexec "os/exec"
25 "syscall"
26 "time"
27 )
28
29 // ErrExecutableNotFound is returned if the executable is not found.
30 var ErrExecutableNotFound = osexec.ErrNotFound
31
32 // Interface is an interface that presents a subset of the os/exec API. Use this
33 // when you want to inject fakeable/mockable exec behavior.
34 type Interface interface {
35 // Command returns a Cmd instance which can be used to run a single command.
36 // This follows the pattern of package os/exec.
37 Command(cmd string, args ...string) Cmd
38
39 // CommandContext returns a Cmd instance which can be used to run a single command.
40 //
41 // The provided context is used to kill the process if the context becomes done
42 // before the command completes on its own. For example, a timeout can be set in
43 // the context.
44 CommandContext(ctx context.Context, cmd string, args ...string) Cmd
45
46 // LookPath wraps os/exec.LookPath
47 LookPath(file string) (string, error)
48 }
49
50 // Cmd is an interface that presents an API that is very similar to Cmd from os/exec.
51 // As more functionality is needed, this can grow. Since Cmd is a struct, we will have
52 // to replace fields with get/set method pairs.
53 type Cmd interface {
54 // Run runs the command to the completion.
55 Run() error
56 // CombinedOutput runs the command and returns its combined standard output
57 // and standard error. This follows the pattern of package os/exec.
58 CombinedOutput() ([]byte, error)
59 // Output runs the command and returns standard output, but not standard err
60 Output() ([]byte, error)
61 SetDir(dir string)
62 SetStdin(in io.Reader)
63 SetStdout(out io.Writer)
64 SetStderr(out io.Writer)
65 SetEnv(env []string)
66
67 // StdoutPipe and StderrPipe for getting the process' Stdout and Stderr as
68 // Readers
69 StdoutPipe() (io.ReadCloser, error)
70 StderrPipe() (io.ReadCloser, error)
71
72 // Start and Wait are for running a process non-blocking
73 Start() error
74 Wait() error
75
76 // Stops the command by sending SIGTERM. It is not guaranteed the
77 // process will stop before this function returns. If the process is not
78 // responding, an internal timer function will send a SIGKILL to force
79 // terminate after 10 seconds.
80 Stop()
81 }
82
83 // ExitError is an interface that presents an API similar to os.ProcessState, which is
84 // what ExitError from os/exec is. This is designed to make testing a bit easier and
85 // probably loses some of the cross-platform properties of the underlying library.
86 type ExitError interface {
87 String() string
88 Error() string
89 Exited() bool
90 ExitStatus() int
91 }
92
93 // Implements Interface in terms of really exec()ing.
94 type executor struct{}
95
96 // New returns a new Interface which will os/exec to run commands.
97 func New() Interface {
98 return &executor{}
99 }
100
101 // maskErrDotCmd reverts the behavior of osexec.Cmd to what it was before go1.19
102 // specifically set the Err field to nil (LookPath returns a new error when the file
103 // is resolved to the current directory.
104 func maskErrDotCmd(cmd *osexec.Cmd) *osexec.Cmd {
105 cmd.Err = maskErrDot(cmd.Err)
106 return cmd
107 }
108
109 func maskErrDot(err error) error {
110 if err != nil && errors.Is(err, osexec.ErrDot) {
111 return nil
112 }
113 return err
114 }
115
116 // Command is part of the Interface interface.
117 func (executor *executor) Command(cmd string, args ...string) Cmd {
118 return (*cmdWrapper)(maskErrDotCmd(osexec.Command(cmd, args...)))
119 }
120
121 // CommandContext is part of the Interface interface.
122 func (executor *executor) CommandContext(ctx context.Context, cmd string, args ...string) Cmd {
123 return (*cmdWrapper)(maskErrDotCmd(osexec.CommandContext(ctx, cmd, args...)))
124 }
125
126 // LookPath is part of the Interface interface
127 func (executor *executor) LookPath(file string) (string, error) {
128 path, err := osexec.LookPath(file)
129 return path, handleError(maskErrDot(err))
130 }
131
132 // Wraps exec.Cmd so we can capture errors.
133 type cmdWrapper osexec.Cmd
134
135 var _ Cmd = &cmdWrapper{}
136
137 func (cmd *cmdWrapper) SetDir(dir string) {
138 cmd.Dir = dir
139 }
140
141 func (cmd *cmdWrapper) SetStdin(in io.Reader) {
142 cmd.Stdin = in
143 }
144
145 func (cmd *cmdWrapper) SetStdout(out io.Writer) {
146 cmd.Stdout = out
147 }
148
149 func (cmd *cmdWrapper) SetStderr(out io.Writer) {
150 cmd.Stderr = out
151 }
152
153 func (cmd *cmdWrapper) SetEnv(env []string) {
154 cmd.Env = env
155 }
156
157 func (cmd *cmdWrapper) StdoutPipe() (io.ReadCloser, error) {
158 r, err := (*osexec.Cmd)(cmd).StdoutPipe()
159 return r, handleError(err)
160 }
161
162 func (cmd *cmdWrapper) StderrPipe() (io.ReadCloser, error) {
163 r, err := (*osexec.Cmd)(cmd).StderrPipe()
164 return r, handleError(err)
165 }
166
167 func (cmd *cmdWrapper) Start() error {
168 err := (*osexec.Cmd)(cmd).Start()
169 return handleError(err)
170 }
171
172 func (cmd *cmdWrapper) Wait() error {
173 err := (*osexec.Cmd)(cmd).Wait()
174 return handleError(err)
175 }
176
177 // Run is part of the Cmd interface.
178 func (cmd *cmdWrapper) Run() error {
179 err := (*osexec.Cmd)(cmd).Run()
180 return handleError(err)
181 }
182
183 // CombinedOutput is part of the Cmd interface.
184 func (cmd *cmdWrapper) CombinedOutput() ([]byte, error) {
185 out, err := (*osexec.Cmd)(cmd).CombinedOutput()
186 return out, handleError(err)
187 }
188
189 func (cmd *cmdWrapper) Output() ([]byte, error) {
190 out, err := (*osexec.Cmd)(cmd).Output()
191 return out, handleError(err)
192 }
193
194 // Stop is part of the Cmd interface.
195 func (cmd *cmdWrapper) Stop() {
196 c := (*osexec.Cmd)(cmd)
197
198 if c.Process == nil {
199 return
200 }
201
202 c.Process.Signal(syscall.SIGTERM)
203
204 time.AfterFunc(10*time.Second, func() {
205 if !c.ProcessState.Exited() {
206 c.Process.Signal(syscall.SIGKILL)
207 }
208 })
209 }
210
211 func handleError(err error) error {
212 if err == nil {
213 return nil
214 }
215
216 switch e := err.(type) {
217 case *osexec.ExitError:
218 return &ExitErrorWrapper{e}
219 case *fs.PathError:
220 return ErrExecutableNotFound
221 case *osexec.Error:
222 if e.Err == osexec.ErrNotFound {
223 return ErrExecutableNotFound
224 }
225 }
226
227 return err
228 }
229
230 // ExitErrorWrapper is an implementation of ExitError in terms of os/exec ExitError.
231 // Note: standard exec.ExitError is type *os.ProcessState, which already implements Exited().
232 type ExitErrorWrapper struct {
233 *osexec.ExitError
234 }
235
236 var _ ExitError = &ExitErrorWrapper{}
237
238 // ExitStatus is part of the ExitError interface.
239 func (eew ExitErrorWrapper) ExitStatus() int {
240 ws, ok := eew.Sys().(syscall.WaitStatus)
241 if !ok {
242 panic("can't call ExitStatus() on a non-WaitStatus exitErrorWrapper")
243 }
244 return ws.ExitStatus()
245 }
246
247 // CodeExitError is an implementation of ExitError consisting of an error object
248 // and an exit code (the upper bits of os.exec.ExitStatus).
249 type CodeExitError struct {
250 Err error
251 Code int
252 }
253
254 var _ ExitError = CodeExitError{}
255
256 func (e CodeExitError) Error() string {
257 return e.Err.Error()
258 }
259
260 func (e CodeExitError) String() string {
261 return e.Err.Error()
262 }
263
264 // Exited is to check if the process has finished
265 func (e CodeExitError) Exited() bool {
266 return true
267 }
268
269 // ExitStatus is for checking the error code
270 func (e CodeExitError) ExitStatus() int {
271 return e.Code
272 }