From 2a745c5da1272a0a1df8e25151ad5483be045aab Mon Sep 17 00:00:00 2001 From: Dane Everitt Date: Tue, 17 Sep 2019 23:10:02 -0700 Subject: [PATCH] Fix CPU calculation --- server/environment_docker.go | 5 +---- server/resources.go | 13 ++++++++----- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/server/environment_docker.go b/server/environment_docker.go index d0a69c1..53b1c43 100644 --- a/server/environment_docker.go +++ b/server/environment_docker.go @@ -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 diff --git a/server/resources.go b/server/resources.go index 44425dc..5cf480a 100644 --- a/server/resources.go +++ b/server/resources.go @@ -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 -} +} \ No newline at end of file