Skip to content

Lightweight server monitoring with historical data, docker stats, and alerts.

refactor(agent): avoid deprecated CPU time total helper (#2459)

user0101011168ca6936a77b
diff --git a/agent/cpu.go b/agent/cpu.go
index f92b9fcde..8ac0c2e9c 100644
--- a/agent/cpu.go
+++ b/agent/cpu.go
@@ -119,7 +119,8 @@ func calculateBusy(t1, t2 cpu.TimesStat) float64 {
// On Linux, it excludes guest and guest_nice time from the total to match kernel behavior.
// Returns total CPU time and busy CPU time (total minus idle and I/O wait time).
func getAllBusy(t cpu.TimesStat) (float64, float64) {
- tot := t.Total()
+ tot := t.User + t.System + t.Idle + t.Nice + t.Iowait + t.Irq +
+ t.Softirq + t.Steal + t.Guest + t.GuestNice
if runtime.GOOS == "linux" {
tot -= t.Guest // Linux 2.6.24+
tot -= t.GuestNice // Linux 3.2.0+
diff --git a/agent/cpu_test.go b/agent/cpu_test.go
new file mode 100644
index 000000000..83b025616
--- /dev/null
+++ b/agent/cpu_test.go
@@ -0,0 +1,28 @@
+//go:build testing
+
+package agent
+
+import (
+ "runtime"
+ "testing"
+
+ "github.com/shirou/gopsutil/v4/cpu"
+ "github.com/stretchr/testify/assert"
+)
+
+func TestGetAllBusy(t *testing.T) {
+ times := cpu.TimesStat{
+ User: 1, System: 2, Idle: 3, Nice: 4, Iowait: 5,
+ Irq: 6, Softirq: 7, Steal: 8, Guest: 9, GuestNice: 10,
+ }
+ wantTotal, wantBusy := 55.0, 47.0
+ if runtime.GOOS == "linux" {
+ wantTotal, wantBusy = 36, 28
+ }
+ total, busy := getAllBusy(times)
+ assert.Equal(t, wantTotal, total)
+ assert.Equal(t, wantBusy, busy)
+ assert.InDelta(t, wantBusy/wantTotal*100, calculateBusy(cpu.TimesStat{}, times), 1e-10)
+ assert.Zero(t, calculateBusy(times, times))
+ assert.Zero(t, calculateBusy(times, cpu.TimesStat{}))
+}