utils_test.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "os/exec"
  6. "path/filepath"
  7. "strings"
  8. "github.com/docker/docker/api/types"
  9. "github.com/docker/docker/client"
  10. "github.com/docker/docker/pkg/stringutils"
  11. "github.com/go-check/check"
  12. "github.com/gotestyourself/gotestyourself/icmd"
  13. "github.com/pkg/errors"
  14. )
  15. func getPrefixAndSlashFromDaemonPlatform() (prefix, slash string) {
  16. if testEnv.DaemonPlatform() == "windows" {
  17. return "c:", `\`
  18. }
  19. return "", "/"
  20. }
  21. // TODO: update code to call cmd.RunCmd directly, and remove this function
  22. // Deprecated: use gotestyourself/gotestyourself/icmd
  23. func runCommandWithOutput(execCmd *exec.Cmd) (string, int, error) {
  24. result := icmd.RunCmd(transformCmd(execCmd))
  25. return result.Combined(), result.ExitCode, result.Error
  26. }
  27. // Temporary shim for migrating commands to the new function
  28. func transformCmd(execCmd *exec.Cmd) icmd.Cmd {
  29. return icmd.Cmd{
  30. Command: execCmd.Args,
  31. Env: execCmd.Env,
  32. Dir: execCmd.Dir,
  33. Stdin: execCmd.Stdin,
  34. Stdout: execCmd.Stdout,
  35. }
  36. }
  37. // ParseCgroupPaths parses 'procCgroupData', which is output of '/proc/<pid>/cgroup', and returns
  38. // a map which cgroup name as key and path as value.
  39. func ParseCgroupPaths(procCgroupData string) map[string]string {
  40. cgroupPaths := map[string]string{}
  41. for _, line := range strings.Split(procCgroupData, "\n") {
  42. parts := strings.Split(line, ":")
  43. if len(parts) != 3 {
  44. continue
  45. }
  46. cgroupPaths[parts[1]] = parts[2]
  47. }
  48. return cgroupPaths
  49. }
  50. // RandomTmpDirPath provides a temporary path with rand string appended.
  51. // does not create or checks if it exists.
  52. func RandomTmpDirPath(s string, platform string) string {
  53. // TODO: why doesn't this use os.TempDir() ?
  54. tmp := "/tmp"
  55. if platform == "windows" {
  56. tmp = os.Getenv("TEMP")
  57. }
  58. path := filepath.Join(tmp, fmt.Sprintf("%s.%s", s, stringutils.GenerateRandomAlphaOnlyString(10)))
  59. if platform == "windows" {
  60. return filepath.FromSlash(path) // Using \
  61. }
  62. return filepath.ToSlash(path) // Using /
  63. }
  64. // RunCommandPipelineWithOutput runs the array of commands with the output
  65. // of each pipelined with the following (like cmd1 | cmd2 | cmd3 would do).
  66. // It returns the final output, the exitCode different from 0 and the error
  67. // if something bad happened.
  68. // Deprecated: use icmd instead
  69. func RunCommandPipelineWithOutput(cmds ...*exec.Cmd) (output string, err error) {
  70. if len(cmds) < 2 {
  71. return "", errors.New("pipeline does not have multiple cmds")
  72. }
  73. // connect stdin of each cmd to stdout pipe of previous cmd
  74. for i, cmd := range cmds {
  75. if i > 0 {
  76. prevCmd := cmds[i-1]
  77. cmd.Stdin, err = prevCmd.StdoutPipe()
  78. if err != nil {
  79. return "", fmt.Errorf("cannot set stdout pipe for %s: %v", cmd.Path, err)
  80. }
  81. }
  82. }
  83. // start all cmds except the last
  84. for _, cmd := range cmds[:len(cmds)-1] {
  85. if err = cmd.Start(); err != nil {
  86. return "", fmt.Errorf("starting %s failed with error: %v", cmd.Path, err)
  87. }
  88. }
  89. defer func() {
  90. var pipeErrMsgs []string
  91. // wait all cmds except the last to release their resources
  92. for _, cmd := range cmds[:len(cmds)-1] {
  93. if pipeErr := cmd.Wait(); pipeErr != nil {
  94. pipeErrMsgs = append(pipeErrMsgs, fmt.Sprintf("command %s failed with error: %v", cmd.Path, pipeErr))
  95. }
  96. }
  97. if len(pipeErrMsgs) > 0 && err == nil {
  98. err = fmt.Errorf("pipelineError from Wait: %v", strings.Join(pipeErrMsgs, ", "))
  99. }
  100. }()
  101. // wait on last cmd
  102. out, err := cmds[len(cmds)-1].CombinedOutput()
  103. return string(out), err
  104. }
  105. type elementListOptions struct {
  106. element, format string
  107. }
  108. func existingElements(c *check.C, opts elementListOptions) []string {
  109. args := []string{}
  110. switch opts.element {
  111. case "container":
  112. args = append(args, "ps", "-a")
  113. case "image":
  114. args = append(args, "images", "-a")
  115. case "network":
  116. args = append(args, "network", "ls")
  117. case "plugin":
  118. args = append(args, "plugin", "ls")
  119. case "volume":
  120. args = append(args, "volume", "ls")
  121. }
  122. if opts.format != "" {
  123. args = append(args, "--format", opts.format)
  124. }
  125. out, _ := dockerCmd(c, args...)
  126. lines := []string{}
  127. for _, l := range strings.Split(out, "\n") {
  128. if l != "" {
  129. lines = append(lines, l)
  130. }
  131. }
  132. return lines
  133. }
  134. // ExistingContainerIDs returns a list of currently existing container IDs.
  135. func ExistingContainerIDs(c *check.C) []string {
  136. return existingElements(c, elementListOptions{element: "container", format: "{{.ID}}"})
  137. }
  138. // ExistingContainerNames returns a list of existing container names.
  139. func ExistingContainerNames(c *check.C) []string {
  140. return existingElements(c, elementListOptions{element: "container", format: "{{.Names}}"})
  141. }
  142. // RemoveLinesForExistingElements removes existing elements from the output of a
  143. // docker command.
  144. // This function takes an output []string and returns a []string.
  145. func RemoveLinesForExistingElements(output, existing []string) []string {
  146. for _, e := range existing {
  147. index := -1
  148. for i, line := range output {
  149. if strings.Contains(line, e) {
  150. index = i
  151. break
  152. }
  153. }
  154. if index != -1 {
  155. output = append(output[:index], output[index+1:]...)
  156. }
  157. }
  158. return output
  159. }
  160. // RemoveOutputForExistingElements removes existing elements from the output of
  161. // a docker command.
  162. // This function takes an output string and returns a string.
  163. func RemoveOutputForExistingElements(output string, existing []string) string {
  164. res := RemoveLinesForExistingElements(strings.Split(output, "\n"), existing)
  165. return strings.Join(res, "\n")
  166. }
  167. // NewEnvClientWithVersion returns a docker client with a specified version.
  168. // See: github.com/docker/docker/client `NewEnvClient()`
  169. func NewEnvClientWithVersion(version string) (*client.Client, error) {
  170. cli, err := client.NewEnvClient()
  171. if err != nil {
  172. return nil, err
  173. }
  174. cli.NegotiateAPIVersionPing(types.Ping{APIVersion: version})
  175. return cli, nil
  176. }