Skip to content
Snippets Groups Projects
Unverified Commit df93b18a authored by Angelo Capossele's avatar Angelo Capossele Committed by GitHub
Browse files

:bug: Fix potential clock race condition (#814)

parent a443f2e0
Branches
No related tags found
No related merge requests found
...@@ -2,6 +2,7 @@ package clock ...@@ -2,6 +2,7 @@ package clock
import ( import (
"errors" "errors"
"sync"
"time" "time"
"github.com/beevik/ntp" "github.com/beevik/ntp"
...@@ -13,6 +14,7 @@ var ErrNTPQueryFailed = errors.New("NTP query failed") ...@@ -13,6 +14,7 @@ var ErrNTPQueryFailed = errors.New("NTP query failed")
// difference between network time and node's local time. // difference between network time and node's local time.
var offset time.Duration var offset time.Duration
var offsetMutex sync.RWMutex
// FetchTimeOffset establishes the difference in local vs network time. // FetchTimeOffset establishes the difference in local vs network time.
// This difference is stored in offset so that it can be used to adjust the local clock. // This difference is stored in offset so that it can be used to adjust the local clock.
...@@ -21,6 +23,8 @@ func FetchTimeOffset(host string) error { ...@@ -21,6 +23,8 @@ func FetchTimeOffset(host string) error {
if err != nil { if err != nil {
return xerrors.Errorf("NTP query error (%v): %w", err, ErrNTPQueryFailed) return xerrors.Errorf("NTP query error (%v): %w", err, ErrNTPQueryFailed)
} }
offsetMutex.Lock()
defer offsetMutex.Unlock()
offset = resp.ClockOffset offset = resp.ClockOffset
return nil return nil
...@@ -28,5 +32,7 @@ func FetchTimeOffset(host string) error { ...@@ -28,5 +32,7 @@ func FetchTimeOffset(host string) error {
// SyncedTime gets the synchronized time (according to the network) of a node. // SyncedTime gets the synchronized time (according to the network) of a node.
func SyncedTime() time.Time { func SyncedTime() time.Time {
offsetMutex.RLock()
defer offsetMutex.RUnlock()
return time.Now().Add(offset) return time.Now().Add(offset)
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment