github.com/panekj/cli@v0.0.0-20230304125325-467dd2f3797e/cli/command/container/kill.go (about)

     1  package container
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"github.com/docker/cli/cli"
     9  	"github.com/docker/cli/cli/command"
    10  	"github.com/docker/cli/cli/command/completion"
    11  	"github.com/pkg/errors"
    12  	"github.com/spf13/cobra"
    13  )
    14  
    15  type killOptions struct {
    16  	signal string
    17  
    18  	containers []string
    19  }
    20  
    21  // NewKillCommand creates a new cobra.Command for `docker kill`
    22  func NewKillCommand(dockerCli command.Cli) *cobra.Command {
    23  	var opts killOptions
    24  
    25  	cmd := &cobra.Command{
    26  		Use:   "kill [OPTIONS] CONTAINER [CONTAINER...]",
    27  		Short: "Kill 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 runKill(dockerCli, &opts)
    32  		},
    33  		Annotations: map[string]string{
    34  			"aliases": "docker container kill, docker kill",
    35  		},
    36  		ValidArgsFunction: completion.ContainerNames(dockerCli, false),
    37  	}
    38  
    39  	flags := cmd.Flags()
    40  	flags.StringVarP(&opts.signal, "signal", "s", "", "Signal to send to the container")
    41  	return cmd
    42  }
    43  
    44  func runKill(dockerCli command.Cli, opts *killOptions) error {
    45  	var errs []string
    46  	ctx := context.Background()
    47  	errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, container string) error {
    48  		return dockerCli.Client().ContainerKill(ctx, container, opts.signal)
    49  	})
    50  	for _, name := range opts.containers {
    51  		if err := <-errChan; err != nil {
    52  			errs = append(errs, err.Error())
    53  		} else {
    54  			fmt.Fprintln(dockerCli.Out(), name)
    55  		}
    56  	}
    57  	if len(errs) > 0 {
    58  		return errors.New(strings.Join(errs, "\n"))
    59  	}
    60  	return nil
    61  }