utils.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "net/http/httptest"
  9. "os"
  10. "os/exec"
  11. "reflect"
  12. "strings"
  13. "syscall"
  14. "testing"
  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 errorOut(err error, t *testing.T, message string) {
  102. if err != nil {
  103. t.Fatal(message)
  104. }
  105. }
  106. func errorOutOnNonNilError(err error, t *testing.T, message string) {
  107. if err == nil {
  108. t.Fatalf(message)
  109. }
  110. }
  111. func nLines(s string) int {
  112. return strings.Count(s, "\n")
  113. }
  114. func unmarshalJSON(data []byte, result interface{}) error {
  115. err := json.Unmarshal(data, result)
  116. if err != nil {
  117. return err
  118. }
  119. return nil
  120. }
  121. func deepEqual(expected interface{}, result interface{}) bool {
  122. return reflect.DeepEqual(result, expected)
  123. }
  124. func convertSliceOfStringsToMap(input []string) map[string]struct{} {
  125. output := make(map[string]struct{})
  126. for _, v := range input {
  127. output[v] = struct{}{}
  128. }
  129. return output
  130. }
  131. func waitForContainer(contId string, args ...string) error {
  132. args = append([]string{"run", "--name", contId}, args...)
  133. cmd := exec.Command(dockerBinary, args...)
  134. if _, err := runCommand(cmd); err != nil {
  135. return err
  136. }
  137. if err := waitRun(contId); err != nil {
  138. return err
  139. }
  140. return nil
  141. }
  142. func waitRun(contId string) error {
  143. after := time.After(5 * time.Second)
  144. for {
  145. cmd := exec.Command(dockerBinary, "inspect", "-f", "{{.State.Running}}", contId)
  146. out, _, err := runCommandWithOutput(cmd)
  147. if err != nil {
  148. return fmt.Errorf("error executing docker inspect: %v", err)
  149. }
  150. if strings.Contains(out, "true") {
  151. break
  152. }
  153. select {
  154. case <-after:
  155. return fmt.Errorf("container did not come up in time")
  156. default:
  157. }
  158. time.Sleep(100 * time.Millisecond)
  159. }
  160. return nil
  161. }
  162. func compareDirectoryEntries(e1 []os.FileInfo, e2 []os.FileInfo) error {
  163. var (
  164. e1Entries = make(map[string]struct{})
  165. e2Entries = make(map[string]struct{})
  166. )
  167. for _, e := range e1 {
  168. e1Entries[e.Name()] = struct{}{}
  169. }
  170. for _, e := range e2 {
  171. e2Entries[e.Name()] = struct{}{}
  172. }
  173. if !reflect.DeepEqual(e1Entries, e2Entries) {
  174. return fmt.Errorf("entries differ")
  175. }
  176. return nil
  177. }
  178. func ListTar(f io.Reader) ([]string, error) {
  179. tr := tar.NewReader(f)
  180. var entries []string
  181. for {
  182. th, err := tr.Next()
  183. if err == io.EOF {
  184. // end of tar archive
  185. return entries, nil
  186. }
  187. if err != nil {
  188. return entries, err
  189. }
  190. entries = append(entries, th.Name)
  191. }
  192. }
  193. type FileServer struct {
  194. *httptest.Server
  195. }
  196. func fileServer(files map[string]string) (*FileServer, error) {
  197. var handler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
  198. if filePath, found := files[r.URL.Path]; found {
  199. http.ServeFile(w, r, filePath)
  200. } else {
  201. http.Error(w, http.StatusText(404), 404)
  202. }
  203. }
  204. for _, file := range files {
  205. if _, err := os.Stat(file); err != nil {
  206. return nil, err
  207. }
  208. }
  209. server := httptest.NewServer(handler)
  210. return &FileServer{
  211. Server: server,
  212. }, nil
  213. }
  214. func copyWithCP(source, target string) error {
  215. copyCmd := exec.Command("cp", "-rp", source, target)
  216. out, exitCode, err := runCommandWithOutput(copyCmd)
  217. if err != nil || exitCode != 0 {
  218. return fmt.Errorf("failed to copy: error: %q ,output: %q", err, out)
  219. }
  220. return nil
  221. }