utils.go 7.5 KB

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