Merge pull request #3179 from jen20/nan-floats

client: Guard against "NaN" values from floats
This commit is contained in:
Michael Schurter
2017-09-08 14:38:55 -07:00
committed by GitHub
2 changed files with 46 additions and 0 deletions

View File

@@ -231,13 +231,27 @@ func (h *HostCpuStatsCalculator) Calculate(times cpu.TimesStat) (idle float64, u
deltaTotal := currentTotal - h.prevTotal
idle = ((currentIdle - h.prevIdle) / deltaTotal) * 100
if math.IsNaN(idle) {
idle = 100.0
}
user = ((currentUser - h.prevUser) / deltaTotal) * 100
if math.IsNaN(user) {
user = 0.0
}
system = ((currentSystem - h.prevSystem) / deltaTotal) * 100
if math.IsNaN(system) {
system = 0.0
}
currentBusy := times.User + times.System + times.Nice + times.Iowait + times.Irq +
times.Softirq + times.Steal + times.Guest + times.GuestNice + times.Stolen
total = ((currentBusy - h.prevBusy) / deltaTotal) * 100
if math.IsNaN(total) {
total = 0.0
}
h.prevIdle = currentIdle
h.prevUser = currentUser

32
client/stats/host_test.go Normal file
View File

@@ -0,0 +1,32 @@
package stats
import (
"testing"
"github.com/shirou/gopsutil/cpu"
)
func TestHostCpuStatsCalculator_Nan(t *testing.T) {
times := cpu.TimesStat{
User: 0.0,
Idle: 100.0,
System: 0.0,
}
calculator := NewHostCpuStatsCalculator()
calculator.Calculate(times)
idle, user, system, total := calculator.Calculate(times)
if idle != 100.0 {
t.Errorf("idle: Expected: %f, Got %f", 100.0, idle)
}
if user != 0.0 {
t.Errorf("user: Expected: %f, Got %f", 0.0, user)
}
if system != 0.0 {
t.Errorf("system: Expected: %f, Got %f", 0.0, system)
}
if total != 0.0 {
t.Errorf("total: Expected: %f, Got %f", 0.0, total)
}
}