build_test.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. package build // import "github.com/docker/docker/integration/build"
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "context"
  6. "encoding/json"
  7. "io"
  8. "os"
  9. "strings"
  10. "testing"
  11. "github.com/docker/docker/api/types"
  12. "github.com/docker/docker/api/types/filters"
  13. "github.com/docker/docker/api/types/versions"
  14. "github.com/docker/docker/errdefs"
  15. "github.com/docker/docker/pkg/jsonmessage"
  16. "github.com/docker/docker/testutil/fakecontext"
  17. "gotest.tools/v3/assert"
  18. is "gotest.tools/v3/assert/cmp"
  19. "gotest.tools/v3/skip"
  20. )
  21. func TestBuildWithRemoveAndForceRemove(t *testing.T) {
  22. t.Cleanup(setupTest(t))
  23. cases := []struct {
  24. name string
  25. dockerfile string
  26. numberOfIntermediateContainers int
  27. rm bool
  28. forceRm bool
  29. }{
  30. {
  31. name: "successful build with no removal",
  32. dockerfile: `FROM busybox
  33. RUN exit 0
  34. RUN exit 0`,
  35. numberOfIntermediateContainers: 2,
  36. rm: false,
  37. forceRm: false,
  38. },
  39. {
  40. name: "successful build with remove",
  41. dockerfile: `FROM busybox
  42. RUN exit 0
  43. RUN exit 0`,
  44. numberOfIntermediateContainers: 0,
  45. rm: true,
  46. forceRm: false,
  47. },
  48. {
  49. name: "successful build with remove and force remove",
  50. dockerfile: `FROM busybox
  51. RUN exit 0
  52. RUN exit 0`,
  53. numberOfIntermediateContainers: 0,
  54. rm: true,
  55. forceRm: true,
  56. },
  57. {
  58. name: "failed build with no removal",
  59. dockerfile: `FROM busybox
  60. RUN exit 0
  61. RUN exit 1`,
  62. numberOfIntermediateContainers: 2,
  63. rm: false,
  64. forceRm: false,
  65. },
  66. {
  67. name: "failed build with remove",
  68. dockerfile: `FROM busybox
  69. RUN exit 0
  70. RUN exit 1`,
  71. numberOfIntermediateContainers: 1,
  72. rm: true,
  73. forceRm: false,
  74. },
  75. {
  76. name: "failed build with remove and force remove",
  77. dockerfile: `FROM busybox
  78. RUN exit 0
  79. RUN exit 1`,
  80. numberOfIntermediateContainers: 0,
  81. rm: true,
  82. forceRm: true,
  83. },
  84. }
  85. client := testEnv.APIClient()
  86. ctx := context.Background()
  87. for _, c := range cases {
  88. c := c
  89. t.Run(c.name, func(t *testing.T) {
  90. t.Parallel()
  91. dockerfile := []byte(c.dockerfile)
  92. buff := bytes.NewBuffer(nil)
  93. tw := tar.NewWriter(buff)
  94. assert.NilError(t, tw.WriteHeader(&tar.Header{
  95. Name: "Dockerfile",
  96. Size: int64(len(dockerfile)),
  97. }))
  98. _, err := tw.Write(dockerfile)
  99. assert.NilError(t, err)
  100. assert.NilError(t, tw.Close())
  101. resp, err := client.ImageBuild(ctx, buff, types.ImageBuildOptions{Remove: c.rm, ForceRemove: c.forceRm, NoCache: true})
  102. assert.NilError(t, err)
  103. defer resp.Body.Close()
  104. filter, err := buildContainerIdsFilter(resp.Body)
  105. assert.NilError(t, err)
  106. remainingContainers, err := client.ContainerList(ctx, types.ContainerListOptions{Filters: filter, All: true})
  107. assert.NilError(t, err)
  108. assert.Equal(t, c.numberOfIntermediateContainers, len(remainingContainers), "Expected %v remaining intermediate containers, got %v", c.numberOfIntermediateContainers, len(remainingContainers))
  109. })
  110. }
  111. }
  112. func buildContainerIdsFilter(buildOutput io.Reader) (filters.Args, error) {
  113. const intermediateContainerPrefix = " ---> Running in "
  114. filter := filters.NewArgs()
  115. dec := json.NewDecoder(buildOutput)
  116. for {
  117. m := jsonmessage.JSONMessage{}
  118. err := dec.Decode(&m)
  119. if err == io.EOF {
  120. return filter, nil
  121. }
  122. if err != nil {
  123. return filter, err
  124. }
  125. if ix := strings.Index(m.Stream, intermediateContainerPrefix); ix != -1 {
  126. filter.Add("id", strings.TrimSpace(m.Stream[ix+len(intermediateContainerPrefix):]))
  127. }
  128. }
  129. }
  130. // TestBuildMultiStageCopy verifies that copying between stages works correctly.
  131. //
  132. // Regression test for docker/for-win#4349, ENGCORE-935, where creating the target
  133. // directory failed on Windows, because `os.MkdirAll()` was called with a volume
  134. // GUID path (\\?\Volume{dae8d3ac-b9a1-11e9-88eb-e8554b2ba1db}\newdir\hello}),
  135. // which currently isn't supported by Golang.
  136. func TestBuildMultiStageCopy(t *testing.T) {
  137. ctx := context.Background()
  138. dockerfile, err := os.ReadFile("testdata/Dockerfile." + t.Name())
  139. assert.NilError(t, err)
  140. source := fakecontext.New(t, "", fakecontext.WithDockerfile(string(dockerfile)))
  141. defer source.Close()
  142. apiclient := testEnv.APIClient()
  143. for _, target := range []string{"copy_to_root", "copy_to_newdir", "copy_to_newdir_nested", "copy_to_existingdir", "copy_to_newsubdir"} {
  144. t.Run(target, func(t *testing.T) {
  145. imgName := strings.ToLower(t.Name())
  146. resp, err := apiclient.ImageBuild(
  147. ctx,
  148. source.AsTarReader(t),
  149. types.ImageBuildOptions{
  150. Remove: true,
  151. ForceRemove: true,
  152. Target: target,
  153. Tags: []string{imgName},
  154. },
  155. )
  156. assert.NilError(t, err)
  157. out := bytes.NewBuffer(nil)
  158. _, err = io.Copy(out, resp.Body)
  159. _ = resp.Body.Close()
  160. if err != nil {
  161. t.Log(out)
  162. }
  163. assert.NilError(t, err)
  164. // verify the image was successfully built
  165. _, _, err = apiclient.ImageInspectWithRaw(ctx, imgName)
  166. if err != nil {
  167. t.Log(out)
  168. }
  169. assert.NilError(t, err)
  170. })
  171. }
  172. }
  173. func TestBuildMultiStageParentConfig(t *testing.T) {
  174. skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.35"), "broken in earlier versions")
  175. dockerfile := `
  176. FROM busybox AS stage0
  177. ENV WHO=parent
  178. WORKDIR /foo
  179. FROM stage0
  180. ENV WHO=sibling1
  181. WORKDIR sub1
  182. FROM stage0
  183. WORKDIR sub2
  184. `
  185. ctx := context.Background()
  186. source := fakecontext.New(t, "", fakecontext.WithDockerfile(dockerfile))
  187. defer source.Close()
  188. apiclient := testEnv.APIClient()
  189. imgName := strings.ToLower(t.Name())
  190. resp, err := apiclient.ImageBuild(ctx,
  191. source.AsTarReader(t),
  192. types.ImageBuildOptions{
  193. Remove: true,
  194. ForceRemove: true,
  195. Tags: []string{imgName},
  196. })
  197. assert.NilError(t, err)
  198. _, err = io.Copy(io.Discard, resp.Body)
  199. resp.Body.Close()
  200. assert.NilError(t, err)
  201. image, _, err := apiclient.ImageInspectWithRaw(ctx, imgName)
  202. assert.NilError(t, err)
  203. expected := "/foo/sub2"
  204. if testEnv.DaemonInfo.OSType == "windows" {
  205. expected = `C:\foo\sub2`
  206. }
  207. assert.Check(t, is.Equal(expected, image.Config.WorkingDir))
  208. assert.Check(t, is.Contains(image.Config.Env, "WHO=parent"))
  209. }
  210. // Test cases in #36996
  211. func TestBuildLabelWithTargets(t *testing.T) {
  212. skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.38"), "test added after 1.38")
  213. skip.If(t, testEnv.DaemonInfo.OSType == "windows", "FIXME")
  214. imgName := strings.ToLower(t.Name() + "-a")
  215. testLabels := map[string]string{
  216. "foo": "bar",
  217. "dead": "beef",
  218. }
  219. dockerfile := `
  220. FROM busybox AS target-a
  221. CMD ["/dev"]
  222. LABEL label-a=inline-a
  223. FROM busybox AS target-b
  224. CMD ["/dist"]
  225. LABEL label-b=inline-b
  226. `
  227. ctx := context.Background()
  228. source := fakecontext.New(t, "", fakecontext.WithDockerfile(dockerfile))
  229. defer source.Close()
  230. apiclient := testEnv.APIClient()
  231. // For `target-a` build
  232. resp, err := apiclient.ImageBuild(ctx,
  233. source.AsTarReader(t),
  234. types.ImageBuildOptions{
  235. Remove: true,
  236. ForceRemove: true,
  237. Tags: []string{imgName},
  238. Labels: testLabels,
  239. Target: "target-a",
  240. })
  241. assert.NilError(t, err)
  242. _, err = io.Copy(io.Discard, resp.Body)
  243. resp.Body.Close()
  244. assert.NilError(t, err)
  245. image, _, err := apiclient.ImageInspectWithRaw(ctx, imgName)
  246. assert.NilError(t, err)
  247. testLabels["label-a"] = "inline-a"
  248. for k, v := range testLabels {
  249. x, ok := image.Config.Labels[k]
  250. assert.Assert(t, ok)
  251. assert.Assert(t, x == v)
  252. }
  253. // For `target-b` build
  254. imgName = strings.ToLower(t.Name() + "-b")
  255. delete(testLabels, "label-a")
  256. resp, err = apiclient.ImageBuild(ctx,
  257. source.AsTarReader(t),
  258. types.ImageBuildOptions{
  259. Remove: true,
  260. ForceRemove: true,
  261. Tags: []string{imgName},
  262. Labels: testLabels,
  263. Target: "target-b",
  264. })
  265. assert.NilError(t, err)
  266. _, err = io.Copy(io.Discard, resp.Body)
  267. resp.Body.Close()
  268. assert.NilError(t, err)
  269. image, _, err = apiclient.ImageInspectWithRaw(ctx, imgName)
  270. assert.NilError(t, err)
  271. testLabels["label-b"] = "inline-b"
  272. for k, v := range testLabels {
  273. x, ok := image.Config.Labels[k]
  274. assert.Assert(t, ok)
  275. assert.Assert(t, x == v)
  276. }
  277. }
  278. func TestBuildWithEmptyLayers(t *testing.T) {
  279. dockerfile := `
  280. FROM busybox
  281. COPY 1/ /target/
  282. COPY 2/ /target/
  283. COPY 3/ /target/
  284. `
  285. ctx := context.Background()
  286. source := fakecontext.New(t, "",
  287. fakecontext.WithDockerfile(dockerfile),
  288. fakecontext.WithFile("1/a", "asdf"),
  289. fakecontext.WithFile("2/a", "asdf"),
  290. fakecontext.WithFile("3/a", "asdf"))
  291. defer source.Close()
  292. apiclient := testEnv.APIClient()
  293. resp, err := apiclient.ImageBuild(ctx,
  294. source.AsTarReader(t),
  295. types.ImageBuildOptions{
  296. Remove: true,
  297. ForceRemove: true,
  298. })
  299. assert.NilError(t, err)
  300. _, err = io.Copy(io.Discard, resp.Body)
  301. resp.Body.Close()
  302. assert.NilError(t, err)
  303. }
  304. // TestBuildMultiStageOnBuild checks that ONBUILD commands are applied to
  305. // multiple subsequent stages
  306. // #35652
  307. func TestBuildMultiStageOnBuild(t *testing.T) {
  308. skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.33"), "broken in earlier versions")
  309. defer setupTest(t)()
  310. // test both metadata and layer based commands as they may be implemented differently
  311. dockerfile := `FROM busybox AS stage1
  312. ONBUILD RUN echo 'foo' >somefile
  313. ONBUILD ENV bar=baz
  314. FROM stage1
  315. # fails if ONBUILD RUN fails
  316. RUN cat somefile
  317. FROM stage1
  318. RUN cat somefile`
  319. ctx := context.Background()
  320. source := fakecontext.New(t, "",
  321. fakecontext.WithDockerfile(dockerfile))
  322. defer source.Close()
  323. apiclient := testEnv.APIClient()
  324. resp, err := apiclient.ImageBuild(ctx,
  325. source.AsTarReader(t),
  326. types.ImageBuildOptions{
  327. Remove: true,
  328. ForceRemove: true,
  329. })
  330. out := bytes.NewBuffer(nil)
  331. assert.NilError(t, err)
  332. _, err = io.Copy(out, resp.Body)
  333. resp.Body.Close()
  334. assert.NilError(t, err)
  335. assert.Check(t, is.Contains(out.String(), "Successfully built"))
  336. imageIDs, err := getImageIDsFromBuild(out.Bytes())
  337. assert.NilError(t, err)
  338. assert.Assert(t, is.Equal(3, len(imageIDs)))
  339. image, _, err := apiclient.ImageInspectWithRaw(context.Background(), imageIDs[2])
  340. assert.NilError(t, err)
  341. assert.Check(t, is.Contains(image.Config.Env, "bar=baz"))
  342. }
  343. // #35403 #36122
  344. func TestBuildUncleanTarFilenames(t *testing.T) {
  345. skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.37"), "broken in earlier versions")
  346. skip.If(t, testEnv.DaemonInfo.OSType == "windows", "FIXME")
  347. ctx := context.TODO()
  348. defer setupTest(t)()
  349. dockerfile := `FROM scratch
  350. COPY foo /
  351. FROM scratch
  352. COPY bar /`
  353. buf := bytes.NewBuffer(nil)
  354. w := tar.NewWriter(buf)
  355. writeTarRecord(t, w, "Dockerfile", dockerfile)
  356. writeTarRecord(t, w, "../foo", "foocontents0")
  357. writeTarRecord(t, w, "/bar", "barcontents0")
  358. err := w.Close()
  359. assert.NilError(t, err)
  360. apiclient := testEnv.APIClient()
  361. resp, err := apiclient.ImageBuild(ctx,
  362. buf,
  363. types.ImageBuildOptions{
  364. Remove: true,
  365. ForceRemove: true,
  366. })
  367. out := bytes.NewBuffer(nil)
  368. assert.NilError(t, err)
  369. _, err = io.Copy(out, resp.Body)
  370. resp.Body.Close()
  371. assert.NilError(t, err)
  372. // repeat with changed data should not cause cache hits
  373. buf = bytes.NewBuffer(nil)
  374. w = tar.NewWriter(buf)
  375. writeTarRecord(t, w, "Dockerfile", dockerfile)
  376. writeTarRecord(t, w, "../foo", "foocontents1")
  377. writeTarRecord(t, w, "/bar", "barcontents1")
  378. err = w.Close()
  379. assert.NilError(t, err)
  380. resp, err = apiclient.ImageBuild(ctx,
  381. buf,
  382. types.ImageBuildOptions{
  383. Remove: true,
  384. ForceRemove: true,
  385. })
  386. out = bytes.NewBuffer(nil)
  387. assert.NilError(t, err)
  388. _, err = io.Copy(out, resp.Body)
  389. resp.Body.Close()
  390. assert.NilError(t, err)
  391. assert.Assert(t, !strings.Contains(out.String(), "Using cache"))
  392. }
  393. // docker/for-linux#135
  394. // #35641
  395. func TestBuildMultiStageLayerLeak(t *testing.T) {
  396. skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.37"), "broken in earlier versions")
  397. ctx := context.TODO()
  398. defer setupTest(t)()
  399. // all commands need to match until COPY
  400. dockerfile := `FROM busybox
  401. WORKDIR /foo
  402. COPY foo .
  403. FROM busybox
  404. WORKDIR /foo
  405. COPY bar .
  406. RUN [ -f bar ]
  407. RUN [ ! -f foo ]
  408. `
  409. source := fakecontext.New(t, "",
  410. fakecontext.WithFile("foo", "0"),
  411. fakecontext.WithFile("bar", "1"),
  412. fakecontext.WithDockerfile(dockerfile))
  413. defer source.Close()
  414. apiclient := testEnv.APIClient()
  415. resp, err := apiclient.ImageBuild(ctx,
  416. source.AsTarReader(t),
  417. types.ImageBuildOptions{
  418. Remove: true,
  419. ForceRemove: true,
  420. })
  421. out := bytes.NewBuffer(nil)
  422. assert.NilError(t, err)
  423. _, err = io.Copy(out, resp.Body)
  424. resp.Body.Close()
  425. assert.NilError(t, err)
  426. assert.Check(t, is.Contains(out.String(), "Successfully built"))
  427. }
  428. // #37581
  429. // #40444 (Windows Containers only)
  430. func TestBuildWithHugeFile(t *testing.T) {
  431. ctx := context.TODO()
  432. defer setupTest(t)()
  433. dockerfile := `FROM busybox
  434. `
  435. if testEnv.DaemonInfo.OSType == "windows" {
  436. dockerfile += `# create a file with size of 8GB
  437. RUN powershell "fsutil.exe file createnew bigfile.txt 8589934592 ; dir bigfile.txt"`
  438. } else {
  439. dockerfile += `# create a sparse file with size over 8GB
  440. RUN for g in $(seq 0 8); do dd if=/dev/urandom of=rnd bs=1K count=1 seek=$((1024*1024*g)) status=none; done && \
  441. ls -la rnd && du -sk rnd`
  442. }
  443. buf := bytes.NewBuffer(nil)
  444. w := tar.NewWriter(buf)
  445. writeTarRecord(t, w, "Dockerfile", dockerfile)
  446. err := w.Close()
  447. assert.NilError(t, err)
  448. apiclient := testEnv.APIClient()
  449. resp, err := apiclient.ImageBuild(ctx,
  450. buf,
  451. types.ImageBuildOptions{
  452. Remove: true,
  453. ForceRemove: true,
  454. })
  455. out := bytes.NewBuffer(nil)
  456. assert.NilError(t, err)
  457. _, err = io.Copy(out, resp.Body)
  458. resp.Body.Close()
  459. assert.NilError(t, err)
  460. assert.Check(t, is.Contains(out.String(), "Successfully built"))
  461. }
  462. func TestBuildWCOWSandboxSize(t *testing.T) {
  463. t.Skip("FLAKY_TEST that needs to be fixed; see https://github.com/moby/moby/issues/42743")
  464. skip.If(t, testEnv.DaemonInfo.OSType != "windows", "only Windows has sandbox size control")
  465. ctx := context.TODO()
  466. defer setupTest(t)()
  467. dockerfile := `FROM busybox AS intermediate
  468. WORKDIR C:\\stuff
  469. # Create and delete a 21GB file
  470. RUN fsutil file createnew C:\\stuff\\bigfile_0.txt 22548578304 && del bigfile_0.txt
  471. # Create three 7GB files
  472. RUN fsutil file createnew C:\\stuff\\bigfile_1.txt 7516192768
  473. RUN fsutil file createnew C:\\stuff\\bigfile_2.txt 7516192768
  474. RUN fsutil file createnew C:\\stuff\\bigfile_3.txt 7516192768
  475. # Copy that 21GB of data out into a new target
  476. FROM busybox
  477. COPY --from=intermediate C:\\stuff C:\\stuff
  478. `
  479. buf := bytes.NewBuffer(nil)
  480. w := tar.NewWriter(buf)
  481. writeTarRecord(t, w, "Dockerfile", dockerfile)
  482. err := w.Close()
  483. assert.NilError(t, err)
  484. apiclient := testEnv.APIClient()
  485. resp, err := apiclient.ImageBuild(ctx,
  486. buf,
  487. types.ImageBuildOptions{
  488. Remove: true,
  489. ForceRemove: true,
  490. })
  491. out := bytes.NewBuffer(nil)
  492. assert.NilError(t, err)
  493. _, err = io.Copy(out, resp.Body)
  494. resp.Body.Close()
  495. assert.NilError(t, err)
  496. // The test passes if either:
  497. // - the image build succeeded; or
  498. // - The "COPY --from=intermediate" step ran out of space during re-exec'd writing of the transport layer information to hcsshim's temp directory
  499. // The latter case means we finished the COPY operation, so the sandbox must have been larger than 20GB, which was the test,
  500. // and _then_ ran out of space on the host during `importLayer` in the WindowsFilter graph driver, while committing the layer.
  501. // See https://github.com/moby/moby/pull/41636#issuecomment-723038517 for more details on the operations being done here.
  502. // Specifically, this happens on the Docker Jenkins CI Windows-RS5 build nodes.
  503. // The two parts of the acceptable-failure case are on different lines, so we need two regexp checks.
  504. assert.Check(t, is.Regexp("Successfully built|COPY --from=intermediate", out.String()))
  505. assert.Check(t, is.Regexp("Successfully built|re-exec error: exit status 1: output: write.*daemon\\\\\\\\tmp\\\\\\\\hcs.*bigfile_[1-3].txt: There is not enough space on the disk.", out.String()))
  506. }
  507. func TestBuildWithEmptyDockerfile(t *testing.T) {
  508. skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.40"), "broken in earlier versions")
  509. ctx := context.TODO()
  510. t.Cleanup(setupTest(t))
  511. tests := []struct {
  512. name string
  513. dockerfile string
  514. expectedErr string
  515. }{
  516. {
  517. name: "empty-dockerfile",
  518. dockerfile: "",
  519. expectedErr: "cannot be empty",
  520. },
  521. {
  522. name: "empty-lines-dockerfile",
  523. dockerfile: `
  524. `,
  525. expectedErr: "file with no instructions",
  526. },
  527. {
  528. name: "comment-only-dockerfile",
  529. dockerfile: `# this is a comment`,
  530. expectedErr: "file with no instructions",
  531. },
  532. }
  533. apiclient := testEnv.APIClient()
  534. for _, tc := range tests {
  535. tc := tc
  536. t.Run(tc.name, func(t *testing.T) {
  537. t.Parallel()
  538. buf := bytes.NewBuffer(nil)
  539. w := tar.NewWriter(buf)
  540. writeTarRecord(t, w, "Dockerfile", tc.dockerfile)
  541. err := w.Close()
  542. assert.NilError(t, err)
  543. _, err = apiclient.ImageBuild(ctx,
  544. buf,
  545. types.ImageBuildOptions{
  546. Remove: true,
  547. ForceRemove: true,
  548. })
  549. assert.Check(t, is.Contains(err.Error(), tc.expectedErr))
  550. })
  551. }
  552. }
  553. func TestBuildPreserveOwnership(t *testing.T) {
  554. skip.If(t, testEnv.DaemonInfo.OSType == "windows", "FIXME")
  555. skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.40"), "broken in earlier versions")
  556. ctx := context.Background()
  557. dockerfile, err := os.ReadFile("testdata/Dockerfile." + t.Name())
  558. assert.NilError(t, err)
  559. source := fakecontext.New(t, "", fakecontext.WithDockerfile(string(dockerfile)))
  560. defer source.Close()
  561. apiclient := testEnv.APIClient()
  562. for _, target := range []string{"copy_from", "copy_from_chowned"} {
  563. t.Run(target, func(t *testing.T) {
  564. resp, err := apiclient.ImageBuild(
  565. ctx,
  566. source.AsTarReader(t),
  567. types.ImageBuildOptions{
  568. Remove: true,
  569. ForceRemove: true,
  570. Target: target,
  571. },
  572. )
  573. assert.NilError(t, err)
  574. out := bytes.NewBuffer(nil)
  575. _, err = io.Copy(out, resp.Body)
  576. _ = resp.Body.Close()
  577. if err != nil {
  578. t.Log(out)
  579. }
  580. assert.NilError(t, err)
  581. })
  582. }
  583. }
  584. func TestBuildPlatformInvalid(t *testing.T) {
  585. skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.40"), "experimental in older versions")
  586. ctx := context.Background()
  587. defer setupTest(t)()
  588. dockerfile := `FROM busybox
  589. `
  590. buf := bytes.NewBuffer(nil)
  591. w := tar.NewWriter(buf)
  592. writeTarRecord(t, w, "Dockerfile", dockerfile)
  593. err := w.Close()
  594. assert.NilError(t, err)
  595. apiclient := testEnv.APIClient()
  596. _, err = apiclient.ImageBuild(ctx,
  597. buf,
  598. types.ImageBuildOptions{
  599. Remove: true,
  600. ForceRemove: true,
  601. Platform: "foobar",
  602. })
  603. assert.Assert(t, err != nil)
  604. assert.ErrorContains(t, err, "unknown operating system or architecture")
  605. assert.Assert(t, errdefs.IsInvalidParameter(err))
  606. }
  607. func writeTarRecord(t *testing.T, w *tar.Writer, fn, contents string) {
  608. err := w.WriteHeader(&tar.Header{
  609. Name: fn,
  610. Mode: 0600,
  611. Size: int64(len(contents)),
  612. Typeflag: '0',
  613. })
  614. assert.NilError(t, err)
  615. _, err = w.Write([]byte(contents))
  616. assert.NilError(t, err)
  617. }
  618. type buildLine struct {
  619. Stream string
  620. Aux struct {
  621. ID string
  622. }
  623. }
  624. func getImageIDsFromBuild(output []byte) ([]string, error) {
  625. var ids []string
  626. for _, line := range bytes.Split(output, []byte("\n")) {
  627. if len(line) == 0 {
  628. continue
  629. }
  630. entry := buildLine{}
  631. if err := json.Unmarshal(line, &entry); err != nil {
  632. return nil, err
  633. }
  634. if entry.Aux.ID != "" {
  635. ids = append(ids, entry.Aux.ID)
  636. }
  637. }
  638. return ids, nil
  639. }