From c98d5fdaf4be434b89cb05cdacd587571fc89ece Mon Sep 17 00:00:00 2001 From: Kevin Wan Date: Sat, 2 Mar 2024 07:13:41 +0800 Subject: [PATCH] chore: simplify linux nocgroup logic (#3953) --- core/stat/internal/cpu_linux.go | 76 ++++++++++++++++++--------------- 1 file changed, 42 insertions(+), 34 deletions(-) diff --git a/core/stat/internal/cpu_linux.go b/core/stat/internal/cpu_linux.go index faf36c70..c10196c1 100644 --- a/core/stat/internal/cpu_linux.go +++ b/core/stat/internal/cpu_linux.go @@ -27,42 +27,9 @@ var ( initOnce sync.Once ) -// if /proc not present, ignore the cpu calculation, like wsl linux -func initialize() { - cpus, err := effectiveCpus() - if err != nil { - noCgroup = true - logx.Error(err) - return - } - - cores = uint64(cpus) - limit = float64(cpus) - quota, err := cpuQuota() - if err == nil && quota > 0 { - if quota < limit { - limit = quota - } - } - - preSystem, err = systemCpuUsage() - if err != nil { - noCgroup = true - logx.Error(err) - return - } - - preTotal, err = cpuUsage() - if err != nil { - noCgroup = true - logx.Error(err) - return - } -} - // RefreshCpu refreshes cpu usage and returns. func RefreshCpu() uint64 { - initOnce.Do(initialize) + initializeOnce() if noCgroup { return 0 @@ -120,6 +87,47 @@ func effectiveCpus() (int, error) { return cg.effectiveCpus() } +// if /proc not present, ignore the cpu calculation, like wsl linux +func initialize() error { + cpus, err := effectiveCpus() + if err != nil { + return err + } + + cores = uint64(cpus) + limit = float64(cpus) + quota, err := cpuQuota() + if err == nil && quota > 0 { + if quota < limit { + limit = quota + } + } + + preSystem, err = systemCpuUsage() + if err != nil { + return err + } + + preTotal, err = cpuUsage() + return err +} + +func initializeOnce() { + initOnce.Do(func() { + defer func() { + if p := recover(); p != nil { + noCgroup = true + logx.Error(p) + } + }() + + if err := initialize(); err != nil { + noCgroup = true + logx.Error(err) + } + }) +} + func systemCpuUsage() (uint64, error) { lines, err := iox.ReadTextLines(statFile, iox.WithoutBlank()) if err != nil {