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