build.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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"
  18. "github.com/docker/docker/builder/dockerignore"
  19. Cli "github.com/docker/docker/cli"
  20. "github.com/docker/docker/opts"
  21. "github.com/docker/docker/pkg/archive"
  22. "github.com/docker/docker/pkg/fileutils"
  23. "github.com/docker/docker/pkg/gitutils"
  24. "github.com/docker/docker/pkg/httputils"
  25. "github.com/docker/docker/pkg/ioutils"
  26. "github.com/docker/docker/pkg/jsonmessage"
  27. flag "github.com/docker/docker/pkg/mflag"
  28. "github.com/docker/docker/pkg/progress"
  29. "github.com/docker/docker/pkg/streamformatter"
  30. "github.com/docker/docker/pkg/urlutil"
  31. "github.com/docker/docker/reference"
  32. runconfigopts "github.com/docker/docker/runconfig/opts"
  33. "github.com/docker/engine-api/types"
  34. "github.com/docker/engine-api/types/container"
  35. "github.com/docker/go-units"
  36. )
  37. type translatorFunc func(reference.NamedTagged) (reference.Canonical, error)
  38. // CmdBuild builds a new image from the source code at a given path.
  39. //
  40. // If '-' is provided instead of a path or URL, Docker will build an image from either a Dockerfile or tar archive read from STDIN.
  41. //
  42. // Usage: docker build [OPTIONS] PATH | URL | -
  43. func (cli *DockerCli) CmdBuild(args ...string) error {
  44. cmd := Cli.Subcmd("build", []string{"PATH | URL | -"}, Cli.DockerCommands["build"].Description, true)
  45. flTags := opts.NewListOpts(validateTag)
  46. cmd.Var(&flTags, []string{"t", "-tag"}, "Name and optionally a tag in the 'name:tag' format")
  47. suppressOutput := cmd.Bool([]string{"q", "-quiet"}, false, "Suppress the build output and print image ID on success")
  48. noCache := cmd.Bool([]string{"-no-cache"}, false, "Do not use cache when building the image")
  49. rm := cmd.Bool([]string{"-rm"}, true, "Remove intermediate containers after a successful build")
  50. forceRm := cmd.Bool([]string{"-force-rm"}, false, "Always remove intermediate containers")
  51. pull := cmd.Bool([]string{"-pull"}, false, "Always attempt to pull a newer version of the image")
  52. dockerfileName := cmd.String([]string{"f", "-file"}, "", "Name of the Dockerfile (Default is 'PATH/Dockerfile')")
  53. flMemoryString := cmd.String([]string{"m", "-memory"}, "", "Memory limit")
  54. flMemorySwap := cmd.String([]string{"-memory-swap"}, "", "Swap limit equal to memory plus swap: '-1' to enable unlimited swap")
  55. flShmSize := cmd.String([]string{"-shm-size"}, "", "Size of /dev/shm, default value is 64MB")
  56. flCPUShares := cmd.Int64([]string{"#c", "-cpu-shares"}, 0, "CPU shares (relative weight)")
  57. flCPUPeriod := cmd.Int64([]string{"-cpu-period"}, 0, "Limit the CPU CFS (Completely Fair Scheduler) period")
  58. flCPUQuota := cmd.Int64([]string{"-cpu-quota"}, 0, "Limit the CPU CFS (Completely Fair Scheduler) quota")
  59. flCPUSetCpus := cmd.String([]string{"-cpuset-cpus"}, "", "CPUs in which to allow execution (0-3, 0,1)")
  60. flCPUSetMems := cmd.String([]string{"-cpuset-mems"}, "", "MEMs in which to allow execution (0-3, 0,1)")
  61. flCgroupParent := cmd.String([]string{"-cgroup-parent"}, "", "Optional parent cgroup for the container")
  62. flBuildArg := opts.NewListOpts(runconfigopts.ValidateEnv)
  63. cmd.Var(&flBuildArg, []string{"-build-arg"}, "Set build-time variables")
  64. isolation := cmd.String([]string{"-isolation"}, "", "Container isolation technology")
  65. ulimits := make(map[string]*units.Ulimit)
  66. flUlimits := runconfigopts.NewUlimitOpt(&ulimits)
  67. cmd.Var(flUlimits, []string{"-ulimit"}, "Ulimit options")
  68. cmd.Require(flag.Exact, 1)
  69. // For trusted pull on "FROM <image>" instruction.
  70. addTrustedFlags(cmd, true)
  71. cmd.ParseFlags(args, true)
  72. var (
  73. ctx io.ReadCloser
  74. err error
  75. )
  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. ctx, relDockerfile, err = getContextFromReader(cli.in, *dockerfileName)
  93. case urlutil.IsGitURL(specifiedContext):
  94. tempDir, relDockerfile, err = getContextFromGitURL(specifiedContext, *dockerfileName)
  95. case urlutil.IsURL(specifiedContext):
  96. ctx, 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 ctx == 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 := builder.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. ctx, 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. ctx = replaceDockerfileTarWrapper(ctx, 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(ctx, 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. Isolation: container.Isolation(*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(context.Background(), 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. // validateTag checks if the given image name can be resolved.
  250. func validateTag(rawRepo string) (string, error) {
  251. _, err := reference.ParseNamed(rawRepo)
  252. if err != nil {
  253. return "", err
  254. }
  255. return rawRepo, nil
  256. }
  257. // isUNC returns true if the path is UNC (one starting \\). It always returns
  258. // false on Linux.
  259. func isUNC(path string) bool {
  260. return runtime.GOOS == "windows" && strings.HasPrefix(path, `\\`)
  261. }
  262. // getDockerfileRelPath uses the given context directory for a `docker build`
  263. // and returns the absolute path to the context directory, the relative path of
  264. // the dockerfile in that context directory, and a non-nil error on success.
  265. func getDockerfileRelPath(givenContextDir, givenDockerfile string) (absContextDir, relDockerfile string, err error) {
  266. if absContextDir, err = filepath.Abs(givenContextDir); err != nil {
  267. return "", "", fmt.Errorf("unable to get absolute context directory: %v", err)
  268. }
  269. // The context dir might be a symbolic link, so follow it to the actual
  270. // target directory.
  271. //
  272. // FIXME. We use isUNC (always false on non-Windows platforms) to workaround
  273. // an issue in golang. On Windows, EvalSymLinks does not work on UNC file
  274. // paths (those starting with \\). This hack means that when using links
  275. // on UNC paths, they will not be followed.
  276. if !isUNC(absContextDir) {
  277. absContextDir, err = filepath.EvalSymlinks(absContextDir)
  278. if err != nil {
  279. return "", "", fmt.Errorf("unable to evaluate symlinks in context path: %v", err)
  280. }
  281. }
  282. stat, err := os.Lstat(absContextDir)
  283. if err != nil {
  284. return "", "", fmt.Errorf("unable to stat context directory %q: %v", absContextDir, err)
  285. }
  286. if !stat.IsDir() {
  287. return "", "", fmt.Errorf("context must be a directory: %s", absContextDir)
  288. }
  289. absDockerfile := givenDockerfile
  290. if absDockerfile == "" {
  291. // No -f/--file was specified so use the default relative to the
  292. // context directory.
  293. absDockerfile = filepath.Join(absContextDir, api.DefaultDockerfileName)
  294. // Just to be nice ;-) look for 'dockerfile' too but only
  295. // use it if we found it, otherwise ignore this check
  296. if _, err = os.Lstat(absDockerfile); os.IsNotExist(err) {
  297. altPath := filepath.Join(absContextDir, strings.ToLower(api.DefaultDockerfileName))
  298. if _, err = os.Lstat(altPath); err == nil {
  299. absDockerfile = altPath
  300. }
  301. }
  302. }
  303. // If not already an absolute path, the Dockerfile path should be joined to
  304. // the base directory.
  305. if !filepath.IsAbs(absDockerfile) {
  306. absDockerfile = filepath.Join(absContextDir, absDockerfile)
  307. }
  308. // Evaluate symlinks in the path to the Dockerfile too.
  309. //
  310. // FIXME. We use isUNC (always false on non-Windows platforms) to workaround
  311. // an issue in golang. On Windows, EvalSymLinks does not work on UNC file
  312. // paths (those starting with \\). This hack means that when using links
  313. // on UNC paths, they will not be followed.
  314. if !isUNC(absDockerfile) {
  315. absDockerfile, err = filepath.EvalSymlinks(absDockerfile)
  316. if err != nil {
  317. return "", "", fmt.Errorf("unable to evaluate symlinks in Dockerfile path: %v", err)
  318. }
  319. }
  320. if _, err := os.Lstat(absDockerfile); err != nil {
  321. if os.IsNotExist(err) {
  322. return "", "", fmt.Errorf("Cannot locate Dockerfile: %q", absDockerfile)
  323. }
  324. return "", "", fmt.Errorf("unable to stat Dockerfile: %v", err)
  325. }
  326. if relDockerfile, err = filepath.Rel(absContextDir, absDockerfile); err != nil {
  327. return "", "", fmt.Errorf("unable to get relative Dockerfile path: %v", err)
  328. }
  329. if strings.HasPrefix(relDockerfile, ".."+string(filepath.Separator)) {
  330. return "", "", fmt.Errorf("The Dockerfile (%s) must be within the build context (%s)", givenDockerfile, givenContextDir)
  331. }
  332. return absContextDir, relDockerfile, nil
  333. }
  334. // writeToFile copies from the given reader and writes it to a file with the
  335. // given filename.
  336. func writeToFile(r io.Reader, filename string) error {
  337. file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0600))
  338. if err != nil {
  339. return fmt.Errorf("unable to create file: %v", err)
  340. }
  341. defer file.Close()
  342. if _, err := io.Copy(file, r); err != nil {
  343. return fmt.Errorf("unable to write file: %v", err)
  344. }
  345. return nil
  346. }
  347. // getContextFromReader will read the contents of the given reader as either a
  348. // Dockerfile or tar archive. Returns a tar archive used as a context and a
  349. // path to the Dockerfile inside the tar.
  350. func getContextFromReader(r io.ReadCloser, dockerfileName string) (out io.ReadCloser, relDockerfile string, err error) {
  351. buf := bufio.NewReader(r)
  352. magic, err := buf.Peek(archive.HeaderSize)
  353. if err != nil && err != io.EOF {
  354. return nil, "", fmt.Errorf("failed to peek context header from STDIN: %v", err)
  355. }
  356. if archive.IsArchive(magic) {
  357. return ioutils.NewReadCloserWrapper(buf, func() error { return r.Close() }), dockerfileName, nil
  358. }
  359. // Input should be read as a Dockerfile.
  360. tmpDir, err := ioutil.TempDir("", "docker-build-context-")
  361. if err != nil {
  362. return nil, "", fmt.Errorf("unbale to create temporary context directory: %v", err)
  363. }
  364. f, err := os.Create(filepath.Join(tmpDir, api.DefaultDockerfileName))
  365. if err != nil {
  366. return nil, "", err
  367. }
  368. _, err = io.Copy(f, buf)
  369. if err != nil {
  370. f.Close()
  371. return nil, "", err
  372. }
  373. if err := f.Close(); err != nil {
  374. return nil, "", err
  375. }
  376. if err := r.Close(); err != nil {
  377. return nil, "", err
  378. }
  379. tar, err := archive.Tar(tmpDir, archive.Uncompressed)
  380. if err != nil {
  381. return nil, "", err
  382. }
  383. return ioutils.NewReadCloserWrapper(tar, func() error {
  384. err := tar.Close()
  385. os.RemoveAll(tmpDir)
  386. return err
  387. }), api.DefaultDockerfileName, nil
  388. }
  389. // getContextFromGitURL uses a Git URL as context for a `docker build`. The
  390. // git repo is cloned into a temporary directory used as the context directory.
  391. // Returns the absolute path to the temporary context directory, the relative
  392. // path of the dockerfile in that context directory, and a non-nil error on
  393. // success.
  394. func getContextFromGitURL(gitURL, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  395. if _, err := exec.LookPath("git"); err != nil {
  396. return "", "", fmt.Errorf("unable to find 'git': %v", err)
  397. }
  398. if absContextDir, err = gitutils.Clone(gitURL); err != nil {
  399. return "", "", fmt.Errorf("unable to 'git clone' to temporary context directory: %v", err)
  400. }
  401. return getDockerfileRelPath(absContextDir, dockerfileName)
  402. }
  403. // getContextFromURL uses a remote URL as context for a `docker build`. The
  404. // remote resource is downloaded as either a Dockerfile or a tar archive.
  405. // Returns the tar archive used for the context and a path of the
  406. // dockerfile inside the tar.
  407. func getContextFromURL(out io.Writer, remoteURL, dockerfileName string) (io.ReadCloser, string, error) {
  408. response, err := httputils.Download(remoteURL)
  409. if err != nil {
  410. return nil, "", fmt.Errorf("unable to download remote context %s: %v", remoteURL, err)
  411. }
  412. progressOutput := streamformatter.NewStreamFormatter().NewProgressOutput(out, true)
  413. // Pass the response body through a progress reader.
  414. progReader := progress.NewProgressReader(response.Body, progressOutput, response.ContentLength, "", fmt.Sprintf("Downloading build context from remote url: %s", remoteURL))
  415. return getContextFromReader(ioutils.NewReadCloserWrapper(progReader, func() error { return response.Body.Close() }), dockerfileName)
  416. }
  417. // getContextFromLocalDir uses the given local directory as context for a
  418. // `docker build`. Returns the absolute path to the local context directory,
  419. // the relative path of the dockerfile in that context directory, and a non-nil
  420. // error on success.
  421. func getContextFromLocalDir(localDir, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  422. // When using a local context directory, when the Dockerfile is specified
  423. // with the `-f/--file` option then it is considered relative to the
  424. // current directory and not the context directory.
  425. if dockerfileName != "" {
  426. if dockerfileName, err = filepath.Abs(dockerfileName); err != nil {
  427. return "", "", fmt.Errorf("unable to get absolute path to Dockerfile: %v", err)
  428. }
  429. }
  430. return getDockerfileRelPath(localDir, dockerfileName)
  431. }
  432. var dockerfileFromLinePattern = regexp.MustCompile(`(?i)^[\s]*FROM[ \f\r\t\v]+(?P<image>[^ \f\r\t\v\n#]+)`)
  433. // resolvedTag records the repository, tag, and resolved digest reference
  434. // from a Dockerfile rewrite.
  435. type resolvedTag struct {
  436. digestRef reference.Canonical
  437. tagRef reference.NamedTagged
  438. }
  439. // rewriteDockerfileFrom rewrites the given Dockerfile by resolving images in
  440. // "FROM <image>" instructions to a digest reference. `translator` is a
  441. // function that takes a repository name and tag reference and returns a
  442. // trusted digest reference.
  443. func rewriteDockerfileFrom(dockerfile io.Reader, translator translatorFunc) (newDockerfile []byte, resolvedTags []*resolvedTag, err error) {
  444. scanner := bufio.NewScanner(dockerfile)
  445. buf := bytes.NewBuffer(nil)
  446. // Scan the lines of the Dockerfile, looking for a "FROM" line.
  447. for scanner.Scan() {
  448. line := scanner.Text()
  449. matches := dockerfileFromLinePattern.FindStringSubmatch(line)
  450. if matches != nil && matches[1] != api.NoBaseImageSpecifier {
  451. // Replace the line with a resolved "FROM repo@digest"
  452. ref, err := reference.ParseNamed(matches[1])
  453. if err != nil {
  454. return nil, nil, err
  455. }
  456. ref = reference.WithDefaultTag(ref)
  457. if ref, ok := ref.(reference.NamedTagged); ok && isTrusted() {
  458. trustedRef, err := translator(ref)
  459. if err != nil {
  460. return nil, nil, err
  461. }
  462. line = dockerfileFromLinePattern.ReplaceAllLiteralString(line, fmt.Sprintf("FROM %s", trustedRef.String()))
  463. resolvedTags = append(resolvedTags, &resolvedTag{
  464. digestRef: trustedRef,
  465. tagRef: ref,
  466. })
  467. }
  468. }
  469. _, err := fmt.Fprintln(buf, line)
  470. if err != nil {
  471. return nil, nil, err
  472. }
  473. }
  474. return buf.Bytes(), resolvedTags, scanner.Err()
  475. }
  476. // replaceDockerfileTarWrapper wraps the given input tar archive stream and
  477. // replaces the entry with the given Dockerfile name with the contents of the
  478. // new Dockerfile. Returns a new tar archive stream with the replaced
  479. // Dockerfile.
  480. func replaceDockerfileTarWrapper(inputTarStream io.ReadCloser, dockerfileName string, translator translatorFunc, resolvedTags *[]*resolvedTag) io.ReadCloser {
  481. pipeReader, pipeWriter := io.Pipe()
  482. go func() {
  483. tarReader := tar.NewReader(inputTarStream)
  484. tarWriter := tar.NewWriter(pipeWriter)
  485. defer inputTarStream.Close()
  486. for {
  487. hdr, err := tarReader.Next()
  488. if err == io.EOF {
  489. // Signals end of archive.
  490. tarWriter.Close()
  491. pipeWriter.Close()
  492. return
  493. }
  494. if err != nil {
  495. pipeWriter.CloseWithError(err)
  496. return
  497. }
  498. var content io.Reader = tarReader
  499. if hdr.Name == dockerfileName {
  500. // This entry is the Dockerfile. Since the tar archive was
  501. // generated from a directory on the local filesystem, the
  502. // Dockerfile will only appear once in the archive.
  503. var newDockerfile []byte
  504. newDockerfile, *resolvedTags, err = rewriteDockerfileFrom(content, translator)
  505. if err != nil {
  506. pipeWriter.CloseWithError(err)
  507. return
  508. }
  509. hdr.Size = int64(len(newDockerfile))
  510. content = bytes.NewBuffer(newDockerfile)
  511. }
  512. if err := tarWriter.WriteHeader(hdr); err != nil {
  513. pipeWriter.CloseWithError(err)
  514. return
  515. }
  516. if _, err := io.Copy(tarWriter, content); err != nil {
  517. pipeWriter.CloseWithError(err)
  518. return
  519. }
  520. }
  521. }()
  522. return pipeReader
  523. }