github.com/portworx/docker@v1.12.1/api/client/container/restart.go (about)

     1  package container
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  	"time"
     7  
     8  	"golang.org/x/net/context"
     9  
    10  	"github.com/docker/docker/api/client"
    11  	"github.com/docker/docker/cli"
    12  	"github.com/spf13/cobra"
    13  )
    14  
    15  type restartOptions struct {
    16  	nSeconds int
    17  
    18  	containers []string
    19  }
    20  
    21  // NewRestartCommand creates a new cobra.Command for `docker restart`
    22  func NewRestartCommand(dockerCli *client.DockerCli) *cobra.Command {
    23  	var opts restartOptions
    24  
    25  	cmd := &cobra.Command{
    26  		Use:   "restart [OPTIONS] CONTAINER [CONTAINER...]",
    27  		Short: "Restart a container",
    28  		Args:  cli.RequiresMinArgs(1),
    29  		RunE: func(cmd *cobra.Command, args []string) error {
    30  			opts.containers = args
    31  			return runRestart(dockerCli, &opts)
    32  		},
    33  	}
    34  
    35  	flags := cmd.Flags()
    36  	flags.IntVarP(&opts.nSeconds, "time", "t", 10, "Seconds to wait for stop before killing the container")
    37  	return cmd
    38  }
    39  
    40  func runRestart(dockerCli *client.DockerCli, opts *restartOptions) error {
    41  	ctx := context.Background()
    42  	var errs []string
    43  	for _, name := range opts.containers {
    44  		timeout := time.Duration(opts.nSeconds) * time.Second
    45  		if err := dockerCli.Client().ContainerRestart(ctx, name, &timeout); err != nil {
    46  			errs = append(errs, err.Error())
    47  		} else {
    48  			fmt.Fprintf(dockerCli.Out(), "%s\n", name)
    49  		}
    50  	}
    51  	if len(errs) > 0 {
    52  		return fmt.Errorf("%s", strings.Join(errs, "\n"))
    53  	}
    54  	return nil
    55  }