utils_test.go 5.1 KB

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