build.go 21 KB

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