diff --git a/cli/command/container/stats_helpers.go b/cli/command/container/stats_helpers.go index 75218f882a..262ce5fc45 100644 --- a/cli/command/container/stats_helpers.go +++ b/cli/command/container/stats_helpers.go @@ -50,12 +50,7 @@ func (s *stats) isKnownContainer(cid string) (int, bool) { } func collect(ctx context.Context, s *Stats, cli client.ContainerAPIClient, streamStats bool, waitFirst *sync.WaitGroup) { //nolint:gocyclo - var ( - getFirst bool - previousCPU uint64 - previousSystem uint64 - u = make(chan error, 1) - ) + var getFirst bool defer func() { // if error happens and we get nothing of stats, release wait group whatever @@ -71,6 +66,7 @@ func collect(ctx context.Context, s *Stats, cli client.ContainerAPIClient, strea return } + u := make(chan error, 1) go func() { defer response.Body.Close() dec := json.NewDecoder(response.Body) @@ -97,9 +93,7 @@ func collect(ctx context.Context, s *Stats, cli client.ContainerAPIClient, strea } if daemonOSType != "windows" { - previousCPU = v.PreCPUStats.CPUUsage.TotalUsage - previousSystem = v.PreCPUStats.SystemUsage - cpuPercent = calculateCPUPercentUnix(previousCPU, previousSystem, v) + cpuPercent = calculateCPUPercentUnix(v.PreCPUStats, v.CPUStats) blkRead, blkWrite = calculateBlockIO(v.BlkioStats) mem = calculateMemUsageUnixNoCache(v.MemoryStats) memLimit = float64(v.MemoryStats.Limit) @@ -165,18 +159,18 @@ func collect(ctx context.Context, s *Stats, cli client.ContainerAPIClient, strea } } -func calculateCPUPercentUnix(previousCPU, previousSystem uint64, v *container.StatsResponse) float64 { +func calculateCPUPercentUnix(previousCPU container.CPUStats, curCPUStats container.CPUStats) float64 { var ( cpuPercent = 0.0 // calculate the change for the cpu usage of the container in between readings - cpuDelta = float64(v.CPUStats.CPUUsage.TotalUsage) - float64(previousCPU) + cpuDelta = float64(curCPUStats.CPUUsage.TotalUsage) - float64(previousCPU.CPUUsage.TotalUsage) // calculate the change for the entire system between readings - systemDelta = float64(v.CPUStats.SystemUsage) - float64(previousSystem) - onlineCPUs = float64(v.CPUStats.OnlineCPUs) + systemDelta = float64(curCPUStats.SystemUsage) - float64(previousCPU.SystemUsage) + onlineCPUs = float64(curCPUStats.OnlineCPUs) ) if onlineCPUs == 0.0 { - onlineCPUs = float64(len(v.CPUStats.CPUUsage.PercpuUsage)) + onlineCPUs = float64(len(curCPUStats.CPUUsage.PercpuUsage)) } if systemDelta > 0.0 && cpuDelta > 0.0 { cpuPercent = (cpuDelta / systemDelta) * onlineCPUs * 100.0