docker_api_build_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. testRequires(c, DaemonIsLinux)
  341. dockerfile := `FROM busybox
  342. RUN echo 'test1:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  343. RUN echo 'test1:x:1001:' >> /etc/group
  344. RUN echo 'test2:x:1002:' >> /etc/group
  345. COPY --chown=test1:1002 . /new_dir
  346. RUN ls -l /
  347. RUN [ $(ls -l / | grep new_dir | awk '{print $3":"$4}') = 'test1:test2' ]
  348. RUN [ $(ls -nl / | grep new_dir | awk '{print $3":"$4}') = '1001:1002' ]
  349. `
  350. bCtx := fakecontext.New(c, "",
  351. fakecontext.WithDockerfile(dockerfile),
  352. fakecontext.WithFile("test_file1", "some test content"),
  353. )
  354. defer bCtx.Close()
  355. ctx := testutil.GetContext(c)
  356. res, body, err := request.Post(
  357. ctx,
  358. "/build",
  359. request.RawContent(bCtx.AsTarReader(c)),
  360. request.ContentType("application/x-tar"))
  361. assert.NilError(c, err)
  362. assert.Equal(c, res.StatusCode, http.StatusOK)
  363. out, err := request.ReadBody(body)
  364. assert.NilError(c, err)
  365. assert.Check(c, is.Contains(string(out), "Successfully built"))
  366. }
  367. func (s *DockerAPISuite) TestBuildCopyCacheOnFileChange(c *testing.T) {
  368. dockerfile := `FROM busybox
  369. COPY file /file`
  370. ctx1 := fakecontext.New(c, "",
  371. fakecontext.WithDockerfile(dockerfile),
  372. fakecontext.WithFile("file", "foo"))
  373. ctx2 := fakecontext.New(c, "",
  374. fakecontext.WithDockerfile(dockerfile),
  375. fakecontext.WithFile("file", "bar"))
  376. ctx := testutil.GetContext(c)
  377. build := func(bCtx *fakecontext.Fake) string {
  378. res, body, err := request.Post(ctx, "/build",
  379. request.RawContent(bCtx.AsTarReader(c)),
  380. request.ContentType("application/x-tar"))
  381. assert.NilError(c, err)
  382. assert.Check(c, is.DeepEqual(http.StatusOK, res.StatusCode))
  383. out, err := request.ReadBody(body)
  384. assert.NilError(c, err)
  385. assert.Assert(c, is.Contains(string(out), "Successfully built"))
  386. ids := getImageIDsFromBuild(c, out)
  387. assert.Assert(c, is.Len(ids, 1))
  388. return ids[len(ids)-1]
  389. }
  390. id1 := build(ctx1)
  391. id2 := build(ctx1)
  392. id3 := build(ctx2)
  393. if id1 != id2 {
  394. c.Fatal("didn't use the cache")
  395. }
  396. if id1 == id3 {
  397. c.Fatal("COPY With different source file should not share same cache")
  398. }
  399. }
  400. func (s *DockerAPISuite) TestBuildAddCacheOnFileChange(c *testing.T) {
  401. dockerfile := `FROM busybox
  402. ADD file /file`
  403. ctx1 := fakecontext.New(c, "",
  404. fakecontext.WithDockerfile(dockerfile),
  405. fakecontext.WithFile("file", "foo"))
  406. ctx2 := fakecontext.New(c, "",
  407. fakecontext.WithDockerfile(dockerfile),
  408. fakecontext.WithFile("file", "bar"))
  409. ctx := testutil.GetContext(c)
  410. build := func(bCtx *fakecontext.Fake) string {
  411. res, body, err := request.Post(ctx, "/build",
  412. request.RawContent(bCtx.AsTarReader(c)),
  413. request.ContentType("application/x-tar"))
  414. assert.NilError(c, err)
  415. assert.Check(c, is.DeepEqual(http.StatusOK, res.StatusCode))
  416. out, err := request.ReadBody(body)
  417. assert.NilError(c, err)
  418. assert.Assert(c, is.Contains(string(out), "Successfully built"))
  419. ids := getImageIDsFromBuild(c, out)
  420. assert.Assert(c, is.Len(ids, 1))
  421. return ids[len(ids)-1]
  422. }
  423. id1 := build(ctx1)
  424. id2 := build(ctx1)
  425. id3 := build(ctx2)
  426. if id1 != id2 {
  427. c.Fatal("didn't use the cache")
  428. }
  429. if id1 == id3 {
  430. c.Fatal("COPY With different source file should not share same cache")
  431. }
  432. }
  433. func (s *DockerAPISuite) TestBuildScratchCopy(c *testing.T) {
  434. testRequires(c, DaemonIsLinux)
  435. dockerfile := `FROM scratch
  436. ADD Dockerfile /
  437. ENV foo bar`
  438. bCtx := fakecontext.New(c, "",
  439. fakecontext.WithDockerfile(dockerfile),
  440. )
  441. defer bCtx.Close()
  442. ctx := testutil.GetContext(c)
  443. res, body, err := request.Post(
  444. ctx,
  445. "/build",
  446. request.RawContent(bCtx.AsTarReader(c)),
  447. request.ContentType("application/x-tar"))
  448. assert.NilError(c, err)
  449. assert.Equal(c, res.StatusCode, http.StatusOK)
  450. out, err := request.ReadBody(body)
  451. assert.NilError(c, err)
  452. assert.Check(c, is.Contains(string(out), "Successfully built"))
  453. }
  454. type buildLine struct {
  455. Stream string
  456. Aux struct {
  457. ID string
  458. }
  459. }
  460. func getImageIDsFromBuild(c *testing.T, output []byte) []string {
  461. var ids []string
  462. for _, line := range bytes.Split(output, []byte("\n")) {
  463. if len(line) == 0 {
  464. continue
  465. }
  466. entry := buildLine{}
  467. assert.NilError(c, json.Unmarshal(line, &entry))
  468. if entry.Aux.ID != "" {
  469. ids = append(ids, entry.Aux.ID)
  470. }
  471. }
  472. return ids
  473. }