/
container.go
312 lines (259 loc) · 6.92 KB
/
container.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
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
/*
Copyright © 2020 The PES Open Source Team pesos@pes.edu
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package container
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
ui "github.com/gizak/termui/v3"
"github.com/vyattalee/grofer/pkg/core"
)
// PerContainerMetrics holds metrics for a given container
type PerContainerMetrics struct {
// Metrics common for Overall and per container
ID string
Image string
Name string
Status string
State string
CPU float64
Mem float64
Net netStat
Blk blkStat
// Metrics specific to per container
Pid string
NetInfo []netInfo
PerCPU []string
PortMap []portMap
Mounts []mountInfo
Procs []procInfo
}
type netStat struct {
Rx float64
Tx float64
}
type blkStat struct {
Read uint64
Write uint64
}
type netInfo struct {
Name string
Driver string
IP string
Ingress bool
}
type mountInfo struct {
Src string
Dst string
Mode string
}
type portMap struct {
IP string
Host int
Container int
Protocol string
}
type procInfo struct {
UID string
PID string
CMD string
}
func getCPUPercent(data *types.StatsJSON) float64 {
cpuPercent := 0.0
numCPUs := len(data.CPUStats.CPUUsage.PercpuUsage)
cpuDelta := float64(data.CPUStats.CPUUsage.TotalUsage) - float64(data.PreCPUStats.CPUUsage.TotalUsage)
systemDelta := float64(data.CPUStats.SystemUsage) - float64(data.PreCPUStats.SystemUsage)
if cpuDelta > 0.0 && systemDelta > 0.0 {
cpuPercent = (cpuDelta / systemDelta) * float64(numCPUs) * 100.0
}
return cpuPercent
}
func getPerCPUPercents(data *types.StatsJSON) []string {
preLen := len(data.PreCPUStats.CPUUsage.PercpuUsage)
postLen := len(data.CPUStats.CPUUsage.PercpuUsage)
numCPUs := ui.MaxInt(preLen, postLen)
perCPUPercents := make([]string, numCPUs)
systemDelta := float64(data.CPUStats.SystemUsage) - float64(data.PreCPUStats.SystemUsage)
// If first run, skip percpu metrics
if preLen != postLen {
for i := range perCPUPercents {
perCPUPercents[i] = "NA"
}
} else {
for i, usage := range data.CPUStats.CPUUsage.PercpuUsage {
perCPUPercent := 0.0
cpuDelta := float64(usage) - float64(data.PreCPUStats.CPUUsage.PercpuUsage[i])
if cpuDelta > 0.0 && systemDelta > 0.0 {
perCPUPercent = (cpuDelta / systemDelta) * float64(numCPUs) * 100.0
}
perCPUPercents[i] = fmt.Sprintf("%.2f%%", perCPUPercent)
}
}
return perCPUPercents
}
// Wait waits for a container of given container id to reach a specified state.
// If an error is encountered during the wait, it is returned.
func Wait(ctx context.Context, cli *client.Client, cid, state string) error {
t := time.NewTicker(100 * time.Millisecond)
tick := t.C
timeout := time.NewTimer(1 * time.Minute)
timeoutChan := timeout.C
for {
select {
case <-timeoutChan:
return fmt.Errorf("failed to reach state '%s' for container %s", state, cid)
case <-tick:
data, err := cli.ContainerInspect(ctx, cid)
if err != nil {
return err
}
if data.State.Status == state {
return nil
}
}
}
}
// GetContainerMetrics provides per container metrics in the form of PerContainerMetrics Structs.
func GetContainerMetrics(ctx context.Context, cli *client.Client, cid string) (PerContainerMetrics, error) {
metrics := PerContainerMetrics{}
// Get container using a filter
args := filters.NewArgs(
filters.KeyValuePair{
Key: "id",
Value: cid,
},
)
containers, err := cli.ContainerList(ctx, types.ContainerListOptions{Filters: args})
if err != nil {
return metrics, err
}
if len(containers) > 1 {
return metrics, fmt.Errorf("multiple containers with same ID exist")
} else if len(containers) < 1 {
return metrics, core.ErrInvalidContainer
}
c := containers[0]
// Get PID
inspectData, err := cli.ContainerInspect(ctx, cid)
if err != nil {
return metrics, nil
}
// Get Container Stats
stats, err := cli.ContainerStats(ctx, cid, false)
if err != nil {
return metrics, err
}
data := types.StatsJSON{}
err = json.NewDecoder(stats.Body).Decode(&data)
if err != nil {
return metrics, err
}
stats.Body.Close()
// Calculate CPU percent
cpuPercent := getCPUPercent(&data)
// Get Per CPU utilizations
perCPUPercents := getPerCPUPercents(&data)
// Calculate Memory usage
memPercent := float64(data.MemoryStats.Usage) / float64(data.MemoryStats.Limit) * 100
// Calculate Network Metrics
var rx, tx float64
for _, v := range data.Networks {
rx += float64(v.RxBytes)
tx += float64(v.TxBytes)
}
// Calculate blk IO
var blkRead, blkWrite uint64
for _, bioEntry := range data.BlkioStats.IoServiceBytesRecursive {
switch strings.ToLower(bioEntry.Op) {
case "read":
blkRead = blkRead + bioEntry.Value
case "write":
blkWrite = blkWrite + bioEntry.Value
}
}
// Get Network Settings
netData := []netInfo{}
for _, network := range c.NetworkSettings.Networks {
id := network.NetworkID
net, err := cli.NetworkInspect(ctx, id, types.NetworkInspectOptions{})
if err != nil {
continue
}
n := netInfo{
Name: net.Name,
Driver: net.Driver,
IP: network.IPAddress,
Ingress: net.Ingress,
}
netData = append(netData, n)
}
// Get Port mappings
portData := []portMap{}
for _, port := range c.Ports {
p := portMap{
IP: port.IP,
Host: int(port.PublicPort),
Container: int(port.PrivatePort),
Protocol: port.Type,
}
portData = append(portData, p)
}
// Get mounted volumes
mountData := []mountInfo{}
for _, mount := range c.Mounts {
m := mountInfo{
Src: mount.Source,
Dst: mount.Destination,
Mode: mount.Mode,
}
mountData = append(mountData, m)
}
// Get processes in container
procs, err := cli.ContainerTop(ctx, cid, []string{})
if err != nil {
return metrics, nil
}
procData := []procInfo{}
for _, proc := range procs.Processes {
p := procInfo{
UID: proc[0],
PID: proc[1],
CMD: proc[7],
}
procData = append(procData, p)
}
// Populate metrics
metrics = PerContainerMetrics{
ID: c.ID[:10],
Image: c.Image,
Name: strings.TrimLeft(strings.Join(c.Names, ","), "/"),
Status: c.Status,
State: c.State,
CPU: cpuPercent,
Mem: memPercent,
Net: netStat{Rx: rx, Tx: tx},
Blk: blkStat{Read: blkRead, Write: blkWrite},
Pid: fmt.Sprintf("%d", inspectData.State.Pid),
NetInfo: netData,
PerCPU: perCPUPercents,
PortMap: portData,
Mounts: mountData,
Procs: procData,
}
return metrics, nil
}