stop.go 1.5 KB

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