aboutsummaryrefslogtreecommitdiff
path: root/cmd/kpod/kill.go
blob: 8a5500031bb62572a69ef39db619b0dcc29c3e38 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main

import (
	"fmt"
	"os"

	"github.com/docker/docker/pkg/signal"
	"github.com/kubernetes-incubator/cri-o/libkpod"
	"github.com/pkg/errors"
	"github.com/urfave/cli"
)

var (
	killFlags = []cli.Flag{
		cli.StringFlag{
			Name:  "signal, s",
			Usage: "Signal to send to the container",
			Value: "KILL",
		},
	}
	killDescription = "The main process inside each container specified will be sent SIGKILL, or any signal specified with option --signal."
	killCommand     = cli.Command{
		Name:        "kill",
		Usage:       "Kill one or more running containers with a specific signal",
		Description: killDescription,
		Flags:       killFlags,
		Action:      killCmd,
		ArgsUsage:   "[CONTAINER_NAME_OR_ID]",
	}
)

// killCmd kills one or more containers with a signal
func killCmd(c *cli.Context) error {
	args := c.Args()
	if len(args) == 0 {
		return errors.Errorf("specify one or more containers to kill")
	}
	if err := validateFlags(c, killFlags); err != nil {
		return err
	}
	config, err := getConfig(c)
	if err != nil {
		return errors.Wrapf(err, "could not get config")
	}
	server, err := libkpod.New(config)
	if err != nil {
		return errors.Wrapf(err, "could not get container server")
	}
	killSignal := c.String("signal")
	// Check if the signalString provided by the user is valid
	// Invalid signals will return err
	sysSignal, err := signal.ParseSignal(killSignal)
	if err != nil {
		return err
	}
	defer server.Shutdown()
	err = server.Update()
	if err != nil {
		return errors.Wrapf(err, "could not update list of containers")
	}
	var lastError error
	for _, container := range c.Args() {
		id, err := server.ContainerKill(container, sysSignal)
		if err != nil {
			if lastError != nil {
				fmt.Fprintln(os.Stderr, lastError)
			}
			lastError = errors.Wrapf(err, "unable to kill %v", container)
		} else {
			fmt.Println(id)
		}
	}
	return lastError
}