utils_test.go 5.5 KB

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