diff --git a/cmd/agent/main.go b/cmd/agent/main.go index ef02247..f5396b5 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -16,6 +16,7 @@ import ( "path/filepath" "runtime" "strings" + "sync/atomic" "time" "github.com/blang/semver" @@ -66,6 +67,8 @@ var ( Timeout: time.Second * 30, Transport: &http3.RoundTripper{}, } + + hostStatus = new(atomic.Bool) ) const ( @@ -423,7 +426,7 @@ func doTask(task *pb.Task) { handleNATTask(task) return case model.TaskTypeReportHostInfo: - reportState(time.Time{}) + reportHost() return case model.TaskTypeFM: handleFMTask(task) @@ -459,22 +462,37 @@ func reportState(lastReportHostInfo time.Time) time.Time { printf("reportState error: %v", err) time.Sleep(delayWhenError) } + // 每10分钟重新获取一次硬件信息 if lastReportHostInfo.Before(time.Now().Add(-10*time.Minute)) || monitor.GeoQueryIPChanged { - monitor.GeoQueryIPChanged = false - lastReportHostInfo = time.Now() - client.ReportSystemInfo(context.Background(), monitor.GetHost().PB()) - if monitor.GeoQueryIP != "" { - geoip, err := client.LookupGeoIP(context.Background(), &pb.GeoIP{Ip: monitor.GeoQueryIP}) - if err == nil { - monitor.CachedCountryCode = geoip.GetCountryCode() - } + if reportHost() { + monitor.GeoQueryIPChanged = false + lastReportHostInfo = time.Now() } } } return lastReportHostInfo } +func reportHost() bool { + if !hostStatus.CompareAndSwap(false, true) { + return false + } + defer hostStatus.Store(false) + + if client != nil && initialized { + client.ReportSystemInfo(context.Background(), monitor.GetHost().PB()) + if monitor.GeoQueryIP != "" { + geoip, err := client.LookupGeoIP(context.Background(), &pb.GeoIP{Ip: monitor.GeoQueryIP}) + if err == nil { + monitor.CachedCountryCode = geoip.GetCountryCode() + } + } + } + + return true +} + // doSelfUpdate 执行更新检查 如果更新成功则会结束进程 func doSelfUpdate(useLocalVersion bool) { v := semver.MustParse("0.1.0") diff --git a/pkg/monitor/monitor.go b/pkg/monitor/monitor.go index 1790baf..7566b5f 100644 --- a/pkg/monitor/monitor.go +++ b/pkg/monitor/monitor.go @@ -57,7 +57,7 @@ var statDataFetchAttempts = map[uint8]uint8{ } var ( - updateTempStatus = new(atomic.Int32) + updateTempStatus = new(atomic.Bool) ) func InitConfig(cfg *model.AgentConfig) { @@ -236,10 +236,10 @@ func getConns() (tcpConnCount, udpConnCount uint64) { } func updateTemperatureStat() { - if !updateTempStatus.CompareAndSwap(0, 1) { + if !updateTempStatus.CompareAndSwap(false, true) { return } - defer updateTempStatus.Store(0) + defer updateTempStatus.Store(false) stat := tryStat(context.Background(), Temperatures, temperature.GetState) temperatureStat = stat