stop.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 creats 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. if err := dockerCli.Client().ContainerStop(ctx, container, time.Duration(opts.time)*time.Second); err != nil {
  37. errs = append(errs, err.Error())
  38. } else {
  39. fmt.Fprintf(dockerCli.Out(), "%s\n", container)
  40. }
  41. }
  42. if len(errs) > 0 {
  43. return fmt.Errorf("%s", strings.Join(errs, "\n"))
  44. }
  45. return nil
  46. }