utils_test.go 5.0 KB

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