From 231d6f3d4ec502cb93f089ad6c9a2e4cb3c61440 Mon Sep 17 00:00:00 2001 From: shirou Date: Sat, 19 Nov 2022 12:21:45 +0000 Subject: [PATCH] [load][windows]: add error detail and context handling. --- load/load_windows.go | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/load/load_windows.go b/load/load_windows.go index 3ff0c0a..b484838 100644 --- a/load/load_windows.go +++ b/load/load_windows.go @@ -26,7 +26,7 @@ var ( // TODO instead of this goroutine, we can register a Win32 counter just as psutil does // see https://psutil.readthedocs.io/en/latest/#psutil.getloadavg // code https://github.com/giampaolo/psutil/blob/8415355c8badc9c94418b19bdf26e622f06f0cce/psutil/arch/windows/wmi.c -func loadAvgGoroutine() { +func loadAvgGoroutine(ctx context.Context) { var ( samplingFrequency time.Duration = 5 * time.Second loadAvgFactor1M float64 = 1 / math.Exp(samplingFrequency.Seconds()/time.Minute.Seconds()) @@ -37,20 +37,30 @@ func loadAvgGoroutine() { counter, err := common.ProcessorQueueLengthCounter() if err != nil || counter == nil { - log.Println("gopsutil: unexpected processor queue length counter error, please file an issue on github: err") + log.Printf("unexpected processor queue length counter error, %v\n", err) return } tick := time.NewTicker(samplingFrequency).C - for { + + f := func() { currentLoad, err = counter.GetValue() - loadAvgMutex.Lock() loadErr = err + loadAvgMutex.Lock() loadAvg1M = loadAvg1M*loadAvgFactor1M + currentLoad*(1-loadAvgFactor1M) loadAvg5M = loadAvg5M*loadAvgFactor5M + currentLoad*(1-loadAvgFactor5M) loadAvg15M = loadAvg15M*loadAvgFactor15M + currentLoad*(1-loadAvgFactor15M) loadAvgMutex.Unlock() - <-tick + } + + f() // run first time + for { + select { + case <-ctx.Done(): + return + case <-tick: + f() + } } } @@ -61,7 +71,7 @@ func Avg() (*AvgStat, error) { func AvgWithContext(ctx context.Context) (*AvgStat, error) { loadAvgGoroutineOnce.Do(func() { - go loadAvgGoroutine() + go loadAvgGoroutine(ctx) }) loadAvgMutex.RLock() defer loadAvgMutex.RUnlock()