exec.go 6.6 KB

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