build.go 22 KB

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