@@ -14,21 +14,24 @@ import (
14
14
type NTPSyncedClock struct {
15
15
offset int64
16
16
logger logging.Logger
17
+ cancel context.CancelFunc
17
18
}
18
19
19
20
// NewNTPSyncedClock creates a new NTP synchronized clock and starts background sync.
20
- func NewNTPSyncedClock (ctx context.Context , server string , syncInterval time.Duration , logger logging.Logger ) (* NTPSyncedClock , error ) {
21
+ func NewNTPSyncedClock (parentCtx context.Context , server string , syncInterval time.Duration , logger logging.Logger ) (* NTPSyncedClock , error ) {
21
22
if logger == nil {
22
23
return nil , fmt .Errorf ("logger must not be nil" )
23
24
}
25
+ ctx , cancel := context .WithCancel (parentCtx )
24
26
25
27
clock := & NTPSyncedClock {
26
28
logger : logger .With ("component" , "NTPSyncedClock" ),
29
+ cancel : cancel ,
27
30
}
28
31
29
- // Try to sync once, but don't fail if it doesn't work
30
32
if err := clock .syncOnce (server ); err != nil {
31
- clock .logger .Warn ("Initial NTP sync failed, will retry in background and use system clock until sync succeeds" , "err" , err )
33
+ cancel ()
34
+ return nil , fmt .Errorf ("initial NTP query failed: %w" , err )
32
35
}
33
36
34
37
go clock .runSyncLoop (ctx , server , syncInterval )
@@ -64,7 +67,6 @@ func (c *NTPSyncedClock) syncOnce(server string) error {
64
67
}
65
68
66
69
// Now returns the current time compensated by the latest NTP offset.
67
- // If the NTP sync has not yet succeeded, it returns the current system time.
68
70
func (c * NTPSyncedClock ) Now () time.Time {
69
71
offset := atomic .LoadInt64 (& c .offset )
70
72
return time .Now ().Add (time .Duration (offset ))
0 commit comments