Skip to content

Commit

Permalink
fix: monitor middleware reporting of CPU usage (#2984)
Browse files Browse the repository at this point in the history
monitPIDCPU should be transient, not persistent.

Co-authored-by: Juan Calderon-Perez <835733+gaby@users.noreply.github.com>
  • Loading branch information
nyufeng and gaby committed Jun 24, 2024
1 parent 232c0fa commit 4262f5b
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions middleware/monitor/monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package monitor

import (
"os"
"runtime"
"sync"
"sync/atomic"
"time"
Expand Down Expand Up @@ -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)
}
}()
})
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit 4262f5b

Please sign in to comment.