utils.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "math/rand"
  8. "net/http"
  9. "net/http/httptest"
  10. "os"
  11. "os/exec"
  12. "reflect"
  13. "strings"
  14. "syscall"
  15. "time"
  16. "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
  17. )
  18. func getExitCode(err error) (int, error) {
  19. exitCode := 0
  20. if exiterr, ok := err.(*exec.ExitError); ok {
  21. if procExit := exiterr.Sys().(syscall.WaitStatus); ok {
  22. return procExit.ExitStatus(), nil
  23. }
  24. }
  25. return exitCode, fmt.Errorf("failed to get exit code")
  26. }
  27. func processExitCode(err error) (exitCode int) {
  28. if err != nil {
  29. var exiterr error
  30. if exitCode, exiterr = getExitCode(err); exiterr != nil {
  31. // TODO: Fix this so we check the error's text.
  32. // we've failed to retrieve exit code, so we set it to 127
  33. exitCode = 127
  34. }
  35. }
  36. return
  37. }
  38. func runCommandWithOutput(cmd *exec.Cmd) (output string, exitCode int, err error) {
  39. exitCode = 0
  40. out, err := cmd.CombinedOutput()
  41. exitCode = processExitCode(err)
  42. output = string(out)
  43. return
  44. }
  45. func runCommandWithStdoutStderr(cmd *exec.Cmd) (stdout string, stderr string, exitCode int, err error) {
  46. var (
  47. stderrBuffer, stdoutBuffer bytes.Buffer
  48. )
  49. exitCode = 0
  50. cmd.Stderr = &stderrBuffer
  51. cmd.Stdout = &stdoutBuffer
  52. err = cmd.Run()
  53. exitCode = processExitCode(err)
  54. stdout = stdoutBuffer.String()
  55. stderr = stderrBuffer.String()
  56. return
  57. }
  58. var ErrCmdTimeout = fmt.Errorf("command timed out")
  59. func runCommandWithOutputAndTimeout(cmd *exec.Cmd, timeout time.Duration) (output string, exitCode int, err error) {
  60. done := make(chan error)
  61. go func() {
  62. output, exitCode, err = runCommandWithOutput(cmd)
  63. if err != nil || exitCode != 0 {
  64. done <- fmt.Errorf("failed to run command: %s", err)
  65. return
  66. }
  67. done <- nil
  68. }()
  69. select {
  70. case <-time.After(timeout):
  71. killFailed := cmd.Process.Kill()
  72. if killFailed == nil {
  73. fmt.Printf("failed to kill (pid=%d): %v\n", cmd.Process.Pid, err)
  74. }
  75. err = ErrCmdTimeout
  76. case <-done:
  77. break
  78. }
  79. return
  80. }
  81. func runCommand(cmd *exec.Cmd) (exitCode int, err error) {
  82. exitCode = 0
  83. err = cmd.Run()
  84. exitCode = processExitCode(err)
  85. return
  86. }
  87. func logDone(message string) {
  88. fmt.Printf("[PASSED]: %s\n", message)
  89. }
  90. func stripTrailingCharacters(target string) string {
  91. return strings.TrimSpace(target)
  92. }
  93. func unmarshalJSON(data []byte, result interface{}) error {
  94. err := json.Unmarshal(data, result)
  95. if err != nil {
  96. return err
  97. }
  98. return nil
  99. }
  100. func convertSliceOfStringsToMap(input []string) map[string]struct{} {
  101. output := make(map[string]struct{})
  102. for _, v := range input {
  103. output[v] = struct{}{}
  104. }
  105. return output
  106. }
  107. func waitForContainer(contID string, args ...string) error {
  108. args = append([]string{"run", "--name", contID}, args...)
  109. cmd := exec.Command(dockerBinary, args...)
  110. if _, err := runCommand(cmd); err != nil {
  111. return err
  112. }
  113. if err := waitRun(contID); err != nil {
  114. return err
  115. }
  116. return nil
  117. }
  118. func waitRun(contID string) error {
  119. return waitInspect(contID, "{{.State.Running}}", "true", 5)
  120. }
  121. func waitInspect(name, expr, expected string, timeout int) error {
  122. after := time.After(time.Duration(timeout) * time.Second)
  123. for {
  124. cmd := exec.Command(dockerBinary, "inspect", "-f", expr, name)
  125. out, _, err := runCommandWithOutput(cmd)
  126. if err != nil {
  127. return fmt.Errorf("error executing docker inspect: %v", err)
  128. }
  129. out = strings.TrimSpace(out)
  130. if out == expected {
  131. break
  132. }
  133. select {
  134. case <-after:
  135. return fmt.Errorf("condition \"%q == %q\" not true in time", out, expected)
  136. default:
  137. }
  138. time.Sleep(100 * time.Millisecond)
  139. }
  140. return nil
  141. }
  142. func compareDirectoryEntries(e1 []os.FileInfo, e2 []os.FileInfo) error {
  143. var (
  144. e1Entries = make(map[string]struct{})
  145. e2Entries = make(map[string]struct{})
  146. )
  147. for _, e := range e1 {
  148. e1Entries[e.Name()] = struct{}{}
  149. }
  150. for _, e := range e2 {
  151. e2Entries[e.Name()] = struct{}{}
  152. }
  153. if !reflect.DeepEqual(e1Entries, e2Entries) {
  154. return fmt.Errorf("entries differ")
  155. }
  156. return nil
  157. }
  158. func ListTar(f io.Reader) ([]string, error) {
  159. tr := tar.NewReader(f)
  160. var entries []string
  161. for {
  162. th, err := tr.Next()
  163. if err == io.EOF {
  164. // end of tar archive
  165. return entries, nil
  166. }
  167. if err != nil {
  168. return entries, err
  169. }
  170. entries = append(entries, th.Name)
  171. }
  172. }
  173. type FileServer struct {
  174. *httptest.Server
  175. }
  176. func fileServer(files map[string]string) (*FileServer, error) {
  177. var handler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
  178. if filePath, found := files[r.URL.Path]; found {
  179. http.ServeFile(w, r, filePath)
  180. } else {
  181. http.Error(w, http.StatusText(404), 404)
  182. }
  183. }
  184. for _, file := range files {
  185. if _, err := os.Stat(file); err != nil {
  186. return nil, err
  187. }
  188. }
  189. server := httptest.NewServer(handler)
  190. return &FileServer{
  191. Server: server,
  192. }, nil
  193. }
  194. func copyWithCP(source, target string) error {
  195. copyCmd := exec.Command("cp", "-rp", source, target)
  196. out, exitCode, err := runCommandWithOutput(copyCmd)
  197. if err != nil || exitCode != 0 {
  198. return fmt.Errorf("failed to copy: error: %q ,output: %q", err, out)
  199. }
  200. return nil
  201. }
  202. func makeRandomString(n int) string {
  203. // make a really long string
  204. letters := []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
  205. b := make([]byte, n)
  206. for i := range b {
  207. b[i] = letters[rand.Intn(len(letters))]
  208. }
  209. return string(b)
  210. }
  211. // Reads chunkSize bytes from reader after every interval.
  212. // Returns total read bytes.
  213. func consumeWithSpeed(reader io.Reader, chunkSize int, interval time.Duration, stop chan bool) (n int, err error) {
  214. buffer := make([]byte, chunkSize)
  215. for {
  216. select {
  217. case <-stop:
  218. return
  219. default:
  220. var readBytes int
  221. readBytes, err = reader.Read(buffer)
  222. n += readBytes
  223. if err != nil {
  224. if err == io.EOF {
  225. err = nil
  226. }
  227. return
  228. }
  229. time.Sleep(interval)
  230. }
  231. }
  232. }