github.com/containerd/nerdctl@v1.7.7/cmd/nerdctl/container_stop.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 main 18 19 import ( 20 "time" 21 22 "github.com/containerd/containerd" 23 "github.com/containerd/nerdctl/pkg/api/types" 24 "github.com/containerd/nerdctl/pkg/clientutil" 25 "github.com/containerd/nerdctl/pkg/cmd/container" 26 "github.com/spf13/cobra" 27 ) 28 29 func newStopCommand() *cobra.Command { 30 var stopCommand = &cobra.Command{ 31 Use: "stop [flags] CONTAINER [CONTAINER, ...]", 32 Args: cobra.MinimumNArgs(1), 33 Short: "Stop one or more running containers", 34 RunE: stopAction, 35 ValidArgsFunction: stopShellComplete, 36 SilenceUsage: true, 37 SilenceErrors: true, 38 } 39 stopCommand.Flags().IntP("time", "t", 10, "Seconds to wait before sending a SIGKILL") 40 return stopCommand 41 } 42 43 func processContainerStopOptions(cmd *cobra.Command) (types.ContainerStopOptions, error) { 44 globalOptions, err := processRootCmdFlags(cmd) 45 if err != nil { 46 return types.ContainerStopOptions{}, err 47 } 48 var timeout *time.Duration 49 if cmd.Flags().Changed("time") { 50 timeValue, err := cmd.Flags().GetInt("time") 51 if err != nil { 52 return types.ContainerStopOptions{}, err 53 } 54 t := time.Duration(timeValue) * time.Second 55 timeout = &t 56 } 57 return types.ContainerStopOptions{ 58 Stdout: cmd.OutOrStdout(), 59 Stderr: cmd.ErrOrStderr(), 60 GOptions: globalOptions, 61 Timeout: timeout, 62 }, nil 63 } 64 65 func stopAction(cmd *cobra.Command, args []string) error { 66 options, err := processContainerStopOptions(cmd) 67 if err != nil { 68 return err 69 } 70 71 client, ctx, cancel, err := clientutil.NewClient(cmd.Context(), options.GOptions.Namespace, options.GOptions.Address) 72 if err != nil { 73 return err 74 } 75 defer cancel() 76 77 return container.Stop(ctx, client, args, options) 78 } 79 80 func stopShellComplete(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { 81 // show non-stopped container names 82 statusFilterFn := func(st containerd.ProcessStatus) bool { 83 return st != containerd.Stopped && st != containerd.Created && st != containerd.Unknown 84 } 85 return shellCompleteContainerNames(cmd, statusFilterFn) 86 }