1
0

exec.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. "strings"
  31. "syscall"
  32. "time"
  33. "github.com/onsi/gomega"
  34. log "github.com/sirupsen/logrus"
  35. )
  36. func (b CmdContext) makeCmd() *exec.Cmd {
  37. return exec.Command(b.command, b.args...)
  38. }
  39. // CmdContext is used to build, customize and execute a command.
  40. // Add more functions to customize the context as needed.
  41. type CmdContext struct {
  42. command string
  43. args []string
  44. envs []string
  45. dir string
  46. stdin io.Reader
  47. timeout <-chan time.Time
  48. retries RetriesContext
  49. }
  50. // RetriesContext is used to tweak retry loop.
  51. type RetriesContext struct {
  52. count int
  53. interval time.Duration
  54. }
  55. // WithinDirectory tells Docker the cwd.
  56. func (b *CmdContext) WithinDirectory(path string) *CmdContext {
  57. b.dir = path
  58. return b
  59. }
  60. // WithEnvs set envs in context.
  61. func (b *CmdContext) WithEnvs(envs []string) *CmdContext {
  62. b.envs = envs
  63. return b
  64. }
  65. // WithTimeout controls maximum duration.
  66. func (b *CmdContext) WithTimeout(t <-chan time.Time) *CmdContext {
  67. b.timeout = t
  68. return b
  69. }
  70. // WithRetries sets how many times to retry the command before issuing an error
  71. func (b *CmdContext) WithRetries(count int) *CmdContext {
  72. b.retries.count = count
  73. return b
  74. }
  75. // Every interval between 2 retries
  76. func (b *CmdContext) Every(interval time.Duration) *CmdContext {
  77. b.retries.interval = interval
  78. return b
  79. }
  80. // WithStdinData feeds via stdin.
  81. func (b CmdContext) WithStdinData(data string) *CmdContext {
  82. b.stdin = strings.NewReader(data)
  83. return &b
  84. }
  85. // WithStdinReader feeds via stdin.
  86. func (b CmdContext) WithStdinReader(reader io.Reader) *CmdContext {
  87. b.stdin = reader
  88. return &b
  89. }
  90. // ExecOrDie runs a docker command.
  91. func (b CmdContext) ExecOrDie() string {
  92. str, err := b.Exec()
  93. log.Debugf("stdout: %s", str)
  94. gomega.Expect(err).NotTo(gomega.HaveOccurred())
  95. return str
  96. }
  97. // Exec runs a docker command.
  98. func (b CmdContext) Exec() (string, error) {
  99. retry := b.retries.count
  100. for ; ; retry-- {
  101. cmd := b.makeCmd()
  102. cmd.Dir = b.dir
  103. cmd.Stdin = b.stdin
  104. if b.envs != nil {
  105. cmd.Env = b.envs
  106. }
  107. stdout, err := Execute(cmd, b.timeout)
  108. if err == nil || retry < 1 {
  109. return stdout, err
  110. }
  111. time.Sleep(b.retries.interval)
  112. }
  113. }
  114. //WaitFor waits for a condition to be true
  115. func WaitFor(interval, duration time.Duration, abort <-chan error, condition func() bool) error {
  116. ticker := time.NewTicker(interval)
  117. defer ticker.Stop()
  118. timeout := make(chan int)
  119. go func() {
  120. time.Sleep(duration)
  121. close(timeout)
  122. }()
  123. for {
  124. select {
  125. case err := <-abort:
  126. return err
  127. case <-timeout:
  128. return fmt.Errorf("timeout after %v", duration)
  129. case <-ticker.C:
  130. if condition() {
  131. return nil
  132. }
  133. }
  134. }
  135. }
  136. // Execute executes a command.
  137. // The command cannot be re-used afterwards.
  138. func Execute(cmd *exec.Cmd, timeout <-chan time.Time) (string, error) {
  139. var stdout, stderr bytes.Buffer
  140. cmd.Stdout = mergeWriter(cmd.Stdout, &stdout)
  141. cmd.Stderr = mergeWriter(cmd.Stderr, &stderr)
  142. log.Infof("Execute '%s %s'", cmd.Path, strings.Join(cmd.Args[1:], " ")) // skip arg[0] as it is printed separately
  143. if err := cmd.Start(); err != nil {
  144. return "", fmt.Errorf("error starting %v:\nCommand stdout:\n%v\nstderr:\n%v\nerror:\n%v", cmd, stdout.String(), stderr.String(), err)
  145. }
  146. errCh := make(chan error, 1)
  147. go func() {
  148. errCh <- cmd.Wait()
  149. }()
  150. select {
  151. case err := <-errCh:
  152. if err != nil {
  153. log.Debugf("%s %s failed: %v", cmd.Path, strings.Join(cmd.Args[1:], " "), err)
  154. return stderr.String(), fmt.Errorf("error running %v:\nCommand stdout:\n%v\nstderr:\n%v\nerror:\n%v", cmd, stdout.String(), stderr.String(), err)
  155. }
  156. case <-timeout:
  157. log.Debugf("%s %s timed-out", cmd.Path, strings.Join(cmd.Args[1:], " "))
  158. if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
  159. return "", err
  160. }
  161. return "", fmt.Errorf(
  162. "timed out waiting for command %v:\nCommand stdout:\n%v\nstderr:\n%v",
  163. cmd.Args, stdout.String(), stderr.String())
  164. }
  165. if stderr.String() != "" {
  166. log.Debugf("stderr: %s", stderr.String())
  167. }
  168. return stdout.String(), nil
  169. }
  170. func mergeWriter(other io.Writer, buf io.Writer) io.Writer {
  171. if other != nil {
  172. return io.MultiWriter(other, buf)
  173. }
  174. return buf
  175. }
  176. // Powershell runs a powershell command.
  177. func Powershell(input string) (string, error) {
  178. output, err := Execute(exec.Command("powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Unrestricted", "-Command", input), nil)
  179. if err != nil {
  180. return "", fmt.Errorf("fail to execute %s: %s", input, err)
  181. }
  182. return strings.TrimSpace(output), nil
  183. }