github.1git.de/docker/cli@v26.1.3+incompatible/cli/command/container/stop.go (about) 1 package container 2 3 import ( 4 "context" 5 "fmt" 6 "strings" 7 8 "github.com/docker/cli/cli" 9 "github.com/docker/cli/cli/command" 10 "github.com/docker/cli/cli/command/completion" 11 "github.com/docker/docker/api/types/container" 12 "github.com/pkg/errors" 13 "github.com/spf13/cobra" 14 ) 15 16 type stopOptions struct { 17 signal string 18 timeout int 19 timeoutChanged bool 20 21 containers []string 22 } 23 24 // NewStopCommand creates a new cobra.Command for `docker stop` 25 func NewStopCommand(dockerCli command.Cli) *cobra.Command { 26 var opts stopOptions 27 28 cmd := &cobra.Command{ 29 Use: "stop [OPTIONS] CONTAINER [CONTAINER...]", 30 Short: "Stop one or more running containers", 31 Args: cli.RequiresMinArgs(1), 32 RunE: func(cmd *cobra.Command, args []string) error { 33 opts.containers = args 34 opts.timeoutChanged = cmd.Flags().Changed("time") 35 return runStop(cmd.Context(), dockerCli, &opts) 36 }, 37 Annotations: map[string]string{ 38 "aliases": "docker container stop, docker stop", 39 }, 40 ValidArgsFunction: completion.ContainerNames(dockerCli, false), 41 } 42 43 flags := cmd.Flags() 44 flags.StringVarP(&opts.signal, "signal", "s", "", "Signal to send to the container") 45 flags.IntVarP(&opts.timeout, "time", "t", 0, "Seconds to wait before killing the container") 46 return cmd 47 } 48 49 func runStop(ctx context.Context, dockerCli command.Cli, opts *stopOptions) error { 50 var timeout *int 51 if opts.timeoutChanged { 52 timeout = &opts.timeout 53 } 54 55 errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, id string) error { 56 return dockerCli.Client().ContainerStop(ctx, id, container.StopOptions{ 57 Signal: opts.signal, 58 Timeout: timeout, 59 }) 60 }) 61 var errs []string 62 for _, ctr := range opts.containers { 63 if err := <-errChan; err != nil { 64 errs = append(errs, err.Error()) 65 continue 66 } 67 _, _ = fmt.Fprintln(dockerCli.Out(), ctr) 68 } 69 if len(errs) > 0 { 70 return errors.New(strings.Join(errs, "\n")) 71 } 72 return nil 73 }