From 4262f5b5911d93afc4d4ccc68514b3732e083988 Mon Sep 17 00:00:00 2001 From: Feng Date: Mon, 24 Jun 2024 22:32:04 +0800 Subject: [PATCH] fix: monitor middleware reporting of CPU usage (#2984) monitPIDCPU should be transient, not persistent. Co-authored-by: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> --- middleware/monitor/monitor.go | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/middleware/monitor/monitor.go b/middleware/monitor/monitor.go index 5eff16b2f8..3f64df95bb 100644 --- a/middleware/monitor/monitor.go +++ b/middleware/monitor/monitor.go @@ -2,6 +2,7 @@ package monitor import ( "os" + "runtime" "sync" "sync/atomic" "time" @@ -59,14 +60,14 @@ func New(config ...Config) fiber.Handler { // Start routine to update statistics once.Do(func() { p, _ := process.NewProcess(int32(os.Getpid())) //nolint:errcheck // TODO: Handle error - - updateStatistics(p) + numcpu := runtime.NumCPU() + updateStatistics(p, numcpu) go func() { for { time.Sleep(cfg.Refresh) - updateStatistics(p) + updateStatistics(p, numcpu) } }() }) @@ -101,10 +102,10 @@ func New(config ...Config) fiber.Handler { } } -func updateStatistics(p *process.Process) { - pidCPU, err := p.CPUPercent() +func updateStatistics(p *process.Process, numcpu int) { + pidCPU, err := p.Percent(0) if err == nil { - monitPIDCPU.Store(pidCPU / 10) + monitPIDCPU.Store(pidCPU / float64(numcpu)) } if osCPU, err := cpu.Percent(0, false); err == nil && len(osCPU) > 0 {