utils.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "math/rand"
  9. "net/http"
  10. "net/http/httptest"
  11. "os"
  12. "os/exec"
  13. "path"
  14. "reflect"
  15. "strings"
  16. "syscall"
  17. "time"
  18. "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
  19. )
  20. func getExitCode(err error) (int, error) {
  21. exitCode := 0
  22. if exiterr, ok := err.(*exec.ExitError); ok {
  23. if procExit := exiterr.Sys().(syscall.WaitStatus); ok {
  24. return procExit.ExitStatus(), nil
  25. }
  26. }
  27. return exitCode, fmt.Errorf("failed to get exit code")
  28. }
  29. func processExitCode(err error) (exitCode int) {
  30. if err != nil {
  31. var exiterr error
  32. if exitCode, exiterr = getExitCode(err); exiterr != nil {
  33. // TODO: Fix this so we check the error's text.
  34. // we've failed to retrieve exit code, so we set it to 127
  35. exitCode = 127
  36. }
  37. }
  38. return
  39. }
  40. func runCommandWithOutput(cmd *exec.Cmd) (output string, exitCode int, err error) {
  41. exitCode = 0
  42. out, err := cmd.CombinedOutput()
  43. exitCode = processExitCode(err)
  44. output = string(out)
  45. return
  46. }
  47. func runCommandWithStdoutStderr(cmd *exec.Cmd) (stdout string, stderr string, exitCode int, err error) {
  48. var (
  49. stderrBuffer, stdoutBuffer bytes.Buffer
  50. )
  51. exitCode = 0
  52. cmd.Stderr = &stderrBuffer
  53. cmd.Stdout = &stdoutBuffer
  54. err = cmd.Run()
  55. exitCode = processExitCode(err)
  56. stdout = stdoutBuffer.String()
  57. stderr = stderrBuffer.String()
  58. return
  59. }
  60. func runCommandWithOutputForDuration(cmd *exec.Cmd, duration time.Duration) (output string, exitCode int, timedOut bool, err error) {
  61. var outputBuffer bytes.Buffer
  62. if cmd.Stdout != nil {
  63. err = errors.New("cmd.Stdout already set")
  64. return
  65. }
  66. cmd.Stdout = &outputBuffer
  67. if cmd.Stderr != nil {
  68. err = errors.New("cmd.Stderr already set")
  69. return
  70. }
  71. cmd.Stderr = &outputBuffer
  72. done := make(chan error)
  73. go func() {
  74. exitErr := cmd.Run()
  75. exitCode = processExitCode(exitErr)
  76. done <- exitErr
  77. }()
  78. select {
  79. case <-time.After(duration):
  80. killErr := cmd.Process.Kill()
  81. if killErr != nil {
  82. fmt.Printf("failed to kill (pid=%d): %v\n", cmd.Process.Pid, killErr)
  83. }
  84. timedOut = true
  85. break
  86. case err = <-done:
  87. break
  88. }
  89. output = outputBuffer.String()
  90. return
  91. }
  92. var ErrCmdTimeout = fmt.Errorf("command timed out")
  93. func runCommandWithOutputAndTimeout(cmd *exec.Cmd, timeout time.Duration) (output string, exitCode int, err error) {
  94. var timedOut bool
  95. output, exitCode, timedOut, err = runCommandWithOutputForDuration(cmd, timeout)
  96. if timedOut {
  97. err = ErrCmdTimeout
  98. }
  99. return
  100. }
  101. func runCommand(cmd *exec.Cmd) (exitCode int, err error) {
  102. exitCode = 0
  103. err = cmd.Run()
  104. exitCode = processExitCode(err)
  105. return
  106. }
  107. func runCommandPipelineWithOutput(cmds ...*exec.Cmd) (output string, exitCode int, err error) {
  108. if len(cmds) < 2 {
  109. return "", 0, errors.New("pipeline does not have multiple cmds")
  110. }
  111. // connect stdin of each cmd to stdout pipe of previous cmd
  112. for i, cmd := range cmds {
  113. if i > 0 {
  114. prevCmd := cmds[i-1]
  115. cmd.Stdin, err = prevCmd.StdoutPipe()
  116. if err != nil {
  117. return "", 0, fmt.Errorf("cannot set stdout pipe for %s: %v", cmd.Path, err)
  118. }
  119. }
  120. }
  121. // start all cmds except the last
  122. for _, cmd := range cmds[:len(cmds)-1] {
  123. if err = cmd.Start(); err != nil {
  124. return "", 0, fmt.Errorf("starting %s failed with error: %v", cmd.Path, err)
  125. }
  126. }
  127. defer func() {
  128. // wait all cmds except the last to release their resources
  129. for _, cmd := range cmds[:len(cmds)-1] {
  130. cmd.Wait()
  131. }
  132. }()
  133. // wait on last cmd
  134. return runCommandWithOutput(cmds[len(cmds)-1])
  135. }
  136. func logDone(message string) {
  137. fmt.Printf("[PASSED]: %s\n", message)
  138. }
  139. func stripTrailingCharacters(target string) string {
  140. return strings.TrimSpace(target)
  141. }
  142. func unmarshalJSON(data []byte, result interface{}) error {
  143. err := json.Unmarshal(data, result)
  144. if err != nil {
  145. return err
  146. }
  147. return nil
  148. }
  149. func convertSliceOfStringsToMap(input []string) map[string]struct{} {
  150. output := make(map[string]struct{})
  151. for _, v := range input {
  152. output[v] = struct{}{}
  153. }
  154. return output
  155. }
  156. func waitForContainer(contID string, args ...string) error {
  157. args = append([]string{"run", "--name", contID}, args...)
  158. cmd := exec.Command(dockerBinary, args...)
  159. if _, err := runCommand(cmd); err != nil {
  160. return err
  161. }
  162. if err := waitRun(contID); err != nil {
  163. return err
  164. }
  165. return nil
  166. }
  167. func waitRun(contID string) error {
  168. return waitInspect(contID, "{{.State.Running}}", "true", 5)
  169. }
  170. func waitInspect(name, expr, expected string, timeout int) error {
  171. after := time.After(time.Duration(timeout) * time.Second)
  172. for {
  173. cmd := exec.Command(dockerBinary, "inspect", "-f", expr, name)
  174. out, _, err := runCommandWithOutput(cmd)
  175. if err != nil {
  176. return fmt.Errorf("error executing docker inspect: %v", err)
  177. }
  178. out = strings.TrimSpace(out)
  179. if out == expected {
  180. break
  181. }
  182. select {
  183. case <-after:
  184. return fmt.Errorf("condition \"%q == %q\" not true in time", out, expected)
  185. default:
  186. }
  187. time.Sleep(100 * time.Millisecond)
  188. }
  189. return nil
  190. }
  191. func compareDirectoryEntries(e1 []os.FileInfo, e2 []os.FileInfo) error {
  192. var (
  193. e1Entries = make(map[string]struct{})
  194. e2Entries = make(map[string]struct{})
  195. )
  196. for _, e := range e1 {
  197. e1Entries[e.Name()] = struct{}{}
  198. }
  199. for _, e := range e2 {
  200. e2Entries[e.Name()] = struct{}{}
  201. }
  202. if !reflect.DeepEqual(e1Entries, e2Entries) {
  203. return fmt.Errorf("entries differ")
  204. }
  205. return nil
  206. }
  207. func ListTar(f io.Reader) ([]string, error) {
  208. tr := tar.NewReader(f)
  209. var entries []string
  210. for {
  211. th, err := tr.Next()
  212. if err == io.EOF {
  213. // end of tar archive
  214. return entries, nil
  215. }
  216. if err != nil {
  217. return entries, err
  218. }
  219. entries = append(entries, th.Name)
  220. }
  221. }
  222. type FileServer struct {
  223. *httptest.Server
  224. }
  225. func fileServer(files map[string]string) (*FileServer, error) {
  226. var handler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
  227. if filePath, found := files[r.URL.Path]; found {
  228. http.ServeFile(w, r, filePath)
  229. } else {
  230. http.Error(w, http.StatusText(404), 404)
  231. }
  232. }
  233. for _, file := range files {
  234. if _, err := os.Stat(file); err != nil {
  235. return nil, err
  236. }
  237. }
  238. server := httptest.NewServer(handler)
  239. return &FileServer{
  240. Server: server,
  241. }, nil
  242. }
  243. func copyWithCP(source, target string) error {
  244. copyCmd := exec.Command("cp", "-rp", source, target)
  245. out, exitCode, err := runCommandWithOutput(copyCmd)
  246. if err != nil || exitCode != 0 {
  247. return fmt.Errorf("failed to copy: error: %q ,output: %q", err, out)
  248. }
  249. return nil
  250. }
  251. func makeRandomString(n int) string {
  252. // make a really long string
  253. letters := []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
  254. b := make([]byte, n)
  255. r := rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
  256. for i := range b {
  257. b[i] = letters[r.Intn(len(letters))]
  258. }
  259. return string(b)
  260. }
  261. // randomUnixTmpDirPath provides a temporary unix path with rand string appended.
  262. // does not create or checks if it exists.
  263. func randomUnixTmpDirPath(s string) string {
  264. return path.Join("/tmp", fmt.Sprintf("%s.%s", s, makeRandomString(10)))
  265. }
  266. // Reads chunkSize bytes from reader after every interval.
  267. // Returns total read bytes.
  268. func consumeWithSpeed(reader io.Reader, chunkSize int, interval time.Duration, stop chan bool) (n int, err error) {
  269. buffer := make([]byte, chunkSize)
  270. for {
  271. select {
  272. case <-stop:
  273. return
  274. default:
  275. var readBytes int
  276. readBytes, err = reader.Read(buffer)
  277. n += readBytes
  278. if err != nil {
  279. if err == io.EOF {
  280. err = nil
  281. }
  282. return
  283. }
  284. time.Sleep(interval)
  285. }
  286. }
  287. }
  288. // Parses 'procCgroupData', which is output of '/proc/<pid>/cgroup', and returns
  289. // a map which cgroup name as key and path as value.
  290. func parseCgroupPaths(procCgroupData string) map[string]string {
  291. cgroupPaths := map[string]string{}
  292. for _, line := range strings.Split(procCgroupData, "\n") {
  293. parts := strings.Split(line, ":")
  294. if len(parts) != 3 {
  295. continue
  296. }
  297. cgroupPaths[parts[1]] = parts[2]
  298. }
  299. return cgroupPaths
  300. }