docker_api_build_test.go 15 KB

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