docker_cli_build_unix_test.go 7.5 KB

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