stop.go 1.4 KB

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