exec.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. /*
  2. Copyright (c) 2020 Docker Inc.
  3. Permission is hereby granted, free of charge, to any person
  4. obtaining a copy of this software and associated documentation
  5. files (the "Software"), to deal in the Software without
  6. restriction, including without limitation the rights to use, copy,
  7. modify, merge, publish, distribute, sublicense, and/or sell copies
  8. of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be
  11. included in all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  13. EXPRESS OR IMPLIED,
  14. INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  16. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  17. HOLDERS BE LIABLE FOR ANY CLAIM,
  18. DAMAGES OR OTHER LIABILITY,
  19. WHETHER IN AN ACTION OF CONTRACT,
  20. TORT OR OTHERWISE,
  21. ARISING FROM, OUT OF OR IN CONNECTION WITH
  22. THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. */
  24. package framework
  25. import (
  26. "bytes"
  27. "fmt"
  28. "io"
  29. "os/exec"
  30. "runtime"
  31. "strings"
  32. "syscall"
  33. "time"
  34. "github.com/onsi/gomega"
  35. log "github.com/sirupsen/logrus"
  36. )
  37. func (b CmdContext) makeCmd() *exec.Cmd {
  38. return exec.Command(b.command, b.args...)
  39. }
  40. // CmdContext is used to build, customize and execute a command.
  41. // Add more functions to customize the context as needed.
  42. type CmdContext struct {
  43. command string
  44. args []string
  45. envs []string
  46. dir string
  47. stdin io.Reader
  48. timeout <-chan time.Time
  49. retries RetriesContext
  50. }
  51. // RetriesContext is used to tweak retry loop.
  52. type RetriesContext struct {
  53. count int
  54. interval time.Duration
  55. }
  56. // WithinDirectory tells Docker the cwd.
  57. func (b *CmdContext) WithinDirectory(path string) *CmdContext {
  58. b.dir = path
  59. return b
  60. }
  61. // WithEnvs set envs in context.
  62. func (b *CmdContext) WithEnvs(envs []string) *CmdContext {
  63. b.envs = envs
  64. return b
  65. }
  66. // WithTimeout controls maximum duration.
  67. func (b *CmdContext) WithTimeout(t <-chan time.Time) *CmdContext {
  68. b.timeout = t
  69. return b
  70. }
  71. // WithRetries sets how many times to retry the command before issuing an error
  72. func (b *CmdContext) WithRetries(count int) *CmdContext {
  73. b.retries.count = count
  74. return b
  75. }
  76. // Every interval between 2 retries
  77. func (b *CmdContext) Every(interval time.Duration) *CmdContext {
  78. b.retries.interval = interval
  79. return b
  80. }
  81. // WithStdinData feeds via stdin.
  82. func (b CmdContext) WithStdinData(data string) *CmdContext {
  83. b.stdin = strings.NewReader(data)
  84. return &b
  85. }
  86. // WithStdinReader feeds via stdin.
  87. func (b CmdContext) WithStdinReader(reader io.Reader) *CmdContext {
  88. b.stdin = reader
  89. return &b
  90. }
  91. // ExecOrDie runs a docker command.
  92. func (b CmdContext) ExecOrDie() string {
  93. str, err := b.Exec()
  94. log.Debugf("stdout: %s", str)
  95. gomega.Expect(err).NotTo(gomega.HaveOccurred())
  96. return str
  97. }
  98. // Exec runs a docker command.
  99. func (b CmdContext) Exec() (string, error) {
  100. retry := b.retries.count
  101. for ; ; retry-- {
  102. cmd := b.makeCmd()
  103. cmd.Dir = b.dir
  104. cmd.Stdin = b.stdin
  105. if b.envs != nil {
  106. cmd.Env = b.envs
  107. }
  108. stdout, err := Execute(cmd, b.timeout)
  109. if err == nil || retry < 1 {
  110. return stdout, err
  111. }
  112. time.Sleep(b.retries.interval)
  113. }
  114. }
  115. //WaitFor waits for a condition to be true
  116. func WaitFor(interval, duration time.Duration, abort <-chan error, condition func() bool) error {
  117. ticker := time.NewTicker(interval)
  118. defer ticker.Stop()
  119. timeout := make(chan int)
  120. go func() {
  121. time.Sleep(duration)
  122. close(timeout)
  123. }()
  124. for {
  125. select {
  126. case err := <-abort:
  127. return err
  128. case <-timeout:
  129. return fmt.Errorf("timeout after %v", duration)
  130. case <-ticker.C:
  131. if condition() {
  132. return nil
  133. }
  134. }
  135. }
  136. }
  137. // Execute executes a command.
  138. // The command cannot be re-used afterwards.
  139. func Execute(cmd *exec.Cmd, timeout <-chan time.Time) (string, error) {
  140. var stdout, stderr bytes.Buffer
  141. cmd.Stdout = mergeWriter(cmd.Stdout, &stdout)
  142. cmd.Stderr = mergeWriter(cmd.Stderr, &stderr)
  143. log.Infof("Execute '%s %s'", cmd.Path, strings.Join(cmd.Args[1:], " ")) // skip arg[0] as it is printed separately
  144. if err := cmd.Start(); err != nil {
  145. return "", fmt.Errorf("error starting %v:\nCommand stdout:\n%v\nstderr:\n%v\nerror:\n%v", cmd, stdout.String(), stderr.String(), err)
  146. }
  147. errCh := make(chan error, 1)
  148. go func() {
  149. errCh <- cmd.Wait()
  150. }()
  151. select {
  152. case err := <-errCh:
  153. if err != nil {
  154. log.Debugf("%s %s failed: %v", cmd.Path, strings.Join(cmd.Args[1:], " "), err)
  155. return stderr.String(), fmt.Errorf("error running %v:\nCommand stdout:\n%v\nstderr:\n%v\nerror:\n%v", cmd, stdout.String(), stderr.String(), err)
  156. }
  157. case <-timeout:
  158. log.Debugf("%s %s timed-out", cmd.Path, strings.Join(cmd.Args[1:], " "))
  159. if err := terminateProcess(cmd); err != nil {
  160. return "", err
  161. }
  162. return "", fmt.Errorf(
  163. "timed out waiting for command %v:\nCommand stdout:\n%v\nstderr:\n%v",
  164. cmd.Args, stdout.String(), stderr.String())
  165. }
  166. if stderr.String() != "" {
  167. log.Debugf("stderr: %s", stderr.String())
  168. }
  169. return stdout.String(), nil
  170. }
  171. func terminateProcess(cmd *exec.Cmd) error {
  172. if runtime.GOOS == "windows" {
  173. return cmd.Process.Kill()
  174. }
  175. return cmd.Process.Signal(syscall.SIGTERM)
  176. }
  177. func mergeWriter(other io.Writer, buf io.Writer) io.Writer {
  178. if other != nil {
  179. return io.MultiWriter(other, buf)
  180. }
  181. return buf
  182. }
  183. // Powershell runs a powershell command.
  184. func Powershell(input string) (string, error) {
  185. output, err := Execute(exec.Command("powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Unrestricted", "-Command", input), nil)
  186. if err != nil {
  187. return "", fmt.Errorf("fail to execute %s: %s", input, err)
  188. }
  189. return strings.TrimSpace(output), nil
  190. }