stop.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package container
  2. import (
  3. "fmt"
  4. "strings"
  5. "time"
  6. "golang.org/x/net/context"
  7. "github.com/docker/docker/api/client"
  8. "github.com/docker/docker/cli"
  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 *client.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. cmd.SetFlagErrorFunc(flagErrorFunc)
  28. flags := cmd.Flags()
  29. flags.IntVarP(&opts.time, "time", "t", 10, "Seconds to wait for stop before killing it")
  30. return cmd
  31. }
  32. func runStop(dockerCli *client.DockerCli, opts *stopOptions) error {
  33. ctx := context.Background()
  34. var errs []string
  35. for _, container := range opts.containers {
  36. timeout := time.Duration(opts.time) * time.Second
  37. if err := dockerCli.Client().ContainerStop(ctx, container, &timeout); err != nil {
  38. errs = append(errs, err.Error())
  39. } else {
  40. fmt.Fprintf(dockerCli.Out(), "%s\n", container)
  41. }
  42. }
  43. if len(errs) > 0 {
  44. return fmt.Errorf("%s", strings.Join(errs, "\n"))
  45. }
  46. return nil
  47. }