查看NTP时间同步情况
NTP:ntpq -pn / ntpstat
chronyd:chronyc sources [-v] / chronyc sourcestats [-v]
ntpstat
ntpstat 可以查看上一次校正了多少时间和多久校正一次时间。
# ntpstat
synchronised to NTP server (172.25.254.1) at stratum 4
time correct to within 63 ms # 时间校正到相差63ms之内
polling server every 512 s # 每512秒会向上级NTP轮询更新一次时间,该值是动态变化的,随意时间偏差自动调整。
ntpq
# ntpq -pn
remote refid st t when poll reach delay offset jitter
==============================================================================
*172.25.254.1 144.17.10.1 3 u 117 512 377 1.618 5.908 1.550
+172.25.254.2 144.17.10.1 3 u 366 512 377 1.930 6.170 2.064
remote: 本机所连接的远程NTP服务器列表,前面的符号含义:
\* 主 NTP Server,时间同步与它进行
+ 辅助 NTP Server
- 不合格的 NTP Server
x 远程 NTP 服务器不可用
refid: 远程NTP服务器的上一级NTP服务器
st: 远程NTP服务器的层级别(stratum)
t: 本机与远程NTP服务器的通信方式,u/单播,b/广播,l:本地
when: 上一次校正距离现在已经过去了多少秒,即多少秒前进行了时间校正
poll: 本机和远程NTP服务器多久进行一次同步(秒)可以看出,当 when 列的值达到 poll 列的值时,就会触发时间同步(实际上 when 列的值会比 poll 列的值多个几秒才进行时间同步)
reach: 衡量前8次查询是否成功,377表示都成功,0表示不成功
delay: 从本地机发送同步要求到服务器的RT(round trip time),即网络延时,单位微秒(1/1000000秒)
offset: 这是个最关键的值, 本机与远程NTP服务器的时间偏移,单位毫秒(1/1000秒)
jitter: 查询偏差的分布值,用于表示远程NTP服务器的网络延时是否稳定,单位微秒(1/1000000秒),越小越好
chronyc sources [-v]
# chronyc sources -v
210 Number of sources = 2
.-- Source mode '^' = server, '=' = peer, '#' = local clock.
/ .- Source state '*' = current synced, '+' = combined , '-' = not combined,
| / '?' = unreachable, 'x' = time may be in error, '~' = time too variable.
|| .- xxxx [ yyyy ] +/- zzzz
|| Reachability register (octal) -. | xxxx = adjusted offset,
|| Log2(Polling interval) --. | | yyyy = measured offset,
|| \ | | zzzz = estimated error.
|| | | \
MS Name/IP address Stratum Poll Reach LastRx Last sample
===============================================================================
^* 10.20.254.1 3 7 377 14 -5519ns[ -56us] +/- 12ms
^+ 10.20.254.2 3 6 377 29 -39us[ -89us] +/- 9489us
Poll:更新频率,4表示2的4次方,即16秒
LastRx: 上一次同步是多少秒之前
Last sample: 上一次同步时的偏差值
chronyc tracking
通过上面的 Last sample 看 offset 有一个弊端,就是单位不统一,不方便写脚本进行监控,也可以使用下面的命令来查看服务器与 NTP Server 的时间偏差。
# chronyc tracking
Reference ID : 0A14FE02 (10.20.254.2)
Stratum : 4
Ref time (UTC) : Wed Sep 09 01:29:01 2020
System time : 0.000094648 seconds fast of NTP time
Last offset : +0.000132643 seconds
RMS offset : 0.000182902 seconds
Frequency : 17.205 ppm slow
Residual freq : +0.011 ppm
Skew : 0.162 ppm
Root delay : 0.006164798 seconds
Root dispersion : 0.011124698 seconds
Update interval : 521.2 seconds
Leap status : Normal
ntpq 等查询返回慢的处理
使用 ntpq 命令时,要等一段时间才返回结果,通常只需要加上 -n 选项即可解决。
如果加上 -n 选项还是不能解决,可以在 ntpq 命令后面直接写上 NTP Server 的 IP 地址即可。
下面是一个案例:
SUSE 11 的主机,使用 ntpq -p -n 命令查看时间同步状态,要等一会儿才能返回,导致 zabbix 监控项超时。
使用 strace 命令进行跟踪,发现 ntpq 执行的过程中会去访问 DNS 服务器查找 localhost 的解析。
查看 /etc/hosts 文件,localhost 的解析记录是正常的。
查看 /etc/nsswitch.conf 文件,发现配置为: hosts: dns files
可见,该主机的名称解析策略是先访问 DNS,如果 DNS 没有,再去访问 hosts 文件。
至于 ntpq -p -n 为什么要去尝试去解析 localhost,这个可能与版本有关,也可能是个 bug。
从最小化影响角度考虑,我们最后没有修改 nsswitch.conf 文件的配置,而是在 zabbix 监控脚本中,直接在 nptq 命令后面跟上 NTP Server 的 IP 地址。