restart.go 1.5 KB

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