utils.go 7.9 KB

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