utils.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. after := time.After(5 * time.Second)
  120. for {
  121. cmd := exec.Command(dockerBinary, "inspect", "-f", "{{.State.Running}}", contID)
  122. out, _, err := runCommandWithOutput(cmd)
  123. if err != nil {
  124. return fmt.Errorf("error executing docker inspect: %v", err)
  125. }
  126. if strings.Contains(out, "true") {
  127. break
  128. }
  129. select {
  130. case <-after:
  131. return fmt.Errorf("container did not come up in time")
  132. default:
  133. }
  134. time.Sleep(100 * time.Millisecond)
  135. }
  136. return nil
  137. }
  138. func compareDirectoryEntries(e1 []os.FileInfo, e2 []os.FileInfo) error {
  139. var (
  140. e1Entries = make(map[string]struct{})
  141. e2Entries = make(map[string]struct{})
  142. )
  143. for _, e := range e1 {
  144. e1Entries[e.Name()] = struct{}{}
  145. }
  146. for _, e := range e2 {
  147. e2Entries[e.Name()] = struct{}{}
  148. }
  149. if !reflect.DeepEqual(e1Entries, e2Entries) {
  150. return fmt.Errorf("entries differ")
  151. }
  152. return nil
  153. }
  154. func ListTar(f io.Reader) ([]string, error) {
  155. tr := tar.NewReader(f)
  156. var entries []string
  157. for {
  158. th, err := tr.Next()
  159. if err == io.EOF {
  160. // end of tar archive
  161. return entries, nil
  162. }
  163. if err != nil {
  164. return entries, err
  165. }
  166. entries = append(entries, th.Name)
  167. }
  168. }
  169. type FileServer struct {
  170. *httptest.Server
  171. }
  172. func fileServer(files map[string]string) (*FileServer, error) {
  173. var handler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
  174. if filePath, found := files[r.URL.Path]; found {
  175. http.ServeFile(w, r, filePath)
  176. } else {
  177. http.Error(w, http.StatusText(404), 404)
  178. }
  179. }
  180. for _, file := range files {
  181. if _, err := os.Stat(file); err != nil {
  182. return nil, err
  183. }
  184. }
  185. server := httptest.NewServer(handler)
  186. return &FileServer{
  187. Server: server,
  188. }, nil
  189. }
  190. func copyWithCP(source, target string) error {
  191. copyCmd := exec.Command("cp", "-rp", source, target)
  192. out, exitCode, err := runCommandWithOutput(copyCmd)
  193. if err != nil || exitCode != 0 {
  194. return fmt.Errorf("failed to copy: error: %q ,output: %q", err, out)
  195. }
  196. return nil
  197. }
  198. func makeRandomString(n int) string {
  199. // make a really long string
  200. letters := []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
  201. b := make([]byte, n)
  202. for i := range b {
  203. b[i] = letters[rand.Intn(len(letters))]
  204. }
  205. return string(b)
  206. }
  207. // Reads chunkSize bytes from reader after every interval.
  208. // Returns total read bytes.
  209. func consumeWithSpeed(reader io.Reader, chunkSize int, interval time.Duration, stop chan bool) (n int, err error) {
  210. buffer := make([]byte, chunkSize)
  211. for {
  212. select {
  213. case <-stop:
  214. return
  215. default:
  216. var readBytes int
  217. readBytes, err = reader.Read(buffer)
  218. n += readBytes
  219. if err != nil {
  220. if err == io.EOF {
  221. err = nil
  222. }
  223. return
  224. }
  225. time.Sleep(interval)
  226. }
  227. }
  228. }