github.com/portworx/docker@v1.12.1/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: "Stop one or more running containers", 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 cmd.SetFlagErrorFunc(flagErrorFunc) 35 36 flags := cmd.Flags() 37 flags.IntVarP(&opts.time, "time", "t", 10, "Seconds to wait for stop before killing it") 38 return cmd 39 } 40 41 func runStop(dockerCli *client.DockerCli, opts *stopOptions) error { 42 ctx := context.Background() 43 44 var errs []string 45 for _, container := range opts.containers { 46 timeout := time.Duration(opts.time) * time.Second 47 if err := dockerCli.Client().ContainerStop(ctx, container, &timeout); err != nil { 48 errs = append(errs, err.Error()) 49 } else { 50 fmt.Fprintf(dockerCli.Out(), "%s\n", container) 51 } 52 } 53 if len(errs) > 0 { 54 return fmt.Errorf("%s", strings.Join(errs, "\n")) 55 } 56 return nil 57 }