utils_test.go 5.1 KB

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