File: clock.go

package info (click to toggle)
gitlab-shell 14.35.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 23,652 kB
  • sloc: ruby: 1,129; makefile: 583; sql: 391; sh: 384
file content (31 lines) | stat: -rw-r--r-- 817 bytes parent folder | download | duplicates (5)
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
package helper

import (
	"fmt"
	"time"

	"github.com/beevik/ntp"
)

// CheckClockSync checks if machine clock has allowed drift threshold compare to NTP service.
// ntpHost is a URL of the NTP service to query, if not set the default pool.ntp.org is used.
// driftThreshold is a time duration that is considered acceptable time offset.
func CheckClockSync(ntpHost string, driftThreshold time.Duration) (bool, error) {
	if ntpHost == "" {
		ntpHost = "pool.ntp.org"
	}

	resp, err := ntp.Query(ntpHost)
	if err != nil {
		return false, fmt.Errorf("query ntp host %s: %w", ntpHost, err)
	}
	if err := resp.Validate(); err != nil {
		return false, fmt.Errorf("validate ntp response: %w", err)
	}

	if resp.ClockOffset > driftThreshold || resp.ClockOffset < -driftThreshold {
		return false, nil
	}

	return true, nil
}