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