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