build.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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/distribution/reference"
  15. "github.com/docker/docker/api"
  16. "github.com/docker/docker/api/types"
  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/httputils"
  22. "github.com/docker/docker/pkg/jsonmessage"
  23. flag "github.com/docker/docker/pkg/mflag"
  24. "github.com/docker/docker/pkg/progress"
  25. "github.com/docker/docker/pkg/streamformatter"
  26. "github.com/docker/docker/pkg/ulimit"
  27. "github.com/docker/docker/pkg/units"
  28. "github.com/docker/docker/pkg/urlutil"
  29. "github.com/docker/docker/registry"
  30. tagpkg "github.com/docker/docker/tag"
  31. "github.com/docker/docker/utils"
  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 = utils.ReadDockerIgnore(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 deamon 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. ref, err := reference.ParseNamed(rawRepo)
  229. if err != nil {
  230. return "", err
  231. }
  232. if err := registry.ValidateRepositoryName(ref); err != nil {
  233. return "", err
  234. }
  235. return rawRepo, nil
  236. }
  237. // isUNC returns true if the path is UNC (one starting \\). It always returns
  238. // false on Linux.
  239. func isUNC(path string) bool {
  240. return runtime.GOOS == "windows" && strings.HasPrefix(path, `\\`)
  241. }
  242. // getDockerfileRelPath uses the given context directory for a `docker build`
  243. // and returns the absolute path to the context directory, the relative path of
  244. // the dockerfile in that context directory, and a non-nil error on success.
  245. func getDockerfileRelPath(givenContextDir, givenDockerfile string) (absContextDir, relDockerfile string, err error) {
  246. if absContextDir, err = filepath.Abs(givenContextDir); err != nil {
  247. return "", "", fmt.Errorf("unable to get absolute context directory: %v", err)
  248. }
  249. // The context dir might be a symbolic link, so follow it to the actual
  250. // target directory.
  251. //
  252. // FIXME. We use isUNC (always false on non-Windows platforms) to workaround
  253. // an issue in golang. On Windows, EvalSymLinks does not work on UNC file
  254. // paths (those starting with \\). This hack means that when using links
  255. // on UNC paths, they will not be followed.
  256. if !isUNC(absContextDir) {
  257. absContextDir, err = filepath.EvalSymlinks(absContextDir)
  258. if err != nil {
  259. return "", "", fmt.Errorf("unable to evaluate symlinks in context path: %v", err)
  260. }
  261. }
  262. stat, err := os.Lstat(absContextDir)
  263. if err != nil {
  264. return "", "", fmt.Errorf("unable to stat context directory %q: %v", absContextDir, err)
  265. }
  266. if !stat.IsDir() {
  267. return "", "", fmt.Errorf("context must be a directory: %s", absContextDir)
  268. }
  269. absDockerfile := givenDockerfile
  270. if absDockerfile == "" {
  271. // No -f/--file was specified so use the default relative to the
  272. // context directory.
  273. absDockerfile = filepath.Join(absContextDir, api.DefaultDockerfileName)
  274. // Just to be nice ;-) look for 'dockerfile' too but only
  275. // use it if we found it, otherwise ignore this check
  276. if _, err = os.Lstat(absDockerfile); os.IsNotExist(err) {
  277. altPath := filepath.Join(absContextDir, strings.ToLower(api.DefaultDockerfileName))
  278. if _, err = os.Lstat(altPath); err == nil {
  279. absDockerfile = altPath
  280. }
  281. }
  282. }
  283. // If not already an absolute path, the Dockerfile path should be joined to
  284. // the base directory.
  285. if !filepath.IsAbs(absDockerfile) {
  286. absDockerfile = filepath.Join(absContextDir, absDockerfile)
  287. }
  288. // Evaluate symlinks in the path to the Dockerfile too.
  289. //
  290. // FIXME. We use isUNC (always false on non-Windows platforms) to workaround
  291. // an issue in golang. On Windows, EvalSymLinks does not work on UNC file
  292. // paths (those starting with \\). This hack means that when using links
  293. // on UNC paths, they will not be followed.
  294. if !isUNC(absDockerfile) {
  295. absDockerfile, err = filepath.EvalSymlinks(absDockerfile)
  296. if err != nil {
  297. return "", "", fmt.Errorf("unable to evaluate symlinks in Dockerfile path: %v", err)
  298. }
  299. }
  300. if _, err := os.Lstat(absDockerfile); err != nil {
  301. if os.IsNotExist(err) {
  302. return "", "", fmt.Errorf("Cannot locate Dockerfile: %q", absDockerfile)
  303. }
  304. return "", "", fmt.Errorf("unable to stat Dockerfile: %v", err)
  305. }
  306. if relDockerfile, err = filepath.Rel(absContextDir, absDockerfile); err != nil {
  307. return "", "", fmt.Errorf("unable to get relative Dockerfile path: %v", err)
  308. }
  309. if strings.HasPrefix(relDockerfile, ".."+string(filepath.Separator)) {
  310. return "", "", fmt.Errorf("The Dockerfile (%s) must be within the build context (%s)", givenDockerfile, givenContextDir)
  311. }
  312. return absContextDir, relDockerfile, nil
  313. }
  314. // writeToFile copies from the given reader and writes it to a file with the
  315. // given filename.
  316. func writeToFile(r io.Reader, filename string) error {
  317. file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0600))
  318. if err != nil {
  319. return fmt.Errorf("unable to create file: %v", err)
  320. }
  321. defer file.Close()
  322. if _, err := io.Copy(file, r); err != nil {
  323. return fmt.Errorf("unable to write file: %v", err)
  324. }
  325. return nil
  326. }
  327. // getContextFromReader will read the contents of the given reader as either a
  328. // Dockerfile or tar archive to be extracted to a temporary directory used as
  329. // the context directory. Returns the absolute path to the temporary context
  330. // directory, the relative path of the dockerfile in that context directory,
  331. // and a non-nil error on success.
  332. func getContextFromReader(r io.Reader, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  333. buf := bufio.NewReader(r)
  334. magic, err := buf.Peek(archive.HeaderSize)
  335. if err != nil && err != io.EOF {
  336. return "", "", fmt.Errorf("failed to peek context header from STDIN: %v", err)
  337. }
  338. if absContextDir, err = ioutil.TempDir("", "docker-build-context-"); err != nil {
  339. return "", "", fmt.Errorf("unbale to create temporary context directory: %v", err)
  340. }
  341. defer func(d string) {
  342. if err != nil {
  343. os.RemoveAll(d)
  344. }
  345. }(absContextDir)
  346. if !archive.IsArchive(magic) { // Input should be read as a Dockerfile.
  347. // -f option has no meaning when we're reading it from stdin,
  348. // so just use our default Dockerfile name
  349. relDockerfile = api.DefaultDockerfileName
  350. return absContextDir, relDockerfile, writeToFile(buf, filepath.Join(absContextDir, relDockerfile))
  351. }
  352. if err := archive.Untar(buf, absContextDir, nil); err != nil {
  353. return "", "", fmt.Errorf("unable to extract stdin to temporary context directory: %v", err)
  354. }
  355. return getDockerfileRelPath(absContextDir, dockerfileName)
  356. }
  357. // getContextFromGitURL uses a Git URL as context for a `docker build`. The
  358. // git repo is cloned into a temporary directory used as the context directory.
  359. // Returns the absolute path to the temporary context directory, the relative
  360. // path of the dockerfile in that context directory, and a non-nil error on
  361. // success.
  362. func getContextFromGitURL(gitURL, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  363. if absContextDir, err = utils.GitClone(gitURL); err != nil {
  364. return "", "", fmt.Errorf("unable to 'git clone' to temporary context directory: %v", err)
  365. }
  366. return getDockerfileRelPath(absContextDir, dockerfileName)
  367. }
  368. // getContextFromURL uses a remote URL as context for a `docker build`. The
  369. // remote resource is downloaded as either a Dockerfile or a context tar
  370. // archive and stored in a temporary directory used as the context directory.
  371. // Returns the absolute path to the temporary context directory, the relative
  372. // path of the dockerfile in that context directory, and a non-nil error on
  373. // success.
  374. func getContextFromURL(out io.Writer, remoteURL, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  375. response, err := httputils.Download(remoteURL)
  376. if err != nil {
  377. return "", "", fmt.Errorf("unable to download remote context %s: %v", remoteURL, err)
  378. }
  379. defer response.Body.Close()
  380. progressOutput := streamformatter.NewStreamFormatter().NewProgressOutput(out, true)
  381. // Pass the response body through a progress reader.
  382. progReader := progress.NewProgressReader(response.Body, progressOutput, response.ContentLength, "", fmt.Sprintf("Downloading build context from remote url: %s", remoteURL))
  383. return getContextFromReader(progReader, dockerfileName)
  384. }
  385. // getContextFromLocalDir uses the given local directory as context for a
  386. // `docker build`. Returns the absolute path to the local context directory,
  387. // the relative path of the dockerfile in that context directory, and a non-nil
  388. // error on success.
  389. func getContextFromLocalDir(localDir, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  390. // When using a local context directory, when the Dockerfile is specified
  391. // with the `-f/--file` option then it is considered relative to the
  392. // current directory and not the context directory.
  393. if dockerfileName != "" {
  394. if dockerfileName, err = filepath.Abs(dockerfileName); err != nil {
  395. return "", "", fmt.Errorf("unable to get absolute path to Dockerfile: %v", err)
  396. }
  397. }
  398. return getDockerfileRelPath(localDir, dockerfileName)
  399. }
  400. var dockerfileFromLinePattern = regexp.MustCompile(`(?i)^[\s]*FROM[ \f\r\t\v]+(?P<image>[^ \f\r\t\v\n#]+)`)
  401. type trustedDockerfile struct {
  402. *os.File
  403. size int64
  404. }
  405. func (td *trustedDockerfile) Close() error {
  406. td.File.Close()
  407. return os.Remove(td.File.Name())
  408. }
  409. // resolvedTag records the repository, tag, and resolved digest reference
  410. // from a Dockerfile rewrite.
  411. type resolvedTag struct {
  412. repoInfo *registry.RepositoryInfo
  413. digestRef reference.Canonical
  414. tagRef reference.NamedTagged
  415. }
  416. // rewriteDockerfileFrom rewrites the given Dockerfile by resolving images in
  417. // "FROM <image>" instructions to a digest reference. `translator` is a
  418. // function that takes a repository name and tag reference and returns a
  419. // trusted digest reference.
  420. func rewriteDockerfileFrom(dockerfileName string, translator func(reference.NamedTagged) (reference.Canonical, error)) (newDockerfile *trustedDockerfile, resolvedTags []*resolvedTag, err error) {
  421. dockerfile, err := os.Open(dockerfileName)
  422. if err != nil {
  423. return nil, nil, fmt.Errorf("unable to open Dockerfile: %v", err)
  424. }
  425. defer dockerfile.Close()
  426. scanner := bufio.NewScanner(dockerfile)
  427. // Make a tempfile to store the rewritten Dockerfile.
  428. tempFile, err := ioutil.TempFile("", "trusted-dockerfile-")
  429. if err != nil {
  430. return nil, nil, fmt.Errorf("unable to make temporary trusted Dockerfile: %v", err)
  431. }
  432. trustedFile := &trustedDockerfile{
  433. File: tempFile,
  434. }
  435. defer func() {
  436. if err != nil {
  437. // Close the tempfile if there was an error during Notary lookups.
  438. // Otherwise the caller should close it.
  439. trustedFile.Close()
  440. }
  441. }()
  442. // Scan the lines of the Dockerfile, looking for a "FROM" line.
  443. for scanner.Scan() {
  444. line := scanner.Text()
  445. matches := dockerfileFromLinePattern.FindStringSubmatch(line)
  446. if matches != nil && matches[1] != "scratch" {
  447. // Replace the line with a resolved "FROM repo@digest"
  448. ref, err := reference.ParseNamed(matches[1])
  449. if err != nil {
  450. return nil, nil, err
  451. }
  452. digested := false
  453. switch ref.(type) {
  454. case reference.Tagged:
  455. case reference.Digested:
  456. digested = true
  457. default:
  458. ref, err = reference.WithTag(ref, tagpkg.DefaultTag)
  459. if err != nil {
  460. return nil, nil, err
  461. }
  462. }
  463. repoInfo, err := registry.ParseRepositoryInfo(ref)
  464. if err != nil {
  465. return nil, nil, fmt.Errorf("unable to parse repository info %q: %v", ref.String(), err)
  466. }
  467. if !digested && isTrusted() {
  468. trustedRef, err := translator(ref.(reference.NamedTagged))
  469. if err != nil {
  470. return nil, nil, err
  471. }
  472. line = dockerfileFromLinePattern.ReplaceAllLiteralString(line, fmt.Sprintf("FROM %s", trustedRef.String()))
  473. resolvedTags = append(resolvedTags, &resolvedTag{
  474. repoInfo: repoInfo,
  475. digestRef: trustedRef,
  476. tagRef: ref.(reference.NamedTagged),
  477. })
  478. }
  479. }
  480. n, err := fmt.Fprintln(tempFile, line)
  481. if err != nil {
  482. return nil, nil, err
  483. }
  484. trustedFile.size += int64(n)
  485. }
  486. tempFile.Seek(0, os.SEEK_SET)
  487. return trustedFile, resolvedTags, scanner.Err()
  488. }
  489. // replaceDockerfileTarWrapper wraps the given input tar archive stream and
  490. // replaces the entry with the given Dockerfile name with the contents of the
  491. // new Dockerfile. Returns a new tar archive stream with the replaced
  492. // Dockerfile.
  493. func replaceDockerfileTarWrapper(inputTarStream io.ReadCloser, newDockerfile *trustedDockerfile, dockerfileName string) io.ReadCloser {
  494. pipeReader, pipeWriter := io.Pipe()
  495. go func() {
  496. tarReader := tar.NewReader(inputTarStream)
  497. tarWriter := tar.NewWriter(pipeWriter)
  498. defer inputTarStream.Close()
  499. for {
  500. hdr, err := tarReader.Next()
  501. if err == io.EOF {
  502. // Signals end of archive.
  503. tarWriter.Close()
  504. pipeWriter.Close()
  505. return
  506. }
  507. if err != nil {
  508. pipeWriter.CloseWithError(err)
  509. return
  510. }
  511. var content io.Reader = tarReader
  512. if hdr.Name == dockerfileName {
  513. // This entry is the Dockerfile. Since the tar archive was
  514. // generated from a directory on the local filesystem, the
  515. // Dockerfile will only appear once in the archive.
  516. hdr.Size = newDockerfile.size
  517. content = newDockerfile
  518. }
  519. if err := tarWriter.WriteHeader(hdr); err != nil {
  520. pipeWriter.CloseWithError(err)
  521. return
  522. }
  523. if _, err := io.Copy(tarWriter, content); err != nil {
  524. pipeWriter.CloseWithError(err)
  525. return
  526. }
  527. }
  528. }()
  529. return pipeReader
  530. }