restart.go 1.3 KB

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