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