docker_api_build_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. package main
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "context"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "regexp"
  12. "strings"
  13. "testing"
  14. "github.com/docker/docker/api/types"
  15. "github.com/docker/docker/testutil/fakecontext"
  16. "github.com/docker/docker/testutil/fakegit"
  17. "github.com/docker/docker/testutil/fakestorage"
  18. "github.com/docker/docker/testutil/request"
  19. "gotest.tools/assert"
  20. is "gotest.tools/assert/cmp"
  21. )
  22. func (s *DockerSuite) TestBuildAPIDockerFileRemote(c *testing.T) {
  23. testRequires(c, NotUserNamespace)
  24. var testD string
  25. if testEnv.OSType == "windows" {
  26. testD = `FROM busybox
  27. RUN find / -name ba*
  28. RUN find /tmp/`
  29. } else {
  30. // -xdev is required because sysfs can cause EPERM
  31. testD = `FROM busybox
  32. RUN find / -xdev -name ba*
  33. RUN find /tmp/`
  34. }
  35. server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{"testD": testD}))
  36. defer server.Close()
  37. res, body, err := request.Post("/build?dockerfile=baz&remote="+server.URL()+"/testD", request.JSON)
  38. assert.NilError(c, err)
  39. assert.Equal(c, res.StatusCode, http.StatusOK)
  40. buf, err := request.ReadBody(body)
  41. assert.NilError(c, err)
  42. // Make sure Dockerfile exists.
  43. // Make sure 'baz' doesn't exist ANYWHERE despite being mentioned in the URL
  44. out := string(buf)
  45. assert.Assert(c, is.Contains(out, "RUN find /tmp"))
  46. assert.Assert(c, !strings.Contains(out, "baz"))
  47. }
  48. func (s *DockerSuite) TestBuildAPIRemoteTarballContext(c *testing.T) {
  49. buffer := new(bytes.Buffer)
  50. tw := tar.NewWriter(buffer)
  51. defer tw.Close()
  52. dockerfile := []byte("FROM busybox")
  53. err := tw.WriteHeader(&tar.Header{
  54. Name: "Dockerfile",
  55. Size: int64(len(dockerfile)),
  56. })
  57. assert.NilError(c, err, "failed to write tar file header")
  58. _, err = tw.Write(dockerfile)
  59. assert.NilError(c, err, "failed to write tar file content")
  60. assert.NilError(c, tw.Close(), "failed to close tar archive")
  61. server := fakestorage.New(c, "", fakecontext.WithBinaryFiles(map[string]*bytes.Buffer{
  62. "testT.tar": buffer,
  63. }))
  64. defer server.Close()
  65. res, b, err := request.Post("/build?remote="+server.URL()+"/testT.tar", request.ContentType("application/tar"))
  66. assert.NilError(c, err)
  67. assert.Equal(c, res.StatusCode, http.StatusOK)
  68. b.Close()
  69. }
  70. func (s *DockerSuite) TestBuildAPIRemoteTarballContextWithCustomDockerfile(c *testing.T) {
  71. buffer := new(bytes.Buffer)
  72. tw := tar.NewWriter(buffer)
  73. defer tw.Close()
  74. dockerfile := []byte(`FROM busybox
  75. RUN echo 'wrong'`)
  76. err := tw.WriteHeader(&tar.Header{
  77. Name: "Dockerfile",
  78. Size: int64(len(dockerfile)),
  79. })
  80. // failed to write tar file header
  81. assert.NilError(c, err)
  82. _, err = tw.Write(dockerfile)
  83. // failed to write tar file content
  84. assert.NilError(c, err)
  85. custom := []byte(`FROM busybox
  86. RUN echo 'right'
  87. `)
  88. err = tw.WriteHeader(&tar.Header{
  89. Name: "custom",
  90. Size: int64(len(custom)),
  91. })
  92. // failed to write tar file header
  93. assert.NilError(c, err)
  94. _, err = tw.Write(custom)
  95. // failed to write tar file content
  96. assert.NilError(c, err)
  97. // failed to close tar archive
  98. assert.NilError(c, tw.Close())
  99. server := fakestorage.New(c, "", fakecontext.WithBinaryFiles(map[string]*bytes.Buffer{
  100. "testT.tar": buffer,
  101. }))
  102. defer server.Close()
  103. url := "/build?dockerfile=custom&remote=" + server.URL() + "/testT.tar"
  104. res, body, err := request.Post(url, request.ContentType("application/tar"))
  105. assert.NilError(c, err)
  106. assert.Equal(c, res.StatusCode, http.StatusOK)
  107. defer body.Close()
  108. content, err := request.ReadBody(body)
  109. assert.NilError(c, err)
  110. // Build used the wrong dockerfile.
  111. assert.Assert(c, !strings.Contains(string(content), "wrong"))
  112. }
  113. func (s *DockerSuite) TestBuildAPILowerDockerfile(c *testing.T) {
  114. git := fakegit.New(c, "repo", map[string]string{
  115. "dockerfile": `FROM busybox
  116. RUN echo from dockerfile`,
  117. }, false)
  118. defer git.Close()
  119. res, body, err := request.Post("/build?remote="+git.RepoURL, request.JSON)
  120. assert.NilError(c, err)
  121. assert.Equal(c, res.StatusCode, http.StatusOK)
  122. buf, err := request.ReadBody(body)
  123. assert.NilError(c, err)
  124. out := string(buf)
  125. assert.Assert(c, is.Contains(out, "from dockerfile"))
  126. }
  127. func (s *DockerSuite) TestBuildAPIBuildGitWithF(c *testing.T) {
  128. git := fakegit.New(c, "repo", map[string]string{
  129. "baz": `FROM busybox
  130. RUN echo from baz`,
  131. "Dockerfile": `FROM busybox
  132. RUN echo from Dockerfile`,
  133. }, false)
  134. defer git.Close()
  135. // Make sure it tries to 'dockerfile' query param value
  136. res, body, err := request.Post("/build?dockerfile=baz&remote="+git.RepoURL, request.JSON)
  137. assert.NilError(c, err)
  138. assert.Equal(c, res.StatusCode, http.StatusOK)
  139. buf, err := request.ReadBody(body)
  140. assert.NilError(c, err)
  141. out := string(buf)
  142. assert.Assert(c, is.Contains(out, "from baz"))
  143. }
  144. func (s *DockerSuite) TestBuildAPIDoubleDockerfile(c *testing.T) {
  145. testRequires(c, UnixCli) // dockerfile overwrites Dockerfile on Windows
  146. git := fakegit.New(c, "repo", map[string]string{
  147. "Dockerfile": `FROM busybox
  148. RUN echo from Dockerfile`,
  149. "dockerfile": `FROM busybox
  150. RUN echo from dockerfile`,
  151. }, false)
  152. defer git.Close()
  153. // Make sure it tries to 'dockerfile' query param value
  154. res, body, err := request.Post("/build?remote="+git.RepoURL, request.JSON)
  155. assert.NilError(c, err)
  156. assert.Equal(c, res.StatusCode, http.StatusOK)
  157. buf, err := request.ReadBody(body)
  158. assert.NilError(c, err)
  159. out := string(buf)
  160. assert.Assert(c, is.Contains(out, "from Dockerfile"))
  161. }
  162. func (s *DockerSuite) TestBuildAPIUnnormalizedTarPaths(c *testing.T) {
  163. // Make sure that build context tars with entries of the form
  164. // x/./y don't cause caching false positives.
  165. buildFromTarContext := func(fileContents []byte) string {
  166. buffer := new(bytes.Buffer)
  167. tw := tar.NewWriter(buffer)
  168. defer tw.Close()
  169. dockerfile := []byte(`FROM busybox
  170. COPY dir /dir/`)
  171. err := tw.WriteHeader(&tar.Header{
  172. Name: "Dockerfile",
  173. Size: int64(len(dockerfile)),
  174. })
  175. assert.NilError(c, err, "failed to write tar file header")
  176. _, err = tw.Write(dockerfile)
  177. assert.NilError(c, err, "failed to write Dockerfile in tar file content")
  178. err = tw.WriteHeader(&tar.Header{
  179. Name: "dir/./file",
  180. Size: int64(len(fileContents)),
  181. })
  182. assert.NilError(c, err, "failed to write tar file header")
  183. _, err = tw.Write(fileContents)
  184. assert.NilError(c, err, "failed to write file contents in tar file content")
  185. assert.NilError(c, tw.Close(), "failed to close tar archive")
  186. res, body, err := request.Post("/build", request.RawContent(ioutil.NopCloser(buffer)), request.ContentType("application/x-tar"))
  187. assert.NilError(c, err)
  188. assert.Equal(c, res.StatusCode, http.StatusOK)
  189. out, err := request.ReadBody(body)
  190. assert.NilError(c, err)
  191. lines := strings.Split(string(out), "\n")
  192. assert.Assert(c, len(lines) > 1)
  193. matched, err := regexp.MatchString(".*Successfully built [0-9a-f]{12}.*", lines[len(lines)-2])
  194. assert.NilError(c, err)
  195. assert.Assert(c, matched)
  196. re := regexp.MustCompile("Successfully built ([0-9a-f]{12})")
  197. matches := re.FindStringSubmatch(lines[len(lines)-2])
  198. return matches[1]
  199. }
  200. imageA := buildFromTarContext([]byte("abc"))
  201. imageB := buildFromTarContext([]byte("def"))
  202. assert.Assert(c, imageA != imageB)
  203. }
  204. func (s *DockerSuite) TestBuildOnBuildWithCopy(c *testing.T) {
  205. dockerfile := `
  206. FROM ` + minimalBaseImage() + ` as onbuildbase
  207. ONBUILD COPY file /file
  208. FROM onbuildbase
  209. `
  210. ctx := fakecontext.New(c, "",
  211. fakecontext.WithDockerfile(dockerfile),
  212. fakecontext.WithFile("file", "some content"),
  213. )
  214. defer ctx.Close()
  215. res, body, err := request.Post(
  216. "/build",
  217. request.RawContent(ctx.AsTarReader(c)),
  218. request.ContentType("application/x-tar"))
  219. assert.NilError(c, err)
  220. assert.Equal(c, res.StatusCode, http.StatusOK)
  221. out, err := request.ReadBody(body)
  222. assert.NilError(c, err)
  223. assert.Assert(c, is.Contains(string(out), "Successfully built"))
  224. }
  225. func (s *DockerSuite) TestBuildOnBuildCache(c *testing.T) {
  226. build := func(dockerfile string) []byte {
  227. ctx := fakecontext.New(c, "",
  228. fakecontext.WithDockerfile(dockerfile),
  229. )
  230. defer ctx.Close()
  231. res, body, err := request.Post(
  232. "/build",
  233. request.RawContent(ctx.AsTarReader(c)),
  234. request.ContentType("application/x-tar"))
  235. assert.NilError(c, err)
  236. assert.Check(c, is.DeepEqual(http.StatusOK, res.StatusCode))
  237. out, err := request.ReadBody(body)
  238. assert.NilError(c, err)
  239. assert.Assert(c, is.Contains(string(out), "Successfully built"))
  240. return out
  241. }
  242. dockerfile := `
  243. FROM ` + minimalBaseImage() + ` as onbuildbase
  244. ENV something=bar
  245. ONBUILD ENV foo=bar
  246. `
  247. build(dockerfile)
  248. dockerfile += "FROM onbuildbase"
  249. out := build(dockerfile)
  250. imageIDs := getImageIDsFromBuild(c, out)
  251. assert.Assert(c, is.Len(imageIDs, 2))
  252. parentID, childID := imageIDs[0], imageIDs[1]
  253. client := testEnv.APIClient()
  254. // check parentID is correct
  255. image, _, err := client.ImageInspectWithRaw(context.Background(), childID)
  256. assert.NilError(c, err)
  257. assert.Check(c, is.Equal(parentID, image.Parent))
  258. }
  259. func (s *DockerRegistrySuite) TestBuildCopyFromForcePull(c *testing.T) {
  260. client := testEnv.APIClient()
  261. repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
  262. // tag the image to upload it to the private registry
  263. err := client.ImageTag(context.TODO(), "busybox", repoName)
  264. assert.Check(c, err)
  265. // push the image to the registry
  266. rc, err := client.ImagePush(context.TODO(), repoName, types.ImagePushOptions{RegistryAuth: "{}"})
  267. assert.Check(c, err)
  268. _, err = io.Copy(ioutil.Discard, rc)
  269. assert.Check(c, err)
  270. dockerfile := fmt.Sprintf(`
  271. FROM %s AS foo
  272. RUN touch abc
  273. FROM %s
  274. COPY --from=foo /abc /
  275. `, repoName, repoName)
  276. ctx := fakecontext.New(c, "",
  277. fakecontext.WithDockerfile(dockerfile),
  278. )
  279. defer ctx.Close()
  280. res, body, err := request.Post(
  281. "/build?pull=1",
  282. request.RawContent(ctx.AsTarReader(c)),
  283. request.ContentType("application/x-tar"))
  284. assert.NilError(c, err)
  285. assert.Check(c, is.DeepEqual(http.StatusOK, res.StatusCode))
  286. out, err := request.ReadBody(body)
  287. assert.NilError(c, err)
  288. assert.Check(c, is.Contains(string(out), "Successfully built"))
  289. }
  290. func (s *DockerSuite) TestBuildAddRemoteNoDecompress(c *testing.T) {
  291. buffer := new(bytes.Buffer)
  292. tw := tar.NewWriter(buffer)
  293. dt := []byte("contents")
  294. err := tw.WriteHeader(&tar.Header{
  295. Name: "foo",
  296. Size: int64(len(dt)),
  297. Mode: 0600,
  298. Typeflag: tar.TypeReg,
  299. })
  300. assert.NilError(c, err)
  301. _, err = tw.Write(dt)
  302. assert.NilError(c, err)
  303. err = tw.Close()
  304. assert.NilError(c, err)
  305. server := fakestorage.New(c, "", fakecontext.WithBinaryFiles(map[string]*bytes.Buffer{
  306. "test.tar": buffer,
  307. }))
  308. defer server.Close()
  309. dockerfile := fmt.Sprintf(`
  310. FROM busybox
  311. ADD %s/test.tar /
  312. RUN [ -f test.tar ]
  313. `, server.URL())
  314. ctx := fakecontext.New(c, "",
  315. fakecontext.WithDockerfile(dockerfile),
  316. )
  317. defer ctx.Close()
  318. res, body, err := request.Post(
  319. "/build",
  320. request.RawContent(ctx.AsTarReader(c)),
  321. request.ContentType("application/x-tar"))
  322. assert.NilError(c, err)
  323. assert.Check(c, is.DeepEqual(http.StatusOK, res.StatusCode))
  324. out, err := request.ReadBody(body)
  325. assert.NilError(c, err)
  326. assert.Check(c, is.Contains(string(out), "Successfully built"))
  327. }
  328. func (s *DockerSuite) TestBuildChownOnCopy(c *testing.T) {
  329. // new feature added in 1.31 - https://github.com/moby/moby/pull/34263
  330. testRequires(c, DaemonIsLinux, MinimumAPIVersion("1.31"))
  331. dockerfile := `FROM busybox
  332. RUN echo 'test1:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  333. RUN echo 'test1:x:1001:' >> /etc/group
  334. RUN echo 'test2:x:1002:' >> /etc/group
  335. COPY --chown=test1:1002 . /new_dir
  336. RUN ls -l /
  337. RUN [ $(ls -l / | grep new_dir | awk '{print $3":"$4}') = 'test1:test2' ]
  338. RUN [ $(ls -nl / | grep new_dir | awk '{print $3":"$4}') = '1001:1002' ]
  339. `
  340. ctx := fakecontext.New(c, "",
  341. fakecontext.WithDockerfile(dockerfile),
  342. fakecontext.WithFile("test_file1", "some test content"),
  343. )
  344. defer ctx.Close()
  345. res, body, err := request.Post(
  346. "/build",
  347. request.RawContent(ctx.AsTarReader(c)),
  348. request.ContentType("application/x-tar"))
  349. assert.NilError(c, err)
  350. assert.Equal(c, res.StatusCode, http.StatusOK)
  351. out, err := request.ReadBody(body)
  352. assert.NilError(c, err)
  353. assert.Check(c, is.Contains(string(out), "Successfully built"))
  354. }
  355. func (s *DockerSuite) TestBuildCopyCacheOnFileChange(c *testing.T) {
  356. dockerfile := `FROM busybox
  357. COPY file /file`
  358. ctx1 := fakecontext.New(c, "",
  359. fakecontext.WithDockerfile(dockerfile),
  360. fakecontext.WithFile("file", "foo"))
  361. ctx2 := fakecontext.New(c, "",
  362. fakecontext.WithDockerfile(dockerfile),
  363. fakecontext.WithFile("file", "bar"))
  364. var build = func(ctx *fakecontext.Fake) string {
  365. res, body, err := request.Post("/build",
  366. request.RawContent(ctx.AsTarReader(c)),
  367. request.ContentType("application/x-tar"))
  368. assert.NilError(c, err)
  369. assert.Check(c, is.DeepEqual(http.StatusOK, res.StatusCode))
  370. out, err := request.ReadBody(body)
  371. assert.NilError(c, err)
  372. assert.Assert(c, is.Contains(string(out), "Successfully built"))
  373. ids := getImageIDsFromBuild(c, out)
  374. assert.Assert(c, is.Len(ids, 1))
  375. return ids[len(ids)-1]
  376. }
  377. id1 := build(ctx1)
  378. id2 := build(ctx1)
  379. id3 := build(ctx2)
  380. if id1 != id2 {
  381. c.Fatal("didn't use the cache")
  382. }
  383. if id1 == id3 {
  384. c.Fatal("COPY With different source file should not share same cache")
  385. }
  386. }
  387. func (s *DockerSuite) TestBuildAddCacheOnFileChange(c *testing.T) {
  388. dockerfile := `FROM busybox
  389. ADD file /file`
  390. ctx1 := fakecontext.New(c, "",
  391. fakecontext.WithDockerfile(dockerfile),
  392. fakecontext.WithFile("file", "foo"))
  393. ctx2 := fakecontext.New(c, "",
  394. fakecontext.WithDockerfile(dockerfile),
  395. fakecontext.WithFile("file", "bar"))
  396. var build = func(ctx *fakecontext.Fake) string {
  397. res, body, err := request.Post("/build",
  398. request.RawContent(ctx.AsTarReader(c)),
  399. request.ContentType("application/x-tar"))
  400. assert.NilError(c, err)
  401. assert.Check(c, is.DeepEqual(http.StatusOK, res.StatusCode))
  402. out, err := request.ReadBody(body)
  403. assert.NilError(c, err)
  404. assert.Assert(c, is.Contains(string(out), "Successfully built"))
  405. ids := getImageIDsFromBuild(c, out)
  406. assert.Assert(c, is.Len(ids, 1))
  407. return ids[len(ids)-1]
  408. }
  409. id1 := build(ctx1)
  410. id2 := build(ctx1)
  411. id3 := build(ctx2)
  412. if id1 != id2 {
  413. c.Fatal("didn't use the cache")
  414. }
  415. if id1 == id3 {
  416. c.Fatal("COPY With different source file should not share same cache")
  417. }
  418. }
  419. func (s *DockerSuite) TestBuildScratchCopy(c *testing.T) {
  420. testRequires(c, DaemonIsLinux)
  421. dockerfile := `FROM scratch
  422. ADD Dockerfile /
  423. ENV foo bar`
  424. ctx := fakecontext.New(c, "",
  425. fakecontext.WithDockerfile(dockerfile),
  426. )
  427. defer ctx.Close()
  428. res, body, err := request.Post(
  429. "/build",
  430. request.RawContent(ctx.AsTarReader(c)),
  431. request.ContentType("application/x-tar"))
  432. assert.NilError(c, err)
  433. assert.Equal(c, res.StatusCode, http.StatusOK)
  434. out, err := request.ReadBody(body)
  435. assert.NilError(c, err)
  436. assert.Check(c, is.Contains(string(out), "Successfully built"))
  437. }
  438. type buildLine struct {
  439. Stream string
  440. Aux struct {
  441. ID string
  442. }
  443. }
  444. func getImageIDsFromBuild(c *testing.T, output []byte) []string {
  445. var ids []string
  446. for _, line := range bytes.Split(output, []byte("\n")) {
  447. if len(line) == 0 {
  448. continue
  449. }
  450. entry := buildLine{}
  451. assert.NilError(c, json.Unmarshal(line, &entry))
  452. if entry.Aux.ID != "" {
  453. ids = append(ids, entry.Aux.ID)
  454. }
  455. }
  456. return ids
  457. }