restart.go 1.3 KB

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