From a366e9a4b5397b7da7040b26dc15b3e0f4457600 Mon Sep 17 00:00:00 2001 From: wwqgtxx Date: Sat, 2 Sep 2023 12:37:43 +0800 Subject: [PATCH] fix: ntp service panic --- common/cmd/cmd_test.go | 2 +- ntp/service.go | 29 ++++++++++++++++++++--------- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/common/cmd/cmd_test.go b/common/cmd/cmd_test.go index 4bba6def..b124a22d 100644 --- a/common/cmd/cmd_test.go +++ b/common/cmd/cmd_test.go @@ -21,7 +21,7 @@ func TestSplitArgs(t *testing.T) { func TestExecCmd(t *testing.T) { if runtime.GOOS == "windows" { - _, err := ExecCmd("dir") + _, err := ExecCmd("cmd -c 'dir'") assert.Nil(t, err) return } diff --git a/ntp/service.go b/ntp/service.go index e8864eb6..af06a571 100644 --- a/ntp/service.go +++ b/ntp/service.go @@ -17,7 +17,7 @@ type Service struct { ticker *time.Ticker ctx context.Context cancel context.CancelFunc - mu *sync.Mutex + mu sync.Mutex running bool } @@ -26,7 +26,7 @@ func ReCreateNTPService(addr string, interval time.Duration) { service.Stop() } ctx, cancel := context.WithCancel(context.Background()) - service = &Service{addr: addr, interval: interval, ctx: ctx, cancel: cancel, mu: &sync.Mutex{}} + service = &Service{addr: addr, interval: interval, ctx: ctx, cancel: cancel} service.Start() } @@ -40,7 +40,7 @@ func (srv *Service) Start() { for { err := srv.updateTime(srv.addr) if err != nil { - log.Warnln("updateTime failed:", err) + log.Warnln("updateTime failed: %s", err) } select { case <-srv.ticker.C: @@ -54,9 +54,20 @@ func (srv *Service) Start() { func (srv *Service) Stop() { srv.mu.Lock() defer srv.mu.Unlock() - srv.ticker.Stop() - srv.cancel() - service.running = false + if service.running { + srv.ticker.Stop() + srv.cancel() + service.running = false + } +} + +func (srv *Service) Running() bool { + if srv == nil { + return false + } + srv.mu.Lock() + defer srv.mu.Unlock() + return srv.running } func (srv *Service) updateTime(addr string) error { @@ -68,16 +79,16 @@ func (srv *Service) updateTime(addr string) error { ntpTime := response.Time offset = localTime.Sub(ntpTime) if offset > time.Duration(0) { - log.Warnln("System clock is ahead of NTP time by", offset) + log.Warnln("System clock is ahead of NTP time by %s", offset) } else if offset < time.Duration(0) { - log.Warnln("System clock is behind NTP time by", -offset) + log.Warnln("System clock is behind NTP time by %s", -offset) } return nil } func Now() time.Time { now := time.Now() - if service.running && offset.Abs() > 0 { + if service.Running() && offset.Abs() > 0 { now = now.Add(offset) } return now