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