github.com/containers/libpod@v1.9.4-0.20220419124438-4284fd425507/cmd/podman/pod_top.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "os" 6 "strings" 7 "text/tabwriter" 8 9 "github.com/containers/libpod/cmd/podman/cliconfig" 10 "github.com/containers/libpod/pkg/adapter" 11 "github.com/containers/libpod/pkg/util" 12 "github.com/pkg/errors" 13 "github.com/spf13/cobra" 14 ) 15 16 var ( 17 podTopCommand cliconfig.PodTopValues 18 19 podTopDescription = fmt.Sprintf(`Specify format descriptors to alter the output. 20 21 You may run "podman pod top -l pid pcpu seccomp" to print the process ID, the CPU percentage and the seccomp mode of each process of the latest pod. 22 %s`, getDescriptorString()) 23 24 _podTopCommand = &cobra.Command{ 25 Use: "top [flags] CONTAINER [FORMAT-DESCRIPTORS]", 26 Short: "Display the running processes of containers in a pod", 27 Long: podTopDescription, 28 RunE: func(cmd *cobra.Command, args []string) error { 29 podTopCommand.InputArgs = args 30 podTopCommand.GlobalFlags = MainGlobalOpts 31 podTopCommand.Remote = remoteclient 32 return podTopCmd(&podTopCommand) 33 }, 34 Example: `podman top ctrID 35 podman top --latest 36 podman top --latest pid seccomp args %C`, 37 } 38 ) 39 40 func init() { 41 podTopCommand.Command = _podTopCommand 42 podTopCommand.SetHelpTemplate(HelpTemplate()) 43 podTopCommand.SetUsageTemplate(UsageTemplate()) 44 flags := podTopCommand.Flags() 45 flags.BoolVarP(&podTopCommand.Latest, "latest", "l", false, "Act on the latest pod podman is aware of") 46 flags.BoolVar(&podTopCommand.ListDescriptors, "list-descriptors", false, "") 47 markFlagHidden(flags, "list-descriptors") 48 } 49 50 func podTopCmd(c *cliconfig.PodTopValues) error { 51 var ( 52 descriptors []string 53 ) 54 args := c.InputArgs 55 56 if c.ListDescriptors { 57 descriptors, err := util.GetContainerPidInformationDescriptors() 58 if err != nil { 59 return err 60 } 61 fmt.Println(strings.Join(descriptors, "\n")) 62 return nil 63 } 64 65 if len(args) < 1 && !c.Latest { 66 return errors.Errorf("you must provide the name or id of a running pod") 67 } 68 69 runtime, err := adapter.GetRuntime(getContext(), &c.PodmanCommand) 70 if err != nil { 71 return errors.Wrapf(err, "error creating libpod runtime") 72 } 73 defer runtime.DeferredShutdown(false) 74 75 if c.Latest { 76 descriptors = args 77 } else { 78 descriptors = args[1:] 79 } 80 81 w := tabwriter.NewWriter(os.Stdout, 5, 1, 3, ' ', 0) 82 psOutput, err := runtime.PodTop(c, descriptors) 83 if err != nil { 84 return err 85 } 86 for _, proc := range psOutput { 87 if _, err := fmt.Fprintln(w, proc); err != nil { 88 return err 89 } 90 } 91 return w.Flush() 92 }