build.go 22 KB

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