check local clock is accurate
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone Build is passing

This commit is contained in:
2025-03-13 14:04:07 +11:00
parent d4f57986cb
commit 578a5de309
3 changed files with 59 additions and 1 deletions

47
main.go
View File

@@ -13,6 +13,7 @@ import (
"time"
_ "time/tzdata"
"github.com/beevik/ntp"
"github.com/vmware/govmomi"
"github.com/vmware/govmomi/find"
"github.com/vmware/govmomi/view"
@@ -39,6 +40,9 @@ var (
hostTimeErrors []HostTimeErrors
)
// maxAllowedDrift is the maximum allowed time difference (1 second).
const maxAllowedDrift = 2 * time.Second
/*
type dateInfo struct {
types.HostDateTimeInfo
@@ -47,6 +51,37 @@ type dateInfo struct {
}
*/
func checkClockDrift(ntpServers []string) bool {
localTime := time.Now()
inSync := false
for _, server := range ntpServers {
ntpTime, err := ntp.Time(server)
if err != nil {
log.Printf("Failed to get time from %s: %v\n", server, err)
continue
}
diff := localTime.Sub(ntpTime)
if diff < 0 {
diff = -diff
}
log.Printf("NTP Server: %s\n", server)
log.Printf("Local Time: %s\n", localTime)
log.Printf("NTP Time : %s\n", ntpTime)
log.Printf("Time Difference: %v\n", diff)
if diff <= maxAllowedDrift {
inSync = true
}
log.Println("----------")
}
return inSync
}
func prettyPrint(args ...interface{}) {
var caller string
@@ -82,6 +117,7 @@ func main() {
vTZ := flag.String("tz", "Australia/Sydney", "The timezone to use when converting vCenter UTC times")
vInsecure := flag.Bool("insecure", true, "Allow insecure connections to vCenter")
vAllowedDiff := flag.Int("diff", 300, "Permitted time difference in seconds")
vNtpServers := flag.String("ntp-servers", "pool.ntp.org", "A comma separated list of NTP sources to validate the local system clock")
flag.Parse()
@@ -99,7 +135,7 @@ func main() {
log.Printf("Setting timezone to '%s'\n", *vTZ)
location, err = time.LoadLocation(*vTZ)
if err != nil {
fmt.Fprintf(os.Stderr, "Error setting timezone to %s : %s\n", *vTZ, err)
log.Printf("Error setting timezone to %s : %s\n", *vTZ, err)
os.Exit(1)
}
@@ -114,6 +150,15 @@ func main() {
}
}
// Validate system clock
ntpList := strings.FieldsFunc(*vNtpServers, func(r rune) bool {
return r == ','
})
if !checkClockDrift(ntpList) {
log.Fatalf("Local system clock is not in sync, unable to proceed")
os.Exit(1)
}
log.Printf("Connecting to vCenter %s\n", u)
u.User = url.UserPassword(*vUser, *vPass)