github.com/containerd/Containerd@v1.4.13/cmd/ctr/commands/tasks/kill.go (about) 1 /* 2 Copyright The containerd Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package tasks 18 19 import ( 20 "github.com/containerd/containerd" 21 "github.com/containerd/containerd/cmd/ctr/commands" 22 "github.com/pkg/errors" 23 "github.com/urfave/cli" 24 ) 25 26 const defaultSignal = "SIGTERM" 27 28 var killCommand = cli.Command{ 29 Name: "kill", 30 Usage: "signal a container (default: SIGTERM)", 31 ArgsUsage: "[flags] CONTAINER", 32 Flags: []cli.Flag{ 33 cli.StringFlag{ 34 Name: "signal, s", 35 Value: "", 36 Usage: "signal to send to the container", 37 }, 38 cli.StringFlag{ 39 Name: "exec-id", 40 Usage: "process ID to kill", 41 }, 42 cli.BoolFlag{ 43 Name: "all, a", 44 Usage: "send signal to all processes inside the container", 45 }, 46 }, 47 Action: func(context *cli.Context) error { 48 id := context.Args().First() 49 if id == "" { 50 return errors.New("container id must be provided") 51 } 52 signal, err := containerd.ParseSignal(defaultSignal) 53 if err != nil { 54 return err 55 } 56 var ( 57 all = context.Bool("all") 58 execID = context.String("exec-id") 59 opts []containerd.KillOpts 60 ) 61 if all && execID != "" { 62 return errors.New("specify an exec-id or all; not both") 63 } 64 client, ctx, cancel, err := commands.NewClient(context) 65 if err != nil { 66 return err 67 } 68 defer cancel() 69 if all { 70 opts = append(opts, containerd.WithKillAll) 71 } 72 if execID != "" { 73 opts = append(opts, containerd.WithKillExecID(execID)) 74 } 75 container, err := client.LoadContainer(ctx, id) 76 if err != nil { 77 return err 78 } 79 if context.String("signal") != "" { 80 signal, err = containerd.ParseSignal(context.String("signal")) 81 if err != nil { 82 return err 83 } 84 } else { 85 signal, err = containerd.GetStopSignal(ctx, container, signal) 86 if err != nil { 87 return err 88 } 89 } 90 task, err := container.Task(ctx, nil) 91 if err != nil { 92 return err 93 } 94 return task.Kill(ctx, signal, opts...) 95 }, 96 }