utils.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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 IsKilled(err error) bool {
  41. if exitErr, ok := err.(*exec.ExitError); ok {
  42. sys := exitErr.ProcessState.Sys()
  43. status, ok := sys.(syscall.WaitStatus)
  44. if !ok {
  45. return false
  46. }
  47. return status.Signaled() && status.Signal() == os.Kill
  48. }
  49. return false
  50. }
  51. func runCommandWithOutput(cmd *exec.Cmd) (output string, exitCode int, err error) {
  52. exitCode = 0
  53. out, err := cmd.CombinedOutput()
  54. exitCode = processExitCode(err)
  55. output = string(out)
  56. return
  57. }
  58. func runCommandWithStdoutStderr(cmd *exec.Cmd) (stdout string, stderr string, exitCode int, err error) {
  59. var (
  60. stderrBuffer, stdoutBuffer bytes.Buffer
  61. )
  62. exitCode = 0
  63. cmd.Stderr = &stderrBuffer
  64. cmd.Stdout = &stdoutBuffer
  65. err = cmd.Run()
  66. exitCode = processExitCode(err)
  67. stdout = stdoutBuffer.String()
  68. stderr = stderrBuffer.String()
  69. return
  70. }
  71. func runCommandWithOutputForDuration(cmd *exec.Cmd, duration time.Duration) (output string, exitCode int, timedOut bool, err error) {
  72. var outputBuffer bytes.Buffer
  73. if cmd.Stdout != nil {
  74. err = errors.New("cmd.Stdout already set")
  75. return
  76. }
  77. cmd.Stdout = &outputBuffer
  78. if cmd.Stderr != nil {
  79. err = errors.New("cmd.Stderr already set")
  80. return
  81. }
  82. cmd.Stderr = &outputBuffer
  83. done := make(chan error)
  84. go func() {
  85. exitErr := cmd.Run()
  86. exitCode = processExitCode(exitErr)
  87. done <- exitErr
  88. }()
  89. select {
  90. case <-time.After(duration):
  91. killErr := cmd.Process.Kill()
  92. if killErr != nil {
  93. fmt.Printf("failed to kill (pid=%d): %v\n", cmd.Process.Pid, killErr)
  94. }
  95. timedOut = true
  96. break
  97. case err = <-done:
  98. break
  99. }
  100. output = outputBuffer.String()
  101. return
  102. }
  103. var ErrCmdTimeout = fmt.Errorf("command timed out")
  104. func runCommandWithOutputAndTimeout(cmd *exec.Cmd, timeout time.Duration) (output string, exitCode int, err error) {
  105. var timedOut bool
  106. output, exitCode, timedOut, err = runCommandWithOutputForDuration(cmd, timeout)
  107. if timedOut {
  108. err = ErrCmdTimeout
  109. }
  110. return
  111. }
  112. func runCommand(cmd *exec.Cmd) (exitCode int, err error) {
  113. exitCode = 0
  114. err = cmd.Run()
  115. exitCode = processExitCode(err)
  116. return
  117. }
  118. func runCommandPipelineWithOutput(cmds ...*exec.Cmd) (output string, exitCode int, err error) {
  119. if len(cmds) < 2 {
  120. return "", 0, errors.New("pipeline does not have multiple cmds")
  121. }
  122. // connect stdin of each cmd to stdout pipe of previous cmd
  123. for i, cmd := range cmds {
  124. if i > 0 {
  125. prevCmd := cmds[i-1]
  126. cmd.Stdin, err = prevCmd.StdoutPipe()
  127. if err != nil {
  128. return "", 0, fmt.Errorf("cannot set stdout pipe for %s: %v", cmd.Path, err)
  129. }
  130. }
  131. }
  132. // start all cmds except the last
  133. for _, cmd := range cmds[:len(cmds)-1] {
  134. if err = cmd.Start(); err != nil {
  135. return "", 0, fmt.Errorf("starting %s failed with error: %v", cmd.Path, err)
  136. }
  137. }
  138. defer func() {
  139. // wait all cmds except the last to release their resources
  140. for _, cmd := range cmds[:len(cmds)-1] {
  141. cmd.Wait()
  142. }
  143. }()
  144. // wait on last cmd
  145. return runCommandWithOutput(cmds[len(cmds)-1])
  146. }
  147. func logDone(message string) {
  148. fmt.Printf("[PASSED]: %s\n", message)
  149. }
  150. func stripTrailingCharacters(target string) string {
  151. return strings.TrimSpace(target)
  152. }
  153. func unmarshalJSON(data []byte, result interface{}) error {
  154. err := json.Unmarshal(data, result)
  155. if err != nil {
  156. return err
  157. }
  158. return nil
  159. }
  160. func convertSliceOfStringsToMap(input []string) map[string]struct{} {
  161. output := make(map[string]struct{})
  162. for _, v := range input {
  163. output[v] = struct{}{}
  164. }
  165. return output
  166. }
  167. func waitForContainer(contID string, args ...string) error {
  168. args = append([]string{"run", "--name", contID}, args...)
  169. cmd := exec.Command(dockerBinary, args...)
  170. if _, err := runCommand(cmd); err != nil {
  171. return err
  172. }
  173. if err := waitRun(contID); err != nil {
  174. return err
  175. }
  176. return nil
  177. }
  178. func waitRun(contID string) error {
  179. return waitInspect(contID, "{{.State.Running}}", "true", 5)
  180. }
  181. func waitInspect(name, expr, expected string, timeout int) error {
  182. after := time.After(time.Duration(timeout) * time.Second)
  183. for {
  184. cmd := exec.Command(dockerBinary, "inspect", "-f", expr, name)
  185. out, _, err := runCommandWithOutput(cmd)
  186. if err != nil {
  187. return fmt.Errorf("error executing docker inspect: %v", err)
  188. }
  189. out = strings.TrimSpace(out)
  190. if out == expected {
  191. break
  192. }
  193. select {
  194. case <-after:
  195. return fmt.Errorf("condition \"%q == %q\" not true in time", out, expected)
  196. default:
  197. }
  198. time.Sleep(100 * time.Millisecond)
  199. }
  200. return nil
  201. }
  202. func compareDirectoryEntries(e1 []os.FileInfo, e2 []os.FileInfo) error {
  203. var (
  204. e1Entries = make(map[string]struct{})
  205. e2Entries = make(map[string]struct{})
  206. )
  207. for _, e := range e1 {
  208. e1Entries[e.Name()] = struct{}{}
  209. }
  210. for _, e := range e2 {
  211. e2Entries[e.Name()] = struct{}{}
  212. }
  213. if !reflect.DeepEqual(e1Entries, e2Entries) {
  214. return fmt.Errorf("entries differ")
  215. }
  216. return nil
  217. }
  218. func ListTar(f io.Reader) ([]string, error) {
  219. tr := tar.NewReader(f)
  220. var entries []string
  221. for {
  222. th, err := tr.Next()
  223. if err == io.EOF {
  224. // end of tar archive
  225. return entries, nil
  226. }
  227. if err != nil {
  228. return entries, err
  229. }
  230. entries = append(entries, th.Name)
  231. }
  232. }
  233. type FileServer struct {
  234. *httptest.Server
  235. }
  236. func fileServer(files map[string]string) (*FileServer, error) {
  237. var handler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
  238. if filePath, found := files[r.URL.Path]; found {
  239. http.ServeFile(w, r, filePath)
  240. } else {
  241. http.Error(w, http.StatusText(404), 404)
  242. }
  243. }
  244. for _, file := range files {
  245. if _, err := os.Stat(file); err != nil {
  246. return nil, err
  247. }
  248. }
  249. server := httptest.NewServer(handler)
  250. return &FileServer{
  251. Server: server,
  252. }, nil
  253. }
  254. func copyWithCP(source, target string) error {
  255. copyCmd := exec.Command("cp", "-rp", source, target)
  256. out, exitCode, err := runCommandWithOutput(copyCmd)
  257. if err != nil || exitCode != 0 {
  258. return fmt.Errorf("failed to copy: error: %q ,output: %q", err, out)
  259. }
  260. return nil
  261. }
  262. func makeRandomString(n int) string {
  263. // make a really long string
  264. letters := []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
  265. b := make([]byte, n)
  266. r := rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
  267. for i := range b {
  268. b[i] = letters[r.Intn(len(letters))]
  269. }
  270. return string(b)
  271. }
  272. // randomUnixTmpDirPath provides a temporary unix path with rand string appended.
  273. // does not create or checks if it exists.
  274. func randomUnixTmpDirPath(s string) string {
  275. return path.Join("/tmp", fmt.Sprintf("%s.%s", s, makeRandomString(10)))
  276. }
  277. // Reads chunkSize bytes from reader after every interval.
  278. // Returns total read bytes.
  279. func consumeWithSpeed(reader io.Reader, chunkSize int, interval time.Duration, stop chan bool) (n int, err error) {
  280. buffer := make([]byte, chunkSize)
  281. for {
  282. select {
  283. case <-stop:
  284. return
  285. default:
  286. var readBytes int
  287. readBytes, err = reader.Read(buffer)
  288. n += readBytes
  289. if err != nil {
  290. if err == io.EOF {
  291. err = nil
  292. }
  293. return
  294. }
  295. time.Sleep(interval)
  296. }
  297. }
  298. }
  299. // Parses 'procCgroupData', which is output of '/proc/<pid>/cgroup', and returns
  300. // a map which cgroup name as key and path as value.
  301. func parseCgroupPaths(procCgroupData string) map[string]string {
  302. cgroupPaths := map[string]string{}
  303. for _, line := range strings.Split(procCgroupData, "\n") {
  304. parts := strings.Split(line, ":")
  305. if len(parts) != 3 {
  306. continue
  307. }
  308. cgroupPaths[parts[1]] = parts[2]
  309. }
  310. return cgroupPaths
  311. }