utils.go 9.4 KB

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