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