From 2a8be30f017270f7cd7f09a12c049830c6fc6d4f Mon Sep 17 00:00:00 2001 From: true1064 Date: Wed, 1 Nov 2023 11:57:46 +0800 Subject: [PATCH] fix(util): check if err occurred when get CPU percent, to avoid panic if got nil result. Signed-off-by: true1064 --- datanode/server.go | 6 ++++-- metanode/manager.go | 6 ++++-- util/loadutil/cpu.go | 24 +++++++++++++++++++++--- util/loadutil/cpu_test.go | 2 +- 4 files changed, 30 insertions(+), 8 deletions(-) diff --git a/datanode/server.go b/datanode/server.go index 58d74c62b..8329b908f 100644 --- a/datanode/server.go +++ b/datanode/server.go @@ -865,8 +865,10 @@ func (s *DataNode) startCpuSample() { return default: // this function will sleep cpuSampleDuration - used := loadutil.GetCpuUtilPercent(cpuSampleDuration) - s.cpuUtil.Store(used) + used, err := loadutil.GetCpuUtilPercent(cpuSampleDuration) + if err == nil { + s.cpuUtil.Store(used) + } } } }() diff --git a/metanode/manager.go b/metanode/manager.go index 3e75fff25..adf6dbb5e 100644 --- a/metanode/manager.go +++ b/metanode/manager.go @@ -331,8 +331,10 @@ func (m *metadataManager) startCpuSample() { case <-m.stopC: return default: - used := loadutil.GetCpuUtilPercent(sampleDuration) - m.cpuUtil.Store(used) + used, err := loadutil.GetCpuUtilPercent(sampleDuration) + if err == nil { + m.cpuUtil.Store(used) + } } } }() diff --git a/util/loadutil/cpu.go b/util/loadutil/cpu.go index 05722971e..4afed68c2 100644 --- a/util/loadutil/cpu.go +++ b/util/loadutil/cpu.go @@ -15,12 +15,30 @@ package loadutil import ( + "fmt" + "github.com/cubefs/cubefs/util/log" "time" "github.com/shirou/gopsutil/cpu" ) -func GetCpuUtilPercent(sampleDuration time.Duration) float64 { - utils, _ := cpu.Percent(sampleDuration, false) - return utils[0] +func GetCpuUtilPercent(sampleDuration time.Duration) (used float64, err error) { + utils, err := cpu.Percent(sampleDuration, false) + if err != nil { + log.LogErrorf("[GetCpuUtilPercent] err: %v", err.Error()) + return + } + if utils == nil { + err = fmt.Errorf("got nil result") + log.LogErrorf("[GetCpuUtilPercent] err: %v", err.Error()) + return + } + if len(utils) == 0 { + err = fmt.Errorf("got result len is 0") + log.LogErrorf("[GetCpuUtilPercent] err: %v", err.Error()) + return + } + + used = utils[0] + return } diff --git a/util/loadutil/cpu_test.go b/util/loadutil/cpu_test.go index 1233e901e..da676f82b 100644 --- a/util/loadutil/cpu_test.go +++ b/util/loadutil/cpu_test.go @@ -22,6 +22,6 @@ import ( ) func TestCpuUtil(t *testing.T) { - used := loadutil.GetCpuUtilPercent(time.Second) + used, _ := loadutil.GetCpuUtilPercent(time.Second) t.Logf("CPU Util: %v\n", used) }