exec.go 4.4 KB

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