fix potential race (#86)

This commit is contained in:
UUBulb 2024-11-18 20:51:15 +08:00 committed by GitHub
parent af41e4d843
commit 32481e2b6f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 30 additions and 12 deletions

View File

@ -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")

View File

@ -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