From 9d2519c085a26e5ce0b289dfaafe8cef88e69651 Mon Sep 17 00:00:00 2001 From: Samuel Lorch Date: Sun, 14 Jul 2024 05:04:25 +0200 Subject: [PATCH] fix cpu usage reporting --- worker/status.go | 29 ++++++++++++++++++++++++----- worker/worker.go | 3 +++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/worker/status.go b/worker/status.go index ec29a0f..703c8a1 100644 --- a/worker/status.go +++ b/worker/status.go @@ -2,6 +2,7 @@ package worker import ( "context" + "time" "github.com/mackerelio/go-osstat/cpu" "github.com/mackerelio/go-osstat/memory" @@ -14,13 +15,31 @@ func init() { rpcServer.RegisterMethod("status", status) } +var cpuBefore *cpu.Stats +var cpuUsage uint64 +var cpuCount uint64 + +func calcUsage() { + for { + cStats, _ := cpu.Get() + if cStats != nil { + cpuUsage = cStats.Total + cpuCount = uint64(cStats.CPUCount) + + if cpuBefore != nil { + total := float64(cStats.Total - cpuBefore.Total) + cpuUsage = uint64(float64((cStats.User-cpuBefore.User)+(cStats.System-cpuBefore.System)) / total * 100) + } + cpuBefore = cStats + } + time.Sleep(time.Second) + } +} + func status(ctx context.Context, req rpc.Request) (any, error) { s := types.WorkerStatus{} - cStats, _ := cpu.Get() - if cStats != nil { - s.CPUUsage = cStats.Total - s.CPUCount = uint64(cStats.CPUCount) - } + s.CPUUsage = cpuUsage + s.CPUCount = cpuCount mStats, _ := memory.Get() if mStats != nil { s.MemoryUsage = uint64(float64(mStats.Used) / float64(mStats.Total) * 100) diff --git a/worker/worker.go b/worker/worker.go index 75bd1bd..9c2c594 100644 --- a/worker/worker.go +++ b/worker/worker.go @@ -60,6 +60,9 @@ func Start(_conf config.Config) { exit = true cancel() }() + + go calcUsage() + for { if exit { slog.InfoContext(ctx, "Done")