/
stat.go
209 lines (166 loc) · 5.58 KB
/
stat.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
package dockergateway
import (
"context"
"encoding/json"
"github.com/docker/docker/api/types"
"github.com/gusantoniassi/navegante/core/entity"
)
type getStatResult struct {
stat *entity.Stat
err error
}
// @TODO: test stats on Windows: https://github.com/docker/cli/blob/96e1d1d6421b725bdd5024f9a97af9bf97ad9619/cli/command/container/stats_helpers.go#L98
// OSType is in types.ContainerStats, along with the JSON response body
/**
* Receives a Docker StatsJSON object and returns stats in a more human-friendly
* format
*/
func hydrateStat(stat types.StatsJSON) entity.Stat {
var cpuPercent, memPercent float64
cpuPercent = getAverageCpuUsage(stat)
memUsage := getMemUsage(stat.MemoryStats)
memPercent = getMemPercent(memUsage, stat.MemoryStats.Limit)
netRx, netTx := getNetworkBytes(stat.Networks)
blkRead, blkWrite := getDiskBytes(stat.BlkioStats.IoServiceBytesRecursive)
entityStat := entity.Stat{
ContainerID: entity.ContainerID(stat.ID),
CPUPercent: cpuPercent,
MemoryPercent: memPercent,
MemoryUsage: memUsage,
MemoryTotal: stat.MemoryStats.Limit,
NetworkInput: netRx,
NetworkOutput: netTx,
BlockRead: blkRead,
BlockWrite: blkWrite,
}
return entityStat
}
/*
* Calculates the average CPU usage based on the previous reading and the overall
* system usage.
* @see https://github.com/docker/cli/blob/96e1d1d6421b725bdd5024f9a97af9bf97ad9619/cli/command/container/stats_helpers.go#L166
* @see https://stackoverflow.com/questions/35692667/in-docker-cpu-usage-calculation-what-are-totalusage-systemusage-percpuusage-a
*/
func getAverageCpuUsage(stat types.StatsJSON) float64 {
previousContainerCpu := stat.PreCPUStats.CPUUsage.TotalUsage
previousSystemCpu := stat.PreCPUStats.SystemUsage
cpuPercent := 0.0
// Container CPU usage changed from last reading
containerCpuDelta := float64(stat.CPUStats.CPUUsage.TotalUsage) - float64(previousContainerCpu)
// System CPU usage changed from last reading
systemCpuDelta := float64(stat.CPUStats.SystemUsage) - float64(previousSystemCpu)
// Number of system cores allocated to the container
containerCPUCores := float64(stat.CPUStats.OnlineCPUs)
// If the onlineCPU metric isn't present, use the number of PercpuUsage statistics returned
if containerCPUCores == 0.0 {
containerCPUCores = float64(len(stat.CPUStats.CPUUsage.PercpuUsage))
}
// If the system and the container CPU usage hasn't changed, we don't need to calc
if systemCpuDelta > 0.0 && containerCpuDelta > 0.0 {
// Calculate the average container CPU usage based on the total system usage
averageCpuUsage := containerCpuDelta / systemCpuDelta
// Multiply by containerCPUCores to consider the number of cores
cpuPercent = averageCpuUsage * containerCPUCores * 100.0
}
return cpuPercent
}
/**
* Extracts current container memory usage from MemoryStats type
* @see https://github.com/docker/cli/blob/96e1d1d6421b725bdd5024f9a97af9bf97ad9619/cli/command/container/stats_helpers.go#L239
*/
func getMemUsage(memStat types.MemoryStats) uint64 {
// Version 1 of the Linux cgroup API uses total_inactive_file
if v, ok := memStat.Stats["total_inactive_file"]; ok && v < memStat.Usage {
return memStat.Usage - v
}
// Version 2 of the Linux cgroup API uses inactive_file
if v := memStat.Stats["inactive_file"]; v < memStat.Usage {
return memStat.Usage - v
}
return memStat.Usage
}
/**
* Extracts current container memory usage percentage, with a check to avoid
* division by zero
*/
func getMemPercent(usage uint64, memLimit uint64) float64 {
if memLimit == 0 {
return 0
}
return float64(usage) / float64(memLimit) * 100
}
func getNetworkBytes(netStats map[string]types.NetworkStats) (uint64, uint64) {
var netRx, netTx uint64
for _, iface := range netStats {
netRx += iface.RxBytes
netTx += iface.TxBytes
}
return netRx, netTx
}
func getDiskBytes(blockStats []types.BlkioStatEntry) (uint64, uint64) {
var blkRead, blkWrite uint64
for _, svcBytes := range blockStats {
switch svcBytes.Op {
case "Read":
blkRead += svcBytes.Value
case "Write":
blkWrite += svcBytes.Value
}
}
return blkRead, blkWrite
}
func getContainerStats(g *Gateway, id string, c chan getStatResult) {
defer close(c)
stat, err := g.ContainerStats(id)
c <- getStatResult{stat: stat, err: err}
}
func getAllContainerStats(g *Gateway, containers []types.Container, c chan getStatResult) {
defer close(c)
var results []chan getStatResult
for i, c := range containers {
results = append(results, make(chan getStatResult))
go getContainerStats(g, c.ID[:12], results[i])
}
for i := range results {
for r1 := range results[i] {
c <- r1
}
}
}
func (g *Gateway) ContainerStatsAll() ([]*entity.Stat, error) {
ctx := context.Background()
containers, err := g.Docker.ContainerList(ctx, types.ContainerListOptions{})
if err != nil {
return nil, err
}
if len(containers) == 0 {
return nil, nil
}
results := make(chan getStatResult, len(containers))
go getAllContainerStats(g, containers, results)
containerStats := make([]*entity.Stat, 0, len(containers))
for r := range results {
if r.err != nil {
return nil, err
}
containerStats = append(containerStats, r.stat)
}
return containerStats, nil
}
func (g *Gateway) ContainerStats(cid string) (*entity.Stat, error) {
ctx := context.Background()
// @TODO: Implement streaming option
response, err := g.Docker.ContainerStats(ctx, cid, false)
if err != nil {
return nil, err
}
defer response.Body.Close()
decoder := json.NewDecoder(response.Body)
var result types.StatsJSON
err = decoder.Decode(&result)
if err != nil {
return nil, err
}
stat := hydrateStat(result)
return &stat, nil
}