utils.go 5.5 KB

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