Fix CPU calculation

This commit is contained in:
Dane Everitt 2019-09-17 23:10:02 -07:00
parent 0b4816b46f
commit 2a745c5da1
No known key found for this signature in database
GPG Key ID: EEA66103B3D71F53
2 changed files with 9 additions and 9 deletions

View File

@ -286,9 +286,6 @@ func (d *DockerEnvironment) EnableResourcePolling() error {
dec := json.NewDecoder(d.stats)
go func(s *Server) {
pCpu := 0.0
pSystem := 0.0
for {
var v *types.StatsJSON
@ -305,7 +302,7 @@ func (d *DockerEnvironment) EnableResourcePolling() error {
return
}
s.Resources.CpuAbsolute = s.Resources.CalculateAbsoluteCpu(pCpu, pSystem, &v.CPUStats)
s.Resources.CpuAbsolute = s.Resources.CalculateAbsoluteCpu(&v.PreCPUStats, &v.CPUStats)
s.Resources.Memory = v.MemoryStats.Usage
s.Resources.MemoryLimit = v.MemoryStats.Limit

View File

@ -32,15 +32,18 @@ type ResourceUsage struct {
// by the defined CPU limits on the container.
//
// @see https://github.com/docker/cli/blob/aa097cf1aa19099da70930460250797c8920b709/cli/command/container/stats_helpers.go#L166
func (ru *ResourceUsage) CalculateAbsoluteCpu(previousCpu, previousSystem float64, stats *types.CPUStats) float64 {
func (ru *ResourceUsage) CalculateAbsoluteCpu(pStats *types.CPUStats, stats *types.CPUStats) float64 {
// Calculate the change in CPU usage between the current and previous reading.
cpuDelta := float64(stats.CPUUsage.TotalUsage) - float64(previousCpu)
cpuDelta := float64(stats.CPUUsage.TotalUsage) - float64(pStats.CPUUsage.TotalUsage)
// Calculate the change for the entire system's CPU usage between current and previous reading.
systemDelta := float64(stats.SystemUsage) - float64(previousSystem)
systemDelta := float64(stats.SystemUsage) - float64(pStats.SystemUsage)
// Calculate the total number of CPU cores being used.
cpus := float64(len(stats.CPUUsage.PercpuUsage))
cpus := float64(stats.OnlineCPUs)
if cpus == 0.0 {
cpus = float64(len(stats.CPUUsage.PercpuUsage))
}
percent := 0.0
if systemDelta > 0.0 && cpuDelta > 0.0 {
@ -48,4 +51,4 @@ func (ru *ResourceUsage) CalculateAbsoluteCpu(previousCpu, previousSystem float6
}
return math.Round(percent*1000) / 1000
}
}