utils.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. package main
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  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/pkg/stringutils"
  19. )
  20. func getExitCode(err error) (int, error) {
  21. exitCode := 0
  22. if exiterr, ok := err.(*exec.ExitError); ok {
  23. if procExit, ok := 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. if err := json.Unmarshal(data, result); err != nil {
  151. return err
  152. }
  153. return nil
  154. }
  155. func convertSliceOfStringsToMap(input []string) map[string]struct{} {
  156. output := make(map[string]struct{})
  157. for _, v := range input {
  158. output[v] = struct{}{}
  159. }
  160. return output
  161. }
  162. func waitForContainer(contID string, args ...string) error {
  163. args = append([]string{"run", "--name", contID}, args...)
  164. cmd := exec.Command(dockerBinary, args...)
  165. if _, err := runCommand(cmd); err != nil {
  166. return err
  167. }
  168. if err := waitRun(contID); err != nil {
  169. return err
  170. }
  171. return nil
  172. }
  173. func waitRun(contID string) error {
  174. return waitInspect(contID, "{{.State.Running}}", "true", 5)
  175. }
  176. func waitInspect(name, expr, expected string, timeout int) error {
  177. after := time.After(time.Duration(timeout) * time.Second)
  178. for {
  179. cmd := exec.Command(dockerBinary, "inspect", "-f", expr, name)
  180. out, _, err := runCommandWithOutput(cmd)
  181. if err != nil {
  182. if !strings.Contains(out, "No such") {
  183. return fmt.Errorf("error executing docker inspect: %v\n%s", err, out)
  184. }
  185. select {
  186. case <-after:
  187. return err
  188. default:
  189. time.Sleep(10 * time.Millisecond)
  190. continue
  191. }
  192. }
  193. out = strings.TrimSpace(out)
  194. if out == expected {
  195. break
  196. }
  197. select {
  198. case <-after:
  199. return fmt.Errorf("condition \"%q == %q\" not true in time", out, expected)
  200. default:
  201. }
  202. time.Sleep(100 * time.Millisecond)
  203. }
  204. return nil
  205. }
  206. func compareDirectoryEntries(e1 []os.FileInfo, e2 []os.FileInfo) error {
  207. var (
  208. e1Entries = make(map[string]struct{})
  209. e2Entries = make(map[string]struct{})
  210. )
  211. for _, e := range e1 {
  212. e1Entries[e.Name()] = struct{}{}
  213. }
  214. for _, e := range e2 {
  215. e2Entries[e.Name()] = struct{}{}
  216. }
  217. if !reflect.DeepEqual(e1Entries, e2Entries) {
  218. return fmt.Errorf("entries differ")
  219. }
  220. return nil
  221. }
  222. func ListTar(f io.Reader) ([]string, error) {
  223. tr := tar.NewReader(f)
  224. var entries []string
  225. for {
  226. th, err := tr.Next()
  227. if err == io.EOF {
  228. // end of tar archive
  229. return entries, nil
  230. }
  231. if err != nil {
  232. return entries, err
  233. }
  234. entries = append(entries, th.Name)
  235. }
  236. }
  237. type FileServer struct {
  238. *httptest.Server
  239. }
  240. func fileServer(files map[string]string) (*FileServer, error) {
  241. var handler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
  242. if filePath, found := files[r.URL.Path]; found {
  243. http.ServeFile(w, r, filePath)
  244. } else {
  245. http.Error(w, http.StatusText(404), 404)
  246. }
  247. }
  248. for _, file := range files {
  249. if _, err := os.Stat(file); err != nil {
  250. return nil, err
  251. }
  252. }
  253. server := httptest.NewServer(handler)
  254. return &FileServer{
  255. Server: server,
  256. }, nil
  257. }
  258. // randomUnixTmpDirPath provides a temporary unix path with rand string appended.
  259. // does not create or checks if it exists.
  260. func randomUnixTmpDirPath(s string) string {
  261. return path.Join("/tmp", fmt.Sprintf("%s.%s", s, stringutils.GenerateRandomAlphaOnlyString(10)))
  262. }
  263. // Reads chunkSize bytes from reader after every interval.
  264. // Returns total read bytes.
  265. func consumeWithSpeed(reader io.Reader, chunkSize int, interval time.Duration, stop chan bool) (n int, err error) {
  266. buffer := make([]byte, chunkSize)
  267. for {
  268. select {
  269. case <-stop:
  270. return
  271. default:
  272. var readBytes int
  273. readBytes, err = reader.Read(buffer)
  274. n += readBytes
  275. if err != nil {
  276. if err == io.EOF {
  277. err = nil
  278. }
  279. return
  280. }
  281. time.Sleep(interval)
  282. }
  283. }
  284. }
  285. // Parses 'procCgroupData', which is output of '/proc/<pid>/cgroup', and returns
  286. // a map which cgroup name as key and path as value.
  287. func parseCgroupPaths(procCgroupData string) map[string]string {
  288. cgroupPaths := map[string]string{}
  289. for _, line := range strings.Split(procCgroupData, "\n") {
  290. parts := strings.Split(line, ":")
  291. if len(parts) != 3 {
  292. continue
  293. }
  294. cgroupPaths[parts[1]] = parts[2]
  295. }
  296. return cgroupPaths
  297. }
  298. type channelBuffer struct {
  299. c chan []byte
  300. }
  301. func (c *channelBuffer) Write(b []byte) (int, error) {
  302. c.c <- b
  303. return len(b), nil
  304. }
  305. func (c *channelBuffer) Close() error {
  306. close(c.c)
  307. return nil
  308. }
  309. func (c *channelBuffer) ReadTimeout(p []byte, n time.Duration) (int, error) {
  310. select {
  311. case b := <-c.c:
  312. return copy(p[0:], b), nil
  313. case <-time.After(n):
  314. return -1, fmt.Errorf("timeout reading from channel")
  315. }
  316. }