docker_cli_build_unix_test.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. // +build !windows
  2. package main
  3. import (
  4. "bufio"
  5. "bytes"
  6. "encoding/json"
  7. "io/ioutil"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "regexp"
  12. "strings"
  13. "time"
  14. "syscall"
  15. "github.com/docker/docker/integration-cli/checker"
  16. "github.com/docker/docker/integration-cli/cli"
  17. "github.com/docker/docker/integration-cli/cli/build"
  18. "github.com/docker/docker/integration-cli/cli/build/fakecontext"
  19. icmd "github.com/docker/docker/pkg/testutil/cmd"
  20. "github.com/go-check/check"
  21. )
  22. func (s *DockerSuite) TestBuildResourceConstraintsAreUsed(c *check.C) {
  23. testRequires(c, cpuCfsQuota)
  24. name := "testbuildresourceconstraints"
  25. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`
  26. FROM hello-world:frozen
  27. RUN ["/hello"]
  28. `))
  29. cli.Docker(
  30. cli.Args("build", "--no-cache", "--rm=false", "--memory=64m", "--memory-swap=-1", "--cpuset-cpus=0", "--cpuset-mems=0", "--cpu-shares=100", "--cpu-quota=8000", "--ulimit", "nofile=42", "-t", name, "."),
  31. cli.InDir(ctx.Dir),
  32. ).Assert(c, icmd.Success)
  33. out := cli.DockerCmd(c, "ps", "-lq").Combined()
  34. cID := strings.TrimSpace(out)
  35. type hostConfig struct {
  36. Memory int64
  37. MemorySwap int64
  38. CpusetCpus string
  39. CpusetMems string
  40. CPUShares int64
  41. CPUQuota int64
  42. Ulimits []*units.Ulimit
  43. }
  44. cfg := inspectFieldJSON(c, cID, "HostConfig")
  45. var c1 hostConfig
  46. err := json.Unmarshal([]byte(cfg), &c1)
  47. c.Assert(err, checker.IsNil, check.Commentf(cfg))
  48. c.Assert(c1.Memory, checker.Equals, int64(64*1024*1024), check.Commentf("resource constraints not set properly for Memory"))
  49. c.Assert(c1.MemorySwap, checker.Equals, int64(-1), check.Commentf("resource constraints not set properly for MemorySwap"))
  50. c.Assert(c1.CpusetCpus, checker.Equals, "0", check.Commentf("resource constraints not set properly for CpusetCpus"))
  51. c.Assert(c1.CpusetMems, checker.Equals, "0", check.Commentf("resource constraints not set properly for CpusetMems"))
  52. c.Assert(c1.CPUShares, checker.Equals, int64(100), check.Commentf("resource constraints not set properly for CPUShares"))
  53. c.Assert(c1.CPUQuota, checker.Equals, int64(8000), check.Commentf("resource constraints not set properly for CPUQuota"))
  54. c.Assert(c1.Ulimits[0].Name, checker.Equals, "nofile", check.Commentf("resource constraints not set properly for Ulimits"))
  55. c.Assert(c1.Ulimits[0].Hard, checker.Equals, int64(42), check.Commentf("resource constraints not set properly for Ulimits"))
  56. // Make sure constraints aren't saved to image
  57. cli.DockerCmd(c, "run", "--name=test", name)
  58. cfg = inspectFieldJSON(c, "test", "HostConfig")
  59. var c2 hostConfig
  60. err = json.Unmarshal([]byte(cfg), &c2)
  61. c.Assert(err, checker.IsNil, check.Commentf(cfg))
  62. c.Assert(c2.Memory, check.Not(checker.Equals), int64(64*1024*1024), check.Commentf("resource leaked from build for Memory"))
  63. c.Assert(c2.MemorySwap, check.Not(checker.Equals), int64(-1), check.Commentf("resource leaked from build for MemorySwap"))
  64. c.Assert(c2.CpusetCpus, check.Not(checker.Equals), "0", check.Commentf("resource leaked from build for CpusetCpus"))
  65. c.Assert(c2.CpusetMems, check.Not(checker.Equals), "0", check.Commentf("resource leaked from build for CpusetMems"))
  66. c.Assert(c2.CPUShares, check.Not(checker.Equals), int64(100), check.Commentf("resource leaked from build for CPUShares"))
  67. c.Assert(c2.CPUQuota, check.Not(checker.Equals), int64(8000), check.Commentf("resource leaked from build for CPUQuota"))
  68. c.Assert(c2.Ulimits, checker.IsNil, check.Commentf("resource leaked from build for Ulimits"))
  69. }
  70. func (s *DockerSuite) TestBuildAddChangeOwnership(c *check.C) {
  71. testRequires(c, DaemonIsLinux)
  72. name := "testbuildaddown"
  73. ctx := func() *fakecontext.Fake {
  74. dockerfile := `
  75. FROM busybox
  76. ADD foo /bar/
  77. RUN [ $(stat -c %U:%G "/bar") = 'root:root' ]
  78. RUN [ $(stat -c %U:%G "/bar/foo") = 'root:root' ]
  79. `
  80. tmpDir, err := ioutil.TempDir("", "fake-context")
  81. c.Assert(err, check.IsNil)
  82. testFile, err := os.Create(filepath.Join(tmpDir, "foo"))
  83. if err != nil {
  84. c.Fatalf("failed to create foo file: %v", err)
  85. }
  86. defer testFile.Close()
  87. icmd.RunCmd(icmd.Cmd{
  88. Command: []string{"chown", "daemon:daemon", "foo"},
  89. Dir: tmpDir,
  90. }).Assert(c, icmd.Success)
  91. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  92. c.Fatalf("failed to open destination dockerfile: %v", err)
  93. }
  94. return fakecontext.New(c, tmpDir)
  95. }()
  96. defer ctx.Close()
  97. buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx))
  98. }
  99. // Test that an infinite sleep during a build is killed if the client disconnects.
  100. // This test is fairly hairy because there are lots of ways to race.
  101. // Strategy:
  102. // * Monitor the output of docker events starting from before
  103. // * Run a 1-year-long sleep from a docker build.
  104. // * When docker events sees container start, close the "docker build" command
  105. // * Wait for docker events to emit a dying event.
  106. func (s *DockerSuite) TestBuildCancellationKillsSleep(c *check.C) {
  107. testRequires(c, DaemonIsLinux)
  108. name := "testbuildcancellation"
  109. observer, err := newEventObserver(c)
  110. c.Assert(err, checker.IsNil)
  111. err = observer.Start()
  112. c.Assert(err, checker.IsNil)
  113. defer observer.Stop()
  114. // (Note: one year, will never finish)
  115. ctx := fakecontext.New(c, "", fakecontext.WithDockerfile("FROM busybox\nRUN sleep 31536000"))
  116. defer ctx.Close()
  117. buildCmd := exec.Command(dockerBinary, "build", "-t", name, ".")
  118. buildCmd.Dir = ctx.Dir
  119. stdoutBuild, err := buildCmd.StdoutPipe()
  120. c.Assert(err, checker.IsNil)
  121. if err := buildCmd.Start(); err != nil {
  122. c.Fatalf("failed to run build: %s", err)
  123. }
  124. matchCID := regexp.MustCompile("Running in (.+)")
  125. scanner := bufio.NewScanner(stdoutBuild)
  126. outputBuffer := new(bytes.Buffer)
  127. var buildID string
  128. for scanner.Scan() {
  129. line := scanner.Text()
  130. outputBuffer.WriteString(line)
  131. outputBuffer.WriteString("\n")
  132. if matches := matchCID.FindStringSubmatch(line); len(matches) > 0 {
  133. buildID = matches[1]
  134. break
  135. }
  136. }
  137. if buildID == "" {
  138. c.Fatalf("Unable to find build container id in build output:\n%s", outputBuffer.String())
  139. }
  140. testActions := map[string]chan bool{
  141. "start": make(chan bool, 1),
  142. "die": make(chan bool, 1),
  143. }
  144. matcher := matchEventLine(buildID, "container", testActions)
  145. processor := processEventMatch(testActions)
  146. go observer.Match(matcher, processor)
  147. select {
  148. case <-time.After(10 * time.Second):
  149. observer.CheckEventError(c, buildID, "start", matcher)
  150. case <-testActions["start"]:
  151. // ignore, done
  152. }
  153. // Send a kill to the `docker build` command.
  154. // Causes the underlying build to be cancelled due to socket close.
  155. if err := buildCmd.Process.Kill(); err != nil {
  156. c.Fatalf("error killing build command: %s", err)
  157. }
  158. // Get the exit status of `docker build`, check it exited because killed.
  159. if err := buildCmd.Wait(); err != nil && !isKilled(err) {
  160. c.Fatalf("wait failed during build run: %T %s", err, err)
  161. }
  162. select {
  163. case <-time.After(10 * time.Second):
  164. observer.CheckEventError(c, buildID, "die", matcher)
  165. case <-testActions["die"]:
  166. // ignore, done
  167. }
  168. }
  169. func isKilled(err error) bool {
  170. if exitErr, ok := err.(*exec.ExitError); ok {
  171. status, ok := exitErr.Sys().(syscall.WaitStatus)
  172. if !ok {
  173. return false
  174. }
  175. // status.ExitStatus() is required on Windows because it does not
  176. // implement Signal() nor Signaled(). Just check it had a bad exit
  177. // status could mean it was killed (and in tests we do kill)
  178. return (status.Signaled() && status.Signal() == os.Kill) || status.ExitStatus() != 0
  179. }
  180. return false
  181. }