exec.go 7.2 KB

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