utils.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "math/rand"
  9. "net/http"
  10. "net/http/httptest"
  11. "os"
  12. "os/exec"
  13. "path"
  14. "reflect"
  15. "strings"
  16. "syscall"
  17. "time"
  18. "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
  19. )
  20. func getExitCode(err error) (int, error) {
  21. exitCode := 0
  22. if exiterr, ok := err.(*exec.ExitError); ok {
  23. if procExit := exiterr.Sys().(syscall.WaitStatus); ok {
  24. return procExit.ExitStatus(), nil
  25. }
  26. }
  27. return exitCode, fmt.Errorf("failed to get exit code")
  28. }
  29. func processExitCode(err error) (exitCode int) {
  30. if err != nil {
  31. var exiterr error
  32. if exitCode, exiterr = getExitCode(err); exiterr != nil {
  33. // TODO: Fix this so we check the error's text.
  34. // we've failed to retrieve exit code, so we set it to 127
  35. exitCode = 127
  36. }
  37. }
  38. return
  39. }
  40. func runCommandWithOutput(cmd *exec.Cmd) (output string, exitCode int, err error) {
  41. exitCode = 0
  42. out, err := cmd.CombinedOutput()
  43. exitCode = processExitCode(err)
  44. output = string(out)
  45. return
  46. }
  47. func runCommandWithStdoutStderr(cmd *exec.Cmd) (stdout string, stderr string, exitCode int, err error) {
  48. var (
  49. stderrBuffer, stdoutBuffer bytes.Buffer
  50. )
  51. exitCode = 0
  52. cmd.Stderr = &stderrBuffer
  53. cmd.Stdout = &stdoutBuffer
  54. err = cmd.Run()
  55. exitCode = processExitCode(err)
  56. stdout = stdoutBuffer.String()
  57. stderr = stderrBuffer.String()
  58. return
  59. }
  60. var ErrCmdTimeout = fmt.Errorf("command timed out")
  61. func runCommandWithOutputAndTimeout(cmd *exec.Cmd, timeout time.Duration) (output string, exitCode int, err error) {
  62. done := make(chan error)
  63. go func() {
  64. output, exitCode, err = runCommandWithOutput(cmd)
  65. if err != nil || exitCode != 0 {
  66. done <- fmt.Errorf("failed to run command: %s", err)
  67. return
  68. }
  69. done <- nil
  70. }()
  71. select {
  72. case <-time.After(timeout):
  73. killFailed := cmd.Process.Kill()
  74. if killFailed == nil {
  75. fmt.Printf("failed to kill (pid=%d): %v\n", cmd.Process.Pid, err)
  76. }
  77. err = ErrCmdTimeout
  78. case <-done:
  79. break
  80. }
  81. return
  82. }
  83. func runCommand(cmd *exec.Cmd) (exitCode int, err error) {
  84. exitCode = 0
  85. err = cmd.Run()
  86. exitCode = processExitCode(err)
  87. return
  88. }
  89. func runCommandPipelineWithOutput(cmds ...*exec.Cmd) (output string, exitCode int, err error) {
  90. if len(cmds) < 2 {
  91. return "", 0, errors.New("pipeline does not have multiple cmds")
  92. }
  93. // connect stdin of each cmd to stdout pipe of previous cmd
  94. for i, cmd := range cmds {
  95. if i > 0 {
  96. prevCmd := cmds[i-1]
  97. cmd.Stdin, err = prevCmd.StdoutPipe()
  98. if err != nil {
  99. return "", 0, fmt.Errorf("cannot set stdout pipe for %s: %v", cmd.Path, err)
  100. }
  101. }
  102. }
  103. // start all cmds except the last
  104. for _, cmd := range cmds[:len(cmds)-1] {
  105. if err = cmd.Start(); err != nil {
  106. return "", 0, fmt.Errorf("starting %s failed with error: %v", cmd.Path, err)
  107. }
  108. }
  109. defer func() {
  110. // wait all cmds except the last to release their resources
  111. for _, cmd := range cmds[:len(cmds)-1] {
  112. cmd.Wait()
  113. }
  114. }()
  115. // wait on last cmd
  116. return runCommandWithOutput(cmds[len(cmds)-1])
  117. }
  118. func logDone(message string) {
  119. fmt.Printf("[PASSED]: %s\n", message)
  120. }
  121. func stripTrailingCharacters(target string) string {
  122. return strings.TrimSpace(target)
  123. }
  124. func unmarshalJSON(data []byte, result interface{}) error {
  125. err := json.Unmarshal(data, result)
  126. if err != nil {
  127. return err
  128. }
  129. return nil
  130. }
  131. func convertSliceOfStringsToMap(input []string) map[string]struct{} {
  132. output := make(map[string]struct{})
  133. for _, v := range input {
  134. output[v] = struct{}{}
  135. }
  136. return output
  137. }
  138. func waitForContainer(contID string, args ...string) error {
  139. args = append([]string{"run", "--name", contID}, args...)
  140. cmd := exec.Command(dockerBinary, args...)
  141. if _, err := runCommand(cmd); err != nil {
  142. return err
  143. }
  144. if err := waitRun(contID); err != nil {
  145. return err
  146. }
  147. return nil
  148. }
  149. func waitRun(contID string) error {
  150. return waitInspect(contID, "{{.State.Running}}", "true", 5)
  151. }
  152. func waitInspect(name, expr, expected string, timeout int) error {
  153. after := time.After(time.Duration(timeout) * time.Second)
  154. for {
  155. cmd := exec.Command(dockerBinary, "inspect", "-f", expr, name)
  156. out, _, err := runCommandWithOutput(cmd)
  157. if err != nil {
  158. return fmt.Errorf("error executing docker inspect: %v", err)
  159. }
  160. out = strings.TrimSpace(out)
  161. if out == expected {
  162. break
  163. }
  164. select {
  165. case <-after:
  166. return fmt.Errorf("condition \"%q == %q\" not true in time", out, expected)
  167. default:
  168. }
  169. time.Sleep(100 * time.Millisecond)
  170. }
  171. return nil
  172. }
  173. func compareDirectoryEntries(e1 []os.FileInfo, e2 []os.FileInfo) error {
  174. var (
  175. e1Entries = make(map[string]struct{})
  176. e2Entries = make(map[string]struct{})
  177. )
  178. for _, e := range e1 {
  179. e1Entries[e.Name()] = struct{}{}
  180. }
  181. for _, e := range e2 {
  182. e2Entries[e.Name()] = struct{}{}
  183. }
  184. if !reflect.DeepEqual(e1Entries, e2Entries) {
  185. return fmt.Errorf("entries differ")
  186. }
  187. return nil
  188. }
  189. func ListTar(f io.Reader) ([]string, error) {
  190. tr := tar.NewReader(f)
  191. var entries []string
  192. for {
  193. th, err := tr.Next()
  194. if err == io.EOF {
  195. // end of tar archive
  196. return entries, nil
  197. }
  198. if err != nil {
  199. return entries, err
  200. }
  201. entries = append(entries, th.Name)
  202. }
  203. }
  204. type FileServer struct {
  205. *httptest.Server
  206. }
  207. func fileServer(files map[string]string) (*FileServer, error) {
  208. var handler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
  209. if filePath, found := files[r.URL.Path]; found {
  210. http.ServeFile(w, r, filePath)
  211. } else {
  212. http.Error(w, http.StatusText(404), 404)
  213. }
  214. }
  215. for _, file := range files {
  216. if _, err := os.Stat(file); err != nil {
  217. return nil, err
  218. }
  219. }
  220. server := httptest.NewServer(handler)
  221. return &FileServer{
  222. Server: server,
  223. }, nil
  224. }
  225. func copyWithCP(source, target string) error {
  226. copyCmd := exec.Command("cp", "-rp", source, target)
  227. out, exitCode, err := runCommandWithOutput(copyCmd)
  228. if err != nil || exitCode != 0 {
  229. return fmt.Errorf("failed to copy: error: %q ,output: %q", err, out)
  230. }
  231. return nil
  232. }
  233. func makeRandomString(n int) string {
  234. // make a really long string
  235. letters := []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
  236. b := make([]byte, n)
  237. r := rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
  238. for i := range b {
  239. b[i] = letters[r.Intn(len(letters))]
  240. }
  241. return string(b)
  242. }
  243. // randomUnixTmpDirPath provides a temporary unix path with rand string appended.
  244. // does not create or checks if it exists.
  245. func randomUnixTmpDirPath(s string) string {
  246. return path.Join("/tmp", fmt.Sprintf("%s.%s", s, makeRandomString(10)))
  247. }
  248. // Reads chunkSize bytes from reader after every interval.
  249. // Returns total read bytes.
  250. func consumeWithSpeed(reader io.Reader, chunkSize int, interval time.Duration, stop chan bool) (n int, err error) {
  251. buffer := make([]byte, chunkSize)
  252. for {
  253. select {
  254. case <-stop:
  255. return
  256. default:
  257. var readBytes int
  258. readBytes, err = reader.Read(buffer)
  259. n += readBytes
  260. if err != nil {
  261. if err == io.EOF {
  262. err = nil
  263. }
  264. return
  265. }
  266. time.Sleep(interval)
  267. }
  268. }
  269. }