diff --git a/core/system_metric/sys_metric_stat.go b/core/system_metric/sys_metric_stat.go index c8751419..0963d4a0 100644 --- a/core/system_metric/sys_metric_stat.go +++ b/core/system_metric/sys_metric_stat.go @@ -16,6 +16,7 @@ package system_metric import ( "os" + "runtime" "sync" "sync/atomic" "time" @@ -176,6 +177,10 @@ func retrieveAndUpdateCpuStat() { return } + // fix getProcessCpuStat return value (in percentage) breaks compatibility. + cpuNum := runtime.NumCPU() + cpuPercent = cpuPercent / float64(cpuNum) / 100.0 + cpuRatioGauge.Set(cpuPercent) currentCpuUsage.Store(cpuPercent) diff --git a/core/system_metric/sys_metric_stat_test.go b/core/system_metric/sys_metric_stat_test.go index e3a6cdf3..1823c659 100644 --- a/core/system_metric/sys_metric_stat_test.go +++ b/core/system_metric/sys_metric_stat_test.go @@ -47,21 +47,8 @@ func TestCurrentCpuUsage(t *testing.T) { assert.True(t, util.Float64Equals(v, cpuUsage)) } -func Test_getProcessCpuStat(t *testing.T) { - wg := &sync.WaitGroup{} - wg.Add(1) - go func() { - i := 0 - wg.Done() - for i < 10000000000 { - i++ - if i == 1000000000 { - i = 0 - } - } - }() - wg.Wait() - +func TestGetProcessCpuStat(t *testing.T) { + upraiseCpuRate() got, err := getProcessCpuStat() if err != nil { t.Error(err) @@ -83,3 +70,28 @@ func Test_getProcessCpuStat(t *testing.T) { assert.True(t, int(got) > 0) time.Sleep(time.Millisecond * 200) } + +func TestRetrieveAndUpdateCpuStatReturnValueRange(t *testing.T) { + // Initial cpu retrieval. + retrieveAndUpdateCpuStat() + upraiseCpuRate() + time.Sleep(time.Millisecond * 200) + retrieveAndUpdateCpuStat() + assert.True(t, true, CurrentCpuUsage() < 1.0) +} + +func upraiseCpuRate() { + wg := &sync.WaitGroup{} + wg.Add(1) + go func() { + i := 0 + wg.Done() + for i < 10000000000 { + i++ + if i == 1000000000 { + i = 0 + } + } + }() + wg.Wait() +}