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