docker_api_build_test.go 15 KB

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