github.com/ali-iotechsys/cli@v20.10.0+incompatible/cli/command/container/restart.go (about) 1 package container 2 3 import ( 4 "context" 5 "fmt" 6 "strings" 7 "time" 8 9 "github.com/docker/cli/cli" 10 "github.com/docker/cli/cli/command" 11 "github.com/pkg/errors" 12 "github.com/spf13/cobra" 13 ) 14 15 type restartOptions struct { 16 nSeconds int 17 nSecondsChanged bool 18 19 containers []string 20 } 21 22 // NewRestartCommand creates a new cobra.Command for `docker restart` 23 func NewRestartCommand(dockerCli command.Cli) *cobra.Command { 24 var opts restartOptions 25 26 cmd := &cobra.Command{ 27 Use: "restart [OPTIONS] CONTAINER [CONTAINER...]", 28 Short: "Restart one or more containers", 29 Args: cli.RequiresMinArgs(1), 30 RunE: func(cmd *cobra.Command, args []string) error { 31 opts.containers = args 32 opts.nSecondsChanged = cmd.Flags().Changed("time") 33 return runRestart(dockerCli, &opts) 34 }, 35 } 36 37 flags := cmd.Flags() 38 flags.IntVarP(&opts.nSeconds, "time", "t", 10, "Seconds to wait for stop before killing the container") 39 return cmd 40 } 41 42 func runRestart(dockerCli command.Cli, opts *restartOptions) error { 43 ctx := context.Background() 44 var errs []string 45 var timeout *time.Duration 46 if opts.nSecondsChanged { 47 timeoutValue := time.Duration(opts.nSeconds) * time.Second 48 timeout = &timeoutValue 49 } 50 51 for _, name := range opts.containers { 52 if err := dockerCli.Client().ContainerRestart(ctx, name, timeout); err != nil { 53 errs = append(errs, err.Error()) 54 continue 55 } 56 fmt.Fprintln(dockerCli.Out(), name) 57 } 58 if len(errs) > 0 { 59 return errors.New(strings.Join(errs, "\n")) 60 } 61 return nil 62 }