stop.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package container
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. "time"
  7. "github.com/docker/docker/cli"
  8. "github.com/docker/docker/cli/command"
  9. "github.com/spf13/cobra"
  10. "golang.org/x/net/context"
  11. )
  12. type stopOptions struct {
  13. time int
  14. timeChanged bool
  15. containers []string
  16. }
  17. // NewStopCommand creates a new cobra.Command for `docker stop`
  18. func NewStopCommand(dockerCli *command.DockerCli) *cobra.Command {
  19. var opts stopOptions
  20. cmd := &cobra.Command{
  21. Use: "stop [OPTIONS] CONTAINER [CONTAINER...]",
  22. Short: "Stop one or more running containers",
  23. Args: cli.RequiresMinArgs(1),
  24. RunE: func(cmd *cobra.Command, args []string) error {
  25. opts.containers = args
  26. opts.timeChanged = cmd.Flags().Changed("time")
  27. return runStop(dockerCli, &opts)
  28. },
  29. }
  30. flags := cmd.Flags()
  31. flags.IntVarP(&opts.time, "time", "t", 10, "Seconds to wait for stop before killing it")
  32. return cmd
  33. }
  34. func runStop(dockerCli *command.DockerCli, opts *stopOptions) error {
  35. ctx := context.Background()
  36. var timeout *time.Duration
  37. if opts.timeChanged {
  38. timeoutValue := time.Duration(opts.time) * time.Second
  39. timeout = &timeoutValue
  40. }
  41. var errs []string
  42. errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, id string) error {
  43. return dockerCli.Client().ContainerStop(ctx, id, timeout)
  44. })
  45. for _, container := range opts.containers {
  46. if err := <-errChan; err != nil {
  47. errs = append(errs, err.Error())
  48. continue
  49. }
  50. fmt.Fprintln(dockerCli.Out(), container)
  51. }
  52. if len(errs) > 0 {
  53. return errors.New(strings.Join(errs, "\n"))
  54. }
  55. return nil
  56. }