build.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. package client
  2. import (
  3. "archive/tar"
  4. "bufio"
  5. "encoding/base64"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "os/exec"
  14. "path"
  15. "path/filepath"
  16. "regexp"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "github.com/docker/docker/api"
  21. Cli "github.com/docker/docker/cli"
  22. "github.com/docker/docker/graph/tags"
  23. "github.com/docker/docker/opts"
  24. "github.com/docker/docker/pkg/archive"
  25. "github.com/docker/docker/pkg/fileutils"
  26. "github.com/docker/docker/pkg/httputils"
  27. "github.com/docker/docker/pkg/jsonmessage"
  28. flag "github.com/docker/docker/pkg/mflag"
  29. "github.com/docker/docker/pkg/parsers"
  30. "github.com/docker/docker/pkg/progressreader"
  31. "github.com/docker/docker/pkg/streamformatter"
  32. "github.com/docker/docker/pkg/ulimit"
  33. "github.com/docker/docker/pkg/units"
  34. "github.com/docker/docker/pkg/urlutil"
  35. "github.com/docker/docker/registry"
  36. "github.com/docker/docker/utils"
  37. )
  38. const (
  39. tarHeaderSize = 512
  40. )
  41. // CmdBuild builds a new image from the source code at a given path.
  42. //
  43. // If '-' is provided instead of a path or URL, Docker will build an image from either a Dockerfile or tar archive read from STDIN.
  44. //
  45. // Usage: docker build [OPTIONS] PATH | URL | -
  46. func (cli *DockerCli) CmdBuild(args ...string) error {
  47. cmd := Cli.Subcmd("build", []string{"PATH | URL | -"}, "Build a new image from the source code at PATH", true)
  48. tag := cmd.String([]string{"t", "-tag"}, "", "Repository name (and optionally a tag) for the image")
  49. suppressOutput := cmd.Bool([]string{"q", "-quiet"}, false, "Suppress the verbose output generated by the containers")
  50. noCache := cmd.Bool([]string{"#no-cache", "-no-cache"}, false, "Do not use cache when building the image")
  51. rm := cmd.Bool([]string{"#rm", "-rm"}, true, "Remove intermediate containers after a successful build")
  52. forceRm := cmd.Bool([]string{"-force-rm"}, false, "Always remove intermediate containers")
  53. pull := cmd.Bool([]string{"-pull"}, false, "Always attempt to pull a newer version of the image")
  54. dockerfileName := cmd.String([]string{"f", "-file"}, "", "Name of the Dockerfile (Default is 'PATH/Dockerfile')")
  55. flMemoryString := cmd.String([]string{"m", "-memory"}, "", "Memory limit")
  56. flMemorySwap := cmd.String([]string{"-memory-swap"}, "", "Total memory (memory + swap), '-1' to disable swap")
  57. flCPUShares := cmd.Int64([]string{"c", "-cpu-shares"}, 0, "CPU shares (relative weight)")
  58. flCPUPeriod := cmd.Int64([]string{"-cpu-period"}, 0, "Limit the CPU CFS (Completely Fair Scheduler) period")
  59. flCPUQuota := cmd.Int64([]string{"-cpu-quota"}, 0, "Limit the CPU CFS (Completely Fair Scheduler) quota")
  60. flCPUSetCpus := cmd.String([]string{"-cpuset-cpus"}, "", "CPUs in which to allow execution (0-3, 0,1)")
  61. flCPUSetMems := cmd.String([]string{"-cpuset-mems"}, "", "MEMs in which to allow execution (0-3, 0,1)")
  62. flCgroupParent := cmd.String([]string{"-cgroup-parent"}, "", "Optional parent cgroup for the container")
  63. ulimits := make(map[string]*ulimit.Ulimit)
  64. flUlimits := opts.NewUlimitOpt(&ulimits)
  65. cmd.Var(flUlimits, []string{"-ulimit"}, "Ulimit options")
  66. cmd.Require(flag.Exact, 1)
  67. // For trusted pull on "FROM <image>" instruction.
  68. addTrustedFlags(cmd, true)
  69. cmd.ParseFlags(args, true)
  70. var (
  71. context io.ReadCloser
  72. isRemote bool
  73. err error
  74. )
  75. _, err = exec.LookPath("git")
  76. hasGit := err == nil
  77. specifiedContext := cmd.Arg(0)
  78. var (
  79. contextDir string
  80. tempDir string
  81. relDockerfile string
  82. )
  83. switch {
  84. case specifiedContext == "-":
  85. tempDir, relDockerfile, err = getContextFromReader(cli.in, *dockerfileName)
  86. case urlutil.IsGitURL(specifiedContext) && hasGit:
  87. tempDir, relDockerfile, err = getContextFromGitURL(specifiedContext, *dockerfileName)
  88. case urlutil.IsURL(specifiedContext):
  89. tempDir, relDockerfile, err = getContextFromURL(cli.out, specifiedContext, *dockerfileName)
  90. default:
  91. contextDir, relDockerfile, err = getContextFromLocalDir(specifiedContext, *dockerfileName)
  92. }
  93. if err != nil {
  94. return fmt.Errorf("unable to prepare context: %s", err)
  95. }
  96. if tempDir != "" {
  97. defer os.RemoveAll(tempDir)
  98. contextDir = tempDir
  99. }
  100. // Resolve the FROM lines in the Dockerfile to trusted digest references
  101. // using Notary.
  102. newDockerfile, err := rewriteDockerfileFrom(filepath.Join(contextDir, relDockerfile), cli.trustedReference)
  103. if err != nil {
  104. return fmt.Errorf("unable to process Dockerfile: %v", err)
  105. }
  106. defer newDockerfile.Close()
  107. // And canonicalize dockerfile name to a platform-independent one
  108. relDockerfile, err = archive.CanonicalTarNameForPath(relDockerfile)
  109. if err != nil {
  110. return fmt.Errorf("cannot canonicalize dockerfile path %s: %v", relDockerfile, err)
  111. }
  112. var includes = []string{"."}
  113. excludes, err := utils.ReadDockerIgnore(path.Join(contextDir, ".dockerignore"))
  114. if err != nil {
  115. return err
  116. }
  117. if err := utils.ValidateContextDirectory(contextDir, excludes); err != nil {
  118. return fmt.Errorf("Error checking context: '%s'.", err)
  119. }
  120. // If .dockerignore mentions .dockerignore or the Dockerfile
  121. // then make sure we send both files over to the daemon
  122. // because Dockerfile is, obviously, needed no matter what, and
  123. // .dockerignore is needed to know if either one needs to be
  124. // removed. The deamon will remove them for us, if needed, after it
  125. // parses the Dockerfile. Ignore errors here, as they will have been
  126. // caught by ValidateContextDirectory above.
  127. keepThem1, _ := fileutils.Matches(".dockerignore", excludes)
  128. keepThem2, _ := fileutils.Matches(relDockerfile, excludes)
  129. if keepThem1 || keepThem2 {
  130. includes = append(includes, ".dockerignore", relDockerfile)
  131. }
  132. context, err = archive.TarWithOptions(contextDir, &archive.TarOptions{
  133. Compression: archive.Uncompressed,
  134. ExcludePatterns: excludes,
  135. IncludeFiles: includes,
  136. })
  137. if err != nil {
  138. return err
  139. }
  140. // Wrap the tar archive to replace the Dockerfile entry with the rewritten
  141. // Dockerfile which uses trusted pulls.
  142. context = replaceDockerfileTarWrapper(context, newDockerfile, relDockerfile)
  143. // Setup an upload progress bar
  144. // FIXME: ProgressReader shouldn't be this annoying to use
  145. sf := streamformatter.NewStreamFormatter()
  146. var body io.Reader = progressreader.New(progressreader.Config{
  147. In: context,
  148. Out: cli.out,
  149. Formatter: sf,
  150. NewLines: true,
  151. ID: "",
  152. Action: "Sending build context to Docker daemon",
  153. })
  154. var memory int64
  155. if *flMemoryString != "" {
  156. parsedMemory, err := units.RAMInBytes(*flMemoryString)
  157. if err != nil {
  158. return err
  159. }
  160. memory = parsedMemory
  161. }
  162. var memorySwap int64
  163. if *flMemorySwap != "" {
  164. if *flMemorySwap == "-1" {
  165. memorySwap = -1
  166. } else {
  167. parsedMemorySwap, err := units.RAMInBytes(*flMemorySwap)
  168. if err != nil {
  169. return err
  170. }
  171. memorySwap = parsedMemorySwap
  172. }
  173. }
  174. // Send the build context
  175. v := &url.Values{}
  176. //Check if the given image name can be resolved
  177. if *tag != "" {
  178. repository, tag := parsers.ParseRepositoryTag(*tag)
  179. if err := registry.ValidateRepositoryName(repository); err != nil {
  180. return err
  181. }
  182. if len(tag) > 0 {
  183. if err := tags.ValidateTagName(tag); err != nil {
  184. return err
  185. }
  186. }
  187. }
  188. v.Set("t", *tag)
  189. if *suppressOutput {
  190. v.Set("q", "1")
  191. }
  192. if isRemote {
  193. v.Set("remote", cmd.Arg(0))
  194. }
  195. if *noCache {
  196. v.Set("nocache", "1")
  197. }
  198. if *rm {
  199. v.Set("rm", "1")
  200. } else {
  201. v.Set("rm", "0")
  202. }
  203. if *forceRm {
  204. v.Set("forcerm", "1")
  205. }
  206. if *pull {
  207. v.Set("pull", "1")
  208. }
  209. v.Set("cpusetcpus", *flCPUSetCpus)
  210. v.Set("cpusetmems", *flCPUSetMems)
  211. v.Set("cpushares", strconv.FormatInt(*flCPUShares, 10))
  212. v.Set("cpuquota", strconv.FormatInt(*flCPUQuota, 10))
  213. v.Set("cpuperiod", strconv.FormatInt(*flCPUPeriod, 10))
  214. v.Set("memory", strconv.FormatInt(memory, 10))
  215. v.Set("memswap", strconv.FormatInt(memorySwap, 10))
  216. v.Set("cgroupparent", *flCgroupParent)
  217. v.Set("dockerfile", relDockerfile)
  218. ulimitsVar := flUlimits.GetList()
  219. ulimitsJSON, err := json.Marshal(ulimitsVar)
  220. if err != nil {
  221. return err
  222. }
  223. v.Set("ulimits", string(ulimitsJSON))
  224. headers := http.Header(make(map[string][]string))
  225. buf, err := json.Marshal(cli.configFile.AuthConfigs)
  226. if err != nil {
  227. return err
  228. }
  229. headers.Add("X-Registry-Config", base64.URLEncoding.EncodeToString(buf))
  230. headers.Set("Content-Type", "application/tar")
  231. sopts := &streamOpts{
  232. rawTerminal: true,
  233. in: body,
  234. out: cli.out,
  235. headers: headers,
  236. }
  237. serverResp, err := cli.stream("POST", fmt.Sprintf("/build?%s", v.Encode()), sopts)
  238. // Windows: show error message about modified file permissions.
  239. if runtime.GOOS == "windows" {
  240. h, err := httputils.ParseServerHeader(serverResp.header.Get("Server"))
  241. if err == nil {
  242. if h.OS != "windows" {
  243. 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.`)
  244. }
  245. }
  246. }
  247. if jerr, ok := err.(*jsonmessage.JSONError); ok {
  248. // If no error code is set, default to 1
  249. if jerr.Code == 0 {
  250. jerr.Code = 1
  251. }
  252. return Cli.StatusError{Status: jerr.Message, StatusCode: jerr.Code}
  253. }
  254. return err
  255. }
  256. // getDockerfileRelPath uses the given context directory for a `docker build`
  257. // and returns the absolute path to the context directory, the relative path of
  258. // the dockerfile in that context directory, and a non-nil error on success.
  259. func getDockerfileRelPath(givenContextDir, givenDockerfile string) (absContextDir, relDockerfile string, err error) {
  260. if absContextDir, err = filepath.Abs(givenContextDir); err != nil {
  261. return "", "", fmt.Errorf("unable to get absolute context directory: %v", err)
  262. }
  263. // The context dir might be a symbolic link, so follow it to the actual
  264. // target directory.
  265. absContextDir, err = filepath.EvalSymlinks(absContextDir)
  266. if err != nil {
  267. return "", "", fmt.Errorf("unable to evaluate symlinks in context path: %v", err)
  268. }
  269. stat, err := os.Lstat(absContextDir)
  270. if err != nil {
  271. return "", "", fmt.Errorf("unable to stat context directory %q: %v", absContextDir, err)
  272. }
  273. if !stat.IsDir() {
  274. return "", "", fmt.Errorf("context must be a directory: %s", absContextDir)
  275. }
  276. absDockerfile := givenDockerfile
  277. if absDockerfile == "" {
  278. // No -f/--file was specified so use the default relative to the
  279. // context directory.
  280. absDockerfile = filepath.Join(absContextDir, api.DefaultDockerfileName)
  281. // Just to be nice ;-) look for 'dockerfile' too but only
  282. // use it if we found it, otherwise ignore this check
  283. if _, err = os.Lstat(absDockerfile); os.IsNotExist(err) {
  284. altPath := filepath.Join(absContextDir, strings.ToLower(api.DefaultDockerfileName))
  285. if _, err = os.Lstat(altPath); err == nil {
  286. absDockerfile = altPath
  287. }
  288. }
  289. }
  290. // If not already an absolute path, the Dockerfile path should be joined to
  291. // the base directory.
  292. if !filepath.IsAbs(absDockerfile) {
  293. absDockerfile = filepath.Join(absContextDir, absDockerfile)
  294. }
  295. // Evaluate symlinks in the path to the Dockerfile too.
  296. absDockerfile, err = filepath.EvalSymlinks(absDockerfile)
  297. if err != nil {
  298. return "", "", fmt.Errorf("unable to evaluate symlinks in Dockerfile path: %v", err)
  299. }
  300. if _, err := os.Lstat(absDockerfile); err != nil {
  301. if os.IsNotExist(err) {
  302. return "", "", fmt.Errorf("Cannot locate Dockerfile: %q", absDockerfile)
  303. }
  304. return "", "", fmt.Errorf("unable to stat Dockerfile: %v", err)
  305. }
  306. if relDockerfile, err = filepath.Rel(absContextDir, absDockerfile); err != nil {
  307. return "", "", fmt.Errorf("unable to get relative Dockerfile path: %v", err)
  308. }
  309. if strings.HasPrefix(relDockerfile, ".."+string(filepath.Separator)) {
  310. return "", "", fmt.Errorf("The Dockerfile (%s) must be within the build context (%s)", givenDockerfile, givenContextDir)
  311. }
  312. return absContextDir, relDockerfile, nil
  313. }
  314. // writeToFile copies from the given reader and writes it to a file with the
  315. // given filename.
  316. func writeToFile(r io.Reader, filename string) error {
  317. file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0600))
  318. if err != nil {
  319. return fmt.Errorf("unable to create file: %v", err)
  320. }
  321. defer file.Close()
  322. if _, err := io.Copy(file, r); err != nil {
  323. return fmt.Errorf("unable to write file: %v", err)
  324. }
  325. return nil
  326. }
  327. // getContextFromReader will read the contents of the given reader as either a
  328. // Dockerfile or tar archive to be extracted to a temporary directory used as
  329. // the context directory. Returns the absolute path to the temporary context
  330. // directory, the relative path of the dockerfile in that context directory,
  331. // and a non-nil error on success.
  332. func getContextFromReader(r io.Reader, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  333. buf := bufio.NewReader(r)
  334. magic, err := buf.Peek(tarHeaderSize)
  335. if err != nil && err != io.EOF {
  336. return "", "", fmt.Errorf("failed to peek context header from STDIN: %v", err)
  337. }
  338. if absContextDir, err = ioutil.TempDir("", "docker-build-context-"); err != nil {
  339. return "", "", fmt.Errorf("unbale to create temporary context directory: %v", err)
  340. }
  341. defer func(d string) {
  342. if err != nil {
  343. os.RemoveAll(d)
  344. }
  345. }(absContextDir)
  346. if !archive.IsArchive(magic) { // Input should be read as a Dockerfile.
  347. // -f option has no meaning when we're reading it from stdin,
  348. // so just use our default Dockerfile name
  349. relDockerfile = api.DefaultDockerfileName
  350. return absContextDir, relDockerfile, writeToFile(buf, filepath.Join(absContextDir, relDockerfile))
  351. }
  352. if err := archive.Untar(buf, absContextDir, nil); err != nil {
  353. return "", "", fmt.Errorf("unable to extract stdin to temporary context directory: %v", err)
  354. }
  355. return getDockerfileRelPath(absContextDir, dockerfileName)
  356. }
  357. // getContextFromGitURL uses a Git URL as context for a `docker build`. The
  358. // git repo is cloned into a temporary directory used as the context directory.
  359. // Returns the absolute path to the temporary context directory, the relative
  360. // path of the dockerfile in that context directory, and a non-nil error on
  361. // success.
  362. func getContextFromGitURL(gitURL, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  363. if absContextDir, err = utils.GitClone(gitURL); err != nil {
  364. return "", "", fmt.Errorf("unable to 'git clone' to temporary context directory: %v", err)
  365. }
  366. return getDockerfileRelPath(absContextDir, dockerfileName)
  367. }
  368. // getContextFromURL uses a remote URL as context for a `docker build`. The
  369. // remote resource is downloaded as either a Dockerfile or a context tar
  370. // archive and stored in a temporary directory used as the context directory.
  371. // Returns the absolute path to the temporary context directory, the relative
  372. // path of the dockerfile in that context directory, and a non-nil error on
  373. // success.
  374. func getContextFromURL(out io.Writer, remoteURL, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  375. response, err := httputils.Download(remoteURL)
  376. if err != nil {
  377. return "", "", fmt.Errorf("unable to download remote context %s: %v", remoteURL, err)
  378. }
  379. defer response.Body.Close()
  380. // Pass the response body through a progress reader.
  381. progReader := &progressreader.Config{
  382. In: response.Body,
  383. Out: out,
  384. Formatter: streamformatter.NewStreamFormatter(),
  385. Size: int(response.ContentLength),
  386. NewLines: true,
  387. ID: "",
  388. Action: fmt.Sprintf("Downloading build context from remote url: %s", remoteURL),
  389. }
  390. return getContextFromReader(progReader, dockerfileName)
  391. }
  392. // getContextFromLocalDir uses the given local directory as context for a
  393. // `docker build`. Returns the absolute path to the local context directory,
  394. // the relative path of the dockerfile in that context directory, and a non-nil
  395. // error on success.
  396. func getContextFromLocalDir(localDir, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  397. // When using a local context directory, when the Dockerfile is specified
  398. // with the `-f/--file` option then it is considered relative to the
  399. // current directory and not the context directory.
  400. if dockerfileName != "" {
  401. if dockerfileName, err = filepath.Abs(dockerfileName); err != nil {
  402. return "", "", fmt.Errorf("unable to get absolute path to Dockerfile: %v", err)
  403. }
  404. }
  405. return getDockerfileRelPath(localDir, dockerfileName)
  406. }
  407. var dockerfileFromLinePattern = regexp.MustCompile(`(?i)^[\s]*FROM[ \f\r\t\v]+(?P<image>[^ \f\r\t\v\n#]+)`)
  408. type trustedDockerfile struct {
  409. *os.File
  410. size int64
  411. }
  412. func (td *trustedDockerfile) Close() error {
  413. td.File.Close()
  414. return os.Remove(td.File.Name())
  415. }
  416. // rewriteDockerfileFrom rewrites the given Dockerfile by resolving images in
  417. // "FROM <image>" instructions to a digest reference. `translator` is a
  418. // function that takes a repository name and tag reference and returns a
  419. // trusted digest reference.
  420. func rewriteDockerfileFrom(dockerfileName string, translator func(string, registry.Reference) (registry.Reference, error)) (newDockerfile *trustedDockerfile, err error) {
  421. dockerfile, err := os.Open(dockerfileName)
  422. if err != nil {
  423. return nil, fmt.Errorf("unable to open Dockerfile: %v", err)
  424. }
  425. defer dockerfile.Close()
  426. scanner := bufio.NewScanner(dockerfile)
  427. // Make a tempfile to store the rewritten Dockerfile.
  428. tempFile, err := ioutil.TempFile("", "trusted-dockerfile-")
  429. if err != nil {
  430. return nil, fmt.Errorf("unable to make temporary trusted Dockerfile: %v", err)
  431. }
  432. trustedFile := &trustedDockerfile{
  433. File: tempFile,
  434. }
  435. defer func() {
  436. if err != nil {
  437. // Close the tempfile if there was an error during Notary lookups.
  438. // Otherwise the caller should close it.
  439. trustedFile.Close()
  440. }
  441. }()
  442. // Scan the lines of the Dockerfile, looking for a "FROM" line.
  443. for scanner.Scan() {
  444. line := scanner.Text()
  445. matches := dockerfileFromLinePattern.FindStringSubmatch(line)
  446. if matches != nil && matches[1] != "scratch" {
  447. // Replace the line with a resolved "FROM repo@digest"
  448. repo, tag := parsers.ParseRepositoryTag(matches[1])
  449. if tag == "" {
  450. tag = tags.DEFAULTTAG
  451. }
  452. ref := registry.ParseReference(tag)
  453. if !ref.HasDigest() && isTrusted() {
  454. trustedRef, err := translator(repo, ref)
  455. if err != nil {
  456. return nil, err
  457. }
  458. line = dockerfileFromLinePattern.ReplaceAllLiteralString(line, fmt.Sprintf("FROM %s", trustedRef.ImageName(repo)))
  459. }
  460. }
  461. n, err := fmt.Fprintln(tempFile, line)
  462. if err != nil {
  463. return nil, err
  464. }
  465. trustedFile.size += int64(n)
  466. }
  467. tempFile.Seek(0, os.SEEK_SET)
  468. return trustedFile, scanner.Err()
  469. }
  470. // replaceDockerfileTarWrapper wraps the given input tar archive stream and
  471. // replaces the entry with the given Dockerfile name with the contents of the
  472. // new Dockerfile. Returns a new tar archive stream with the replaced
  473. // Dockerfile.
  474. func replaceDockerfileTarWrapper(inputTarStream io.ReadCloser, newDockerfile *trustedDockerfile, dockerfileName string) io.ReadCloser {
  475. pipeReader, pipeWriter := io.Pipe()
  476. go func() {
  477. tarReader := tar.NewReader(inputTarStream)
  478. tarWriter := tar.NewWriter(pipeWriter)
  479. defer inputTarStream.Close()
  480. for {
  481. hdr, err := tarReader.Next()
  482. if err == io.EOF {
  483. // Signals end of archive.
  484. tarWriter.Close()
  485. pipeWriter.Close()
  486. return
  487. }
  488. if err != nil {
  489. pipeWriter.CloseWithError(err)
  490. return
  491. }
  492. var content io.Reader = tarReader
  493. if hdr.Name == dockerfileName {
  494. // This entry is the Dockerfile. Since the tar archive was
  495. // generated from a directory on the local filesystem, the
  496. // Dockerfile will only appear once in the archive.
  497. hdr.Size = newDockerfile.size
  498. content = newDockerfile
  499. }
  500. if err := tarWriter.WriteHeader(hdr); err != nil {
  501. pipeWriter.CloseWithError(err)
  502. return
  503. }
  504. if _, err := io.Copy(tarWriter, content); err != nil {
  505. pipeWriter.CloseWithError(err)
  506. return
  507. }
  508. }
  509. }()
  510. return pipeReader
  511. }