diff --git a/utils/cpu.go b/utils/cpu.go index 7f8ed2e4..1dc2dca9 100644 --- a/utils/cpu.go +++ b/utils/cpu.go @@ -15,7 +15,6 @@ package utils import ( - "fmt" "time" "github.com/frostbyte73/core" @@ -50,13 +49,7 @@ func NewCPUStats(updateCallback func(idle float64)) (*CPUStats, error) { return nil, err } - self, err := procfs.Self() - if err != nil { - return nil, err - } - c := &CPUStats{ - pid: self.PID, platform: p, warningThrottle: core.NewThrottle(time.Minute), updateCallback: updateCallback, @@ -97,6 +90,7 @@ func (c *CPUStats) monitorCPULoad() { c.idleCPUs.Store(idle) idleRatio := idle / c.platform.numCPU() + logger.Infow("cpu load", "load", c.platform.numCPU()-idle) if idleRatio < 0.1 { c.warningThrottle(func() { logger.Infow("high cpu load", "load", 1-idleRatio) }) @@ -120,6 +114,7 @@ func (c *CPUStats) MonitorProcesses(updateCallback func(map[int]float64)) error if err != nil { return err } + logger.Infow("svc process", "pid", self.PID) ticker := time.NewTicker(time.Second) defer ticker.Stop() @@ -141,40 +136,41 @@ func (c *CPUStats) MonitorProcesses(updateCallback func(map[int]float64)) error if err != nil { return err } + + ppids := make(map[int]int) for _, proc := range procs { - fmt.Print(proc.PID, ", ") nextStats[proc.PID], err = proc.Stat() if err != nil { return err } + if proc.PID != self.PID { + ppids[proc.PID], err = getPPID(proc.PID) + if err != nil { + return err + } + } } - fmt.Println() nextTotalTime := total.CPUTotal.User + total.CPUTotal.Nice + total.CPUTotal.System + total.CPUTotal.Idle - ppids := make(map[int]int) usage := make(map[int]float64) + all := 0.0 for pid, stat := range nextStats { t := float64(stat.UTime + stat.STime - prevStats[pid].UTime - prevStats[pid].STime) - s := numCPU*t*100/nextTotalTime - prevTotalTime - - if pid == self.PID { - usage[pid] = s + if t == 0 { continue } - ppid, err := getPPID(pid) - if err != nil { - return err - } - for ppids[ppid] != self.PID && ppids[ppid] != 0 { - pid = ppid - ppid = ppids[ppid] + for ppids[pid] != self.PID && ppids[pid] != 0 { + // attribute usage to parent process, stopping before service process + pid = ppids[pid] } - + s := numCPU * t * 100 / (nextTotalTime - prevTotalTime) usage[pid] += s + all += s } + logger.Infow("cpu usage (proc)", "load", all) updateCallback(usage) prevTotalTime = nextTotalTime