exec.go 5.0 KB

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