-
Notifications
You must be signed in to change notification settings - Fork 2
/
ntp.go
47 lines (41 loc) · 1.26 KB
/
ntp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package ntp
import (
"time"
beevik_ntp "github.com/beevik/ntp"
"github.com/pkg/errors"
)
const (
// tolerance range of local clock with NTP time server
toleranceRangeWarning = time.Duration(10 * time.Second)
toleranceRangeError = time.Duration(30 * time.Second)
)
var (
errDriftTooMuch = errors.New("local time drift off ntp server more than 30 seconds")
errDriftInRange = errors.New("local time drift off ntp server more than 10 seconds")
)
// CheckLocalTimeAccurate returns whether the local clock accurate or not
func CheckLocalTimeAccurate(ntpServer string) (bool, error) {
options := beevik_ntp.QueryOptions{Timeout: 10 * time.Second}
response, err := beevik_ntp.QueryWithOptions(ntpServer, options)
// failed to query ntp time
if err != nil {
return false, err
}
// drift too much
if response.ClockOffset > toleranceRangeError {
return false, errDriftTooMuch
}
if response.ClockOffset > toleranceRangeWarning {
return true, errDriftInRange
}
return true, nil
}
// CurrentTime return the current time calibrated using ntp server
func CurrentTime(ntpServer string) time.Time {
options := beevik_ntp.QueryOptions{Timeout: 2 * time.Second}
t, err := beevik_ntp.QueryWithOptions(ntpServer, options)
if err == nil {
return t.Time
}
return time.Now()
}