aboutsummaryrefslogtreecommitdiff
path: root/cmd/podman/pod_stats.go
blob: 29760341068a5d5b87b26a4574df3a7ea9a2d0fc (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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package main

import (
	"fmt"
	"html/template"
	"os"
	"reflect"
	"strings"
	"text/tabwriter"
	"time"

	tm "github.com/buger/goterm"
	"github.com/containers/buildah/pkg/formats"
	"github.com/containers/libpod/cmd/podman/cliconfig"
	"github.com/containers/libpod/libpod"
	"github.com/containers/libpod/libpod/define"
	"github.com/containers/libpod/pkg/adapter"
	"github.com/containers/libpod/pkg/cgroups"
	"github.com/containers/libpod/pkg/rootless"
	"github.com/pkg/errors"
	"github.com/spf13/cobra"
)

var (
	podStatsCommand     cliconfig.PodStatsValues
	podStatsDescription = `For each specified pod this command will display percentage of CPU, memory, network I/O, block I/O and PIDs for containers in one the pods.`

	_podStatsCommand = &cobra.Command{
		Use:   "stats [flags] [POD...]",
		Short: "Display a live stream of resource usage statistics for the containers in one or more pods",
		Long:  podStatsDescription,
		RunE: func(cmd *cobra.Command, args []string) error {
			podStatsCommand.InputArgs = args
			podStatsCommand.GlobalFlags = MainGlobalOpts
			podStatsCommand.Remote = remoteclient
			return podStatsCmd(&podStatsCommand)
		},
		Example: `podman stats -a --no-stream
  podman stats --no-reset ctrID
  podman stats --no-stream --format "table {{.ID}} {{.Name}} {{.MemUsage}}" ctrID`,
	}
)

func init() {
	podStatsCommand.Command = _podStatsCommand
	podStatsCommand.SetHelpTemplate(HelpTemplate())
	podStatsCommand.SetUsageTemplate(UsageTemplate())
	flags := podStatsCommand.Flags()
	flags.BoolVarP(&podStatsCommand.All, "all", "a", false, "Provide stats for all running pods")
	flags.StringVar(&podStatsCommand.Format, "format", "", "Pretty-print container statistics to JSON or using a Go template")
	flags.BoolVarP(&podStatsCommand.Latest, "latest", "l", false, "Provide stats on the latest pod podman is aware of")
	flags.BoolVar(&podStatsCommand.NoStream, "no-stream", false, "Disable streaming stats and only pull the first result, default setting is false")
	flags.BoolVar(&podStatsCommand.NoReset, "no-reset", false, "Disable resetting the screen between intervals")
	markFlagHiddenForRemoteClient("latest", flags)
}

func podStatsCmd(c *cliconfig.PodStatsValues) error {
	if rootless.IsRootless() {
		unified, err := cgroups.IsCgroup2UnifiedMode()
		if err != nil {
			return err
		}
		if !unified {
			return errors.New("stats is not supported in rootless mode without cgroups v2")
		}
	}

	format := c.Format
	all := c.All
	latest := c.Latest
	ctr := 0
	if all {
		ctr += 1
	}
	if latest {
		ctr += 1
	}
	if len(c.InputArgs) > 0 {
		ctr += 1
	}

	if ctr > 1 {
		return errors.Errorf("--all, --latest and containers cannot be used together")
	}

	runtime, err := adapter.GetRuntime(getContext(), &c.PodmanCommand)
	if err != nil {
		return errors.Wrapf(err, "could not get runtime")
	}
	defer runtime.DeferredShutdown(false)

	times := -1
	if c.NoStream {
		times = 1
	}

	pods, err := runtime.GetStatPods(c)
	if err != nil {
		return errors.Wrapf(err, "unable to get a list of pods")
	}

	// Create empty container stat results for our first pass
	var previousPodStats []*adapter.PodContainerStats
	for _, p := range pods {
		cs := make(map[string]*libpod.ContainerStats)
		pcs := adapter.PodContainerStats{
			Pod:            p,
			ContainerStats: cs,
		}
		previousPodStats = append(previousPodStats, &pcs)
	}

	step := 1
	if times == -1 {
		times = 1
		step = 0
	}

	headerNames := make(map[string]string)
	if c.Format != "" {
		// Make a map of the field names for the headers
		v := reflect.ValueOf(podStatOut{})
		t := v.Type()
		for i := 0; i < t.NumField(); i++ {
			value := strings.ToUpper(splitCamelCase(t.Field(i).Name))
			switch value {
			case "CPU", "MEM":
				value += " %"
			case "MEM USAGE":
				value = "MEM USAGE / LIMIT"
			}
			headerNames[t.Field(i).Name] = value
		}
	}

	for i := 0; i < times; i += step {
		var newStats []*adapter.PodContainerStats
		for _, p := range pods {
			prevStat := getPreviousPodContainerStats(p.ID(), previousPodStats)
			newPodStats, err := p.GetPodStats(prevStat)
			if errors.Cause(err) == define.ErrNoSuchPod {
				continue
			}
			if err != nil {
				return err
			}
			newPod := adapter.PodContainerStats{
				Pod:            p,
				ContainerStats: newPodStats,
			}
			newStats = append(newStats, &newPod)
		}
		//Output
		if strings.ToLower(format) != formats.JSONString && !c.NoReset {
			tm.Clear()
			tm.MoveCursor(1, 1)
			tm.Flush()
		}
		if strings.ToLower(format) == formats.JSONString {
			if err := outputJson(newStats); err != nil {
				return err
			}

		} else {
			results := podContainerStatsToPodStatOut(newStats)
			if len(format) == 0 {
				outputToStdOut(results)
			} else if err := printPSFormat(c.Format, results, headerNames); err != nil {
				return err
			}
		}
		time.Sleep(time.Second)
		previousPodStats := new([]*libpod.PodContainerStats)
		if err := libpod.JSONDeepCopy(newStats, previousPodStats); err != nil {
			return err
		}
		pods, err = runtime.GetStatPods(c)
		if err != nil {
			return err
		}
	}

	return nil
}

func podContainerStatsToPodStatOut(stats []*adapter.PodContainerStats) []*podStatOut {
	var out []*podStatOut
	for _, p := range stats {
		for _, c := range p.ContainerStats {
			o := podStatOut{
				CPU:      floatToPercentString(c.CPU),
				MemUsage: combineHumanValues(c.MemUsage, c.MemLimit),
				Mem:      floatToPercentString(c.MemPerc),
				NetIO:    combineHumanValues(c.NetInput, c.NetOutput),
				BlockIO:  combineHumanValues(c.BlockInput, c.BlockOutput),
				PIDS:     pidsToString(c.PIDs),
				CID:      c.ContainerID[:12],
				Name:     c.Name,
				Pod:      p.Pod.ID()[:12],
			}
			out = append(out, &o)
		}
	}
	return out
}

type podStatOut struct {
	CPU      string
	MemUsage string
	Mem      string
	NetIO    string
	BlockIO  string
	PIDS     string
	Pod      string
	CID      string
	Name     string
}

func printPSFormat(format string, stats []*podStatOut, headerNames map[string]string) error {
	if len(stats) == 0 {
		return nil
	}

	// Use a tabwriter to align column format
	w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0)
	// Spit out the header if "table" is present in the format
	if strings.HasPrefix(format, "table") {
		hformat := strings.Replace(strings.TrimSpace(format[5:]), " ", "\t", -1)
		format = hformat
		headerTmpl, err := template.New("header").Parse(hformat)
		if err != nil {
			return err
		}
		if err := headerTmpl.Execute(w, headerNames); err != nil {
			return err
		}
		fmt.Fprintln(w, "")
	}

	// Spit out the data rows now
	dataTmpl, err := template.New("data").Parse(format)
	if err != nil {
		return err
	}
	for _, container := range stats {
		if err := dataTmpl.Execute(w, container); err != nil {
			return err
		}
		fmt.Fprintln(w, "")
	}
	// Flush the writer
	return w.Flush()

}

func outputToStdOut(stats []*podStatOut) {
	w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
	outFormat := "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n"
	fmt.Fprintf(w, outFormat, "POD", "CID", "NAME", "CPU %", "MEM USAGE/ LIMIT", "MEM %", "NET IO", "BLOCK IO", "PIDS")
	for _, i := range stats {
		if len(stats) == 0 {
			fmt.Fprintf(w, outFormat, i.Pod, "--", "--", "--", "--", "--", "--", "--", "--")
		} else {
			fmt.Fprintf(w, outFormat, i.Pod, i.CID, i.Name, i.CPU, i.MemUsage, i.Mem, i.NetIO, i.BlockIO, i.PIDS)
		}
	}
	w.Flush()
}

func getPreviousPodContainerStats(podID string, prev []*adapter.PodContainerStats) map[string]*libpod.ContainerStats {
	for _, p := range prev {
		if podID == p.Pod.ID() {
			return p.ContainerStats
		}
	}
	return map[string]*libpod.ContainerStats{}
}

func outputJson(stats []*adapter.PodContainerStats) error {
	b, err := json.MarshalIndent(&stats, "", "     ")
	if err != nil {
		return err
	}
	fmt.Println(string(b))
	return nil
}