build.go 21 KB

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