github.com/reds/docker@v1.11.2-rc1/builder/dockerfile/internals.go (about) 1 package dockerfile 2 3 // internals for handling commands. Covers many areas and a lot of 4 // non-contiguous functionality. Please read the comments. 5 6 import ( 7 "crypto/sha256" 8 "encoding/hex" 9 "fmt" 10 "io" 11 "io/ioutil" 12 "net/http" 13 "net/url" 14 "os" 15 "path/filepath" 16 "runtime" 17 "sort" 18 "strings" 19 "time" 20 21 "github.com/Sirupsen/logrus" 22 "github.com/docker/docker/builder" 23 "github.com/docker/docker/builder/dockerfile/parser" 24 "github.com/docker/docker/pkg/archive" 25 "github.com/docker/docker/pkg/httputils" 26 "github.com/docker/docker/pkg/ioutils" 27 "github.com/docker/docker/pkg/jsonmessage" 28 "github.com/docker/docker/pkg/progress" 29 "github.com/docker/docker/pkg/streamformatter" 30 "github.com/docker/docker/pkg/stringid" 31 "github.com/docker/docker/pkg/system" 32 "github.com/docker/docker/pkg/tarsum" 33 "github.com/docker/docker/pkg/urlutil" 34 "github.com/docker/docker/runconfig/opts" 35 "github.com/docker/engine-api/types" 36 "github.com/docker/engine-api/types/container" 37 "github.com/docker/engine-api/types/strslice" 38 ) 39 40 func (b *Builder) commit(id string, autoCmd strslice.StrSlice, comment string) error { 41 if b.disableCommit { 42 return nil 43 } 44 if b.image == "" && !b.noBaseImage { 45 return fmt.Errorf("Please provide a source image with `from` prior to commit") 46 } 47 b.runConfig.Image = b.image 48 49 if id == "" { 50 cmd := b.runConfig.Cmd 51 if runtime.GOOS != "windows" { 52 b.runConfig.Cmd = strslice.StrSlice{"/bin/sh", "-c", "#(nop) " + comment} 53 } else { 54 b.runConfig.Cmd = strslice.StrSlice{"cmd", "/S /C", "REM (nop) " + comment} 55 } 56 defer func(cmd strslice.StrSlice) { b.runConfig.Cmd = cmd }(cmd) 57 58 hit, err := b.probeCache() 59 if err != nil { 60 return err 61 } else if hit { 62 return nil 63 } 64 id, err = b.create() 65 if err != nil { 66 return err 67 } 68 } 69 70 // Note: Actually copy the struct 71 autoConfig := *b.runConfig 72 autoConfig.Cmd = autoCmd 73 74 commitCfg := &types.ContainerCommitConfig{ 75 Author: b.maintainer, 76 Pause: true, 77 Config: &autoConfig, 78 } 79 80 // Commit the container 81 imageID, err := b.docker.Commit(id, commitCfg) 82 if err != nil { 83 return err 84 } 85 86 b.image = imageID 87 return nil 88 } 89 90 type copyInfo struct { 91 builder.FileInfo 92 decompress bool 93 } 94 95 func (b *Builder) runContextCommand(args []string, allowRemote bool, allowLocalDecompression bool, cmdName string) error { 96 if b.context == nil { 97 return fmt.Errorf("No context given. Impossible to use %s", cmdName) 98 } 99 100 if len(args) < 2 { 101 return fmt.Errorf("Invalid %s format - at least two arguments required", cmdName) 102 } 103 104 // Work in daemon-specific filepath semantics 105 dest := filepath.FromSlash(args[len(args)-1]) // last one is always the dest 106 107 b.runConfig.Image = b.image 108 109 var infos []copyInfo 110 111 // Loop through each src file and calculate the info we need to 112 // do the copy (e.g. hash value if cached). Don't actually do 113 // the copy until we've looked at all src files 114 var err error 115 for _, orig := range args[0 : len(args)-1] { 116 var fi builder.FileInfo 117 decompress := allowLocalDecompression 118 if urlutil.IsURL(orig) { 119 if !allowRemote { 120 return fmt.Errorf("Source can't be a URL for %s", cmdName) 121 } 122 fi, err = b.download(orig) 123 if err != nil { 124 return err 125 } 126 defer os.RemoveAll(filepath.Dir(fi.Path())) 127 decompress = false 128 infos = append(infos, copyInfo{fi, decompress}) 129 continue 130 } 131 // not a URL 132 subInfos, err := b.calcCopyInfo(cmdName, orig, allowLocalDecompression, true) 133 if err != nil { 134 return err 135 } 136 137 infos = append(infos, subInfos...) 138 } 139 140 if len(infos) == 0 { 141 return fmt.Errorf("No source files were specified") 142 } 143 if len(infos) > 1 && !strings.HasSuffix(dest, string(os.PathSeparator)) { 144 return fmt.Errorf("When using %s with more than one source file, the destination must be a directory and end with a /", cmdName) 145 } 146 147 // For backwards compat, if there's just one info then use it as the 148 // cache look-up string, otherwise hash 'em all into one 149 var srcHash string 150 var origPaths string 151 152 if len(infos) == 1 { 153 fi := infos[0].FileInfo 154 origPaths = fi.Name() 155 if hfi, ok := fi.(builder.Hashed); ok { 156 srcHash = hfi.Hash() 157 } 158 } else { 159 var hashs []string 160 var origs []string 161 for _, info := range infos { 162 fi := info.FileInfo 163 origs = append(origs, fi.Name()) 164 if hfi, ok := fi.(builder.Hashed); ok { 165 hashs = append(hashs, hfi.Hash()) 166 } 167 } 168 hasher := sha256.New() 169 hasher.Write([]byte(strings.Join(hashs, ","))) 170 srcHash = "multi:" + hex.EncodeToString(hasher.Sum(nil)) 171 origPaths = strings.Join(origs, " ") 172 } 173 174 cmd := b.runConfig.Cmd 175 if runtime.GOOS != "windows" { 176 b.runConfig.Cmd = strslice.StrSlice{"/bin/sh", "-c", fmt.Sprintf("#(nop) %s %s in %s", cmdName, srcHash, dest)} 177 } else { 178 b.runConfig.Cmd = strslice.StrSlice{"cmd", "/S", "/C", fmt.Sprintf("REM (nop) %s %s in %s", cmdName, srcHash, dest)} 179 } 180 defer func(cmd strslice.StrSlice) { b.runConfig.Cmd = cmd }(cmd) 181 182 if hit, err := b.probeCache(); err != nil { 183 return err 184 } else if hit { 185 return nil 186 } 187 188 container, err := b.docker.ContainerCreate(types.ContainerCreateConfig{Config: b.runConfig}) 189 if err != nil { 190 return err 191 } 192 b.tmpContainers[container.ID] = struct{}{} 193 194 comment := fmt.Sprintf("%s %s in %s", cmdName, origPaths, dest) 195 196 // Twiddle the destination when its a relative path - meaning, make it 197 // relative to the WORKINGDIR 198 if !system.IsAbs(dest) { 199 hasSlash := strings.HasSuffix(dest, string(os.PathSeparator)) 200 dest = filepath.Join(string(os.PathSeparator), filepath.FromSlash(b.runConfig.WorkingDir), dest) 201 202 // Make sure we preserve any trailing slash 203 if hasSlash { 204 dest += string(os.PathSeparator) 205 } 206 } 207 208 for _, info := range infos { 209 if err := b.docker.CopyOnBuild(container.ID, dest, info.FileInfo, info.decompress); err != nil { 210 return err 211 } 212 } 213 214 return b.commit(container.ID, cmd, comment) 215 } 216 217 func (b *Builder) download(srcURL string) (fi builder.FileInfo, err error) { 218 // get filename from URL 219 u, err := url.Parse(srcURL) 220 if err != nil { 221 return 222 } 223 path := filepath.FromSlash(u.Path) // Ensure in platform semantics 224 if strings.HasSuffix(path, string(os.PathSeparator)) { 225 path = path[:len(path)-1] 226 } 227 parts := strings.Split(path, string(os.PathSeparator)) 228 filename := parts[len(parts)-1] 229 if filename == "" { 230 err = fmt.Errorf("cannot determine filename from url: %s", u) 231 return 232 } 233 234 // Initiate the download 235 resp, err := httputils.Download(srcURL) 236 if err != nil { 237 return 238 } 239 240 // Prepare file in a tmp dir 241 tmpDir, err := ioutils.TempDir("", "docker-remote") 242 if err != nil { 243 return 244 } 245 defer func() { 246 if err != nil { 247 os.RemoveAll(tmpDir) 248 } 249 }() 250 tmpFileName := filepath.Join(tmpDir, filename) 251 tmpFile, err := os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) 252 if err != nil { 253 return 254 } 255 256 stdoutFormatter := b.Stdout.(*streamformatter.StdoutFormatter) 257 progressOutput := stdoutFormatter.StreamFormatter.NewProgressOutput(stdoutFormatter.Writer, true) 258 progressReader := progress.NewProgressReader(resp.Body, progressOutput, resp.ContentLength, "", "Downloading") 259 // Download and dump result to tmp file 260 if _, err = io.Copy(tmpFile, progressReader); err != nil { 261 tmpFile.Close() 262 return 263 } 264 fmt.Fprintln(b.Stdout) 265 // ignoring error because the file was already opened successfully 266 tmpFileSt, err := tmpFile.Stat() 267 if err != nil { 268 return 269 } 270 tmpFile.Close() 271 272 // Set the mtime to the Last-Modified header value if present 273 // Otherwise just remove atime and mtime 274 mTime := time.Time{} 275 276 lastMod := resp.Header.Get("Last-Modified") 277 if lastMod != "" { 278 // If we can't parse it then just let it default to 'zero' 279 // otherwise use the parsed time value 280 if parsedMTime, err := http.ParseTime(lastMod); err == nil { 281 mTime = parsedMTime 282 } 283 } 284 285 if err = system.Chtimes(tmpFileName, mTime, mTime); err != nil { 286 return 287 } 288 289 // Calc the checksum, even if we're using the cache 290 r, err := archive.Tar(tmpFileName, archive.Uncompressed) 291 if err != nil { 292 return 293 } 294 tarSum, err := tarsum.NewTarSum(r, true, tarsum.Version1) 295 if err != nil { 296 return 297 } 298 if _, err = io.Copy(ioutil.Discard, tarSum); err != nil { 299 return 300 } 301 hash := tarSum.Sum(nil) 302 r.Close() 303 return &builder.HashedFileInfo{FileInfo: builder.PathFileInfo{FileInfo: tmpFileSt, FilePath: tmpFileName}, FileHash: hash}, nil 304 } 305 306 func (b *Builder) calcCopyInfo(cmdName, origPath string, allowLocalDecompression, allowWildcards bool) ([]copyInfo, error) { 307 308 // Work in daemon-specific OS filepath semantics 309 origPath = filepath.FromSlash(origPath) 310 311 if origPath != "" && origPath[0] == os.PathSeparator && len(origPath) > 1 { 312 origPath = origPath[1:] 313 } 314 origPath = strings.TrimPrefix(origPath, "."+string(os.PathSeparator)) 315 316 // Deal with wildcards 317 if allowWildcards && containsWildcards(origPath) { 318 var copyInfos []copyInfo 319 if err := b.context.Walk("", func(path string, info builder.FileInfo, err error) error { 320 if err != nil { 321 return err 322 } 323 if info.Name() == "" { 324 // Why are we doing this check? 325 return nil 326 } 327 if match, _ := filepath.Match(origPath, path); !match { 328 return nil 329 } 330 331 // Note we set allowWildcards to false in case the name has 332 // a * in it 333 subInfos, err := b.calcCopyInfo(cmdName, path, allowLocalDecompression, false) 334 if err != nil { 335 return err 336 } 337 copyInfos = append(copyInfos, subInfos...) 338 return nil 339 }); err != nil { 340 return nil, err 341 } 342 return copyInfos, nil 343 } 344 345 // Must be a dir or a file 346 347 statPath, fi, err := b.context.Stat(origPath) 348 if err != nil { 349 return nil, err 350 } 351 352 copyInfos := []copyInfo{{FileInfo: fi, decompress: allowLocalDecompression}} 353 354 hfi, handleHash := fi.(builder.Hashed) 355 if !handleHash { 356 return copyInfos, nil 357 } 358 359 // Deal with the single file case 360 if !fi.IsDir() { 361 hfi.SetHash("file:" + hfi.Hash()) 362 return copyInfos, nil 363 } 364 // Must be a dir 365 var subfiles []string 366 err = b.context.Walk(statPath, func(path string, info builder.FileInfo, err error) error { 367 if err != nil { 368 return err 369 } 370 // we already checked handleHash above 371 subfiles = append(subfiles, info.(builder.Hashed).Hash()) 372 return nil 373 }) 374 if err != nil { 375 return nil, err 376 } 377 378 sort.Strings(subfiles) 379 hasher := sha256.New() 380 hasher.Write([]byte(strings.Join(subfiles, ","))) 381 hfi.SetHash("dir:" + hex.EncodeToString(hasher.Sum(nil))) 382 383 return copyInfos, nil 384 } 385 386 func containsWildcards(name string) bool { 387 for i := 0; i < len(name); i++ { 388 ch := name[i] 389 if ch == '\\' { 390 i++ 391 } else if ch == '*' || ch == '?' || ch == '[' { 392 return true 393 } 394 } 395 return false 396 } 397 398 func (b *Builder) processImageFrom(img builder.Image) error { 399 if img != nil { 400 b.image = img.ImageID() 401 402 if img.RunConfig() != nil { 403 b.runConfig = img.RunConfig() 404 } 405 } 406 407 // Check to see if we have a default PATH, note that windows won't 408 // have one as its set by HCS 409 if system.DefaultPathEnv != "" { 410 // Convert the slice of strings that represent the current list 411 // of env vars into a map so we can see if PATH is already set. 412 // If its not set then go ahead and give it our default value 413 configEnv := opts.ConvertKVStringsToMap(b.runConfig.Env) 414 if _, ok := configEnv["PATH"]; !ok { 415 b.runConfig.Env = append(b.runConfig.Env, 416 "PATH="+system.DefaultPathEnv) 417 } 418 } 419 420 if img == nil { 421 // Typically this means they used "FROM scratch" 422 return nil 423 } 424 425 // Process ONBUILD triggers if they exist 426 if nTriggers := len(b.runConfig.OnBuild); nTriggers != 0 { 427 word := "trigger" 428 if nTriggers > 1 { 429 word = "triggers" 430 } 431 fmt.Fprintf(b.Stderr, "# Executing %d build %s...\n", nTriggers, word) 432 } 433 434 // Copy the ONBUILD triggers, and remove them from the config, since the config will be committed. 435 onBuildTriggers := b.runConfig.OnBuild 436 b.runConfig.OnBuild = []string{} 437 438 // parse the ONBUILD triggers by invoking the parser 439 for _, step := range onBuildTriggers { 440 ast, err := parser.Parse(strings.NewReader(step)) 441 if err != nil { 442 return err 443 } 444 445 for i, n := range ast.Children { 446 switch strings.ToUpper(n.Value) { 447 case "ONBUILD": 448 return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") 449 case "MAINTAINER", "FROM": 450 return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", n.Value) 451 } 452 453 if err := b.dispatch(i, n); err != nil { 454 return err 455 } 456 } 457 } 458 459 return nil 460 } 461 462 // probeCache checks if `b.docker` implements builder.ImageCache and image-caching 463 // is enabled (`b.UseCache`). 464 // If so attempts to look up the current `b.image` and `b.runConfig` pair with `b.docker`. 465 // If an image is found, probeCache returns `(true, nil)`. 466 // If no image is found, it returns `(false, nil)`. 467 // If there is any error, it returns `(false, err)`. 468 func (b *Builder) probeCache() (bool, error) { 469 c, ok := b.docker.(builder.ImageCache) 470 if !ok || b.options.NoCache || b.cacheBusted { 471 return false, nil 472 } 473 cache, err := c.GetCachedImageOnBuild(b.image, b.runConfig) 474 if err != nil { 475 return false, err 476 } 477 if len(cache) == 0 { 478 logrus.Debugf("[BUILDER] Cache miss: %s", b.runConfig.Cmd) 479 b.cacheBusted = true 480 return false, nil 481 } 482 483 fmt.Fprintf(b.Stdout, " ---> Using cache\n") 484 logrus.Debugf("[BUILDER] Use cached version: %s", b.runConfig.Cmd) 485 b.image = string(cache) 486 487 return true, nil 488 } 489 490 func (b *Builder) create() (string, error) { 491 if b.image == "" && !b.noBaseImage { 492 return "", fmt.Errorf("Please provide a source image with `from` prior to run") 493 } 494 b.runConfig.Image = b.image 495 496 resources := container.Resources{ 497 CgroupParent: b.options.CgroupParent, 498 CPUShares: b.options.CPUShares, 499 CPUPeriod: b.options.CPUPeriod, 500 CPUQuota: b.options.CPUQuota, 501 CpusetCpus: b.options.CPUSetCPUs, 502 CpusetMems: b.options.CPUSetMems, 503 Memory: b.options.Memory, 504 MemorySwap: b.options.MemorySwap, 505 Ulimits: b.options.Ulimits, 506 } 507 508 // TODO: why not embed a hostconfig in builder? 509 hostConfig := &container.HostConfig{ 510 Isolation: b.options.Isolation, 511 ShmSize: b.options.ShmSize, 512 Resources: resources, 513 } 514 515 config := *b.runConfig 516 517 // Create the container 518 c, err := b.docker.ContainerCreate(types.ContainerCreateConfig{ 519 Config: b.runConfig, 520 HostConfig: hostConfig, 521 }) 522 if err != nil { 523 return "", err 524 } 525 for _, warning := range c.Warnings { 526 fmt.Fprintf(b.Stdout, " ---> [Warning] %s\n", warning) 527 } 528 529 b.tmpContainers[c.ID] = struct{}{} 530 fmt.Fprintf(b.Stdout, " ---> Running in %s\n", stringid.TruncateID(c.ID)) 531 532 // override the entry point that may have been picked up from the base image 533 if err := b.docker.ContainerUpdateCmdOnBuild(c.ID, config.Cmd); err != nil { 534 return "", err 535 } 536 537 return c.ID, nil 538 } 539 540 func (b *Builder) run(cID string) (err error) { 541 errCh := make(chan error) 542 go func() { 543 errCh <- b.docker.ContainerAttachRaw(cID, nil, b.Stdout, b.Stderr, true) 544 }() 545 546 finished := make(chan struct{}) 547 defer close(finished) 548 go func() { 549 select { 550 case <-b.cancelled: 551 logrus.Debugln("Build cancelled, killing and removing container:", cID) 552 b.docker.ContainerKill(cID, 0) 553 b.removeContainer(cID) 554 case <-finished: 555 } 556 }() 557 558 if err := b.docker.ContainerStart(cID, nil); err != nil { 559 return err 560 } 561 562 // Block on reading output from container, stop on err or chan closed 563 if err := <-errCh; err != nil { 564 return err 565 } 566 567 if ret, _ := b.docker.ContainerWait(cID, -1); ret != 0 { 568 // TODO: change error type, because jsonmessage.JSONError assumes HTTP 569 return &jsonmessage.JSONError{ 570 Message: fmt.Sprintf("The command '%s' returned a non-zero code: %d", strings.Join(b.runConfig.Cmd, " "), ret), 571 Code: ret, 572 } 573 } 574 575 return nil 576 } 577 578 func (b *Builder) removeContainer(c string) error { 579 rmConfig := &types.ContainerRmConfig{ 580 ForceRemove: true, 581 RemoveVolume: true, 582 } 583 if err := b.docker.ContainerRm(c, rmConfig); err != nil { 584 fmt.Fprintf(b.Stdout, "Error removing intermediate container %s: %v\n", stringid.TruncateID(c), err) 585 return err 586 } 587 return nil 588 } 589 590 func (b *Builder) clearTmp() { 591 for c := range b.tmpContainers { 592 if err := b.removeContainer(c); err != nil { 593 return 594 } 595 delete(b.tmpContainers, c) 596 fmt.Fprintf(b.Stdout, "Removing intermediate container %s\n", stringid.TruncateID(c)) 597 } 598 } 599 600 // readDockerfile reads a Dockerfile from the current context. 601 func (b *Builder) readDockerfile() error { 602 // If no -f was specified then look for 'Dockerfile'. If we can't find 603 // that then look for 'dockerfile'. If neither are found then default 604 // back to 'Dockerfile' and use that in the error message. 605 if b.options.Dockerfile == "" { 606 b.options.Dockerfile = builder.DefaultDockerfileName 607 if _, _, err := b.context.Stat(b.options.Dockerfile); os.IsNotExist(err) { 608 lowercase := strings.ToLower(b.options.Dockerfile) 609 if _, _, err := b.context.Stat(lowercase); err == nil { 610 b.options.Dockerfile = lowercase 611 } 612 } 613 } 614 615 f, err := b.context.Open(b.options.Dockerfile) 616 if err != nil { 617 if os.IsNotExist(err) { 618 return fmt.Errorf("Cannot locate specified Dockerfile: %s", b.options.Dockerfile) 619 } 620 return err 621 } 622 if f, ok := f.(*os.File); ok { 623 // ignoring error because Open already succeeded 624 fi, err := f.Stat() 625 if err != nil { 626 return fmt.Errorf("Unexpected error reading Dockerfile: %v", err) 627 } 628 if fi.Size() == 0 { 629 return fmt.Errorf("The Dockerfile (%s) cannot be empty", b.options.Dockerfile) 630 } 631 } 632 b.dockerfile, err = parser.Parse(f) 633 f.Close() 634 if err != nil { 635 return err 636 } 637 638 // After the Dockerfile has been parsed, we need to check the .dockerignore 639 // file for either "Dockerfile" or ".dockerignore", and if either are 640 // present then erase them from the build context. These files should never 641 // have been sent from the client but we did send them to make sure that 642 // we had the Dockerfile to actually parse, and then we also need the 643 // .dockerignore file to know whether either file should be removed. 644 // Note that this assumes the Dockerfile has been read into memory and 645 // is now safe to be removed. 646 if dockerIgnore, ok := b.context.(builder.DockerIgnoreContext); ok { 647 dockerIgnore.Process([]string{b.options.Dockerfile}) 648 } 649 return nil 650 } 651 652 // determine if build arg is part of built-in args or user 653 // defined args in Dockerfile at any point in time. 654 func (b *Builder) isBuildArgAllowed(arg string) bool { 655 if _, ok := BuiltinAllowedBuildArgs[arg]; ok { 656 return true 657 } 658 if _, ok := b.allowedBuildArgs[arg]; ok { 659 return true 660 } 661 return false 662 }