build.go 22 KB

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