forked from hyperhq/runv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ps.go
86 lines (76 loc) · 2.05 KB
/
ps.go
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
83
84
85
86
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"text/tabwriter"
"github.com/hyperhq/runv/containerd/api/grpc/types"
"github.com/urfave/cli"
netcontext "golang.org/x/net/context"
)
var psCommand = cli.Command{
Name: "ps",
Usage: "ps displays the processes running inside a container",
ArgsUsage: `<container-id> [ps options]`, Flags: []cli.Flag{
cli.StringFlag{
Name: "format, f",
Value: "table",
Usage: `select one of: ` + formatOptions,
},
},
Action: func(context *cli.Context) error {
container := context.Args().First()
if container == "" {
return cli.NewExitError("container id cannot be empty", -1)
}
c, err := getContainerApi(context, container)
if err != nil {
return cli.NewExitError(fmt.Sprintf("can't access container, %v", err), -1)
}
switch context.String("format") {
case "table":
w := tabwriter.NewWriter(os.Stdout, 12, 1, 3, ' ', 0)
fmt.Fprint(w, "PROCESS\tCMD\n")
// we are limited by the containerd interface for now
for _, p := range c.Processes {
fmt.Fprintf(w, "%s\t%s\n",
p.Pid,
p.Args)
}
if err := w.Flush(); err != nil {
fatal(err)
}
case "json":
pids := make([]string, 0)
for _, p := range c.Processes {
pids = append(pids, p.Pid)
}
data, err := json.Marshal(pids)
if err != nil {
fatal(err)
}
os.Stdout.Write(data)
return nil
default:
return cli.NewExitError(fmt.Sprintf("invalid format option"), -1)
}
return nil
},
}
func getContainerApi(context *cli.Context, container string) (*types.Container, error) {
api, err := getClient(filepath.Join(context.GlobalString("root"), container, "namespace/namespaced.sock"))
if err != nil {
return nil, fmt.Errorf("failed to get client: %v", err)
}
s, err := api.State(netcontext.Background(), &types.StateRequest{Id: container})
if err != nil {
return nil, fmt.Errorf("get container state failed, %v", err)
}
for _, c := range s.Containers {
if c.Id == container {
return c, nil
}
}
return nil, fmt.Errorf("container %s not found", container)
}