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