github.com/vieux/docker@v0.6.3-0.20161004191708-e097c2a938c7/cli/command/container/stop.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/cli"
    11  	"github.com/docker/docker/cli/command"
    12  	"github.com/spf13/cobra"
    13  )
    14  
    15  type stopOptions struct {
    16  	time int
    17  
    18  	containers []string
    19  }
    20  
    21  // NewStopCommand creates a new cobra.Command for `docker stop`
    22  func NewStopCommand(dockerCli *command.DockerCli) *cobra.Command {
    23  	var opts stopOptions
    24  
    25  	cmd := &cobra.Command{
    26  		Use:   "stop [OPTIONS] CONTAINER [CONTAINER...]",
    27  		Short: "Stop one or more running containers",
    28  		Args:  cli.RequiresMinArgs(1),
    29  		RunE: func(cmd *cobra.Command, args []string) error {
    30  			opts.containers = args
    31  			return runStop(dockerCli, &opts)
    32  		},
    33  	}
    34  
    35  	flags := cmd.Flags()
    36  	flags.IntVarP(&opts.time, "time", "t", 10, "Seconds to wait for stop before killing it")
    37  	return cmd
    38  }
    39  
    40  func runStop(dockerCli *command.DockerCli, opts *stopOptions) error {
    41  	ctx := context.Background()
    42  	timeout := time.Duration(opts.time) * time.Second
    43  
    44  	var errs []string
    45  
    46  	errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, id string) error {
    47  		return dockerCli.Client().ContainerStop(ctx, id, &timeout)
    48  	})
    49  	for _, container := range opts.containers {
    50  		if err := <-errChan; err != nil {
    51  			errs = append(errs, err.Error())
    52  		} else {
    53  			fmt.Fprintf(dockerCli.Out(), "%s\n", container)
    54  		}
    55  	}
    56  	if len(errs) > 0 {
    57  		return fmt.Errorf("%s", strings.Join(errs, "\n"))
    58  	}
    59  	return nil
    60  }