utils.go 5.6 KB

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