exec.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. // Stops the command by sending SIGTERM. It is not guaranteed the
  54. // process will stop before this function returns. If the process is not
  55. // responding, an internal timer function will send a SIGKILL to force
  56. // terminate after 10 seconds.
  57. Stop()
  58. }
  59. // ExitError is an interface that presents an API similar to os.ProcessState, which is
  60. // what ExitError from os/exec is. This is designed to make testing a bit easier and
  61. // probably loses some of the cross-platform properties of the underlying library.
  62. type ExitError interface {
  63. String() string
  64. Error() string
  65. Exited() bool
  66. ExitStatus() int
  67. }
  68. // Implements Interface in terms of really exec()ing.
  69. type executor struct{}
  70. // New returns a new Interface which will os/exec to run commands.
  71. func New() Interface {
  72. return &executor{}
  73. }
  74. // Command is part of the Interface interface.
  75. func (executor *executor) Command(cmd string, args ...string) Cmd {
  76. return (*cmdWrapper)(osexec.Command(cmd, args...))
  77. }
  78. // CommandContext is part of the Interface interface.
  79. func (executor *executor) CommandContext(ctx context.Context, cmd string, args ...string) Cmd {
  80. return (*cmdWrapper)(osexec.CommandContext(ctx, cmd, args...))
  81. }
  82. // LookPath is part of the Interface interface
  83. func (executor *executor) LookPath(file string) (string, error) {
  84. return osexec.LookPath(file)
  85. }
  86. // Wraps exec.Cmd so we can capture errors.
  87. type cmdWrapper osexec.Cmd
  88. var _ Cmd = &cmdWrapper{}
  89. func (cmd *cmdWrapper) SetDir(dir string) {
  90. cmd.Dir = dir
  91. }
  92. func (cmd *cmdWrapper) SetStdin(in io.Reader) {
  93. cmd.Stdin = in
  94. }
  95. func (cmd *cmdWrapper) SetStdout(out io.Writer) {
  96. cmd.Stdout = out
  97. }
  98. func (cmd *cmdWrapper) SetStderr(out io.Writer) {
  99. cmd.Stderr = out
  100. }
  101. // Run is part of the Cmd interface.
  102. func (cmd *cmdWrapper) Run() error {
  103. err := (*osexec.Cmd)(cmd).Run()
  104. return handleError(err)
  105. }
  106. // CombinedOutput is part of the Cmd interface.
  107. func (cmd *cmdWrapper) CombinedOutput() ([]byte, error) {
  108. out, err := (*osexec.Cmd)(cmd).CombinedOutput()
  109. return out, handleError(err)
  110. }
  111. func (cmd *cmdWrapper) Output() ([]byte, error) {
  112. out, err := (*osexec.Cmd)(cmd).Output()
  113. return out, handleError(err)
  114. }
  115. // Stop is part of the Cmd interface.
  116. func (cmd *cmdWrapper) Stop() {
  117. c := (*osexec.Cmd)(cmd)
  118. if c.Process == nil {
  119. return
  120. }
  121. c.Process.Signal(syscall.SIGTERM)
  122. time.AfterFunc(10*time.Second, func() {
  123. if !c.ProcessState.Exited() {
  124. c.Process.Signal(syscall.SIGKILL)
  125. }
  126. })
  127. }
  128. func handleError(err error) error {
  129. if err == nil {
  130. return nil
  131. }
  132. switch e := err.(type) {
  133. case *osexec.ExitError:
  134. return &ExitErrorWrapper{e}
  135. case *osexec.Error:
  136. if e.Err == osexec.ErrNotFound {
  137. return ErrExecutableNotFound
  138. }
  139. }
  140. return err
  141. }
  142. // ExitErrorWrapper is an implementation of ExitError in terms of os/exec ExitError.
  143. // Note: standard exec.ExitError is type *os.ProcessState, which already implements Exited().
  144. type ExitErrorWrapper struct {
  145. *osexec.ExitError
  146. }
  147. var _ ExitError = &ExitErrorWrapper{}
  148. // ExitStatus is part of the ExitError interface.
  149. func (eew ExitErrorWrapper) ExitStatus() int {
  150. ws, ok := eew.Sys().(syscall.WaitStatus)
  151. if !ok {
  152. panic("can't call ExitStatus() on a non-WaitStatus exitErrorWrapper")
  153. }
  154. return ws.ExitStatus()
  155. }
  156. // CodeExitError is an implementation of ExitError consisting of an error object
  157. // and an exit code (the upper bits of os.exec.ExitStatus).
  158. type CodeExitError struct {
  159. Err error
  160. Code int
  161. }
  162. var _ ExitError = CodeExitError{}
  163. func (e CodeExitError) Error() string {
  164. return e.Err.Error()
  165. }
  166. func (e CodeExitError) String() string {
  167. return e.Err.Error()
  168. }
  169. func (e CodeExitError) Exited() bool {
  170. return true
  171. }
  172. func (e CodeExitError) ExitStatus() int {
  173. return e.Code
  174. }