github.com/grange74/docker@v1.6.0-rc3/api/client/commands.go (about) 1 package client 2 3 import ( 4 "bufio" 5 "bytes" 6 "encoding/base64" 7 "encoding/json" 8 "errors" 9 "fmt" 10 "io" 11 "io/ioutil" 12 "net/http" 13 "net/url" 14 "os" 15 "os/exec" 16 "path" 17 "path/filepath" 18 "runtime" 19 "sort" 20 "strconv" 21 "strings" 22 "sync" 23 "text/tabwriter" 24 "text/template" 25 "time" 26 27 log "github.com/Sirupsen/logrus" 28 "github.com/docker/docker/api" 29 "github.com/docker/docker/api/types" 30 "github.com/docker/docker/autogen/dockerversion" 31 "github.com/docker/docker/engine" 32 "github.com/docker/docker/graph" 33 "github.com/docker/docker/nat" 34 "github.com/docker/docker/opts" 35 "github.com/docker/docker/pkg/archive" 36 "github.com/docker/docker/pkg/common" 37 "github.com/docker/docker/pkg/fileutils" 38 "github.com/docker/docker/pkg/homedir" 39 flag "github.com/docker/docker/pkg/mflag" 40 "github.com/docker/docker/pkg/networkfs/resolvconf" 41 "github.com/docker/docker/pkg/parsers" 42 "github.com/docker/docker/pkg/parsers/filters" 43 "github.com/docker/docker/pkg/progressreader" 44 "github.com/docker/docker/pkg/promise" 45 "github.com/docker/docker/pkg/signal" 46 "github.com/docker/docker/pkg/symlink" 47 "github.com/docker/docker/pkg/term" 48 "github.com/docker/docker/pkg/timeutils" 49 "github.com/docker/docker/pkg/units" 50 "github.com/docker/docker/pkg/urlutil" 51 "github.com/docker/docker/registry" 52 "github.com/docker/docker/runconfig" 53 "github.com/docker/docker/utils" 54 ) 55 56 const ( 57 tarHeaderSize = 512 58 ) 59 60 func (cli *DockerCli) CmdHelp(args ...string) error { 61 if len(args) > 1 { 62 method, exists := cli.getMethod(args[:2]...) 63 if exists { 64 method("--help") 65 return nil 66 } 67 } 68 if len(args) > 0 { 69 method, exists := cli.getMethod(args[0]) 70 if !exists { 71 fmt.Fprintf(cli.err, "docker: '%s' is not a docker command. See 'docker --help'.\n", args[0]) 72 os.Exit(1) 73 } else { 74 method("--help") 75 return nil 76 } 77 } 78 79 flag.Usage() 80 81 return nil 82 } 83 84 func (cli *DockerCli) CmdBuild(args ...string) error { 85 cmd := cli.Subcmd("build", "PATH | URL | -", "Build a new image from the source code at PATH", true) 86 tag := cmd.String([]string{"t", "-tag"}, "", "Repository name (and optionally a tag) for the image") 87 suppressOutput := cmd.Bool([]string{"q", "-quiet"}, false, "Suppress the verbose output generated by the containers") 88 noCache := cmd.Bool([]string{"#no-cache", "-no-cache"}, false, "Do not use cache when building the image") 89 rm := cmd.Bool([]string{"#rm", "-rm"}, true, "Remove intermediate containers after a successful build") 90 forceRm := cmd.Bool([]string{"-force-rm"}, false, "Always remove intermediate containers") 91 pull := cmd.Bool([]string{"-pull"}, false, "Always attempt to pull a newer version of the image") 92 dockerfileName := cmd.String([]string{"f", "-file"}, "", "Name of the Dockerfile (Default is 'PATH/Dockerfile')") 93 flMemoryString := cmd.String([]string{"m", "-memory"}, "", "Memory limit") 94 flMemorySwap := cmd.String([]string{"-memory-swap"}, "", "Total memory (memory + swap), '-1' to disable swap") 95 flCpuShares := cmd.Int64([]string{"c", "-cpu-shares"}, 0, "CPU shares (relative weight)") 96 flCpuSetCpus := cmd.String([]string{"-cpuset-cpus"}, "", "CPUs in which to allow execution (0-3, 0,1)") 97 98 cmd.Require(flag.Exact, 1) 99 100 utils.ParseFlags(cmd, args, true) 101 102 var ( 103 context archive.Archive 104 isRemote bool 105 err error 106 ) 107 108 _, err = exec.LookPath("git") 109 hasGit := err == nil 110 if cmd.Arg(0) == "-" { 111 // As a special case, 'docker build -' will build from either an empty context with the 112 // contents of stdin as a Dockerfile, or a tar-ed context from stdin. 113 buf := bufio.NewReader(cli.in) 114 magic, err := buf.Peek(tarHeaderSize) 115 if err != nil && err != io.EOF { 116 return fmt.Errorf("failed to peek context header from STDIN: %v", err) 117 } 118 if !archive.IsArchive(magic) { 119 dockerfile, err := ioutil.ReadAll(buf) 120 if err != nil { 121 return fmt.Errorf("failed to read Dockerfile from STDIN: %v", err) 122 } 123 124 // -f option has no meaning when we're reading it from stdin, 125 // so just use our default Dockerfile name 126 *dockerfileName = api.DefaultDockerfileName 127 context, err = archive.Generate(*dockerfileName, string(dockerfile)) 128 } else { 129 context = ioutil.NopCloser(buf) 130 } 131 } else if urlutil.IsURL(cmd.Arg(0)) && (!urlutil.IsGitURL(cmd.Arg(0)) || !hasGit) { 132 isRemote = true 133 } else { 134 root := cmd.Arg(0) 135 if urlutil.IsGitURL(root) { 136 remoteURL := cmd.Arg(0) 137 if !urlutil.IsGitTransport(remoteURL) { 138 remoteURL = "https://" + remoteURL 139 } 140 141 root, err = ioutil.TempDir("", "docker-build-git") 142 if err != nil { 143 return err 144 } 145 defer os.RemoveAll(root) 146 147 if output, err := exec.Command("git", "clone", "--recursive", remoteURL, root).CombinedOutput(); err != nil { 148 return fmt.Errorf("Error trying to use git: %s (%s)", err, output) 149 } 150 } 151 if _, err := os.Stat(root); err != nil { 152 return err 153 } 154 155 absRoot, err := filepath.Abs(root) 156 if err != nil { 157 return err 158 } 159 160 filename := *dockerfileName // path to Dockerfile 161 162 if *dockerfileName == "" { 163 // No -f/--file was specified so use the default 164 *dockerfileName = api.DefaultDockerfileName 165 filename = filepath.Join(absRoot, *dockerfileName) 166 167 // Just to be nice ;-) look for 'dockerfile' too but only 168 // use it if we found it, otherwise ignore this check 169 if _, err = os.Lstat(filename); os.IsNotExist(err) { 170 tmpFN := path.Join(absRoot, strings.ToLower(*dockerfileName)) 171 if _, err = os.Lstat(tmpFN); err == nil { 172 *dockerfileName = strings.ToLower(*dockerfileName) 173 filename = tmpFN 174 } 175 } 176 } 177 178 origDockerfile := *dockerfileName // used for error msg 179 if filename, err = filepath.Abs(filename); err != nil { 180 return err 181 } 182 183 // Verify that 'filename' is within the build context 184 filename, err = symlink.FollowSymlinkInScope(filename, absRoot) 185 if err != nil { 186 return fmt.Errorf("The Dockerfile (%s) must be within the build context (%s)", origDockerfile, root) 187 } 188 189 // Now reset the dockerfileName to be relative to the build context 190 *dockerfileName, err = filepath.Rel(absRoot, filename) 191 if err != nil { 192 return err 193 } 194 // And canonicalize dockerfile name to a platform-independent one 195 *dockerfileName, err = archive.CanonicalTarNameForPath(*dockerfileName) 196 if err != nil { 197 return fmt.Errorf("Cannot canonicalize dockerfile path %s: %v", dockerfileName, err) 198 } 199 200 if _, err = os.Lstat(filename); os.IsNotExist(err) { 201 return fmt.Errorf("Cannot locate Dockerfile: %s", origDockerfile) 202 } 203 var includes = []string{"."} 204 205 excludes, err := utils.ReadDockerIgnore(path.Join(root, ".dockerignore")) 206 if err != nil { 207 return err 208 } 209 210 // If .dockerignore mentions .dockerignore or the Dockerfile 211 // then make sure we send both files over to the daemon 212 // because Dockerfile is, obviously, needed no matter what, and 213 // .dockerignore is needed to know if either one needs to be 214 // removed. The deamon will remove them for us, if needed, after it 215 // parses the Dockerfile. 216 keepThem1, _ := fileutils.Matches(".dockerignore", excludes) 217 keepThem2, _ := fileutils.Matches(*dockerfileName, excludes) 218 if keepThem1 || keepThem2 { 219 includes = append(includes, ".dockerignore", *dockerfileName) 220 } 221 222 if err = utils.ValidateContextDirectory(root, excludes); err != nil { 223 return fmt.Errorf("Error checking context is accessible: '%s'. Please check permissions and try again.", err) 224 } 225 options := &archive.TarOptions{ 226 Compression: archive.Uncompressed, 227 ExcludePatterns: excludes, 228 IncludeFiles: includes, 229 } 230 context, err = archive.TarWithOptions(root, options) 231 if err != nil { 232 return err 233 } 234 } 235 236 // windows: show error message about modified file permissions 237 // FIXME: this is not a valid warning when the daemon is running windows. should be removed once docker engine for windows can build. 238 if runtime.GOOS == "windows" { 239 log.Warn(`SECURITY WARNING: You are building a Docker image from Windows against a Linux 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.`) 240 } 241 242 var body io.Reader 243 // Setup an upload progress bar 244 // FIXME: ProgressReader shouldn't be this annoying to use 245 if context != nil { 246 sf := utils.NewStreamFormatter(false) 247 body = progressreader.New(progressreader.Config{ 248 In: context, 249 Out: cli.out, 250 Formatter: sf, 251 NewLines: true, 252 ID: "", 253 Action: "Sending build context to Docker daemon", 254 }) 255 } 256 257 var memory int64 258 if *flMemoryString != "" { 259 parsedMemory, err := units.RAMInBytes(*flMemoryString) 260 if err != nil { 261 return err 262 } 263 memory = parsedMemory 264 } 265 266 var memorySwap int64 267 if *flMemorySwap != "" { 268 if *flMemorySwap == "-1" { 269 memorySwap = -1 270 } else { 271 parsedMemorySwap, err := units.RAMInBytes(*flMemorySwap) 272 if err != nil { 273 return err 274 } 275 memorySwap = parsedMemorySwap 276 } 277 } 278 // Send the build context 279 v := &url.Values{} 280 281 //Check if the given image name can be resolved 282 if *tag != "" { 283 repository, tag := parsers.ParseRepositoryTag(*tag) 284 if err := registry.ValidateRepositoryName(repository); err != nil { 285 return err 286 } 287 if len(tag) > 0 { 288 if err := graph.ValidateTagName(tag); err != nil { 289 return err 290 } 291 } 292 } 293 294 v.Set("t", *tag) 295 296 if *suppressOutput { 297 v.Set("q", "1") 298 } 299 if isRemote { 300 v.Set("remote", cmd.Arg(0)) 301 } 302 if *noCache { 303 v.Set("nocache", "1") 304 } 305 if *rm { 306 v.Set("rm", "1") 307 } else { 308 v.Set("rm", "0") 309 } 310 311 if *forceRm { 312 v.Set("forcerm", "1") 313 } 314 315 if *pull { 316 v.Set("pull", "1") 317 } 318 319 v.Set("cpusetcpus", *flCpuSetCpus) 320 v.Set("cpushares", strconv.FormatInt(*flCpuShares, 10)) 321 v.Set("memory", strconv.FormatInt(memory, 10)) 322 v.Set("memswap", strconv.FormatInt(memorySwap, 10)) 323 324 v.Set("dockerfile", *dockerfileName) 325 326 cli.LoadConfigFile() 327 328 headers := http.Header(make(map[string][]string)) 329 buf, err := json.Marshal(cli.configFile) 330 if err != nil { 331 return err 332 } 333 headers.Add("X-Registry-Config", base64.URLEncoding.EncodeToString(buf)) 334 335 if context != nil { 336 headers.Set("Content-Type", "application/tar") 337 } 338 err = cli.stream("POST", fmt.Sprintf("/build?%s", v.Encode()), body, cli.out, headers) 339 if jerr, ok := err.(*utils.JSONError); ok { 340 // If no error code is set, default to 1 341 if jerr.Code == 0 { 342 jerr.Code = 1 343 } 344 return &utils.StatusError{Status: jerr.Message, StatusCode: jerr.Code} 345 } 346 return err 347 } 348 349 // 'docker login': login / register a user to registry service. 350 func (cli *DockerCli) CmdLogin(args ...string) error { 351 cmd := cli.Subcmd("login", "[SERVER]", "Register or log in to a Docker registry server, if no server is\nspecified \""+registry.IndexServerAddress()+"\" is the default.", true) 352 cmd.Require(flag.Max, 1) 353 354 var username, password, email string 355 356 cmd.StringVar(&username, []string{"u", "-username"}, "", "Username") 357 cmd.StringVar(&password, []string{"p", "-password"}, "", "Password") 358 cmd.StringVar(&email, []string{"e", "-email"}, "", "Email") 359 360 utils.ParseFlags(cmd, args, true) 361 362 serverAddress := registry.IndexServerAddress() 363 if len(cmd.Args()) > 0 { 364 serverAddress = cmd.Arg(0) 365 } 366 367 promptDefault := func(prompt string, configDefault string) { 368 if configDefault == "" { 369 fmt.Fprintf(cli.out, "%s: ", prompt) 370 } else { 371 fmt.Fprintf(cli.out, "%s (%s): ", prompt, configDefault) 372 } 373 } 374 375 readInput := func(in io.Reader, out io.Writer) string { 376 reader := bufio.NewReader(in) 377 line, _, err := reader.ReadLine() 378 if err != nil { 379 fmt.Fprintln(out, err.Error()) 380 os.Exit(1) 381 } 382 return string(line) 383 } 384 385 cli.LoadConfigFile() 386 authconfig, ok := cli.configFile.Configs[serverAddress] 387 if !ok { 388 authconfig = registry.AuthConfig{} 389 } 390 391 if username == "" { 392 promptDefault("Username", authconfig.Username) 393 username = readInput(cli.in, cli.out) 394 username = strings.Trim(username, " ") 395 if username == "" { 396 username = authconfig.Username 397 } 398 } 399 // Assume that a different username means they may not want to use 400 // the password or email from the config file, so prompt them 401 if username != authconfig.Username { 402 if password == "" { 403 oldState, err := term.SaveState(cli.inFd) 404 if err != nil { 405 return err 406 } 407 fmt.Fprintf(cli.out, "Password: ") 408 term.DisableEcho(cli.inFd, oldState) 409 410 password = readInput(cli.in, cli.out) 411 fmt.Fprint(cli.out, "\n") 412 413 term.RestoreTerminal(cli.inFd, oldState) 414 if password == "" { 415 return fmt.Errorf("Error : Password Required") 416 } 417 } 418 419 if email == "" { 420 promptDefault("Email", authconfig.Email) 421 email = readInput(cli.in, cli.out) 422 if email == "" { 423 email = authconfig.Email 424 } 425 } 426 } else { 427 // However, if they don't override the username use the 428 // password or email from the cmd line if specified. IOW, allow 429 // then to change/override them. And if not specified, just 430 // use what's in the config file 431 if password == "" { 432 password = authconfig.Password 433 } 434 if email == "" { 435 email = authconfig.Email 436 } 437 } 438 authconfig.Username = username 439 authconfig.Password = password 440 authconfig.Email = email 441 authconfig.ServerAddress = serverAddress 442 cli.configFile.Configs[serverAddress] = authconfig 443 444 stream, statusCode, err := cli.call("POST", "/auth", cli.configFile.Configs[serverAddress], nil) 445 if statusCode == 401 { 446 delete(cli.configFile.Configs, serverAddress) 447 registry.SaveConfig(cli.configFile) 448 return err 449 } 450 if err != nil { 451 return err 452 } 453 var out2 engine.Env 454 err = out2.Decode(stream) 455 if err != nil { 456 cli.configFile, _ = registry.LoadConfig(homedir.Get()) 457 return err 458 } 459 registry.SaveConfig(cli.configFile) 460 fmt.Fprintf(cli.out, "WARNING: login credentials saved in %s.\n", path.Join(homedir.Get(), registry.CONFIGFILE)) 461 462 if out2.Get("Status") != "" { 463 fmt.Fprintf(cli.out, "%s\n", out2.Get("Status")) 464 } 465 return nil 466 } 467 468 // log out from a Docker registry 469 func (cli *DockerCli) CmdLogout(args ...string) error { 470 cmd := cli.Subcmd("logout", "[SERVER]", "Log out from a Docker registry, if no server is\nspecified \""+registry.IndexServerAddress()+"\" is the default.", true) 471 cmd.Require(flag.Max, 1) 472 473 utils.ParseFlags(cmd, args, false) 474 serverAddress := registry.IndexServerAddress() 475 if len(cmd.Args()) > 0 { 476 serverAddress = cmd.Arg(0) 477 } 478 479 cli.LoadConfigFile() 480 if _, ok := cli.configFile.Configs[serverAddress]; !ok { 481 fmt.Fprintf(cli.out, "Not logged in to %s\n", serverAddress) 482 } else { 483 fmt.Fprintf(cli.out, "Remove login credentials for %s\n", serverAddress) 484 delete(cli.configFile.Configs, serverAddress) 485 486 if err := registry.SaveConfig(cli.configFile); err != nil { 487 return fmt.Errorf("Failed to save docker config: %v", err) 488 } 489 } 490 return nil 491 } 492 493 // 'docker wait': block until a container stops 494 func (cli *DockerCli) CmdWait(args ...string) error { 495 cmd := cli.Subcmd("wait", "CONTAINER [CONTAINER...]", "Block until a container stops, then print its exit code.", true) 496 cmd.Require(flag.Min, 1) 497 498 utils.ParseFlags(cmd, args, true) 499 500 var encounteredError error 501 for _, name := range cmd.Args() { 502 status, err := waitForExit(cli, name) 503 if err != nil { 504 fmt.Fprintf(cli.err, "%s\n", err) 505 encounteredError = fmt.Errorf("Error: failed to wait one or more containers") 506 } else { 507 fmt.Fprintf(cli.out, "%d\n", status) 508 } 509 } 510 return encounteredError 511 } 512 513 // 'docker version': show version information 514 func (cli *DockerCli) CmdVersion(args ...string) error { 515 cmd := cli.Subcmd("version", "", "Show the Docker version information.", true) 516 cmd.Require(flag.Exact, 0) 517 518 utils.ParseFlags(cmd, args, false) 519 520 if dockerversion.VERSION != "" { 521 fmt.Fprintf(cli.out, "Client version: %s\n", dockerversion.VERSION) 522 } 523 fmt.Fprintf(cli.out, "Client API version: %s\n", api.APIVERSION) 524 fmt.Fprintf(cli.out, "Go version (client): %s\n", runtime.Version()) 525 if dockerversion.GITCOMMIT != "" { 526 fmt.Fprintf(cli.out, "Git commit (client): %s\n", dockerversion.GITCOMMIT) 527 } 528 fmt.Fprintf(cli.out, "OS/Arch (client): %s/%s\n", runtime.GOOS, runtime.GOARCH) 529 530 body, _, err := readBody(cli.call("GET", "/version", nil, nil)) 531 if err != nil { 532 return err 533 } 534 535 out := engine.NewOutput() 536 remoteVersion, err := out.AddEnv() 537 if err != nil { 538 log.Errorf("Error reading remote version: %s", err) 539 return err 540 } 541 if _, err := out.Write(body); err != nil { 542 log.Errorf("Error reading remote version: %s", err) 543 return err 544 } 545 out.Close() 546 fmt.Fprintf(cli.out, "Server version: %s\n", remoteVersion.Get("Version")) 547 if apiVersion := remoteVersion.Get("ApiVersion"); apiVersion != "" { 548 fmt.Fprintf(cli.out, "Server API version: %s\n", apiVersion) 549 } 550 fmt.Fprintf(cli.out, "Go version (server): %s\n", remoteVersion.Get("GoVersion")) 551 fmt.Fprintf(cli.out, "Git commit (server): %s\n", remoteVersion.Get("GitCommit")) 552 fmt.Fprintf(cli.out, "OS/Arch (server): %s/%s\n", remoteVersion.Get("Os"), remoteVersion.Get("Arch")) 553 return nil 554 } 555 556 // 'docker info': display system-wide information. 557 func (cli *DockerCli) CmdInfo(args ...string) error { 558 cmd := cli.Subcmd("info", "", "Display system-wide information", true) 559 cmd.Require(flag.Exact, 0) 560 utils.ParseFlags(cmd, args, false) 561 562 body, _, err := readBody(cli.call("GET", "/info", nil, nil)) 563 if err != nil { 564 return err 565 } 566 567 out := engine.NewOutput() 568 remoteInfo, err := out.AddEnv() 569 if err != nil { 570 return err 571 } 572 573 if _, err := out.Write(body); err != nil { 574 log.Errorf("Error reading remote info: %s", err) 575 return err 576 } 577 out.Close() 578 579 if remoteInfo.Exists("Containers") { 580 fmt.Fprintf(cli.out, "Containers: %d\n", remoteInfo.GetInt("Containers")) 581 } 582 if remoteInfo.Exists("Images") { 583 fmt.Fprintf(cli.out, "Images: %d\n", remoteInfo.GetInt("Images")) 584 } 585 if remoteInfo.Exists("Driver") { 586 fmt.Fprintf(cli.out, "Storage Driver: %s\n", remoteInfo.Get("Driver")) 587 } 588 if remoteInfo.Exists("DriverStatus") { 589 var driverStatus [][2]string 590 if err := remoteInfo.GetJson("DriverStatus", &driverStatus); err != nil { 591 return err 592 } 593 for _, pair := range driverStatus { 594 fmt.Fprintf(cli.out, " %s: %s\n", pair[0], pair[1]) 595 } 596 } 597 if remoteInfo.Exists("ExecutionDriver") { 598 fmt.Fprintf(cli.out, "Execution Driver: %s\n", remoteInfo.Get("ExecutionDriver")) 599 } 600 if remoteInfo.Exists("KernelVersion") { 601 fmt.Fprintf(cli.out, "Kernel Version: %s\n", remoteInfo.Get("KernelVersion")) 602 } 603 if remoteInfo.Exists("OperatingSystem") { 604 fmt.Fprintf(cli.out, "Operating System: %s\n", remoteInfo.Get("OperatingSystem")) 605 } 606 if remoteInfo.Exists("NCPU") { 607 fmt.Fprintf(cli.out, "CPUs: %d\n", remoteInfo.GetInt("NCPU")) 608 } 609 if remoteInfo.Exists("MemTotal") { 610 fmt.Fprintf(cli.out, "Total Memory: %s\n", units.BytesSize(float64(remoteInfo.GetInt64("MemTotal")))) 611 } 612 if remoteInfo.Exists("Name") { 613 fmt.Fprintf(cli.out, "Name: %s\n", remoteInfo.Get("Name")) 614 } 615 if remoteInfo.Exists("ID") { 616 fmt.Fprintf(cli.out, "ID: %s\n", remoteInfo.Get("ID")) 617 } 618 619 if remoteInfo.GetBool("Debug") || os.Getenv("DEBUG") != "" { 620 if remoteInfo.Exists("Debug") { 621 fmt.Fprintf(cli.out, "Debug mode (server): %v\n", remoteInfo.GetBool("Debug")) 622 } 623 fmt.Fprintf(cli.out, "Debug mode (client): %v\n", os.Getenv("DEBUG") != "") 624 if remoteInfo.Exists("NFd") { 625 fmt.Fprintf(cli.out, "Fds: %d\n", remoteInfo.GetInt("NFd")) 626 } 627 if remoteInfo.Exists("NGoroutines") { 628 fmt.Fprintf(cli.out, "Goroutines: %d\n", remoteInfo.GetInt("NGoroutines")) 629 } 630 if remoteInfo.Exists("SystemTime") { 631 t, err := remoteInfo.GetTime("SystemTime") 632 if err != nil { 633 log.Errorf("Error reading system time: %v", err) 634 } else { 635 fmt.Fprintf(cli.out, "System Time: %s\n", t.Format(time.UnixDate)) 636 } 637 } 638 if remoteInfo.Exists("NEventsListener") { 639 fmt.Fprintf(cli.out, "EventsListeners: %d\n", remoteInfo.GetInt("NEventsListener")) 640 } 641 if initSha1 := remoteInfo.Get("InitSha1"); initSha1 != "" { 642 fmt.Fprintf(cli.out, "Init SHA1: %s\n", initSha1) 643 } 644 if initPath := remoteInfo.Get("InitPath"); initPath != "" { 645 fmt.Fprintf(cli.out, "Init Path: %s\n", initPath) 646 } 647 if root := remoteInfo.Get("DockerRootDir"); root != "" { 648 fmt.Fprintf(cli.out, "Docker Root Dir: %s\n", root) 649 } 650 } 651 if remoteInfo.Exists("HttpProxy") { 652 fmt.Fprintf(cli.out, "Http Proxy: %s\n", remoteInfo.Get("HttpProxy")) 653 } 654 if remoteInfo.Exists("HttpsProxy") { 655 fmt.Fprintf(cli.out, "Https Proxy: %s\n", remoteInfo.Get("HttpsProxy")) 656 } 657 if remoteInfo.Exists("NoProxy") { 658 fmt.Fprintf(cli.out, "No Proxy: %s\n", remoteInfo.Get("NoProxy")) 659 } 660 if len(remoteInfo.GetList("IndexServerAddress")) != 0 { 661 cli.LoadConfigFile() 662 u := cli.configFile.Configs[remoteInfo.Get("IndexServerAddress")].Username 663 if len(u) > 0 { 664 fmt.Fprintf(cli.out, "Username: %v\n", u) 665 fmt.Fprintf(cli.out, "Registry: %v\n", remoteInfo.GetList("IndexServerAddress")) 666 } 667 } 668 if remoteInfo.Exists("MemoryLimit") && !remoteInfo.GetBool("MemoryLimit") { 669 fmt.Fprintf(cli.err, "WARNING: No memory limit support\n") 670 } 671 if remoteInfo.Exists("SwapLimit") && !remoteInfo.GetBool("SwapLimit") { 672 fmt.Fprintf(cli.err, "WARNING: No swap limit support\n") 673 } 674 if remoteInfo.Exists("IPv4Forwarding") && !remoteInfo.GetBool("IPv4Forwarding") { 675 fmt.Fprintf(cli.err, "WARNING: IPv4 forwarding is disabled.\n") 676 } 677 if remoteInfo.Exists("Labels") { 678 fmt.Fprintln(cli.out, "Labels:") 679 for _, attribute := range remoteInfo.GetList("Labels") { 680 fmt.Fprintf(cli.out, " %s\n", attribute) 681 } 682 } 683 684 return nil 685 } 686 687 func (cli *DockerCli) CmdStop(args ...string) error { 688 cmd := cli.Subcmd("stop", "CONTAINER [CONTAINER...]", "Stop a running container by sending SIGTERM and then SIGKILL after a\ngrace period", true) 689 nSeconds := cmd.Int([]string{"t", "-time"}, 10, "Seconds to wait for stop before killing it") 690 cmd.Require(flag.Min, 1) 691 692 utils.ParseFlags(cmd, args, true) 693 694 v := url.Values{} 695 v.Set("t", strconv.Itoa(*nSeconds)) 696 697 var encounteredError error 698 for _, name := range cmd.Args() { 699 _, _, err := readBody(cli.call("POST", "/containers/"+name+"/stop?"+v.Encode(), nil, nil)) 700 if err != nil { 701 fmt.Fprintf(cli.err, "%s\n", err) 702 encounteredError = fmt.Errorf("Error: failed to stop one or more containers") 703 } else { 704 fmt.Fprintf(cli.out, "%s\n", name) 705 } 706 } 707 return encounteredError 708 } 709 710 func (cli *DockerCli) CmdRestart(args ...string) error { 711 cmd := cli.Subcmd("restart", "CONTAINER [CONTAINER...]", "Restart a running container", true) 712 nSeconds := cmd.Int([]string{"t", "-time"}, 10, "Seconds to wait for stop before killing the container") 713 cmd.Require(flag.Min, 1) 714 715 utils.ParseFlags(cmd, args, true) 716 717 v := url.Values{} 718 v.Set("t", strconv.Itoa(*nSeconds)) 719 720 var encounteredError error 721 for _, name := range cmd.Args() { 722 _, _, err := readBody(cli.call("POST", "/containers/"+name+"/restart?"+v.Encode(), nil, nil)) 723 if err != nil { 724 fmt.Fprintf(cli.err, "%s\n", err) 725 encounteredError = fmt.Errorf("Error: failed to restart one or more containers") 726 } else { 727 fmt.Fprintf(cli.out, "%s\n", name) 728 } 729 } 730 return encounteredError 731 } 732 733 func (cli *DockerCli) forwardAllSignals(cid string) chan os.Signal { 734 sigc := make(chan os.Signal, 128) 735 signal.CatchAll(sigc) 736 go func() { 737 for s := range sigc { 738 if s == signal.SIGCHLD { 739 continue 740 } 741 var sig string 742 for sigStr, sigN := range signal.SignalMap { 743 if sigN == s { 744 sig = sigStr 745 break 746 } 747 } 748 if sig == "" { 749 log.Errorf("Unsupported signal: %v. Discarding.", s) 750 } 751 if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%s", cid, sig), nil, nil)); err != nil { 752 log.Debugf("Error sending signal: %s", err) 753 } 754 } 755 }() 756 return sigc 757 } 758 759 func (cli *DockerCli) CmdStart(args ...string) error { 760 var ( 761 cErr chan error 762 tty bool 763 764 cmd = cli.Subcmd("start", "CONTAINER [CONTAINER...]", "Start one or more stopped containers", true) 765 attach = cmd.Bool([]string{"a", "-attach"}, false, "Attach STDOUT/STDERR and forward signals") 766 openStdin = cmd.Bool([]string{"i", "-interactive"}, false, "Attach container's STDIN") 767 ) 768 769 cmd.Require(flag.Min, 1) 770 utils.ParseFlags(cmd, args, true) 771 772 if *attach || *openStdin { 773 if cmd.NArg() > 1 { 774 return fmt.Errorf("You cannot start and attach multiple containers at once.") 775 } 776 777 stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, nil) 778 if err != nil { 779 return err 780 } 781 782 env := engine.Env{} 783 if err := env.Decode(stream); err != nil { 784 return err 785 } 786 config := env.GetSubEnv("Config") 787 tty = config.GetBool("Tty") 788 789 if !tty { 790 sigc := cli.forwardAllSignals(cmd.Arg(0)) 791 defer signal.StopCatch(sigc) 792 } 793 794 var in io.ReadCloser 795 796 v := url.Values{} 797 v.Set("stream", "1") 798 799 if *openStdin && config.GetBool("OpenStdin") { 800 v.Set("stdin", "1") 801 in = cli.in 802 } 803 804 v.Set("stdout", "1") 805 v.Set("stderr", "1") 806 807 hijacked := make(chan io.Closer) 808 // Block the return until the chan gets closed 809 defer func() { 810 log.Debugf("CmdStart() returned, defer waiting for hijack to finish.") 811 if _, ok := <-hijacked; ok { 812 log.Errorf("Hijack did not finish (chan still open)") 813 } 814 cli.in.Close() 815 }() 816 cErr = promise.Go(func() error { 817 return cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), tty, in, cli.out, cli.err, hijacked, nil) 818 }) 819 820 // Acknowledge the hijack before starting 821 select { 822 case closer := <-hijacked: 823 // Make sure that the hijack gets closed when returning (results 824 // in closing the hijack chan and freeing server's goroutines) 825 if closer != nil { 826 defer closer.Close() 827 } 828 case err := <-cErr: 829 if err != nil { 830 return err 831 } 832 } 833 } 834 835 var encounteredError error 836 for _, name := range cmd.Args() { 837 _, _, err := readBody(cli.call("POST", "/containers/"+name+"/start", nil, nil)) 838 if err != nil { 839 if !*attach && !*openStdin { 840 // attach and openStdin is false means it could be starting multiple containers 841 // when a container start failed, show the error message and start next 842 fmt.Fprintf(cli.err, "%s\n", err) 843 encounteredError = fmt.Errorf("Error: failed to start one or more containers") 844 } else { 845 encounteredError = err 846 } 847 } else { 848 if !*attach && !*openStdin { 849 fmt.Fprintf(cli.out, "%s\n", name) 850 } 851 } 852 } 853 854 if encounteredError != nil { 855 return encounteredError 856 } 857 858 if *openStdin || *attach { 859 if tty && cli.isTerminalOut { 860 if err := cli.monitorTtySize(cmd.Arg(0), false); err != nil { 861 log.Errorf("Error monitoring TTY size: %s", err) 862 } 863 } 864 if attchErr := <-cErr; attchErr != nil { 865 return attchErr 866 } 867 _, status, err := getExitCode(cli, cmd.Arg(0)) 868 if err != nil { 869 return err 870 } 871 if status != 0 { 872 return &utils.StatusError{StatusCode: status} 873 } 874 } 875 return nil 876 } 877 878 func (cli *DockerCli) CmdUnpause(args ...string) error { 879 cmd := cli.Subcmd("unpause", "CONTAINER [CONTAINER...]", "Unpause all processes within a container", true) 880 cmd.Require(flag.Min, 1) 881 utils.ParseFlags(cmd, args, false) 882 883 var encounteredError error 884 for _, name := range cmd.Args() { 885 if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/unpause", name), nil, nil)); err != nil { 886 fmt.Fprintf(cli.err, "%s\n", err) 887 encounteredError = fmt.Errorf("Error: failed to unpause container named %s", name) 888 } else { 889 fmt.Fprintf(cli.out, "%s\n", name) 890 } 891 } 892 return encounteredError 893 } 894 895 func (cli *DockerCli) CmdPause(args ...string) error { 896 cmd := cli.Subcmd("pause", "CONTAINER [CONTAINER...]", "Pause all processes within a container", true) 897 cmd.Require(flag.Min, 1) 898 utils.ParseFlags(cmd, args, false) 899 900 var encounteredError error 901 for _, name := range cmd.Args() { 902 if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/pause", name), nil, nil)); err != nil { 903 fmt.Fprintf(cli.err, "%s\n", err) 904 encounteredError = fmt.Errorf("Error: failed to pause container named %s", name) 905 } else { 906 fmt.Fprintf(cli.out, "%s\n", name) 907 } 908 } 909 return encounteredError 910 } 911 912 func (cli *DockerCli) CmdRename(args ...string) error { 913 cmd := cli.Subcmd("rename", "OLD_NAME NEW_NAME", "Rename a container", true) 914 if err := cmd.Parse(args); err != nil { 915 return nil 916 } 917 918 if cmd.NArg() != 2 { 919 cmd.Usage() 920 return nil 921 } 922 old_name := cmd.Arg(0) 923 new_name := cmd.Arg(1) 924 925 if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/rename?name=%s", old_name, new_name), nil, nil)); err != nil { 926 fmt.Fprintf(cli.err, "%s\n", err) 927 return fmt.Errorf("Error: failed to rename container named %s", old_name) 928 } 929 return nil 930 } 931 932 func (cli *DockerCli) CmdInspect(args ...string) error { 933 cmd := cli.Subcmd("inspect", "CONTAINER|IMAGE [CONTAINER|IMAGE...]", "Return low-level information on a container or image", true) 934 tmplStr := cmd.String([]string{"f", "#format", "-format"}, "", "Format the output using the given go template") 935 cmd.Require(flag.Min, 1) 936 937 utils.ParseFlags(cmd, args, true) 938 939 var tmpl *template.Template 940 if *tmplStr != "" { 941 var err error 942 if tmpl, err = template.New("").Funcs(funcMap).Parse(*tmplStr); err != nil { 943 fmt.Fprintf(cli.err, "Template parsing error: %v\n", err) 944 return &utils.StatusError{StatusCode: 64, 945 Status: "Template parsing error: " + err.Error()} 946 } 947 } 948 949 indented := new(bytes.Buffer) 950 indented.WriteByte('[') 951 status := 0 952 953 for _, name := range cmd.Args() { 954 obj, _, err := readBody(cli.call("GET", "/containers/"+name+"/json", nil, nil)) 955 if err != nil { 956 if strings.Contains(err.Error(), "Too many") { 957 fmt.Fprintf(cli.err, "Error: %v", err) 958 status = 1 959 continue 960 } 961 962 obj, _, err = readBody(cli.call("GET", "/images/"+name+"/json", nil, nil)) 963 if err != nil { 964 if strings.Contains(err.Error(), "No such") { 965 fmt.Fprintf(cli.err, "Error: No such image or container: %s\n", name) 966 } else { 967 fmt.Fprintf(cli.err, "%s", err) 968 } 969 status = 1 970 continue 971 } 972 } 973 974 if tmpl == nil { 975 if err = json.Indent(indented, obj, "", " "); err != nil { 976 fmt.Fprintf(cli.err, "%s\n", err) 977 status = 1 978 continue 979 } 980 } else { 981 // Has template, will render 982 var value interface{} 983 if err := json.Unmarshal(obj, &value); err != nil { 984 fmt.Fprintf(cli.err, "%s\n", err) 985 status = 1 986 continue 987 } 988 if err := tmpl.Execute(cli.out, value); err != nil { 989 return err 990 } 991 cli.out.Write([]byte{'\n'}) 992 } 993 indented.WriteString(",") 994 } 995 996 if indented.Len() > 1 { 997 // Remove trailing ',' 998 indented.Truncate(indented.Len() - 1) 999 } 1000 indented.WriteString("]\n") 1001 1002 if tmpl == nil { 1003 if _, err := io.Copy(cli.out, indented); err != nil { 1004 return err 1005 } 1006 } 1007 1008 if status != 0 { 1009 return &utils.StatusError{StatusCode: status} 1010 } 1011 return nil 1012 } 1013 1014 func (cli *DockerCli) CmdTop(args ...string) error { 1015 cmd := cli.Subcmd("top", "CONTAINER [ps OPTIONS]", "Display the running processes of a container", true) 1016 cmd.Require(flag.Min, 1) 1017 1018 utils.ParseFlags(cmd, args, true) 1019 1020 val := url.Values{} 1021 if cmd.NArg() > 1 { 1022 val.Set("ps_args", strings.Join(cmd.Args()[1:], " ")) 1023 } 1024 1025 stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil, nil) 1026 if err != nil { 1027 return err 1028 } 1029 var procs engine.Env 1030 if err := procs.Decode(stream); err != nil { 1031 return err 1032 } 1033 w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0) 1034 fmt.Fprintln(w, strings.Join(procs.GetList("Titles"), "\t")) 1035 processes := [][]string{} 1036 if err := procs.GetJson("Processes", &processes); err != nil { 1037 return err 1038 } 1039 for _, proc := range processes { 1040 fmt.Fprintln(w, strings.Join(proc, "\t")) 1041 } 1042 w.Flush() 1043 return nil 1044 } 1045 1046 func (cli *DockerCli) CmdPort(args ...string) error { 1047 cmd := cli.Subcmd("port", "CONTAINER [PRIVATE_PORT[/PROTO]]", "List port mappings for the CONTAINER, or lookup the public-facing port that\nis NAT-ed to the PRIVATE_PORT", true) 1048 cmd.Require(flag.Min, 1) 1049 utils.ParseFlags(cmd, args, true) 1050 1051 stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, nil) 1052 if err != nil { 1053 return err 1054 } 1055 1056 env := engine.Env{} 1057 if err := env.Decode(stream); err != nil { 1058 return err 1059 } 1060 ports := nat.PortMap{} 1061 if err := env.GetSubEnv("NetworkSettings").GetJson("Ports", &ports); err != nil { 1062 return err 1063 } 1064 1065 if cmd.NArg() == 2 { 1066 var ( 1067 port = cmd.Arg(1) 1068 proto = "tcp" 1069 parts = strings.SplitN(port, "/", 2) 1070 ) 1071 1072 if len(parts) == 2 && len(parts[1]) != 0 { 1073 port = parts[0] 1074 proto = parts[1] 1075 } 1076 natPort := port + "/" + proto 1077 if frontends, exists := ports[nat.Port(port+"/"+proto)]; exists && frontends != nil { 1078 for _, frontend := range frontends { 1079 fmt.Fprintf(cli.out, "%s:%s\n", frontend.HostIp, frontend.HostPort) 1080 } 1081 return nil 1082 } 1083 return fmt.Errorf("Error: No public port '%s' published for %s", natPort, cmd.Arg(0)) 1084 } 1085 1086 for from, frontends := range ports { 1087 for _, frontend := range frontends { 1088 fmt.Fprintf(cli.out, "%s -> %s:%s\n", from, frontend.HostIp, frontend.HostPort) 1089 } 1090 } 1091 1092 return nil 1093 } 1094 1095 // 'docker rmi IMAGE' removes all images with the name IMAGE 1096 func (cli *DockerCli) CmdRmi(args ...string) error { 1097 var ( 1098 cmd = cli.Subcmd("rmi", "IMAGE [IMAGE...]", "Remove one or more images", true) 1099 force = cmd.Bool([]string{"f", "-force"}, false, "Force removal of the image") 1100 noprune = cmd.Bool([]string{"-no-prune"}, false, "Do not delete untagged parents") 1101 ) 1102 cmd.Require(flag.Min, 1) 1103 1104 utils.ParseFlags(cmd, args, true) 1105 1106 v := url.Values{} 1107 if *force { 1108 v.Set("force", "1") 1109 } 1110 if *noprune { 1111 v.Set("noprune", "1") 1112 } 1113 1114 var encounteredError error 1115 for _, name := range cmd.Args() { 1116 body, _, err := readBody(cli.call("DELETE", "/images/"+name+"?"+v.Encode(), nil, nil)) 1117 if err != nil { 1118 fmt.Fprintf(cli.err, "%s\n", err) 1119 encounteredError = fmt.Errorf("Error: failed to remove one or more images") 1120 } else { 1121 outs := engine.NewTable("Created", 0) 1122 if _, err := outs.ReadListFrom(body); err != nil { 1123 fmt.Fprintf(cli.err, "%s\n", err) 1124 encounteredError = fmt.Errorf("Error: failed to remove one or more images") 1125 continue 1126 } 1127 for _, out := range outs.Data { 1128 if out.Get("Deleted") != "" { 1129 fmt.Fprintf(cli.out, "Deleted: %s\n", out.Get("Deleted")) 1130 } else { 1131 fmt.Fprintf(cli.out, "Untagged: %s\n", out.Get("Untagged")) 1132 } 1133 } 1134 } 1135 } 1136 return encounteredError 1137 } 1138 1139 func (cli *DockerCli) CmdHistory(args ...string) error { 1140 cmd := cli.Subcmd("history", "IMAGE", "Show the history of an image", true) 1141 quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only show numeric IDs") 1142 noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output") 1143 cmd.Require(flag.Exact, 1) 1144 1145 utils.ParseFlags(cmd, args, true) 1146 1147 body, _, err := readBody(cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil, nil)) 1148 if err != nil { 1149 return err 1150 } 1151 1152 outs := engine.NewTable("Created", 0) 1153 if _, err := outs.ReadListFrom(body); err != nil { 1154 return err 1155 } 1156 1157 w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0) 1158 if !*quiet { 1159 fmt.Fprintln(w, "IMAGE\tCREATED\tCREATED BY\tSIZE") 1160 } 1161 1162 for _, out := range outs.Data { 1163 outID := out.Get("Id") 1164 if !*quiet { 1165 if *noTrunc { 1166 fmt.Fprintf(w, "%s\t", outID) 1167 } else { 1168 fmt.Fprintf(w, "%s\t", common.TruncateID(outID)) 1169 } 1170 1171 fmt.Fprintf(w, "%s ago\t", units.HumanDuration(time.Now().UTC().Sub(time.Unix(out.GetInt64("Created"), 0)))) 1172 1173 if *noTrunc { 1174 fmt.Fprintf(w, "%s\t", out.Get("CreatedBy")) 1175 } else { 1176 fmt.Fprintf(w, "%s\t", utils.Trunc(out.Get("CreatedBy"), 45)) 1177 } 1178 fmt.Fprintf(w, "%s\n", units.HumanSize(float64(out.GetInt64("Size")))) 1179 } else { 1180 if *noTrunc { 1181 fmt.Fprintln(w, outID) 1182 } else { 1183 fmt.Fprintln(w, common.TruncateID(outID)) 1184 } 1185 } 1186 } 1187 w.Flush() 1188 return nil 1189 } 1190 1191 func (cli *DockerCli) CmdRm(args ...string) error { 1192 cmd := cli.Subcmd("rm", "CONTAINER [CONTAINER...]", "Remove one or more containers", true) 1193 v := cmd.Bool([]string{"v", "-volumes"}, false, "Remove the volumes associated with the container") 1194 link := cmd.Bool([]string{"l", "#link", "-link"}, false, "Remove the specified link") 1195 force := cmd.Bool([]string{"f", "-force"}, false, "Force the removal of a running container (uses SIGKILL)") 1196 cmd.Require(flag.Min, 1) 1197 1198 utils.ParseFlags(cmd, args, true) 1199 1200 val := url.Values{} 1201 if *v { 1202 val.Set("v", "1") 1203 } 1204 if *link { 1205 val.Set("link", "1") 1206 } 1207 1208 if *force { 1209 val.Set("force", "1") 1210 } 1211 1212 var encounteredError error 1213 for _, name := range cmd.Args() { 1214 _, _, err := readBody(cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil, nil)) 1215 if err != nil { 1216 fmt.Fprintf(cli.err, "%s\n", err) 1217 encounteredError = fmt.Errorf("Error: failed to remove one or more containers") 1218 } else { 1219 fmt.Fprintf(cli.out, "%s\n", name) 1220 } 1221 } 1222 return encounteredError 1223 } 1224 1225 // 'docker kill NAME' kills a running container 1226 func (cli *DockerCli) CmdKill(args ...string) error { 1227 cmd := cli.Subcmd("kill", "CONTAINER [CONTAINER...]", "Kill a running container using SIGKILL or a specified signal", true) 1228 signal := cmd.String([]string{"s", "-signal"}, "KILL", "Signal to send to the container") 1229 cmd.Require(flag.Min, 1) 1230 1231 utils.ParseFlags(cmd, args, true) 1232 1233 var encounteredError error 1234 for _, name := range cmd.Args() { 1235 if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%s", name, *signal), nil, nil)); err != nil { 1236 fmt.Fprintf(cli.err, "%s\n", err) 1237 encounteredError = fmt.Errorf("Error: failed to kill one or more containers") 1238 } else { 1239 fmt.Fprintf(cli.out, "%s\n", name) 1240 } 1241 } 1242 return encounteredError 1243 } 1244 1245 func (cli *DockerCli) CmdImport(args ...string) error { 1246 cmd := cli.Subcmd("import", "URL|- [REPOSITORY[:TAG]]", "Create an empty filesystem image and import the contents of the\ntarball (.tar, .tar.gz, .tgz, .bzip, .tar.xz, .txz) into it, then\noptionally tag it.", true) 1247 flChanges := opts.NewListOpts(nil) 1248 cmd.Var(&flChanges, []string{"c", "-change"}, "Apply Dockerfile instruction to the created image") 1249 cmd.Require(flag.Min, 1) 1250 1251 utils.ParseFlags(cmd, args, true) 1252 1253 var ( 1254 v = url.Values{} 1255 src = cmd.Arg(0) 1256 repository = cmd.Arg(1) 1257 ) 1258 1259 v.Set("fromSrc", src) 1260 v.Set("repo", repository) 1261 for _, change := range flChanges.GetAll() { 1262 v.Add("changes", change) 1263 } 1264 if cmd.NArg() == 3 { 1265 fmt.Fprintf(cli.err, "[DEPRECATED] The format 'URL|- [REPOSITORY [TAG]]' has been deprecated. Please use URL|- [REPOSITORY[:TAG]]\n") 1266 v.Set("tag", cmd.Arg(2)) 1267 } 1268 1269 if repository != "" { 1270 //Check if the given image name can be resolved 1271 repo, _ := parsers.ParseRepositoryTag(repository) 1272 if err := registry.ValidateRepositoryName(repo); err != nil { 1273 return err 1274 } 1275 } 1276 1277 var in io.Reader 1278 1279 if src == "-" { 1280 in = cli.in 1281 } 1282 1283 return cli.stream("POST", "/images/create?"+v.Encode(), in, cli.out, nil) 1284 } 1285 1286 func (cli *DockerCli) CmdPush(args ...string) error { 1287 cmd := cli.Subcmd("push", "NAME[:TAG]", "Push an image or a repository to the registry", true) 1288 cmd.Require(flag.Exact, 1) 1289 1290 utils.ParseFlags(cmd, args, true) 1291 1292 name := cmd.Arg(0) 1293 1294 cli.LoadConfigFile() 1295 1296 remote, tag := parsers.ParseRepositoryTag(name) 1297 1298 // Resolve the Repository name from fqn to RepositoryInfo 1299 repoInfo, err := registry.ParseRepositoryInfo(remote) 1300 if err != nil { 1301 return err 1302 } 1303 // Resolve the Auth config relevant for this server 1304 authConfig := cli.configFile.ResolveAuthConfig(repoInfo.Index) 1305 // If we're not using a custom registry, we know the restrictions 1306 // applied to repository names and can warn the user in advance. 1307 // Custom repositories can have different rules, and we must also 1308 // allow pushing by image ID. 1309 if repoInfo.Official { 1310 username := authConfig.Username 1311 if username == "" { 1312 username = "<user>" 1313 } 1314 return fmt.Errorf("You cannot push a \"root\" repository. Please rename your repository to <user>/<repo> (ex: %s/%s)", username, repoInfo.LocalName) 1315 } 1316 1317 v := url.Values{} 1318 v.Set("tag", tag) 1319 1320 _, _, err = cli.clientRequestAttemptLogin("POST", "/images/"+remote+"/push?"+v.Encode(), nil, cli.out, repoInfo.Index, "push") 1321 return err 1322 } 1323 1324 func (cli *DockerCli) CmdPull(args ...string) error { 1325 cmd := cli.Subcmd("pull", "NAME[:TAG|@DIGEST]", "Pull an image or a repository from the registry", true) 1326 allTags := cmd.Bool([]string{"a", "-all-tags"}, false, "Download all tagged images in the repository") 1327 cmd.Require(flag.Exact, 1) 1328 1329 utils.ParseFlags(cmd, args, true) 1330 1331 var ( 1332 v = url.Values{} 1333 remote = cmd.Arg(0) 1334 newRemote = remote 1335 ) 1336 taglessRemote, tag := parsers.ParseRepositoryTag(remote) 1337 if tag == "" && !*allTags { 1338 newRemote = utils.ImageReference(taglessRemote, graph.DEFAULTTAG) 1339 } 1340 if tag != "" && *allTags { 1341 return fmt.Errorf("tag can't be used with --all-tags/-a") 1342 } 1343 1344 v.Set("fromImage", newRemote) 1345 1346 // Resolve the Repository name from fqn to RepositoryInfo 1347 repoInfo, err := registry.ParseRepositoryInfo(taglessRemote) 1348 if err != nil { 1349 return err 1350 } 1351 1352 cli.LoadConfigFile() 1353 1354 _, _, err = cli.clientRequestAttemptLogin("POST", "/images/create?"+v.Encode(), nil, cli.out, repoInfo.Index, "pull") 1355 return err 1356 } 1357 1358 func (cli *DockerCli) CmdImages(args ...string) error { 1359 cmd := cli.Subcmd("images", "[REPOSITORY]", "List images", true) 1360 quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only show numeric IDs") 1361 all := cmd.Bool([]string{"a", "-all"}, false, "Show all images (default hides intermediate images)") 1362 noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output") 1363 showDigests := cmd.Bool([]string{"-digests"}, false, "Show digests") 1364 // FIXME: --viz and --tree are deprecated. Remove them in a future version. 1365 flViz := cmd.Bool([]string{"#v", "#viz", "#-viz"}, false, "Output graph in graphviz format") 1366 flTree := cmd.Bool([]string{"#t", "#tree", "#-tree"}, false, "Output graph in tree format") 1367 1368 flFilter := opts.NewListOpts(nil) 1369 cmd.Var(&flFilter, []string{"f", "-filter"}, "Filter output based on conditions provided") 1370 cmd.Require(flag.Max, 1) 1371 1372 utils.ParseFlags(cmd, args, true) 1373 1374 // Consolidate all filter flags, and sanity check them early. 1375 // They'll get process in the daemon/server. 1376 imageFilterArgs := filters.Args{} 1377 for _, f := range flFilter.GetAll() { 1378 var err error 1379 imageFilterArgs, err = filters.ParseFlag(f, imageFilterArgs) 1380 if err != nil { 1381 return err 1382 } 1383 } 1384 1385 matchName := cmd.Arg(0) 1386 // FIXME: --viz and --tree are deprecated. Remove them in a future version. 1387 if *flViz || *flTree { 1388 v := url.Values{ 1389 "all": []string{"1"}, 1390 } 1391 if len(imageFilterArgs) > 0 { 1392 filterJson, err := filters.ToParam(imageFilterArgs) 1393 if err != nil { 1394 return err 1395 } 1396 v.Set("filters", filterJson) 1397 } 1398 1399 body, _, err := readBody(cli.call("GET", "/images/json?"+v.Encode(), nil, nil)) 1400 if err != nil { 1401 return err 1402 } 1403 1404 outs := engine.NewTable("Created", 0) 1405 if _, err := outs.ReadListFrom(body); err != nil { 1406 return err 1407 } 1408 1409 var ( 1410 printNode func(cli *DockerCli, noTrunc bool, image *engine.Env, prefix string) 1411 startImage *engine.Env 1412 1413 roots = engine.NewTable("Created", outs.Len()) 1414 byParent = make(map[string]*engine.Table) 1415 ) 1416 1417 for _, image := range outs.Data { 1418 if image.Get("ParentId") == "" { 1419 roots.Add(image) 1420 } else { 1421 if children, exists := byParent[image.Get("ParentId")]; exists { 1422 children.Add(image) 1423 } else { 1424 byParent[image.Get("ParentId")] = engine.NewTable("Created", 1) 1425 byParent[image.Get("ParentId")].Add(image) 1426 } 1427 } 1428 1429 if matchName != "" { 1430 if matchName == image.Get("Id") || matchName == common.TruncateID(image.Get("Id")) { 1431 startImage = image 1432 } 1433 1434 for _, repotag := range image.GetList("RepoTags") { 1435 if repotag == matchName { 1436 startImage = image 1437 } 1438 } 1439 } 1440 } 1441 1442 if *flViz { 1443 fmt.Fprintf(cli.out, "digraph docker {\n") 1444 printNode = (*DockerCli).printVizNode 1445 } else { 1446 printNode = (*DockerCli).printTreeNode 1447 } 1448 1449 if startImage != nil { 1450 root := engine.NewTable("Created", 1) 1451 root.Add(startImage) 1452 cli.WalkTree(*noTrunc, root, byParent, "", printNode) 1453 } else if matchName == "" { 1454 cli.WalkTree(*noTrunc, roots, byParent, "", printNode) 1455 } 1456 if *flViz { 1457 fmt.Fprintf(cli.out, " base [style=invisible]\n}\n") 1458 } 1459 } else { 1460 v := url.Values{} 1461 if len(imageFilterArgs) > 0 { 1462 filterJson, err := filters.ToParam(imageFilterArgs) 1463 if err != nil { 1464 return err 1465 } 1466 v.Set("filters", filterJson) 1467 } 1468 1469 if cmd.NArg() == 1 { 1470 // FIXME rename this parameter, to not be confused with the filters flag 1471 v.Set("filter", matchName) 1472 } 1473 if *all { 1474 v.Set("all", "1") 1475 } 1476 1477 body, _, err := readBody(cli.call("GET", "/images/json?"+v.Encode(), nil, nil)) 1478 1479 if err != nil { 1480 return err 1481 } 1482 1483 outs := engine.NewTable("Created", 0) 1484 if _, err := outs.ReadListFrom(body); err != nil { 1485 return err 1486 } 1487 1488 w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0) 1489 if !*quiet { 1490 if *showDigests { 1491 fmt.Fprintln(w, "REPOSITORY\tTAG\tDIGEST\tIMAGE ID\tCREATED\tVIRTUAL SIZE") 1492 } else { 1493 fmt.Fprintln(w, "REPOSITORY\tTAG\tIMAGE ID\tCREATED\tVIRTUAL SIZE") 1494 } 1495 } 1496 1497 for _, out := range outs.Data { 1498 outID := out.Get("Id") 1499 if !*noTrunc { 1500 outID = common.TruncateID(outID) 1501 } 1502 1503 repoTags := out.GetList("RepoTags") 1504 repoDigests := out.GetList("RepoDigests") 1505 1506 if len(repoTags) == 1 && repoTags[0] == "<none>:<none>" && len(repoDigests) == 1 && repoDigests[0] == "<none>@<none>" { 1507 // dangling image - clear out either repoTags or repoDigsts so we only show it once below 1508 repoDigests = []string{} 1509 } 1510 1511 // combine the tags and digests lists 1512 tagsAndDigests := append(repoTags, repoDigests...) 1513 for _, repoAndRef := range tagsAndDigests { 1514 repo, ref := parsers.ParseRepositoryTag(repoAndRef) 1515 // default tag and digest to none - if there's a value, it'll be set below 1516 tag := "<none>" 1517 digest := "<none>" 1518 if utils.DigestReference(ref) { 1519 digest = ref 1520 } else { 1521 tag = ref 1522 } 1523 1524 if !*quiet { 1525 if *showDigests { 1526 fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s ago\t%s\n", repo, tag, digest, outID, units.HumanDuration(time.Now().UTC().Sub(time.Unix(out.GetInt64("Created"), 0))), units.HumanSize(float64(out.GetInt64("VirtualSize")))) 1527 } else { 1528 fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\n", repo, tag, outID, units.HumanDuration(time.Now().UTC().Sub(time.Unix(out.GetInt64("Created"), 0))), units.HumanSize(float64(out.GetInt64("VirtualSize")))) 1529 } 1530 } else { 1531 fmt.Fprintln(w, outID) 1532 } 1533 } 1534 } 1535 1536 if !*quiet { 1537 w.Flush() 1538 } 1539 } 1540 return nil 1541 } 1542 1543 // FIXME: --viz and --tree are deprecated. Remove them in a future version. 1544 func (cli *DockerCli) WalkTree(noTrunc bool, images *engine.Table, byParent map[string]*engine.Table, prefix string, printNode func(cli *DockerCli, noTrunc bool, image *engine.Env, prefix string)) { 1545 length := images.Len() 1546 if length > 1 { 1547 for index, image := range images.Data { 1548 if index+1 == length { 1549 printNode(cli, noTrunc, image, prefix+"└─") 1550 if subimages, exists := byParent[image.Get("Id")]; exists { 1551 cli.WalkTree(noTrunc, subimages, byParent, prefix+" ", printNode) 1552 } 1553 } else { 1554 printNode(cli, noTrunc, image, prefix+"\u251C─") 1555 if subimages, exists := byParent[image.Get("Id")]; exists { 1556 cli.WalkTree(noTrunc, subimages, byParent, prefix+"\u2502 ", printNode) 1557 } 1558 } 1559 } 1560 } else { 1561 for _, image := range images.Data { 1562 printNode(cli, noTrunc, image, prefix+"└─") 1563 if subimages, exists := byParent[image.Get("Id")]; exists { 1564 cli.WalkTree(noTrunc, subimages, byParent, prefix+" ", printNode) 1565 } 1566 } 1567 } 1568 } 1569 1570 // FIXME: --viz and --tree are deprecated. Remove them in a future version. 1571 func (cli *DockerCli) printVizNode(noTrunc bool, image *engine.Env, prefix string) { 1572 var ( 1573 imageID string 1574 parentID string 1575 ) 1576 if noTrunc { 1577 imageID = image.Get("Id") 1578 parentID = image.Get("ParentId") 1579 } else { 1580 imageID = common.TruncateID(image.Get("Id")) 1581 parentID = common.TruncateID(image.Get("ParentId")) 1582 } 1583 if parentID == "" { 1584 fmt.Fprintf(cli.out, " base -> \"%s\" [style=invis]\n", imageID) 1585 } else { 1586 fmt.Fprintf(cli.out, " \"%s\" -> \"%s\"\n", parentID, imageID) 1587 } 1588 if image.GetList("RepoTags")[0] != "<none>:<none>" { 1589 fmt.Fprintf(cli.out, " \"%s\" [label=\"%s\\n%s\",shape=box,fillcolor=\"paleturquoise\",style=\"filled,rounded\"];\n", 1590 imageID, imageID, strings.Join(image.GetList("RepoTags"), "\\n")) 1591 } 1592 } 1593 1594 // FIXME: --viz and --tree are deprecated. Remove them in a future version. 1595 func (cli *DockerCli) printTreeNode(noTrunc bool, image *engine.Env, prefix string) { 1596 var imageID string 1597 if noTrunc { 1598 imageID = image.Get("Id") 1599 } else { 1600 imageID = common.TruncateID(image.Get("Id")) 1601 } 1602 1603 fmt.Fprintf(cli.out, "%s%s Virtual Size: %s", prefix, imageID, units.HumanSize(float64(image.GetInt64("VirtualSize")))) 1604 if image.GetList("RepoTags")[0] != "<none>:<none>" { 1605 fmt.Fprintf(cli.out, " Tags: %s\n", strings.Join(image.GetList("RepoTags"), ", ")) 1606 } else { 1607 fmt.Fprint(cli.out, "\n") 1608 } 1609 } 1610 1611 func (cli *DockerCli) CmdPs(args ...string) error { 1612 var ( 1613 err error 1614 1615 psFilterArgs = filters.Args{} 1616 v = url.Values{} 1617 1618 cmd = cli.Subcmd("ps", "", "List containers", true) 1619 quiet = cmd.Bool([]string{"q", "-quiet"}, false, "Only display numeric IDs") 1620 size = cmd.Bool([]string{"s", "-size"}, false, "Display total file sizes") 1621 all = cmd.Bool([]string{"a", "-all"}, false, "Show all containers (default shows just running)") 1622 noTrunc = cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output") 1623 nLatest = cmd.Bool([]string{"l", "-latest"}, false, "Show the latest created container, include non-running") 1624 since = cmd.String([]string{"#sinceId", "#-since-id", "-since"}, "", "Show created since Id or Name, include non-running") 1625 before = cmd.String([]string{"#beforeId", "#-before-id", "-before"}, "", "Show only container created before Id or Name") 1626 last = cmd.Int([]string{"n"}, -1, "Show n last created containers, include non-running") 1627 flFilter = opts.NewListOpts(nil) 1628 ) 1629 cmd.Require(flag.Exact, 0) 1630 1631 cmd.Var(&flFilter, []string{"f", "-filter"}, "Filter output based on conditions provided") 1632 1633 utils.ParseFlags(cmd, args, true) 1634 if *last == -1 && *nLatest { 1635 *last = 1 1636 } 1637 1638 if *all { 1639 v.Set("all", "1") 1640 } 1641 1642 if *last != -1 { 1643 v.Set("limit", strconv.Itoa(*last)) 1644 } 1645 1646 if *since != "" { 1647 v.Set("since", *since) 1648 } 1649 1650 if *before != "" { 1651 v.Set("before", *before) 1652 } 1653 1654 if *size { 1655 v.Set("size", "1") 1656 } 1657 1658 // Consolidate all filter flags, and sanity check them. 1659 // They'll get processed in the daemon/server. 1660 for _, f := range flFilter.GetAll() { 1661 if psFilterArgs, err = filters.ParseFlag(f, psFilterArgs); err != nil { 1662 return err 1663 } 1664 } 1665 1666 if len(psFilterArgs) > 0 { 1667 filterJson, err := filters.ToParam(psFilterArgs) 1668 if err != nil { 1669 return err 1670 } 1671 1672 v.Set("filters", filterJson) 1673 } 1674 1675 body, _, err := readBody(cli.call("GET", "/containers/json?"+v.Encode(), nil, nil)) 1676 if err != nil { 1677 return err 1678 } 1679 1680 outs := engine.NewTable("Created", 0) 1681 if _, err := outs.ReadListFrom(body); err != nil { 1682 return err 1683 } 1684 1685 w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0) 1686 if !*quiet { 1687 fmt.Fprint(w, "CONTAINER ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS\tNAMES") 1688 1689 if *size { 1690 fmt.Fprintln(w, "\tSIZE") 1691 } else { 1692 fmt.Fprint(w, "\n") 1693 } 1694 } 1695 1696 stripNamePrefix := func(ss []string) []string { 1697 for i, s := range ss { 1698 ss[i] = s[1:] 1699 } 1700 1701 return ss 1702 } 1703 1704 for _, out := range outs.Data { 1705 outID := out.Get("Id") 1706 1707 if !*noTrunc { 1708 outID = common.TruncateID(outID) 1709 } 1710 1711 if *quiet { 1712 fmt.Fprintln(w, outID) 1713 1714 continue 1715 } 1716 1717 var ( 1718 outNames = stripNamePrefix(out.GetList("Names")) 1719 outCommand = strconv.Quote(out.Get("Command")) 1720 ports = engine.NewTable("", 0) 1721 ) 1722 1723 if !*noTrunc { 1724 outCommand = utils.Trunc(outCommand, 20) 1725 1726 // only display the default name for the container with notrunc is passed 1727 for _, name := range outNames { 1728 if len(strings.Split(name, "/")) == 1 { 1729 outNames = []string{name} 1730 1731 break 1732 } 1733 } 1734 } 1735 1736 ports.ReadListFrom([]byte(out.Get("Ports"))) 1737 1738 image := out.Get("Image") 1739 if image == "" { 1740 image = "<no image>" 1741 } 1742 1743 fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\t%s\t%s\t", outID, image, outCommand, 1744 units.HumanDuration(time.Now().UTC().Sub(time.Unix(out.GetInt64("Created"), 0))), 1745 out.Get("Status"), api.DisplayablePorts(ports), strings.Join(outNames, ",")) 1746 1747 if *size { 1748 if out.GetInt("SizeRootFs") > 0 { 1749 fmt.Fprintf(w, "%s (virtual %s)\n", units.HumanSize(float64(out.GetInt64("SizeRw"))), units.HumanSize(float64(out.GetInt64("SizeRootFs")))) 1750 } else { 1751 fmt.Fprintf(w, "%s\n", units.HumanSize(float64(out.GetInt64("SizeRw")))) 1752 } 1753 1754 continue 1755 } 1756 1757 fmt.Fprint(w, "\n") 1758 } 1759 1760 if !*quiet { 1761 w.Flush() 1762 } 1763 1764 return nil 1765 } 1766 1767 func (cli *DockerCli) CmdCommit(args ...string) error { 1768 cmd := cli.Subcmd("commit", "CONTAINER [REPOSITORY[:TAG]]", "Create a new image from a container's changes", true) 1769 flPause := cmd.Bool([]string{"p", "-pause"}, true, "Pause container during commit") 1770 flComment := cmd.String([]string{"m", "-message"}, "", "Commit message") 1771 flAuthor := cmd.String([]string{"a", "#author", "-author"}, "", "Author (e.g., \"John Hannibal Smith <hannibal@a-team.com>\")") 1772 flChanges := opts.NewListOpts(nil) 1773 cmd.Var(&flChanges, []string{"c", "-change"}, "Apply Dockerfile instruction to the created image") 1774 // FIXME: --run is deprecated, it will be replaced with inline Dockerfile commands. 1775 flConfig := cmd.String([]string{"#run", "#-run"}, "", "This option is deprecated and will be removed in a future version in favor of inline Dockerfile-compatible commands") 1776 cmd.Require(flag.Max, 2) 1777 cmd.Require(flag.Min, 1) 1778 utils.ParseFlags(cmd, args, true) 1779 1780 var ( 1781 name = cmd.Arg(0) 1782 repository, tag = parsers.ParseRepositoryTag(cmd.Arg(1)) 1783 ) 1784 1785 //Check if the given image name can be resolved 1786 if repository != "" { 1787 if err := registry.ValidateRepositoryName(repository); err != nil { 1788 return err 1789 } 1790 } 1791 1792 v := url.Values{} 1793 v.Set("container", name) 1794 v.Set("repo", repository) 1795 v.Set("tag", tag) 1796 v.Set("comment", *flComment) 1797 v.Set("author", *flAuthor) 1798 for _, change := range flChanges.GetAll() { 1799 v.Add("changes", change) 1800 } 1801 1802 if *flPause != true { 1803 v.Set("pause", "0") 1804 } 1805 1806 var ( 1807 config *runconfig.Config 1808 env engine.Env 1809 ) 1810 if *flConfig != "" { 1811 config = &runconfig.Config{} 1812 if err := json.Unmarshal([]byte(*flConfig), config); err != nil { 1813 return err 1814 } 1815 } 1816 stream, _, err := cli.call("POST", "/commit?"+v.Encode(), config, nil) 1817 if err != nil { 1818 return err 1819 } 1820 if err := env.Decode(stream); err != nil { 1821 return err 1822 } 1823 1824 fmt.Fprintf(cli.out, "%s\n", env.Get("Id")) 1825 return nil 1826 } 1827 1828 func (cli *DockerCli) CmdEvents(args ...string) error { 1829 cmd := cli.Subcmd("events", "", "Get real time events from the server", true) 1830 since := cmd.String([]string{"#since", "-since"}, "", "Show all events created since timestamp") 1831 until := cmd.String([]string{"-until"}, "", "Stream events until this timestamp") 1832 flFilter := opts.NewListOpts(nil) 1833 cmd.Var(&flFilter, []string{"f", "-filter"}, "Filter output based on conditions provided") 1834 cmd.Require(flag.Exact, 0) 1835 1836 utils.ParseFlags(cmd, args, true) 1837 1838 var ( 1839 v = url.Values{} 1840 loc = time.FixedZone(time.Now().Zone()) 1841 eventFilterArgs = filters.Args{} 1842 ) 1843 1844 // Consolidate all filter flags, and sanity check them early. 1845 // They'll get process in the daemon/server. 1846 for _, f := range flFilter.GetAll() { 1847 var err error 1848 eventFilterArgs, err = filters.ParseFlag(f, eventFilterArgs) 1849 if err != nil { 1850 return err 1851 } 1852 } 1853 var setTime = func(key, value string) { 1854 format := timeutils.RFC3339NanoFixed 1855 if len(value) < len(format) { 1856 format = format[:len(value)] 1857 } 1858 if t, err := time.ParseInLocation(format, value, loc); err == nil { 1859 v.Set(key, strconv.FormatInt(t.Unix(), 10)) 1860 } else { 1861 v.Set(key, value) 1862 } 1863 } 1864 if *since != "" { 1865 setTime("since", *since) 1866 } 1867 if *until != "" { 1868 setTime("until", *until) 1869 } 1870 if len(eventFilterArgs) > 0 { 1871 filterJson, err := filters.ToParam(eventFilterArgs) 1872 if err != nil { 1873 return err 1874 } 1875 v.Set("filters", filterJson) 1876 } 1877 if err := cli.stream("GET", "/events?"+v.Encode(), nil, cli.out, nil); err != nil { 1878 return err 1879 } 1880 return nil 1881 } 1882 1883 func (cli *DockerCli) CmdExport(args ...string) error { 1884 cmd := cli.Subcmd("export", "CONTAINER", "Export a filesystem as a tar archive (streamed to STDOUT by default)", true) 1885 outfile := cmd.String([]string{"o", "-output"}, "", "Write to a file, instead of STDOUT") 1886 cmd.Require(flag.Exact, 1) 1887 1888 utils.ParseFlags(cmd, args, true) 1889 1890 var ( 1891 output io.Writer = cli.out 1892 err error 1893 ) 1894 if *outfile != "" { 1895 output, err = os.Create(*outfile) 1896 if err != nil { 1897 return err 1898 } 1899 } else if cli.isTerminalOut { 1900 return errors.New("Cowardly refusing to save to a terminal. Use the -o flag or redirect.") 1901 } 1902 1903 if len(cmd.Args()) == 1 { 1904 image := cmd.Arg(0) 1905 if err := cli.stream("GET", "/containers/"+image+"/export", nil, output, nil); err != nil { 1906 return err 1907 } 1908 } else { 1909 v := url.Values{} 1910 for _, arg := range cmd.Args() { 1911 v.Add("names", arg) 1912 } 1913 if err := cli.stream("GET", "/containers/get?"+v.Encode(), nil, output, nil); err != nil { 1914 return err 1915 } 1916 } 1917 1918 return nil 1919 } 1920 1921 func (cli *DockerCli) CmdDiff(args ...string) error { 1922 cmd := cli.Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem", true) 1923 cmd.Require(flag.Exact, 1) 1924 1925 utils.ParseFlags(cmd, args, true) 1926 1927 body, _, err := readBody(cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil, nil)) 1928 1929 if err != nil { 1930 return err 1931 } 1932 1933 outs := engine.NewTable("", 0) 1934 if _, err := outs.ReadListFrom(body); err != nil { 1935 return err 1936 } 1937 for _, change := range outs.Data { 1938 var kind string 1939 switch change.GetInt("Kind") { 1940 case archive.ChangeModify: 1941 kind = "C" 1942 case archive.ChangeAdd: 1943 kind = "A" 1944 case archive.ChangeDelete: 1945 kind = "D" 1946 } 1947 fmt.Fprintf(cli.out, "%s %s\n", kind, change.Get("Path")) 1948 } 1949 return nil 1950 } 1951 1952 func (cli *DockerCli) CmdLogs(args ...string) error { 1953 var ( 1954 cmd = cli.Subcmd("logs", "CONTAINER", "Fetch the logs of a container", true) 1955 follow = cmd.Bool([]string{"f", "-follow"}, false, "Follow log output") 1956 times = cmd.Bool([]string{"t", "-timestamps"}, false, "Show timestamps") 1957 tail = cmd.String([]string{"-tail"}, "all", "Number of lines to show from the end of the logs") 1958 ) 1959 cmd.Require(flag.Exact, 1) 1960 1961 utils.ParseFlags(cmd, args, true) 1962 1963 name := cmd.Arg(0) 1964 1965 stream, _, err := cli.call("GET", "/containers/"+name+"/json", nil, nil) 1966 if err != nil { 1967 return err 1968 } 1969 1970 env := engine.Env{} 1971 if err := env.Decode(stream); err != nil { 1972 return err 1973 } 1974 1975 if env.GetSubEnv("HostConfig").GetSubEnv("LogConfig").Get("Type") != "json-file" { 1976 return fmt.Errorf("\"logs\" command is supported only for \"json-file\" logging driver") 1977 } 1978 1979 v := url.Values{} 1980 v.Set("stdout", "1") 1981 v.Set("stderr", "1") 1982 1983 if *times { 1984 v.Set("timestamps", "1") 1985 } 1986 1987 if *follow { 1988 v.Set("follow", "1") 1989 } 1990 v.Set("tail", *tail) 1991 1992 return cli.streamHelper("GET", "/containers/"+name+"/logs?"+v.Encode(), env.GetSubEnv("Config").GetBool("Tty"), nil, cli.out, cli.err, nil) 1993 } 1994 1995 func (cli *DockerCli) CmdAttach(args ...string) error { 1996 var ( 1997 cmd = cli.Subcmd("attach", "CONTAINER", "Attach to a running container", true) 1998 noStdin = cmd.Bool([]string{"#nostdin", "-no-stdin"}, false, "Do not attach STDIN") 1999 proxy = cmd.Bool([]string{"#sig-proxy", "-sig-proxy"}, true, "Proxy all received signals to the process") 2000 ) 2001 cmd.Require(flag.Exact, 1) 2002 2003 utils.ParseFlags(cmd, args, true) 2004 name := cmd.Arg(0) 2005 2006 stream, _, err := cli.call("GET", "/containers/"+name+"/json", nil, nil) 2007 if err != nil { 2008 return err 2009 } 2010 2011 env := engine.Env{} 2012 if err := env.Decode(stream); err != nil { 2013 return err 2014 } 2015 2016 if !env.GetSubEnv("State").GetBool("Running") { 2017 return fmt.Errorf("You cannot attach to a stopped container, start it first") 2018 } 2019 2020 var ( 2021 config = env.GetSubEnv("Config") 2022 tty = config.GetBool("Tty") 2023 ) 2024 2025 if err := cli.CheckTtyInput(!*noStdin, tty); err != nil { 2026 return err 2027 } 2028 2029 if tty && cli.isTerminalOut { 2030 if err := cli.monitorTtySize(cmd.Arg(0), false); err != nil { 2031 log.Debugf("Error monitoring TTY size: %s", err) 2032 } 2033 } 2034 2035 var in io.ReadCloser 2036 2037 v := url.Values{} 2038 v.Set("stream", "1") 2039 if !*noStdin && config.GetBool("OpenStdin") { 2040 v.Set("stdin", "1") 2041 in = cli.in 2042 } 2043 2044 v.Set("stdout", "1") 2045 v.Set("stderr", "1") 2046 2047 if *proxy && !tty { 2048 sigc := cli.forwardAllSignals(cmd.Arg(0)) 2049 defer signal.StopCatch(sigc) 2050 } 2051 2052 if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), tty, in, cli.out, cli.err, nil, nil); err != nil { 2053 return err 2054 } 2055 2056 _, status, err := getExitCode(cli, cmd.Arg(0)) 2057 if err != nil { 2058 return err 2059 } 2060 if status != 0 { 2061 return &utils.StatusError{StatusCode: status} 2062 } 2063 2064 return nil 2065 } 2066 2067 func (cli *DockerCli) CmdSearch(args ...string) error { 2068 cmd := cli.Subcmd("search", "TERM", "Search the Docker Hub for images", true) 2069 noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output") 2070 trusted := cmd.Bool([]string{"#t", "#trusted", "#-trusted"}, false, "Only show trusted builds") 2071 automated := cmd.Bool([]string{"-automated"}, false, "Only show automated builds") 2072 stars := cmd.Int([]string{"s", "#stars", "-stars"}, 0, "Only displays with at least x stars") 2073 cmd.Require(flag.Exact, 1) 2074 2075 utils.ParseFlags(cmd, args, true) 2076 2077 name := cmd.Arg(0) 2078 v := url.Values{} 2079 v.Set("term", name) 2080 2081 // Resolve the Repository name from fqn to hostname + name 2082 taglessRemote, _ := parsers.ParseRepositoryTag(name) 2083 repoInfo, err := registry.ParseRepositoryInfo(taglessRemote) 2084 if err != nil { 2085 return err 2086 } 2087 2088 cli.LoadConfigFile() 2089 2090 body, statusCode, errReq := cli.clientRequestAttemptLogin("GET", "/images/search?"+v.Encode(), nil, nil, repoInfo.Index, "search") 2091 rawBody, _, err := readBody(body, statusCode, errReq) 2092 if err != nil { 2093 return err 2094 } 2095 2096 outs := engine.NewTable("star_count", 0) 2097 if _, err := outs.ReadListFrom(rawBody); err != nil { 2098 return err 2099 } 2100 w := tabwriter.NewWriter(cli.out, 10, 1, 3, ' ', 0) 2101 fmt.Fprintf(w, "NAME\tDESCRIPTION\tSTARS\tOFFICIAL\tAUTOMATED\n") 2102 for _, out := range outs.Data { 2103 if ((*automated || *trusted) && (!out.GetBool("is_trusted") && !out.GetBool("is_automated"))) || (*stars > out.GetInt("star_count")) { 2104 continue 2105 } 2106 desc := strings.Replace(out.Get("description"), "\n", " ", -1) 2107 desc = strings.Replace(desc, "\r", " ", -1) 2108 if !*noTrunc && len(desc) > 45 { 2109 desc = utils.Trunc(desc, 42) + "..." 2110 } 2111 fmt.Fprintf(w, "%s\t%s\t%d\t", out.Get("name"), desc, out.GetInt("star_count")) 2112 if out.GetBool("is_official") { 2113 fmt.Fprint(w, "[OK]") 2114 2115 } 2116 fmt.Fprint(w, "\t") 2117 if out.GetBool("is_automated") || out.GetBool("is_trusted") { 2118 fmt.Fprint(w, "[OK]") 2119 } 2120 fmt.Fprint(w, "\n") 2121 } 2122 w.Flush() 2123 return nil 2124 } 2125 2126 // Ports type - Used to parse multiple -p flags 2127 type ports []int 2128 2129 func (cli *DockerCli) CmdTag(args ...string) error { 2130 cmd := cli.Subcmd("tag", "IMAGE[:TAG] [REGISTRYHOST/][USERNAME/]NAME[:TAG]", "Tag an image into a repository", true) 2131 force := cmd.Bool([]string{"f", "#force", "-force"}, false, "Force") 2132 cmd.Require(flag.Exact, 2) 2133 2134 utils.ParseFlags(cmd, args, true) 2135 2136 var ( 2137 repository, tag = parsers.ParseRepositoryTag(cmd.Arg(1)) 2138 v = url.Values{} 2139 ) 2140 2141 //Check if the given image name can be resolved 2142 if err := registry.ValidateRepositoryName(repository); err != nil { 2143 return err 2144 } 2145 v.Set("repo", repository) 2146 v.Set("tag", tag) 2147 2148 if *force { 2149 v.Set("force", "1") 2150 } 2151 2152 if _, _, err := readBody(cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil, nil)); err != nil { 2153 return err 2154 } 2155 return nil 2156 } 2157 2158 func (cli *DockerCli) pullImage(image string) error { 2159 return cli.pullImageCustomOut(image, cli.out) 2160 } 2161 2162 func (cli *DockerCli) pullImageCustomOut(image string, out io.Writer) error { 2163 v := url.Values{} 2164 repos, tag := parsers.ParseRepositoryTag(image) 2165 // pull only the image tagged 'latest' if no tag was specified 2166 if tag == "" { 2167 tag = graph.DEFAULTTAG 2168 } 2169 v.Set("fromImage", repos) 2170 v.Set("tag", tag) 2171 2172 // Resolve the Repository name from fqn to RepositoryInfo 2173 repoInfo, err := registry.ParseRepositoryInfo(repos) 2174 if err != nil { 2175 return err 2176 } 2177 2178 // Load the auth config file, to be able to pull the image 2179 cli.LoadConfigFile() 2180 2181 // Resolve the Auth config relevant for this server 2182 authConfig := cli.configFile.ResolveAuthConfig(repoInfo.Index) 2183 buf, err := json.Marshal(authConfig) 2184 if err != nil { 2185 return err 2186 } 2187 2188 registryAuthHeader := []string{ 2189 base64.URLEncoding.EncodeToString(buf), 2190 } 2191 if err = cli.stream("POST", "/images/create?"+v.Encode(), nil, out, map[string][]string{"X-Registry-Auth": registryAuthHeader}); err != nil { 2192 return err 2193 } 2194 return nil 2195 } 2196 2197 type cidFile struct { 2198 path string 2199 file *os.File 2200 written bool 2201 } 2202 2203 func newCIDFile(path string) (*cidFile, error) { 2204 if _, err := os.Stat(path); err == nil { 2205 return nil, fmt.Errorf("Container ID file found, make sure the other container isn't running or delete %s", path) 2206 } 2207 2208 f, err := os.Create(path) 2209 if err != nil { 2210 return nil, fmt.Errorf("Failed to create the container ID file: %s", err) 2211 } 2212 2213 return &cidFile{path: path, file: f}, nil 2214 } 2215 2216 func (cid *cidFile) Close() error { 2217 cid.file.Close() 2218 2219 if !cid.written { 2220 if err := os.Remove(cid.path); err != nil { 2221 return fmt.Errorf("failed to remove the CID file '%s': %s \n", cid.path, err) 2222 } 2223 } 2224 2225 return nil 2226 } 2227 2228 func (cid *cidFile) Write(id string) error { 2229 if _, err := cid.file.Write([]byte(id)); err != nil { 2230 return fmt.Errorf("Failed to write the container ID to the file: %s", err) 2231 } 2232 cid.written = true 2233 return nil 2234 } 2235 2236 func (cli *DockerCli) createContainer(config *runconfig.Config, hostConfig *runconfig.HostConfig, cidfile, name string) (*types.ContainerCreateResponse, error) { 2237 containerValues := url.Values{} 2238 if name != "" { 2239 containerValues.Set("name", name) 2240 } 2241 2242 mergedConfig := runconfig.MergeConfigs(config, hostConfig) 2243 2244 var containerIDFile *cidFile 2245 if cidfile != "" { 2246 var err error 2247 if containerIDFile, err = newCIDFile(cidfile); err != nil { 2248 return nil, err 2249 } 2250 defer containerIDFile.Close() 2251 } 2252 2253 //create the container 2254 stream, statusCode, err := cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, nil) 2255 //if image not found try to pull it 2256 if statusCode == 404 { 2257 repo, tag := parsers.ParseRepositoryTag(config.Image) 2258 if tag == "" { 2259 tag = graph.DEFAULTTAG 2260 } 2261 fmt.Fprintf(cli.err, "Unable to find image '%s' locally\n", utils.ImageReference(repo, tag)) 2262 2263 // we don't want to write to stdout anything apart from container.ID 2264 if err = cli.pullImageCustomOut(config.Image, cli.err); err != nil { 2265 return nil, err 2266 } 2267 // Retry 2268 if stream, _, err = cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, nil); err != nil { 2269 return nil, err 2270 } 2271 } else if err != nil { 2272 return nil, err 2273 } 2274 2275 var response types.ContainerCreateResponse 2276 if err := json.NewDecoder(stream).Decode(&response); err != nil { 2277 return nil, err 2278 } 2279 for _, warning := range response.Warnings { 2280 fmt.Fprintf(cli.err, "WARNING: %s\n", warning) 2281 } 2282 if containerIDFile != nil { 2283 if err = containerIDFile.Write(response.ID); err != nil { 2284 return nil, err 2285 } 2286 } 2287 return &response, nil 2288 } 2289 2290 func (cli *DockerCli) CmdCreate(args ...string) error { 2291 cmd := cli.Subcmd("create", "IMAGE [COMMAND] [ARG...]", "Create a new container", true) 2292 2293 // These are flags not stored in Config/HostConfig 2294 var ( 2295 flName = cmd.String([]string{"-name"}, "", "Assign a name to the container") 2296 ) 2297 2298 config, hostConfig, cmd, err := runconfig.Parse(cmd, args) 2299 if err != nil { 2300 utils.ReportError(cmd, err.Error(), true) 2301 } 2302 if config.Image == "" { 2303 cmd.Usage() 2304 return nil 2305 } 2306 response, err := cli.createContainer(config, hostConfig, hostConfig.ContainerIDFile, *flName) 2307 if err != nil { 2308 return err 2309 } 2310 fmt.Fprintf(cli.out, "%s\n", response.ID) 2311 return nil 2312 } 2313 2314 func (cli *DockerCli) CmdRun(args ...string) error { 2315 // FIXME: just use runconfig.Parse already 2316 cmd := cli.Subcmd("run", "IMAGE [COMMAND] [ARG...]", "Run a command in a new container", true) 2317 2318 // These are flags not stored in Config/HostConfig 2319 var ( 2320 flAutoRemove = cmd.Bool([]string{"#rm", "-rm"}, false, "Automatically remove the container when it exits") 2321 flDetach = cmd.Bool([]string{"d", "-detach"}, false, "Run container in background and print container ID") 2322 flSigProxy = cmd.Bool([]string{"#sig-proxy", "-sig-proxy"}, true, "Proxy received signals to the process") 2323 flName = cmd.String([]string{"#name", "-name"}, "", "Assign a name to the container") 2324 flAttach *opts.ListOpts 2325 2326 ErrConflictAttachDetach = fmt.Errorf("Conflicting options: -a and -d") 2327 ErrConflictRestartPolicyAndAutoRemove = fmt.Errorf("Conflicting options: --restart and --rm") 2328 ErrConflictDetachAutoRemove = fmt.Errorf("Conflicting options: --rm and -d") 2329 ) 2330 2331 config, hostConfig, cmd, err := runconfig.Parse(cmd, args) 2332 // just in case the Parse does not exit 2333 if err != nil { 2334 utils.ReportError(cmd, err.Error(), true) 2335 } 2336 2337 if len(hostConfig.Dns) > 0 { 2338 // check the DNS settings passed via --dns against 2339 // localhost regexp to warn if they are trying to 2340 // set a DNS to a localhost address 2341 for _, dnsIP := range hostConfig.Dns { 2342 if resolvconf.IsLocalhost(dnsIP) { 2343 fmt.Fprintf(cli.err, "WARNING: Localhost DNS setting (--dns=%s) may fail in containers.\n", dnsIP) 2344 break 2345 } 2346 } 2347 } 2348 if config.Image == "" { 2349 cmd.Usage() 2350 return nil 2351 } 2352 2353 if !*flDetach { 2354 if err := cli.CheckTtyInput(config.AttachStdin, config.Tty); err != nil { 2355 return err 2356 } 2357 } else { 2358 if fl := cmd.Lookup("-attach"); fl != nil { 2359 flAttach = fl.Value.(*opts.ListOpts) 2360 if flAttach.Len() != 0 { 2361 return ErrConflictAttachDetach 2362 } 2363 } 2364 if *flAutoRemove { 2365 return ErrConflictDetachAutoRemove 2366 } 2367 2368 config.AttachStdin = false 2369 config.AttachStdout = false 2370 config.AttachStderr = false 2371 config.StdinOnce = false 2372 } 2373 2374 // Disable flSigProxy when in TTY mode 2375 sigProxy := *flSigProxy 2376 if config.Tty { 2377 sigProxy = false 2378 } 2379 2380 createResponse, err := cli.createContainer(config, hostConfig, hostConfig.ContainerIDFile, *flName) 2381 if err != nil { 2382 return err 2383 } 2384 if sigProxy { 2385 sigc := cli.forwardAllSignals(createResponse.ID) 2386 defer signal.StopCatch(sigc) 2387 } 2388 var ( 2389 waitDisplayId chan struct{} 2390 errCh chan error 2391 ) 2392 if !config.AttachStdout && !config.AttachStderr { 2393 // Make this asynchronous to allow the client to write to stdin before having to read the ID 2394 waitDisplayId = make(chan struct{}) 2395 go func() { 2396 defer close(waitDisplayId) 2397 fmt.Fprintf(cli.out, "%s\n", createResponse.ID) 2398 }() 2399 } 2400 if *flAutoRemove && (hostConfig.RestartPolicy.Name == "always" || hostConfig.RestartPolicy.Name == "on-failure") { 2401 return ErrConflictRestartPolicyAndAutoRemove 2402 } 2403 // We need to instantiate the chan because the select needs it. It can 2404 // be closed but can't be uninitialized. 2405 hijacked := make(chan io.Closer) 2406 // Block the return until the chan gets closed 2407 defer func() { 2408 log.Debugf("End of CmdRun(), Waiting for hijack to finish.") 2409 if _, ok := <-hijacked; ok { 2410 log.Errorf("Hijack did not finish (chan still open)") 2411 } 2412 }() 2413 if config.AttachStdin || config.AttachStdout || config.AttachStderr { 2414 var ( 2415 out, stderr io.Writer 2416 in io.ReadCloser 2417 v = url.Values{} 2418 ) 2419 v.Set("stream", "1") 2420 if config.AttachStdin { 2421 v.Set("stdin", "1") 2422 in = cli.in 2423 } 2424 if config.AttachStdout { 2425 v.Set("stdout", "1") 2426 out = cli.out 2427 } 2428 if config.AttachStderr { 2429 v.Set("stderr", "1") 2430 if config.Tty { 2431 stderr = cli.out 2432 } else { 2433 stderr = cli.err 2434 } 2435 } 2436 errCh = promise.Go(func() error { 2437 return cli.hijack("POST", "/containers/"+createResponse.ID+"/attach?"+v.Encode(), config.Tty, in, out, stderr, hijacked, nil) 2438 }) 2439 } else { 2440 close(hijacked) 2441 } 2442 // Acknowledge the hijack before starting 2443 select { 2444 case closer := <-hijacked: 2445 // Make sure that the hijack gets closed when returning (results 2446 // in closing the hijack chan and freeing server's goroutines) 2447 if closer != nil { 2448 defer closer.Close() 2449 } 2450 case err := <-errCh: 2451 if err != nil { 2452 log.Debugf("Error hijack: %s", err) 2453 return err 2454 } 2455 } 2456 2457 //start the container 2458 if _, _, err = readBody(cli.call("POST", "/containers/"+createResponse.ID+"/start", nil, nil)); err != nil { 2459 return err 2460 } 2461 2462 if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && cli.isTerminalOut { 2463 if err := cli.monitorTtySize(createResponse.ID, false); err != nil { 2464 log.Errorf("Error monitoring TTY size: %s", err) 2465 } 2466 } 2467 2468 if errCh != nil { 2469 if err := <-errCh; err != nil { 2470 log.Debugf("Error hijack: %s", err) 2471 return err 2472 } 2473 } 2474 2475 // Detached mode: wait for the id to be displayed and return. 2476 if !config.AttachStdout && !config.AttachStderr { 2477 // Detached mode 2478 <-waitDisplayId 2479 return nil 2480 } 2481 2482 var status int 2483 2484 // Attached mode 2485 if *flAutoRemove { 2486 // Autoremove: wait for the container to finish, retrieve 2487 // the exit code and remove the container 2488 if _, _, err := readBody(cli.call("POST", "/containers/"+createResponse.ID+"/wait", nil, nil)); err != nil { 2489 return err 2490 } 2491 if _, status, err = getExitCode(cli, createResponse.ID); err != nil { 2492 return err 2493 } 2494 if _, _, err := readBody(cli.call("DELETE", "/containers/"+createResponse.ID+"?v=1", nil, nil)); err != nil { 2495 return err 2496 } 2497 } else { 2498 // No Autoremove: Simply retrieve the exit code 2499 if !config.Tty { 2500 // In non-TTY mode, we can't detach, so we must wait for container exit 2501 if status, err = waitForExit(cli, createResponse.ID); err != nil { 2502 return err 2503 } 2504 } else { 2505 // In TTY mode, there is a race: if the process dies too slowly, the state could 2506 // be updated after the getExitCode call and result in the wrong exit code being reported 2507 if _, status, err = getExitCode(cli, createResponse.ID); err != nil { 2508 return err 2509 } 2510 } 2511 } 2512 if status != 0 { 2513 return &utils.StatusError{StatusCode: status} 2514 } 2515 return nil 2516 } 2517 2518 func (cli *DockerCli) CmdCp(args ...string) error { 2519 cmd := cli.Subcmd("cp", "CONTAINER:PATH HOSTDIR|-", "Copy files/folders from a PATH on the container to a HOSTDIR on the host\nrunning the command. Use '-' to write the data\nas a tar file to STDOUT.", true) 2520 cmd.Require(flag.Exact, 2) 2521 2522 utils.ParseFlags(cmd, args, true) 2523 2524 var copyData engine.Env 2525 info := strings.Split(cmd.Arg(0), ":") 2526 2527 if len(info) != 2 { 2528 return fmt.Errorf("Error: Path not specified") 2529 } 2530 2531 copyData.Set("Resource", info[1]) 2532 copyData.Set("HostPath", cmd.Arg(1)) 2533 2534 stream, statusCode, err := cli.call("POST", "/containers/"+info[0]+"/copy", copyData, nil) 2535 if stream != nil { 2536 defer stream.Close() 2537 } 2538 if statusCode == 404 { 2539 return fmt.Errorf("No such container: %v", info[0]) 2540 } 2541 if err != nil { 2542 return err 2543 } 2544 2545 if statusCode == 200 { 2546 dest := copyData.Get("HostPath") 2547 2548 if dest == "-" { 2549 _, err = io.Copy(cli.out, stream) 2550 } else { 2551 err = archive.Untar(stream, dest, &archive.TarOptions{NoLchown: true}) 2552 } 2553 if err != nil { 2554 return err 2555 } 2556 } 2557 return nil 2558 } 2559 2560 func (cli *DockerCli) CmdSave(args ...string) error { 2561 cmd := cli.Subcmd("save", "IMAGE [IMAGE...]", "Save an image(s) to a tar archive (streamed to STDOUT by default)", true) 2562 outfile := cmd.String([]string{"o", "-output"}, "", "Write to an file, instead of STDOUT") 2563 cmd.Require(flag.Min, 1) 2564 2565 utils.ParseFlags(cmd, args, true) 2566 2567 var ( 2568 output io.Writer = cli.out 2569 err error 2570 ) 2571 if *outfile != "" { 2572 output, err = os.Create(*outfile) 2573 if err != nil { 2574 return err 2575 } 2576 } else if cli.isTerminalOut { 2577 return errors.New("Cowardly refusing to save to a terminal. Use the -o flag or redirect.") 2578 } 2579 2580 if len(cmd.Args()) == 1 { 2581 image := cmd.Arg(0) 2582 if err := cli.stream("GET", "/images/"+image+"/get", nil, output, nil); err != nil { 2583 return err 2584 } 2585 } else { 2586 v := url.Values{} 2587 for _, arg := range cmd.Args() { 2588 v.Add("names", arg) 2589 } 2590 if err := cli.stream("GET", "/images/get?"+v.Encode(), nil, output, nil); err != nil { 2591 return err 2592 } 2593 } 2594 return nil 2595 } 2596 2597 func (cli *DockerCli) CmdLoad(args ...string) error { 2598 cmd := cli.Subcmd("load", "", "Load an image from a tar archive on STDIN", true) 2599 infile := cmd.String([]string{"i", "-input"}, "", "Read from a tar archive file, instead of STDIN") 2600 cmd.Require(flag.Exact, 0) 2601 2602 utils.ParseFlags(cmd, args, true) 2603 2604 var ( 2605 input io.Reader = cli.in 2606 err error 2607 ) 2608 if *infile != "" { 2609 input, err = os.Open(*infile) 2610 if err != nil { 2611 return err 2612 } 2613 } 2614 if err := cli.stream("POST", "/images/load", input, cli.out, nil); err != nil { 2615 return err 2616 } 2617 return nil 2618 } 2619 2620 func (cli *DockerCli) CmdExec(args ...string) error { 2621 cmd := cli.Subcmd("exec", "CONTAINER COMMAND [ARG...]", "Run a command in a running container", true) 2622 2623 execConfig, err := runconfig.ParseExec(cmd, args) 2624 // just in case the ParseExec does not exit 2625 if execConfig.Container == "" || err != nil { 2626 return &utils.StatusError{StatusCode: 1} 2627 } 2628 2629 stream, _, err := cli.call("POST", "/containers/"+execConfig.Container+"/exec", execConfig, nil) 2630 if err != nil { 2631 return err 2632 } 2633 2634 var execResult engine.Env 2635 if err := execResult.Decode(stream); err != nil { 2636 return err 2637 } 2638 2639 execID := execResult.Get("Id") 2640 2641 if execID == "" { 2642 fmt.Fprintf(cli.out, "exec ID empty") 2643 return nil 2644 } 2645 2646 if !execConfig.Detach { 2647 if err := cli.CheckTtyInput(execConfig.AttachStdin, execConfig.Tty); err != nil { 2648 return err 2649 } 2650 } else { 2651 if _, _, err := readBody(cli.call("POST", "/exec/"+execID+"/start", execConfig, nil)); err != nil { 2652 return err 2653 } 2654 // For now don't print this - wait for when we support exec wait() 2655 // fmt.Fprintf(cli.out, "%s\n", execID) 2656 return nil 2657 } 2658 2659 // Interactive exec requested. 2660 var ( 2661 out, stderr io.Writer 2662 in io.ReadCloser 2663 hijacked = make(chan io.Closer) 2664 errCh chan error 2665 ) 2666 2667 // Block the return until the chan gets closed 2668 defer func() { 2669 log.Debugf("End of CmdExec(), Waiting for hijack to finish.") 2670 if _, ok := <-hijacked; ok { 2671 log.Errorf("Hijack did not finish (chan still open)") 2672 } 2673 }() 2674 2675 if execConfig.AttachStdin { 2676 in = cli.in 2677 } 2678 if execConfig.AttachStdout { 2679 out = cli.out 2680 } 2681 if execConfig.AttachStderr { 2682 if execConfig.Tty { 2683 stderr = cli.out 2684 } else { 2685 stderr = cli.err 2686 } 2687 } 2688 errCh = promise.Go(func() error { 2689 return cli.hijack("POST", "/exec/"+execID+"/start", execConfig.Tty, in, out, stderr, hijacked, execConfig) 2690 }) 2691 2692 // Acknowledge the hijack before starting 2693 select { 2694 case closer := <-hijacked: 2695 // Make sure that hijack gets closed when returning. (result 2696 // in closing hijack chan and freeing server's goroutines. 2697 if closer != nil { 2698 defer closer.Close() 2699 } 2700 case err := <-errCh: 2701 if err != nil { 2702 log.Debugf("Error hijack: %s", err) 2703 return err 2704 } 2705 } 2706 2707 if execConfig.Tty && cli.isTerminalIn { 2708 if err := cli.monitorTtySize(execID, true); err != nil { 2709 log.Errorf("Error monitoring TTY size: %s", err) 2710 } 2711 } 2712 2713 if err := <-errCh; err != nil { 2714 log.Debugf("Error hijack: %s", err) 2715 return err 2716 } 2717 2718 var status int 2719 if _, status, err = getExecExitCode(cli, execID); err != nil { 2720 return err 2721 } 2722 2723 if status != 0 { 2724 return &utils.StatusError{StatusCode: status} 2725 } 2726 2727 return nil 2728 } 2729 2730 type containerStats struct { 2731 Name string 2732 CpuPercentage float64 2733 Memory float64 2734 MemoryLimit float64 2735 MemoryPercentage float64 2736 NetworkRx float64 2737 NetworkTx float64 2738 mu sync.RWMutex 2739 err error 2740 } 2741 2742 func (s *containerStats) Collect(cli *DockerCli) { 2743 stream, _, err := cli.call("GET", "/containers/"+s.Name+"/stats", nil, nil) 2744 if err != nil { 2745 s.err = err 2746 return 2747 } 2748 defer stream.Close() 2749 var ( 2750 previousCpu uint64 2751 previousSystem uint64 2752 start = true 2753 dec = json.NewDecoder(stream) 2754 u = make(chan error, 1) 2755 ) 2756 go func() { 2757 for { 2758 var v *types.Stats 2759 if err := dec.Decode(&v); err != nil { 2760 u <- err 2761 return 2762 } 2763 var ( 2764 memPercent = float64(v.MemoryStats.Usage) / float64(v.MemoryStats.Limit) * 100.0 2765 cpuPercent = 0.0 2766 ) 2767 if !start { 2768 cpuPercent = calculateCpuPercent(previousCpu, previousSystem, v) 2769 } 2770 start = false 2771 s.mu.Lock() 2772 s.CpuPercentage = cpuPercent 2773 s.Memory = float64(v.MemoryStats.Usage) 2774 s.MemoryLimit = float64(v.MemoryStats.Limit) 2775 s.MemoryPercentage = memPercent 2776 s.NetworkRx = float64(v.Network.RxBytes) 2777 s.NetworkTx = float64(v.Network.TxBytes) 2778 s.mu.Unlock() 2779 previousCpu = v.CpuStats.CpuUsage.TotalUsage 2780 previousSystem = v.CpuStats.SystemUsage 2781 u <- nil 2782 } 2783 }() 2784 for { 2785 select { 2786 case <-time.After(2 * time.Second): 2787 // zero out the values if we have not received an update within 2788 // the specified duration. 2789 s.mu.Lock() 2790 s.CpuPercentage = 0 2791 s.Memory = 0 2792 s.MemoryPercentage = 0 2793 s.mu.Unlock() 2794 case err := <-u: 2795 if err != nil { 2796 s.mu.Lock() 2797 s.err = err 2798 s.mu.Unlock() 2799 return 2800 } 2801 } 2802 } 2803 } 2804 2805 func (s *containerStats) Display(w io.Writer) error { 2806 s.mu.RLock() 2807 defer s.mu.RUnlock() 2808 if s.err != nil { 2809 return s.err 2810 } 2811 fmt.Fprintf(w, "%s\t%.2f%%\t%s/%s\t%.2f%%\t%s/%s\n", 2812 s.Name, 2813 s.CpuPercentage, 2814 units.BytesSize(s.Memory), units.BytesSize(s.MemoryLimit), 2815 s.MemoryPercentage, 2816 units.BytesSize(s.NetworkRx), units.BytesSize(s.NetworkTx)) 2817 return nil 2818 } 2819 2820 func (cli *DockerCli) CmdStats(args ...string) error { 2821 cmd := cli.Subcmd("stats", "CONTAINER [CONTAINER...]", "Display a live stream of one or more containers' resource usage statistics", true) 2822 cmd.Require(flag.Min, 1) 2823 utils.ParseFlags(cmd, args, true) 2824 2825 names := cmd.Args() 2826 sort.Strings(names) 2827 var ( 2828 cStats []*containerStats 2829 w = tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0) 2830 ) 2831 printHeader := func() { 2832 fmt.Fprint(cli.out, "\033[2J") 2833 fmt.Fprint(cli.out, "\033[H") 2834 fmt.Fprintln(w, "CONTAINER\tCPU %\tMEM USAGE/LIMIT\tMEM %\tNET I/O") 2835 } 2836 for _, n := range names { 2837 s := &containerStats{Name: n} 2838 cStats = append(cStats, s) 2839 go s.Collect(cli) 2840 } 2841 // do a quick pause so that any failed connections for containers that do not exist are able to be 2842 // evicted before we display the initial or default values. 2843 time.Sleep(500 * time.Millisecond) 2844 var errs []string 2845 for _, c := range cStats { 2846 c.mu.Lock() 2847 if c.err != nil { 2848 errs = append(errs, fmt.Sprintf("%s: %v", c.Name, c.err)) 2849 } 2850 c.mu.Unlock() 2851 } 2852 if len(errs) > 0 { 2853 return fmt.Errorf("%s", strings.Join(errs, ", ")) 2854 } 2855 for _ = range time.Tick(500 * time.Millisecond) { 2856 printHeader() 2857 toRemove := []int{} 2858 for i, s := range cStats { 2859 if err := s.Display(w); err != nil { 2860 toRemove = append(toRemove, i) 2861 } 2862 } 2863 for j := len(toRemove) - 1; j >= 0; j-- { 2864 i := toRemove[j] 2865 cStats = append(cStats[:i], cStats[i+1:]...) 2866 } 2867 if len(cStats) == 0 { 2868 return nil 2869 } 2870 w.Flush() 2871 } 2872 return nil 2873 } 2874 2875 func calculateCpuPercent(previousCpu, previousSystem uint64, v *types.Stats) float64 { 2876 var ( 2877 cpuPercent = 0.0 2878 // calculate the change for the cpu usage of the container in between readings 2879 cpuDelta = float64(v.CpuStats.CpuUsage.TotalUsage - previousCpu) 2880 // calculate the change for the entire system between readings 2881 systemDelta = float64(v.CpuStats.SystemUsage - previousSystem) 2882 ) 2883 2884 if systemDelta > 0.0 && cpuDelta > 0.0 { 2885 cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CpuStats.CpuUsage.PercpuUsage)) * 100.0 2886 } 2887 return cpuPercent 2888 }