build.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. package client
  2. import (
  3. "archive/tar"
  4. "bufio"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "regexp"
  12. "runtime"
  13. "strings"
  14. "github.com/docker/docker/api"
  15. "github.com/docker/docker/api/types"
  16. "github.com/docker/docker/builder/dockerignore"
  17. Cli "github.com/docker/docker/cli"
  18. "github.com/docker/docker/opts"
  19. "github.com/docker/docker/pkg/archive"
  20. "github.com/docker/docker/pkg/fileutils"
  21. "github.com/docker/docker/pkg/gitutils"
  22. "github.com/docker/docker/pkg/httputils"
  23. "github.com/docker/docker/pkg/jsonmessage"
  24. flag "github.com/docker/docker/pkg/mflag"
  25. "github.com/docker/docker/pkg/progress"
  26. "github.com/docker/docker/pkg/streamformatter"
  27. "github.com/docker/docker/pkg/ulimit"
  28. "github.com/docker/docker/pkg/urlutil"
  29. "github.com/docker/docker/reference"
  30. "github.com/docker/docker/utils"
  31. "github.com/docker/go-units"
  32. )
  33. // CmdBuild builds a new image from the source code at a given path.
  34. //
  35. // If '-' is provided instead of a path or URL, Docker will build an image from either a Dockerfile or tar archive read from STDIN.
  36. //
  37. // Usage: docker build [OPTIONS] PATH | URL | -
  38. func (cli *DockerCli) CmdBuild(args ...string) error {
  39. cmd := Cli.Subcmd("build", []string{"PATH | URL | -"}, Cli.DockerCommands["build"].Description, true)
  40. flTags := opts.NewListOpts(validateTag)
  41. cmd.Var(&flTags, []string{"t", "-tag"}, "Name and optionally a tag in the 'name:tag' format")
  42. suppressOutput := cmd.Bool([]string{"q", "-quiet"}, false, "Suppress the verbose output generated by the containers")
  43. noCache := cmd.Bool([]string{"-no-cache"}, false, "Do not use cache when building the image")
  44. rm := cmd.Bool([]string{"-rm"}, true, "Remove intermediate containers after a successful build")
  45. forceRm := cmd.Bool([]string{"-force-rm"}, false, "Always remove intermediate containers")
  46. pull := cmd.Bool([]string{"-pull"}, false, "Always attempt to pull a newer version of the image")
  47. dockerfileName := cmd.String([]string{"f", "-file"}, "", "Name of the Dockerfile (Default is 'PATH/Dockerfile')")
  48. flMemoryString := cmd.String([]string{"m", "-memory"}, "", "Memory limit")
  49. flMemorySwap := cmd.String([]string{"-memory-swap"}, "", "Total memory (memory + swap), '-1' to disable swap")
  50. flShmSize := cmd.String([]string{"-shm-size"}, "", "Size of /dev/shm, default value is 64MB")
  51. flCPUShares := cmd.Int64([]string{"#c", "-cpu-shares"}, 0, "CPU shares (relative weight)")
  52. flCPUPeriod := cmd.Int64([]string{"-cpu-period"}, 0, "Limit the CPU CFS (Completely Fair Scheduler) period")
  53. flCPUQuota := cmd.Int64([]string{"-cpu-quota"}, 0, "Limit the CPU CFS (Completely Fair Scheduler) quota")
  54. flCPUSetCpus := cmd.String([]string{"-cpuset-cpus"}, "", "CPUs in which to allow execution (0-3, 0,1)")
  55. flCPUSetMems := cmd.String([]string{"-cpuset-mems"}, "", "MEMs in which to allow execution (0-3, 0,1)")
  56. flCgroupParent := cmd.String([]string{"-cgroup-parent"}, "", "Optional parent cgroup for the container")
  57. flBuildArg := opts.NewListOpts(opts.ValidateEnv)
  58. cmd.Var(&flBuildArg, []string{"-build-arg"}, "Set build-time variables")
  59. isolation := cmd.String([]string{"-isolation"}, "", "Container isolation level")
  60. ulimits := make(map[string]*ulimit.Ulimit)
  61. flUlimits := opts.NewUlimitOpt(&ulimits)
  62. cmd.Var(flUlimits, []string{"-ulimit"}, "Ulimit options")
  63. cmd.Require(flag.Exact, 1)
  64. // For trusted pull on "FROM <image>" instruction.
  65. addTrustedFlags(cmd, true)
  66. cmd.ParseFlags(args, true)
  67. var (
  68. context io.ReadCloser
  69. isRemote bool
  70. err error
  71. )
  72. _, err = exec.LookPath("git")
  73. hasGit := err == nil
  74. specifiedContext := cmd.Arg(0)
  75. var (
  76. contextDir string
  77. tempDir string
  78. relDockerfile string
  79. )
  80. switch {
  81. case specifiedContext == "-":
  82. tempDir, relDockerfile, err = getContextFromReader(cli.in, *dockerfileName)
  83. case urlutil.IsGitURL(specifiedContext) && hasGit:
  84. tempDir, relDockerfile, err = getContextFromGitURL(specifiedContext, *dockerfileName)
  85. case urlutil.IsURL(specifiedContext):
  86. tempDir, relDockerfile, err = getContextFromURL(cli.out, specifiedContext, *dockerfileName)
  87. default:
  88. contextDir, relDockerfile, err = getContextFromLocalDir(specifiedContext, *dockerfileName)
  89. }
  90. if err != nil {
  91. return fmt.Errorf("unable to prepare context: %s", err)
  92. }
  93. if tempDir != "" {
  94. defer os.RemoveAll(tempDir)
  95. contextDir = tempDir
  96. }
  97. // Resolve the FROM lines in the Dockerfile to trusted digest references
  98. // using Notary. On a successful build, we must tag the resolved digests
  99. // to the original name specified in the Dockerfile.
  100. newDockerfile, resolvedTags, err := rewriteDockerfileFrom(filepath.Join(contextDir, relDockerfile), cli.trustedReference)
  101. if err != nil {
  102. return fmt.Errorf("unable to process Dockerfile: %v", err)
  103. }
  104. defer newDockerfile.Close()
  105. // And canonicalize dockerfile name to a platform-independent one
  106. relDockerfile, err = archive.CanonicalTarNameForPath(relDockerfile)
  107. if err != nil {
  108. return fmt.Errorf("cannot canonicalize dockerfile path %s: %v", relDockerfile, err)
  109. }
  110. f, err := os.Open(filepath.Join(contextDir, ".dockerignore"))
  111. if err != nil && !os.IsNotExist(err) {
  112. return err
  113. }
  114. var excludes []string
  115. if err == nil {
  116. excludes, err = dockerignore.ReadAll(f)
  117. if err != nil {
  118. return err
  119. }
  120. }
  121. if err := utils.ValidateContextDirectory(contextDir, excludes); err != nil {
  122. return fmt.Errorf("Error checking context: '%s'.", err)
  123. }
  124. // If .dockerignore mentions .dockerignore or the Dockerfile
  125. // then make sure we send both files over to the daemon
  126. // because Dockerfile is, obviously, needed no matter what, and
  127. // .dockerignore is needed to know if either one needs to be
  128. // removed. The daemon will remove them for us, if needed, after it
  129. // parses the Dockerfile. Ignore errors here, as they will have been
  130. // caught by ValidateContextDirectory above.
  131. var includes = []string{"."}
  132. keepThem1, _ := fileutils.Matches(".dockerignore", excludes)
  133. keepThem2, _ := fileutils.Matches(relDockerfile, excludes)
  134. if keepThem1 || keepThem2 {
  135. includes = append(includes, ".dockerignore", relDockerfile)
  136. }
  137. context, err = archive.TarWithOptions(contextDir, &archive.TarOptions{
  138. Compression: archive.Uncompressed,
  139. ExcludePatterns: excludes,
  140. IncludeFiles: includes,
  141. })
  142. if err != nil {
  143. return err
  144. }
  145. // Wrap the tar archive to replace the Dockerfile entry with the rewritten
  146. // Dockerfile which uses trusted pulls.
  147. context = replaceDockerfileTarWrapper(context, newDockerfile, relDockerfile)
  148. // Setup an upload progress bar
  149. progressOutput := streamformatter.NewStreamFormatter().NewProgressOutput(cli.out, true)
  150. var body io.Reader = progress.NewProgressReader(context, progressOutput, 0, "", "Sending build context to Docker daemon")
  151. var memory int64
  152. if *flMemoryString != "" {
  153. parsedMemory, err := units.RAMInBytes(*flMemoryString)
  154. if err != nil {
  155. return err
  156. }
  157. memory = parsedMemory
  158. }
  159. var memorySwap int64
  160. if *flMemorySwap != "" {
  161. if *flMemorySwap == "-1" {
  162. memorySwap = -1
  163. } else {
  164. parsedMemorySwap, err := units.RAMInBytes(*flMemorySwap)
  165. if err != nil {
  166. return err
  167. }
  168. memorySwap = parsedMemorySwap
  169. }
  170. }
  171. var remoteContext string
  172. if isRemote {
  173. remoteContext = cmd.Arg(0)
  174. }
  175. options := types.ImageBuildOptions{
  176. Context: body,
  177. Memory: memory,
  178. MemorySwap: memorySwap,
  179. Tags: flTags.GetAll(),
  180. SuppressOutput: *suppressOutput,
  181. RemoteContext: remoteContext,
  182. NoCache: *noCache,
  183. Remove: *rm,
  184. ForceRemove: *forceRm,
  185. PullParent: *pull,
  186. Isolation: *isolation,
  187. CPUSetCPUs: *flCPUSetCpus,
  188. CPUSetMems: *flCPUSetMems,
  189. CPUShares: *flCPUShares,
  190. CPUQuota: *flCPUQuota,
  191. CPUPeriod: *flCPUPeriod,
  192. CgroupParent: *flCgroupParent,
  193. ShmSize: *flShmSize,
  194. Dockerfile: relDockerfile,
  195. Ulimits: flUlimits.GetList(),
  196. BuildArgs: flBuildArg.GetAll(),
  197. AuthConfigs: cli.configFile.AuthConfigs,
  198. }
  199. response, err := cli.client.ImageBuild(options)
  200. if err != nil {
  201. return err
  202. }
  203. err = jsonmessage.DisplayJSONMessagesStream(response.Body, cli.out, cli.outFd, cli.isTerminalOut)
  204. if err != nil {
  205. if jerr, ok := err.(*jsonmessage.JSONError); ok {
  206. // If no error code is set, default to 1
  207. if jerr.Code == 0 {
  208. jerr.Code = 1
  209. }
  210. return Cli.StatusError{Status: jerr.Message, StatusCode: jerr.Code}
  211. }
  212. }
  213. // Windows: show error message about modified file permissions.
  214. if response.OSType == "windows" {
  215. fmt.Fprintln(cli.err, `SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.`)
  216. }
  217. // Since the build was successful, now we must tag any of the resolved
  218. // images from the above Dockerfile rewrite.
  219. for _, resolved := range resolvedTags {
  220. if err := cli.tagTrusted(resolved.digestRef, resolved.tagRef); err != nil {
  221. return err
  222. }
  223. }
  224. return nil
  225. }
  226. // validateTag checks if the given image name can be resolved.
  227. func validateTag(rawRepo string) (string, error) {
  228. _, err := reference.ParseNamed(rawRepo)
  229. if err != nil {
  230. return "", err
  231. }
  232. return rawRepo, nil
  233. }
  234. // isUNC returns true if the path is UNC (one starting \\). It always returns
  235. // false on Linux.
  236. func isUNC(path string) bool {
  237. return runtime.GOOS == "windows" && strings.HasPrefix(path, `\\`)
  238. }
  239. // getDockerfileRelPath uses the given context directory for a `docker build`
  240. // and returns the absolute path to the context directory, the relative path of
  241. // the dockerfile in that context directory, and a non-nil error on success.
  242. func getDockerfileRelPath(givenContextDir, givenDockerfile string) (absContextDir, relDockerfile string, err error) {
  243. if absContextDir, err = filepath.Abs(givenContextDir); err != nil {
  244. return "", "", fmt.Errorf("unable to get absolute context directory: %v", err)
  245. }
  246. // The context dir might be a symbolic link, so follow it to the actual
  247. // target directory.
  248. //
  249. // FIXME. We use isUNC (always false on non-Windows platforms) to workaround
  250. // an issue in golang. On Windows, EvalSymLinks does not work on UNC file
  251. // paths (those starting with \\). This hack means that when using links
  252. // on UNC paths, they will not be followed.
  253. if !isUNC(absContextDir) {
  254. absContextDir, err = filepath.EvalSymlinks(absContextDir)
  255. if err != nil {
  256. return "", "", fmt.Errorf("unable to evaluate symlinks in context path: %v", err)
  257. }
  258. }
  259. stat, err := os.Lstat(absContextDir)
  260. if err != nil {
  261. return "", "", fmt.Errorf("unable to stat context directory %q: %v", absContextDir, err)
  262. }
  263. if !stat.IsDir() {
  264. return "", "", fmt.Errorf("context must be a directory: %s", absContextDir)
  265. }
  266. absDockerfile := givenDockerfile
  267. if absDockerfile == "" {
  268. // No -f/--file was specified so use the default relative to the
  269. // context directory.
  270. absDockerfile = filepath.Join(absContextDir, api.DefaultDockerfileName)
  271. // Just to be nice ;-) look for 'dockerfile' too but only
  272. // use it if we found it, otherwise ignore this check
  273. if _, err = os.Lstat(absDockerfile); os.IsNotExist(err) {
  274. altPath := filepath.Join(absContextDir, strings.ToLower(api.DefaultDockerfileName))
  275. if _, err = os.Lstat(altPath); err == nil {
  276. absDockerfile = altPath
  277. }
  278. }
  279. }
  280. // If not already an absolute path, the Dockerfile path should be joined to
  281. // the base directory.
  282. if !filepath.IsAbs(absDockerfile) {
  283. absDockerfile = filepath.Join(absContextDir, absDockerfile)
  284. }
  285. // Evaluate symlinks in the path to the Dockerfile too.
  286. //
  287. // FIXME. We use isUNC (always false on non-Windows platforms) to workaround
  288. // an issue in golang. On Windows, EvalSymLinks does not work on UNC file
  289. // paths (those starting with \\). This hack means that when using links
  290. // on UNC paths, they will not be followed.
  291. if !isUNC(absDockerfile) {
  292. absDockerfile, err = filepath.EvalSymlinks(absDockerfile)
  293. if err != nil {
  294. return "", "", fmt.Errorf("unable to evaluate symlinks in Dockerfile path: %v", err)
  295. }
  296. }
  297. if _, err := os.Lstat(absDockerfile); err != nil {
  298. if os.IsNotExist(err) {
  299. return "", "", fmt.Errorf("Cannot locate Dockerfile: %q", absDockerfile)
  300. }
  301. return "", "", fmt.Errorf("unable to stat Dockerfile: %v", err)
  302. }
  303. if relDockerfile, err = filepath.Rel(absContextDir, absDockerfile); err != nil {
  304. return "", "", fmt.Errorf("unable to get relative Dockerfile path: %v", err)
  305. }
  306. if strings.HasPrefix(relDockerfile, ".."+string(filepath.Separator)) {
  307. return "", "", fmt.Errorf("The Dockerfile (%s) must be within the build context (%s)", givenDockerfile, givenContextDir)
  308. }
  309. return absContextDir, relDockerfile, nil
  310. }
  311. // writeToFile copies from the given reader and writes it to a file with the
  312. // given filename.
  313. func writeToFile(r io.Reader, filename string) error {
  314. file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0600))
  315. if err != nil {
  316. return fmt.Errorf("unable to create file: %v", err)
  317. }
  318. defer file.Close()
  319. if _, err := io.Copy(file, r); err != nil {
  320. return fmt.Errorf("unable to write file: %v", err)
  321. }
  322. return nil
  323. }
  324. // getContextFromReader will read the contents of the given reader as either a
  325. // Dockerfile or tar archive to be extracted to a temporary directory used as
  326. // the context directory. Returns the absolute path to the temporary context
  327. // directory, the relative path of the dockerfile in that context directory,
  328. // and a non-nil error on success.
  329. func getContextFromReader(r io.Reader, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  330. buf := bufio.NewReader(r)
  331. magic, err := buf.Peek(archive.HeaderSize)
  332. if err != nil && err != io.EOF {
  333. return "", "", fmt.Errorf("failed to peek context header from STDIN: %v", err)
  334. }
  335. if absContextDir, err = ioutil.TempDir("", "docker-build-context-"); err != nil {
  336. return "", "", fmt.Errorf("unbale to create temporary context directory: %v", err)
  337. }
  338. defer func(d string) {
  339. if err != nil {
  340. os.RemoveAll(d)
  341. }
  342. }(absContextDir)
  343. if !archive.IsArchive(magic) { // Input should be read as a Dockerfile.
  344. // -f option has no meaning when we're reading it from stdin,
  345. // so just use our default Dockerfile name
  346. relDockerfile = api.DefaultDockerfileName
  347. return absContextDir, relDockerfile, writeToFile(buf, filepath.Join(absContextDir, relDockerfile))
  348. }
  349. if err := archive.Untar(buf, absContextDir, nil); err != nil {
  350. return "", "", fmt.Errorf("unable to extract stdin to temporary context directory: %v", err)
  351. }
  352. return getDockerfileRelPath(absContextDir, dockerfileName)
  353. }
  354. // getContextFromGitURL uses a Git URL as context for a `docker build`. The
  355. // git repo is cloned into a temporary directory used as the context directory.
  356. // Returns the absolute path to the temporary context directory, the relative
  357. // path of the dockerfile in that context directory, and a non-nil error on
  358. // success.
  359. func getContextFromGitURL(gitURL, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  360. if absContextDir, err = gitutils.Clone(gitURL); err != nil {
  361. return "", "", fmt.Errorf("unable to 'git clone' to temporary context directory: %v", err)
  362. }
  363. return getDockerfileRelPath(absContextDir, dockerfileName)
  364. }
  365. // getContextFromURL uses a remote URL as context for a `docker build`. The
  366. // remote resource is downloaded as either a Dockerfile or a context tar
  367. // archive and stored in a temporary directory used as the context directory.
  368. // Returns the absolute path to the temporary context directory, the relative
  369. // path of the dockerfile in that context directory, and a non-nil error on
  370. // success.
  371. func getContextFromURL(out io.Writer, remoteURL, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  372. response, err := httputils.Download(remoteURL)
  373. if err != nil {
  374. return "", "", fmt.Errorf("unable to download remote context %s: %v", remoteURL, err)
  375. }
  376. defer response.Body.Close()
  377. progressOutput := streamformatter.NewStreamFormatter().NewProgressOutput(out, true)
  378. // Pass the response body through a progress reader.
  379. progReader := progress.NewProgressReader(response.Body, progressOutput, response.ContentLength, "", fmt.Sprintf("Downloading build context from remote url: %s", remoteURL))
  380. return getContextFromReader(progReader, dockerfileName)
  381. }
  382. // getContextFromLocalDir uses the given local directory as context for a
  383. // `docker build`. Returns the absolute path to the local context directory,
  384. // the relative path of the dockerfile in that context directory, and a non-nil
  385. // error on success.
  386. func getContextFromLocalDir(localDir, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  387. // When using a local context directory, when the Dockerfile is specified
  388. // with the `-f/--file` option then it is considered relative to the
  389. // current directory and not the context directory.
  390. if dockerfileName != "" {
  391. if dockerfileName, err = filepath.Abs(dockerfileName); err != nil {
  392. return "", "", fmt.Errorf("unable to get absolute path to Dockerfile: %v", err)
  393. }
  394. }
  395. return getDockerfileRelPath(localDir, dockerfileName)
  396. }
  397. var dockerfileFromLinePattern = regexp.MustCompile(`(?i)^[\s]*FROM[ \f\r\t\v]+(?P<image>[^ \f\r\t\v\n#]+)`)
  398. type trustedDockerfile struct {
  399. *os.File
  400. size int64
  401. }
  402. func (td *trustedDockerfile) Close() error {
  403. td.File.Close()
  404. return os.Remove(td.File.Name())
  405. }
  406. // resolvedTag records the repository, tag, and resolved digest reference
  407. // from a Dockerfile rewrite.
  408. type resolvedTag struct {
  409. digestRef reference.Canonical
  410. tagRef reference.NamedTagged
  411. }
  412. // rewriteDockerfileFrom rewrites the given Dockerfile by resolving images in
  413. // "FROM <image>" instructions to a digest reference. `translator` is a
  414. // function that takes a repository name and tag reference and returns a
  415. // trusted digest reference.
  416. func rewriteDockerfileFrom(dockerfileName string, translator func(reference.NamedTagged) (reference.Canonical, error)) (newDockerfile *trustedDockerfile, resolvedTags []*resolvedTag, err error) {
  417. dockerfile, err := os.Open(dockerfileName)
  418. if err != nil {
  419. return nil, nil, fmt.Errorf("unable to open Dockerfile: %v", err)
  420. }
  421. defer dockerfile.Close()
  422. scanner := bufio.NewScanner(dockerfile)
  423. // Make a tempfile to store the rewritten Dockerfile.
  424. tempFile, err := ioutil.TempFile("", "trusted-dockerfile-")
  425. if err != nil {
  426. return nil, nil, fmt.Errorf("unable to make temporary trusted Dockerfile: %v", err)
  427. }
  428. trustedFile := &trustedDockerfile{
  429. File: tempFile,
  430. }
  431. defer func() {
  432. if err != nil {
  433. // Close the tempfile if there was an error during Notary lookups.
  434. // Otherwise the caller should close it.
  435. trustedFile.Close()
  436. }
  437. }()
  438. // Scan the lines of the Dockerfile, looking for a "FROM" line.
  439. for scanner.Scan() {
  440. line := scanner.Text()
  441. matches := dockerfileFromLinePattern.FindStringSubmatch(line)
  442. if matches != nil && matches[1] != "scratch" {
  443. // Replace the line with a resolved "FROM repo@digest"
  444. ref, err := reference.ParseNamed(matches[1])
  445. if err != nil {
  446. return nil, nil, err
  447. }
  448. ref = reference.WithDefaultTag(ref)
  449. if ref, ok := ref.(reference.NamedTagged); ok && isTrusted() {
  450. trustedRef, err := translator(ref)
  451. if err != nil {
  452. return nil, nil, err
  453. }
  454. line = dockerfileFromLinePattern.ReplaceAllLiteralString(line, fmt.Sprintf("FROM %s", trustedRef.String()))
  455. resolvedTags = append(resolvedTags, &resolvedTag{
  456. digestRef: trustedRef,
  457. tagRef: ref,
  458. })
  459. }
  460. }
  461. n, err := fmt.Fprintln(tempFile, line)
  462. if err != nil {
  463. return nil, nil, err
  464. }
  465. trustedFile.size += int64(n)
  466. }
  467. tempFile.Seek(0, os.SEEK_SET)
  468. return trustedFile, resolvedTags, scanner.Err()
  469. }
  470. // replaceDockerfileTarWrapper wraps the given input tar archive stream and
  471. // replaces the entry with the given Dockerfile name with the contents of the
  472. // new Dockerfile. Returns a new tar archive stream with the replaced
  473. // Dockerfile.
  474. func replaceDockerfileTarWrapper(inputTarStream io.ReadCloser, newDockerfile *trustedDockerfile, dockerfileName string) io.ReadCloser {
  475. pipeReader, pipeWriter := io.Pipe()
  476. go func() {
  477. tarReader := tar.NewReader(inputTarStream)
  478. tarWriter := tar.NewWriter(pipeWriter)
  479. defer inputTarStream.Close()
  480. for {
  481. hdr, err := tarReader.Next()
  482. if err == io.EOF {
  483. // Signals end of archive.
  484. tarWriter.Close()
  485. pipeWriter.Close()
  486. return
  487. }
  488. if err != nil {
  489. pipeWriter.CloseWithError(err)
  490. return
  491. }
  492. var content io.Reader = tarReader
  493. if hdr.Name == dockerfileName {
  494. // This entry is the Dockerfile. Since the tar archive was
  495. // generated from a directory on the local filesystem, the
  496. // Dockerfile will only appear once in the archive.
  497. hdr.Size = newDockerfile.size
  498. content = newDockerfile
  499. }
  500. if err := tarWriter.WriteHeader(hdr); err != nil {
  501. pipeWriter.CloseWithError(err)
  502. return
  503. }
  504. if _, err := io.Copy(tarWriter, content); err != nil {
  505. pipeWriter.CloseWithError(err)
  506. return
  507. }
  508. }
  509. }()
  510. return pipeReader
  511. }