github.com/DaoCloud/dao@v0.0.0-20161212064103-c3dbfd13ee36/api/client/container/stop.go (about) 1 package container 2 3 import ( 4 "fmt" 5 "strings" 6 "time" 7 8 "golang.org/x/net/context" 9 10 "github.com/docker/docker/api/client" 11 "github.com/docker/docker/cli" 12 "github.com/spf13/cobra" 13 ) 14 15 type stopOptions struct { 16 time int 17 18 containers []string 19 } 20 21 // NewStopCommand creats a new cobra.Command for `docker stop` 22 func NewStopCommand(dockerCli *client.DockerCli) *cobra.Command { 23 var opts stopOptions 24 25 cmd := &cobra.Command{ 26 Use: "stop [OPTIONS] CONTAINER [CONTAINER...]", 27 Short: "停止一个或多个运行容器", 28 Args: cli.RequiresMinArgs(1), 29 RunE: func(cmd *cobra.Command, args []string) error { 30 opts.containers = args 31 return runStop(dockerCli, &opts) 32 }, 33 } 34 35 flags := cmd.Flags() 36 flags.IntVarP(&opts.time, "time", "t", 10, "终止容器前等待容器停止的秒数") 37 return cmd 38 } 39 40 func runStop(dockerCli *client.DockerCli, opts *stopOptions) error { 41 ctx := context.Background() 42 43 var errs []string 44 for _, container := range opts.containers { 45 timeout := time.Duration(opts.time) * time.Second 46 if err := dockerCli.Client().ContainerStop(ctx, container, &timeout); err != nil { 47 errs = append(errs, err.Error()) 48 } else { 49 fmt.Fprintf(dockerCli.Out(), "%s\n", container) 50 } 51 } 52 if len(errs) > 0 { 53 return fmt.Errorf("%s", strings.Join(errs, "\n")) 54 } 55 return nil 56 }