utils.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. package integration
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "reflect"
  13. "strings"
  14. "syscall"
  15. "time"
  16. "github.com/docker/docker/pkg/stringutils"
  17. )
  18. // GetExitCode returns the ExitStatus of the specified error if its type is
  19. // exec.ExitError, returns 0 and an error otherwise.
  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. // ProcessExitCode process the specified error and returns the exit status code
  30. // if the error was of type exec.ExitError, returns nothing otherwise.
  31. func ProcessExitCode(err error) (exitCode int) {
  32. if err != nil {
  33. var exiterr error
  34. if exitCode, exiterr = GetExitCode(err); exiterr != nil {
  35. // TODO: Fix this so we check the error's text.
  36. // we've failed to retrieve exit code, so we set it to 127
  37. exitCode = 127
  38. }
  39. }
  40. return
  41. }
  42. // IsKilled process the specified error and returns whether the process was killed or not.
  43. func IsKilled(err error) bool {
  44. if exitErr, ok := err.(*exec.ExitError); ok {
  45. status, ok := exitErr.Sys().(syscall.WaitStatus)
  46. if !ok {
  47. return false
  48. }
  49. // status.ExitStatus() is required on Windows because it does not
  50. // implement Signal() nor Signaled(). Just check it had a bad exit
  51. // status could mean it was killed (and in tests we do kill)
  52. return (status.Signaled() && status.Signal() == os.Kill) || status.ExitStatus() != 0
  53. }
  54. return false
  55. }
  56. // RunCommandWithOutput runs the specified command and returns the combined output (stdout/stderr)
  57. // with the exitCode different from 0 and the error if something bad happened
  58. func RunCommandWithOutput(cmd *exec.Cmd) (output string, exitCode int, err error) {
  59. exitCode = 0
  60. out, err := cmd.CombinedOutput()
  61. exitCode = ProcessExitCode(err)
  62. output = string(out)
  63. return
  64. }
  65. // RunCommandWithStdoutStderr runs the specified command and returns stdout and stderr separately
  66. // with the exitCode different from 0 and the error if something bad happened
  67. func RunCommandWithStdoutStderr(cmd *exec.Cmd) (stdout string, stderr string, exitCode int, err error) {
  68. var (
  69. stderrBuffer, stdoutBuffer bytes.Buffer
  70. )
  71. exitCode = 0
  72. cmd.Stderr = &stderrBuffer
  73. cmd.Stdout = &stdoutBuffer
  74. err = cmd.Run()
  75. exitCode = ProcessExitCode(err)
  76. stdout = stdoutBuffer.String()
  77. stderr = stderrBuffer.String()
  78. return
  79. }
  80. // RunCommandWithOutputForDuration runs the specified command "timeboxed" by the specified duration.
  81. // If the process is still running when the timebox is finished, the process will be killed and .
  82. // It will returns the output with the exitCode different from 0 and the error if something bad happened
  83. // and a boolean whether it has been killed or not.
  84. func RunCommandWithOutputForDuration(cmd *exec.Cmd, duration time.Duration) (output string, exitCode int, timedOut bool, err error) {
  85. var outputBuffer bytes.Buffer
  86. if cmd.Stdout != nil {
  87. err = errors.New("cmd.Stdout already set")
  88. return
  89. }
  90. cmd.Stdout = &outputBuffer
  91. if cmd.Stderr != nil {
  92. err = errors.New("cmd.Stderr already set")
  93. return
  94. }
  95. cmd.Stderr = &outputBuffer
  96. done := make(chan error)
  97. // Start the command in the main thread..
  98. err = cmd.Start()
  99. if err != nil {
  100. err = fmt.Errorf("Fail to start command %v : %v", cmd, err)
  101. }
  102. go func() {
  103. // And wait for it to exit in the goroutine :)
  104. exitErr := cmd.Wait()
  105. exitCode = ProcessExitCode(exitErr)
  106. done <- exitErr
  107. }()
  108. select {
  109. case <-time.After(duration):
  110. killErr := cmd.Process.Kill()
  111. if killErr != nil {
  112. fmt.Printf("failed to kill (pid=%d): %v\n", cmd.Process.Pid, killErr)
  113. }
  114. timedOut = true
  115. break
  116. case err = <-done:
  117. break
  118. }
  119. output = outputBuffer.String()
  120. return
  121. }
  122. var errCmdTimeout = fmt.Errorf("command timed out")
  123. // RunCommandWithOutputAndTimeout runs the specified command "timeboxed" by the specified duration.
  124. // It returns the output with the exitCode different from 0 and the error if something bad happened or
  125. // if the process timed out (and has been killed).
  126. func RunCommandWithOutputAndTimeout(cmd *exec.Cmd, timeout time.Duration) (output string, exitCode int, err error) {
  127. var timedOut bool
  128. output, exitCode, timedOut, err = RunCommandWithOutputForDuration(cmd, timeout)
  129. if timedOut {
  130. err = errCmdTimeout
  131. }
  132. return
  133. }
  134. // RunCommand runs the specified command and returns the exitCode different from 0
  135. // and the error if something bad happened.
  136. func RunCommand(cmd *exec.Cmd) (exitCode int, err error) {
  137. exitCode = 0
  138. err = cmd.Run()
  139. exitCode = ProcessExitCode(err)
  140. return
  141. }
  142. // RunCommandPipelineWithOutput runs the array of commands with the output
  143. // of each pipelined with the following (like cmd1 | cmd2 | cmd3 would do).
  144. // It returns the final output, the exitCode different from 0 and the error
  145. // if something bad happened.
  146. func RunCommandPipelineWithOutput(cmds ...*exec.Cmd) (output string, exitCode int, err error) {
  147. if len(cmds) < 2 {
  148. return "", 0, errors.New("pipeline does not have multiple cmds")
  149. }
  150. // connect stdin of each cmd to stdout pipe of previous cmd
  151. for i, cmd := range cmds {
  152. if i > 0 {
  153. prevCmd := cmds[i-1]
  154. cmd.Stdin, err = prevCmd.StdoutPipe()
  155. if err != nil {
  156. return "", 0, fmt.Errorf("cannot set stdout pipe for %s: %v", cmd.Path, err)
  157. }
  158. }
  159. }
  160. // start all cmds except the last
  161. for _, cmd := range cmds[:len(cmds)-1] {
  162. if err = cmd.Start(); err != nil {
  163. return "", 0, fmt.Errorf("starting %s failed with error: %v", cmd.Path, err)
  164. }
  165. }
  166. defer func() {
  167. // wait all cmds except the last to release their resources
  168. for _, cmd := range cmds[:len(cmds)-1] {
  169. cmd.Wait()
  170. }
  171. }()
  172. // wait on last cmd
  173. return RunCommandWithOutput(cmds[len(cmds)-1])
  174. }
  175. // UnmarshalJSON deserialize a JSON in the given interface.
  176. func UnmarshalJSON(data []byte, result interface{}) error {
  177. if err := json.Unmarshal(data, result); err != nil {
  178. return err
  179. }
  180. return nil
  181. }
  182. // ConvertSliceOfStringsToMap converts a slices of string in a map
  183. // with the strings as key and an empty string as values.
  184. func ConvertSliceOfStringsToMap(input []string) map[string]struct{} {
  185. output := make(map[string]struct{})
  186. for _, v := range input {
  187. output[v] = struct{}{}
  188. }
  189. return output
  190. }
  191. // CompareDirectoryEntries compares two sets of FileInfo (usually taken from a directory)
  192. // and returns an error if different.
  193. func CompareDirectoryEntries(e1 []os.FileInfo, e2 []os.FileInfo) error {
  194. var (
  195. e1Entries = make(map[string]struct{})
  196. e2Entries = make(map[string]struct{})
  197. )
  198. for _, e := range e1 {
  199. e1Entries[e.Name()] = struct{}{}
  200. }
  201. for _, e := range e2 {
  202. e2Entries[e.Name()] = struct{}{}
  203. }
  204. if !reflect.DeepEqual(e1Entries, e2Entries) {
  205. return fmt.Errorf("entries differ")
  206. }
  207. return nil
  208. }
  209. // ListTar lists the entries of a tar.
  210. func ListTar(f io.Reader) ([]string, error) {
  211. tr := tar.NewReader(f)
  212. var entries []string
  213. for {
  214. th, err := tr.Next()
  215. if err == io.EOF {
  216. // end of tar archive
  217. return entries, nil
  218. }
  219. if err != nil {
  220. return entries, err
  221. }
  222. entries = append(entries, th.Name)
  223. }
  224. }
  225. // RandomTmpDirPath provides a temporary path with rand string appended.
  226. // does not create or checks if it exists.
  227. func RandomTmpDirPath(s string, platform string) string {
  228. tmp := "/tmp"
  229. if platform == "windows" {
  230. tmp = os.Getenv("TEMP")
  231. }
  232. path := filepath.Join(tmp, fmt.Sprintf("%s.%s", s, stringutils.GenerateRandomAlphaOnlyString(10)))
  233. if platform == "windows" {
  234. return filepath.FromSlash(path) // Using \
  235. }
  236. return filepath.ToSlash(path) // Using /
  237. }
  238. // ConsumeWithSpeed reads chunkSize bytes from reader after every interval.
  239. // Returns total read bytes.
  240. func ConsumeWithSpeed(reader io.Reader, chunkSize int, interval time.Duration, stop chan bool) (n int, err error) {
  241. buffer := make([]byte, chunkSize)
  242. for {
  243. select {
  244. case <-stop:
  245. return
  246. default:
  247. var readBytes int
  248. readBytes, err = reader.Read(buffer)
  249. n += readBytes
  250. if err != nil {
  251. if err == io.EOF {
  252. err = nil
  253. }
  254. return
  255. }
  256. time.Sleep(interval)
  257. }
  258. }
  259. }
  260. // ParseCgroupPaths arses 'procCgroupData', which is output of '/proc/<pid>/cgroup', and returns
  261. // a map which cgroup name as key and path as value.
  262. func ParseCgroupPaths(procCgroupData string) map[string]string {
  263. cgroupPaths := map[string]string{}
  264. for _, line := range strings.Split(procCgroupData, "\n") {
  265. parts := strings.Split(line, ":")
  266. if len(parts) != 3 {
  267. continue
  268. }
  269. cgroupPaths[parts[1]] = parts[2]
  270. }
  271. return cgroupPaths
  272. }
  273. // ChannelBuffer holds a chan of byte array that can be populate in a goroutine.
  274. type ChannelBuffer struct {
  275. C chan []byte
  276. }
  277. // Write implements Writer.
  278. func (c *ChannelBuffer) Write(b []byte) (int, error) {
  279. c.C <- b
  280. return len(b), nil
  281. }
  282. // Close closes the go channel.
  283. func (c *ChannelBuffer) Close() error {
  284. close(c.C)
  285. return nil
  286. }
  287. // ReadTimeout reads the content of the channel in the specified byte array with
  288. // the specified duration as timeout.
  289. func (c *ChannelBuffer) ReadTimeout(p []byte, n time.Duration) (int, error) {
  290. select {
  291. case b := <-c.C:
  292. return copy(p[0:], b), nil
  293. case <-time.After(n):
  294. return -1, fmt.Errorf("timeout reading from channel")
  295. }
  296. }
  297. // RunAtDifferentDate runs the specifed function with the given time.
  298. // It changes the date of the system, which can led to weird behaviors.
  299. func RunAtDifferentDate(date time.Time, block func()) {
  300. // Layout for date. MMDDhhmmYYYY
  301. const timeLayout = "010203042006"
  302. // Ensure we bring time back to now
  303. now := time.Now().Format(timeLayout)
  304. dateReset := exec.Command("date", now)
  305. defer RunCommand(dateReset)
  306. dateChange := exec.Command("date", date.Format(timeLayout))
  307. RunCommand(dateChange)
  308. block()
  309. return
  310. }