github.1git.de/docker/cli@v26.1.3+incompatible/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(cmd.Context(), 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(ctx context.Context, dockerCli command.Cli, opts *killOptions) error {
    45  	var errs []string
    46  	errChan := parallelOperation(ctx, opts.containers, func(ctx context.Context, container string) error {
    47  		return dockerCli.Client().ContainerKill(ctx, container, opts.signal)
    48  	})
    49  	for _, name := range opts.containers {
    50  		if err := <-errChan; err != nil {
    51  			errs = append(errs, err.Error())
    52  		} else {
    53  			fmt.Fprintln(dockerCli.Out(), name)
    54  		}
    55  	}
    56  	if len(errs) > 0 {
    57  		return errors.New(strings.Join(errs, "\n"))
    58  	}
    59  	return nil
    60  }