summaryrefslogtreecommitdiff
path: root/cmd/podman/top.go
blob: 7ea8a1169849ddf6799d966cca13bdae399e8a13 (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
75
76
77
78
79
80
81
82
package main

import (
	"fmt"

	"github.com/pkg/errors"
	"github.com/projectatomic/libpod/cmd/podman/libpodruntime"
	"github.com/projectatomic/libpod/libpod"
	"github.com/urfave/cli"
)

var (
	topFlags = []cli.Flag{
		LatestFlag,
	}
	topDescription = `
   podman top

	Display the running processes of the container.
`

	topCommand = cli.Command{
		Name:           "top",
		Usage:          "Display the running processes of a container",
		Description:    topDescription,
		Flags:          topFlags,
		Action:         topCmd,
		ArgsUsage:      "CONTAINER-NAME",
		SkipArgReorder: true,
	}
)

func topCmd(c *cli.Context) error {
	var container *libpod.Container
	var err error
	args := c.Args()
	var psArgs []string
	psOpts := []string{"-o", "uid,pid,ppid,c,stime,tname,time,cmd"}
	if len(args) < 1 && !c.Bool("latest") {
		return errors.Errorf("you must provide the name or id of a running container")
	}
	if err := validateFlags(c, topFlags); err != nil {
		return err
	}

	runtime, err := libpodruntime.GetRuntime(c)
	if err != nil {
		return errors.Wrapf(err, "error creating libpod runtime")
	}
	defer runtime.Shutdown(false)
	if len(args) > 1 {
		psOpts = args[1:]
	}

	if c.Bool("latest") {
		container, err = runtime.GetLatestContainer()
	} else {
		container, err = runtime.LookupContainer(args[0])
	}

	if err != nil {
		return errors.Wrapf(err, "unable to lookup %s", args[0])
	}
	conStat, err := container.State()
	if err != nil {
		return errors.Wrapf(err, "unable to look up state for %s", args[0])
	}
	if conStat != libpod.ContainerStateRunning {
		return errors.Errorf("top can only be used on running containers")
	}

	psArgs = append(psArgs, psOpts...)

	psOutput, err := container.GetContainerPidInformation(psArgs)
	if err != nil {
		return err
	}
	for _, line := range psOutput {
		fmt.Println(line)
	}
	return nil
}