fix(ntp): prevent panic on NTP query error and add IPv6 server in defaultNTPServers

This commit is contained in:
Qishuai Liu 2025-05-06 22:50:27 +09:00
parent d79f359c43
commit 77089ea497
No known key found for this signature in database
1 changed files with 21 additions and 20 deletions

View File

@ -13,7 +13,8 @@ var defaultNTPServers = []string{
"time.aws.com",
"time.windows.com",
"time.google.com",
"162.159.200.123", // time.cloudflare.com
"162.159.200.123", // time.cloudflare.com IPv4
"2606:4700:f1::123", // time.cloudflare.com IPv6
"0.pool.ntp.org",
"1.pool.ntp.org",
"2.pool.ntp.org",
@ -57,6 +58,12 @@ func (t *TimeSync) queryMultipleNTP(servers []string, timeout time.Duration) (no
// query the server
now, response, err := queryNtpServer(server, timeout)
if err != nil {
scopedLogger.Warn().
Str("error", err.Error()).
Msg("failed to query NTP server")
return
}
// set the last RTT
metricNtpServerLastRTT.WithLabelValues(
@ -76,26 +83,20 @@ func (t *TimeSync) queryMultipleNTP(servers []string, timeout time.Duration) (no
strconv.Itoa(int(response.Precision)),
).Set(1)
if err == nil {
// increase success count
metricNtpTotalSuccessCount.Inc()
metricNtpSuccessCount.WithLabelValues(server).Inc()
// increase success count
metricNtpTotalSuccessCount.Inc()
metricNtpSuccessCount.WithLabelValues(server).Inc()
scopedLogger.Info().
Str("time", now.Format(time.RFC3339)).
Str("reference", response.ReferenceString()).
Str("rtt", response.RTT.String()).
Str("clockOffset", response.ClockOffset.String()).
Uint8("stratum", response.Stratum).
Msg("NTP server returned time")
results <- &ntpResult{
now: now,
offset: &response.ClockOffset,
}
} else {
scopedLogger.Warn().
Str("error", err.Error()).
Msg("failed to query NTP server")
scopedLogger.Info().
Str("time", now.Format(time.RFC3339)).
Str("reference", response.ReferenceString()).
Str("rtt", response.RTT.String()).
Str("clockOffset", response.ClockOffset.String()).
Uint8("stratum", response.Stratum).
Msg("NTP server returned time")
results <- &ntpResult{
now: now,
offset: &response.ClockOffset,
}
}(server)
}