restart.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 restartOptions struct {
  13. nSeconds int
  14. nSecondsChanged bool
  15. containers []string
  16. }
  17. // NewRestartCommand creates a new cobra.Command for `docker restart`
  18. func NewRestartCommand(dockerCli *command.DockerCli) *cobra.Command {
  19. var opts restartOptions
  20. cmd := &cobra.Command{
  21. Use: "restart [OPTIONS] CONTAINER [CONTAINER...]",
  22. Short: "Restart one or more containers",
  23. Args: cli.RequiresMinArgs(1),
  24. RunE: func(cmd *cobra.Command, args []string) error {
  25. opts.containers = args
  26. opts.nSecondsChanged = cmd.Flags().Changed("time")
  27. return runRestart(dockerCli, &opts)
  28. },
  29. }
  30. flags := cmd.Flags()
  31. flags.IntVarP(&opts.nSeconds, "time", "t", 10, "Seconds to wait for stop before killing the container")
  32. return cmd
  33. }
  34. func runRestart(dockerCli *command.DockerCli, opts *restartOptions) error {
  35. ctx := context.Background()
  36. var errs []string
  37. var timeout *time.Duration
  38. if opts.nSecondsChanged {
  39. timeoutValue := time.Duration(opts.nSeconds) * time.Second
  40. timeout = &timeoutValue
  41. }
  42. for _, name := range opts.containers {
  43. if err := dockerCli.Client().ContainerRestart(ctx, name, timeout); err != nil {
  44. errs = append(errs, err.Error())
  45. continue
  46. }
  47. fmt.Fprintln(dockerCli.Out(), name)
  48. }
  49. if len(errs) > 0 {
  50. return errors.New(strings.Join(errs, "\n"))
  51. }
  52. return nil
  53. }