github.com/kunnos/engine@v1.13.1/cli/command/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/cli" 11 "github.com/docker/docker/cli/command" 12 "github.com/spf13/cobra" 13 ) 14 15 type stopOptions struct { 16 time int 17 timeChanged bool 18 19 containers []string 20 } 21 22 // NewStopCommand creates a new cobra.Command for `docker stop` 23 func NewStopCommand(dockerCli *command.DockerCli) *cobra.Command { 24 var opts stopOptions 25 26 cmd := &cobra.Command{ 27 Use: "stop [OPTIONS] CONTAINER [CONTAINER...]", 28 Short: "Stop one or more running containers", 29 Args: cli.RequiresMinArgs(1), 30 RunE: func(cmd *cobra.Command, args []string) error { 31 opts.containers = args 32 opts.timeChanged = cmd.Flags().Changed("time") 33 return runStop(dockerCli, &opts) 34 }, 35 } 36 37 flags := cmd.Flags() 38 flags.IntVarP(&opts.time, "time", "t", 10, "Seconds to wait for stop before killing it") 39 return cmd 40 } 41 42 func runStop(dockerCli *command.DockerCli, opts *stopOptions) error { 43 ctx := context.Background() 44 45 var timeout *time.Duration 46 if opts.timeChanged { 47 timeoutValue := time.Duration(opts.time) * time.Second 48 timeout = &timeoutValue 49 } 50 51 var errs []string 52 53 errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, id string) error { 54 return dockerCli.Client().ContainerStop(ctx, id, timeout) 55 }) 56 for _, container := range opts.containers { 57 if err := <-errChan; err != nil { 58 errs = append(errs, err.Error()) 59 } else { 60 fmt.Fprintf(dockerCli.Out(), "%s\n", container) 61 } 62 } 63 if len(errs) > 0 { 64 return fmt.Errorf("%s", strings.Join(errs, "\n")) 65 } 66 return nil 67 }