utils.go 5.8 KB

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