utils.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. // Start the command in the main thread..
  97. err = cmd.Start()
  98. if err != nil {
  99. err = fmt.Errorf("Fail to start command %v : %v", cmd, err)
  100. }
  101. type exitInfo struct {
  102. exitErr error
  103. exitCode int
  104. }
  105. done := make(chan exitInfo, 1)
  106. go func() {
  107. // And wait for it to exit in the goroutine :)
  108. info := exitInfo{}
  109. info.exitErr = cmd.Wait()
  110. info.exitCode = ProcessExitCode(info.exitErr)
  111. done <- info
  112. }()
  113. select {
  114. case <-time.After(duration):
  115. killErr := cmd.Process.Kill()
  116. if killErr != nil {
  117. fmt.Printf("failed to kill (pid=%d): %v\n", cmd.Process.Pid, killErr)
  118. }
  119. timedOut = true
  120. case info := <-done:
  121. err = info.exitErr
  122. exitCode = info.exitCode
  123. }
  124. output = outputBuffer.String()
  125. return
  126. }
  127. var errCmdTimeout = fmt.Errorf("command timed out")
  128. // RunCommandWithOutputAndTimeout runs the specified command "timeboxed" by the specified duration.
  129. // It returns the output with the exitCode different from 0 and the error if something bad happened or
  130. // if the process timed out (and has been killed).
  131. func RunCommandWithOutputAndTimeout(cmd *exec.Cmd, timeout time.Duration) (output string, exitCode int, err error) {
  132. var timedOut bool
  133. output, exitCode, timedOut, err = RunCommandWithOutputForDuration(cmd, timeout)
  134. if timedOut {
  135. err = errCmdTimeout
  136. }
  137. return
  138. }
  139. // RunCommand runs the specified command and returns the exitCode different from 0
  140. // and the error if something bad happened.
  141. func RunCommand(cmd *exec.Cmd) (exitCode int, err error) {
  142. exitCode = 0
  143. err = cmd.Run()
  144. exitCode = ProcessExitCode(err)
  145. return
  146. }
  147. // RunCommandPipelineWithOutput runs the array of commands with the output
  148. // of each pipelined with the following (like cmd1 | cmd2 | cmd3 would do).
  149. // It returns the final output, the exitCode different from 0 and the error
  150. // if something bad happened.
  151. func RunCommandPipelineWithOutput(cmds ...*exec.Cmd) (output string, exitCode int, err error) {
  152. if len(cmds) < 2 {
  153. return "", 0, errors.New("pipeline does not have multiple cmds")
  154. }
  155. // connect stdin of each cmd to stdout pipe of previous cmd
  156. for i, cmd := range cmds {
  157. if i > 0 {
  158. prevCmd := cmds[i-1]
  159. cmd.Stdin, err = prevCmd.StdoutPipe()
  160. if err != nil {
  161. return "", 0, fmt.Errorf("cannot set stdout pipe for %s: %v", cmd.Path, err)
  162. }
  163. }
  164. }
  165. // start all cmds except the last
  166. for _, cmd := range cmds[:len(cmds)-1] {
  167. if err = cmd.Start(); err != nil {
  168. return "", 0, fmt.Errorf("starting %s failed with error: %v", cmd.Path, err)
  169. }
  170. }
  171. defer func() {
  172. // wait all cmds except the last to release their resources
  173. for _, cmd := range cmds[:len(cmds)-1] {
  174. cmd.Wait()
  175. }
  176. }()
  177. // wait on last cmd
  178. return RunCommandWithOutput(cmds[len(cmds)-1])
  179. }
  180. // UnmarshalJSON deserialize a JSON in the given interface.
  181. func UnmarshalJSON(data []byte, result interface{}) error {
  182. if err := json.Unmarshal(data, result); err != nil {
  183. return err
  184. }
  185. return nil
  186. }
  187. // ConvertSliceOfStringsToMap converts a slices of string in a map
  188. // with the strings as key and an empty string as values.
  189. func ConvertSliceOfStringsToMap(input []string) map[string]struct{} {
  190. output := make(map[string]struct{})
  191. for _, v := range input {
  192. output[v] = struct{}{}
  193. }
  194. return output
  195. }
  196. // CompareDirectoryEntries compares two sets of FileInfo (usually taken from a directory)
  197. // and returns an error if different.
  198. func CompareDirectoryEntries(e1 []os.FileInfo, e2 []os.FileInfo) error {
  199. var (
  200. e1Entries = make(map[string]struct{})
  201. e2Entries = make(map[string]struct{})
  202. )
  203. for _, e := range e1 {
  204. e1Entries[e.Name()] = struct{}{}
  205. }
  206. for _, e := range e2 {
  207. e2Entries[e.Name()] = struct{}{}
  208. }
  209. if !reflect.DeepEqual(e1Entries, e2Entries) {
  210. return fmt.Errorf("entries differ")
  211. }
  212. return nil
  213. }
  214. // ListTar lists the entries of a tar.
  215. func ListTar(f io.Reader) ([]string, error) {
  216. tr := tar.NewReader(f)
  217. var entries []string
  218. for {
  219. th, err := tr.Next()
  220. if err == io.EOF {
  221. // end of tar archive
  222. return entries, nil
  223. }
  224. if err != nil {
  225. return entries, err
  226. }
  227. entries = append(entries, th.Name)
  228. }
  229. }
  230. // RandomTmpDirPath provides a temporary path with rand string appended.
  231. // does not create or checks if it exists.
  232. func RandomTmpDirPath(s string, platform string) string {
  233. tmp := "/tmp"
  234. if platform == "windows" {
  235. tmp = os.Getenv("TEMP")
  236. }
  237. path := filepath.Join(tmp, fmt.Sprintf("%s.%s", s, stringutils.GenerateRandomAlphaOnlyString(10)))
  238. if platform == "windows" {
  239. return filepath.FromSlash(path) // Using \
  240. }
  241. return filepath.ToSlash(path) // Using /
  242. }
  243. // ConsumeWithSpeed reads chunkSize bytes from reader before sleeping
  244. // for interval duration. Returns total read bytes. Send true to the
  245. // stop channel to return before reading to EOF on the reader.
  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. var readBytes int
  250. readBytes, err = reader.Read(buffer)
  251. n += readBytes
  252. if err != nil {
  253. if err == io.EOF {
  254. err = nil
  255. }
  256. return
  257. }
  258. select {
  259. case <-stop:
  260. return
  261. case <-time.After(interval):
  262. }
  263. }
  264. }
  265. // ParseCgroupPaths arses 'procCgroupData', which is output of '/proc/<pid>/cgroup', and returns
  266. // a map which cgroup name as key and path as value.
  267. func ParseCgroupPaths(procCgroupData string) map[string]string {
  268. cgroupPaths := map[string]string{}
  269. for _, line := range strings.Split(procCgroupData, "\n") {
  270. parts := strings.Split(line, ":")
  271. if len(parts) != 3 {
  272. continue
  273. }
  274. cgroupPaths[parts[1]] = parts[2]
  275. }
  276. return cgroupPaths
  277. }
  278. // ChannelBuffer holds a chan of byte array that can be populate in a goroutine.
  279. type ChannelBuffer struct {
  280. C chan []byte
  281. }
  282. // Write implements Writer.
  283. func (c *ChannelBuffer) Write(b []byte) (int, error) {
  284. c.C <- b
  285. return len(b), nil
  286. }
  287. // Close closes the go channel.
  288. func (c *ChannelBuffer) Close() error {
  289. close(c.C)
  290. return nil
  291. }
  292. // ReadTimeout reads the content of the channel in the specified byte array with
  293. // the specified duration as timeout.
  294. func (c *ChannelBuffer) ReadTimeout(p []byte, n time.Duration) (int, error) {
  295. select {
  296. case b := <-c.C:
  297. return copy(p[0:], b), nil
  298. case <-time.After(n):
  299. return -1, fmt.Errorf("timeout reading from channel")
  300. }
  301. }
  302. // RunAtDifferentDate runs the specifed function with the given time.
  303. // It changes the date of the system, which can led to weird behaviors.
  304. func RunAtDifferentDate(date time.Time, block func()) {
  305. // Layout for date. MMDDhhmmYYYY
  306. const timeLayout = "010203042006"
  307. // Ensure we bring time back to now
  308. now := time.Now().Format(timeLayout)
  309. dateReset := exec.Command("date", now)
  310. defer RunCommand(dateReset)
  311. dateChange := exec.Command("date", date.Format(timeLayout))
  312. RunCommand(dateChange)
  313. block()
  314. return
  315. }