github.com/containerd/nerdctl@v1.7.7/cmd/nerdctl/container_top.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 "errors" 21 "fmt" 22 23 "github.com/containerd/containerd" 24 "github.com/containerd/nerdctl/pkg/api/types" 25 "github.com/containerd/nerdctl/pkg/clientutil" 26 "github.com/containerd/nerdctl/pkg/cmd/container" 27 "github.com/containerd/nerdctl/pkg/infoutil" 28 "github.com/containerd/nerdctl/pkg/rootlessutil" 29 30 "github.com/spf13/cobra" 31 ) 32 33 func newTopCommand() *cobra.Command { 34 var topCommand = &cobra.Command{ 35 Use: "top CONTAINER [ps OPTIONS]", 36 Args: cobra.MinimumNArgs(1), 37 Short: "Display the running processes of a container", 38 RunE: topAction, 39 ValidArgsFunction: topShellComplete, 40 SilenceUsage: true, 41 SilenceErrors: true, 42 } 43 topCommand.Flags().SetInterspersed(false) 44 return topCommand 45 } 46 47 func topAction(cmd *cobra.Command, args []string) error { 48 // NOTE: rootless container does not rely on cgroupv1. 49 // more details about possible ways to resolve this concern: #223 50 globalOptions, err := processRootCmdFlags(cmd) 51 if err != nil { 52 return err 53 } 54 if rootlessutil.IsRootless() && infoutil.CgroupsVersion() == "1" { 55 return fmt.Errorf("top requires cgroup v2 for rootless containers, see https://rootlesscontaine.rs/getting-started/common/cgroup2/") 56 } 57 58 if globalOptions.CgroupManager == "none" { 59 return errors.New("cgroup manager must not be \"none\"") 60 } 61 client, ctx, cancel, err := clientutil.NewClient(cmd.Context(), globalOptions.Namespace, globalOptions.Address) 62 if err != nil { 63 return err 64 } 65 defer cancel() 66 return container.Top(ctx, client, args, types.ContainerTopOptions{ 67 Stdout: cmd.OutOrStdout(), 68 GOptions: globalOptions, 69 }) 70 71 } 72 73 func topShellComplete(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { 74 // show running container names 75 statusFilterFn := func(st containerd.ProcessStatus) bool { 76 return st == containerd.Running 77 } 78 return shellCompleteContainerNames(cmd, statusFilterFn) 79 }