作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
一.时间服务概述
1>.为什么需要时间服务器
事实上,我们各种电子设备它们都是靠时钟驱动的,在分布式场景当中,更多主机的协作也是靠时钟驱动的。因此,多节点的主机时间必须要一致。
以Linux为例,Linux的时间是系统启动时,内核会从主板的硬件资源读取时间并设置为内核中的时钟。接下来系统时间和硬件的内核时间是各自分开独立运行的。
由于操作系统在运行过程中CPU繁忙等各种原因,久而久之很可能会导致系统时钟不精确的显现,这种不精确反应在同一个集群的多台主机上其实就是集群时间不一致。
我们大家都知道虚拟机并获得的CPU是虚拟机产品虚拟出来的CPU,并不是我们真正物理机上的CPU,因此出现时间误差的概率是相当的大,所以在我们普遍使用云计算的虚拟机上,必须要配置一个时间服务器,否则可能各个虚拟机的时间出现不一致的情况。
2>.ntpd时间服务
以RedHat的Linux发行版为例,早期用来解决时间服务器(CentOS 6.x版本之前)的程序包是ntpd,该程序包既可以用作服务端又可以用作客户端。ntpd是基于NTP(Network Time Protocal)实现时间同步的。
ntdp的实现同步时间的逻辑:
它的思想是把时间的周期缩短,举个例一个比较极限的例子,假设一台服务器两台服务器时间相差1小时,它的思想就是将自己现有的时间周期缩短,从而间接追上时间服务器的时间。比如时间服务器跑一分钟需要60秒,而ntpd的思想是跑一分钟使用30秒甚至1秒实现跑一分钟的的时间周期,这样随着时间的推移一定会追上服务器时间的。这种方式的确是可以追到服务器时间,但是为了追到服务器时间会付出一定时间的代价,这也是ntpd之所以被淘汰的根本原因。
生产环境中,你是否也发现了这样的现象呢?明明在部署集群时时间配置是正确的,可能过了2三个月后,你会发现集群中总有那么几台及其出现时间不同步的情况。这里的根本问题在于ntpd在和时间服务器进行时间同步的核心逻辑问题,因此CentOS7.x版本将CentOS6.x版本的ntpd替换为chronyd服务啦。
配置ntpd作为时间服务器案例(博主推荐使用使用chronyd作为服务端,尽管我之前也分效果使用ntpd作为服务端的比较):
https://www.cnblogs.com/yinzhengjie/p/9480665.html
3>.chrony时间服务
chrony是网络时间协议(NTP)的通用实现。它可以将系统时钟与NTP服务器、参考时钟(例如GPS接收器)和使用手表和键盘的手动输入同步。它还可以作为NTPv4(RFC 5905)服务器和对等服务器运行,为网络中的其他计算机提供时间服务。
它被设计成在各种条件下都能很好地运行,包括断续的网络连接、严重拥挤的网络、不断变化的温度(普通的计算机时钟对温度很敏感),以及不连续运行或在虚拟机上运行的系统。
chrony是ntpd的替代方案。在互联网上同步的两台机器之间的典型精度在几毫秒内;在局域网上,精度通常在几十微秒内。使用硬件时间戳或硬件参考时钟,可以达到亚微秒精度。
chrony中包含两个程序,chronyd是一个可以在启动时启动的守护程序,chronyc是一个命令行接口程序,可用于监视chronyd的性能,并在运行时更改各种操作参数。
如果非要把NTP和chrony做一个对比的话,我们就以手动调整手表时间为例,我们假设手表时间和实际服务器时间相差3小时:
ntpd的解决思路就是飞速的转动秒针,以最快的速度调准时间,可想而是,我们需要非常快的速度转动180圈秒针才能追上时间服务器的时间,真个转动过程是相当费时间的。
chrony的解决思路就是直接调整时针,可想而知,我们挑拨时针不到一圈就能把问题解决掉了,这就是为什么生产环境中大家使用的时间服务器基本上都是chrony啦。
和ntpd一样,chronyd程序包既可以做服务端也可以做客户端,实际上chrony服务本身是兼容ntpd服务的,我们直到123/UDP是传统的NTP服务所默认监听的端口,而323/UDP是chrony所默认监听的端口。因此我们使用chronyd做服务端后,我们既可以使用ntpd做客户端也可以使用chronyd做客户端。
chrony的官方网站:
https://chrony.tuxfamily.org/
4>.chrony的优势
chrony是网络时间协议(NTP)的另一种实现,与网络时间协议后台程序(ntpd)不同,它可以更快地且更准确地同步系统时钟,请注意,ntpd仍然包含其中以供需要运行NTP服务的客户使用。
chrony的优势包括以下几点:
(1)更快的同步只需要数分钟而非数小时时间,从而最大程度减少时间和频率误差,这对于并非全天24小时的运行的台式计算机或系统而言非常有用;
(2)能够更好地响应时钟频率的快速变化,这对于具备不稳定时钟的虚拟机或导致赛事中频率发生比变化的节能技术;
(3)在初始同步后,它不会停止时钟,以防对需要系统时间保持单调的应用程序造成影响;
(4)在应对临时非对称延迟时(例如大规模下载造成链接饱和等情况)提供了更好的稳定性;
(5)无需对时间服务器进行定期轮询,因此具备间歇性网络连接(如网络不稳定的场景)的系统仍然可以快速同步时钟。
二.安装并配置chrony服务
1>.安装chrony
[root@master200.yinzhengjie.org.cn ~]# yum -y install chrony
Loaded plugins: fastestmirror
Determining fastest mirrors
* base: mirror.bit.edu.cn
* extras: mirror.bit.edu.cn
* updates: mirrors.huaweicloud.com
ambari-repo | 2.9 kB 00:00:00
base | 3.6 kB 00:00:00
extras | 2.9 kB 00:00:00
mysql-connectors-community | 2.5 kB 00:00:00
mysql-tools-community | 2.5 kB 00:00:00
mysql80-community | 2.5 kB 00:00:00
updates | 2.9 kB 00:00:00
(1/2): extras/7/x86_64/primary_db | 159 kB 00:00:00
(2/2): updates/7/x86_64/primary_db | 5.9 MB 00:00:00
Resolving Dependencies
--> Running transaction check
---> Package chrony.x86_64 0:3.4-1.el7 will be installed
--> Processing Dependency: libseccomp.so.2()(64bit) for package: chrony-3.4-1.el7.x86_64
--> Running transaction check
---> Package libseccomp.x86_64 0:2.3.1-3.el7 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
==============================================================================================================================================================================================================================================================================
Package Arch Version Repository Size
==============================================================================================================================================================================================================================================================================
Installing:
chrony x86_64 3.4-1.el7 base 251 k
Installing for dependencies:
libseccomp x86_64 2.3.1-3.el7 base 56 k
Transaction Summary
==============================================================================================================================================================================================================================================================================
Install 1 Package (+1 Dependent package)
Total download size: 306 k
Installed size: 788 k
Downloading packages:
(1/2): libseccomp-2.3.1-3.el7.x86_64.rpm | 56 kB 00:00:00
(2/2): chrony-3.4-1.el7.x86_64.rpm | 251 kB 00:00:00
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total 957 kB/s | 306 kB 00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : libseccomp-2.3.1-3.el7.x86_64 1/2
Installing : chrony-3.4-1.el7.x86_64 2/2
Verifying : libseccomp-2.3.1-3.el7.x86_64 1/2
Verifying : chrony-3.4-1.el7.x86_64 2/2
Installed:
chrony.x86_64 0:3.4-1.el7
Dependency Installed:
libseccomp.x86_64 0:2.3.1-3.el7
Complete!
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# yum -y install chrony
2>.查看chrony是否已经安装
[root@master200.yinzhengjie.org.cn ~]# yum info chrony
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.aliyun.com
* extras: mirror.bit.edu.cn
* updates: mirror.bit.edu.cn
Installed Packages
Name : chrony
Arch : x86_64
Version : 3.4
Release : 1.el7
Size : 491 k
Repo : installed #很显然,这里已经提示咱们该程序包已经安装成功啦~
From repo : base
Summary : An NTP client/server
URL : https://chrony.tuxfamily.org
License : GPLv2
Description : A client/server for the Network Time Protocol, this program keeps your
: computer's clock accurate. It was specially designed to support
: systems with intermittent internet connections, but it also works well
: in permanently connected environments. It can use also hardware reference
: clocks, system real-time clock or manual input as time references.
[root@master200.yinzhengjie.org.cn ~]#
3>.查看chrony服务安装的文件
[root@master200.yinzhengjie.org.cn ~]# rpm -ql chrony
/etc/NetworkManager/dispatcher.d/20-chrony
/etc/chrony.conf #chrony的主配置文件
/etc/chrony.keys
/etc/dhcp/dhclient.d/chrony.sh
/etc/logrotate.d/chrony
/etc/sysconfig/chronyd
/usr/bin/chronyc #chronyc是一个命令行交互式接口程序,可用于监视chronyd的性能,并在运行时更改各种操作参数。
/usr/lib/systemd/ntp-units.d/50-chronyd.list
/usr/lib/systemd/system/chrony-dnssrv@.service
/usr/lib/systemd/system/chrony-dnssrv@.timer
/usr/lib/systemd/system/chrony-wait.service
/usr/lib/systemd/system/chronyd.service #CentOS 7.x版本对应的unit file
/usr/libexec/chrony-helper
/usr/sbin/chronyd #chronyd是一个可以在启动时启动的守护程序,它既可以充当服务端进程也可以充当服务端进程
/usr/share/doc/chrony-3.4
/usr/share/doc/chrony-3.4/COPYING
/usr/share/doc/chrony-3.4/FAQ
/usr/share/doc/chrony-3.4/NEWS
/usr/share/doc/chrony-3.4/README
/usr/share/man/man1/chronyc.1.gz
/usr/share/man/man5/chrony.conf.5.gz
/usr/share/man/man8/chronyd.8.gz
/var/lib/chrony
/var/lib/chrony/drift
/var/lib/chrony/rtc
/var/log/chrony
[root@master200.yinzhengjie.org.cn ~]#
4>.查看chrony的帮助手册
[root@master200.yinzhengjie.org.cn ~]# man chrony.conf #查看chrony的配置文件帮助信息
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# man chronyd #查看chrony的守护进程帮助信息
5>.服务端的配置文件(标记为粉红色字体需要注意,其它使用默认参数即可,对其它字段感兴趣的小伙伴可以参考上面的帮助信息哟)
[root@master200.yinzhengjie.org.cn ~]# cat /etc/chrony.conf
#指定当前节点为服务器时间,生产环境中建议大家指定多个事件服务器哟,起到对时间服务器备份的效果
server master200.yinzhengjie.org.cn iburst
# Record the rate at which the system clock gains/losses time.
driftfile /var/lib/chrony/drift
# Allow the system clock to be stepped in the first three updates
# if its offset is larger than 1 second.
makestep 1.0 3
# Enable kernel synchronization of the real-time clock (RTC).
rtcsync
# Enable hardware timestamping on all interfaces that support it.
#hwtimestamp *
# Increase the minimum number of selectable sources required to adjust
# the system clock.
#minsources 2
#指定允许的客户端网段来当前时间服务器节点同步时间,我们可以使用deny all拒绝所有客户端。
allow 172.200.0.0/21
#注意,如果主机位是0的话可以简写,比如下面的地址可以简写为"127/8",不过建议大家还是写完整,可读性更强。
allow 127.0.0.0/8
#如果上面使用server字段配置的时间服务器同步时间失败,默认情况下当前时间服务器是不会向客户端同步时间的,
#这是因为担心当前节点的时间不准确(因为当前节点没有和定义中的server时间服务器进行同步),如果我们想要在
#server指定的时间服务器同步失败的情况下依旧返回当前时间服务器的时间给客户端,需要开启该参数,这一项参
#数配置在生产环境中还是相当危险的,因此建议大家在server字段中指定互联网的网络时间,否则可能会出现整个
#集群时间都错的的一致!
local stratum 10
# Specify file containing keys for NTP authentication.
#keyfile /etc/chrony.keys
# Specify directory for log files.
logdir /var/log/chrony
# Select which information is logged.
#log measurements statistics tracking
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]#
6>.客户端配置(标记为粉红色字体需要注意,其它使用默认参数即可,对其它字段感兴趣的小伙伴可以参考上面的帮助信息哟)
[root@node201.yinzhengjie.org.cn ~]# egrep -v "^#|^$" /etc/chrony.conf
server master200.yinzhengjie.org.cn iburst
driftfile /var/lib/chrony/drift
makestep 1.0 3
rtcsync
logdir /var/log/chrony
[root@node201.yinzhengjie.org.cn ~]#
7>.将chrony服务设置为开启自启动
[root@master200.yinzhengjie.org.cn ~]# systemctl start chronyd
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# systemctl enable chronyd
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# systemctl list-unit-files | grep chronyd
chronyd.service enabled
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# systemctl status chronyd
● chronyd.service - NTP client/server
Loaded: loaded (/usr/lib/systemd/system/chronyd.service; enabled; vendor preset: enabled)
Active: active (running) since Sun 2020-02-09 23:42:18 CST; 15h ago
Docs: man:chronyd(8)
man:chrony.conf(5)
Main PID: 4678 (chronyd)
CGroup: /system.slice/chronyd.service
└─4678 /usr/sbin/chronyd
Feb 09 23:42:17 master200.yinzhengjie.org.cn systemd[1]: Starting NTP client/server...
Feb 09 23:42:18 master200.yinzhengjie.org.cn chronyd[4678]: chronyd version 3.4 starting (+CMDMON +NTP +REFCLOCK +RTC +PRIVDROP +SCFILTER +SIGND +ASYNCDNS +SECHASH +IPV6 +DEBUG)
Feb 09 23:42:18 master200.yinzhengjie.org.cn chronyd[4678]: Frequency 0.298 +/- 0.488 ppm read from /var/lib/chrony/drift
Feb 09 23:42:18 master200.yinzhengjie.org.cn systemd[1]: Started NTP client/server.
Feb 09 23:42:28 master200.yinzhengjie.org.cn chronyd[4678]: Selected source 172.200.1.200
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]#
8>.查看chrony服务的监听端口
[root@master200.yinzhengjie.org.cn ~]# ss -untlp
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port
udp UNCONN 0 0 *:123 *:*
users:(("chronyd",pid=4678,fd=7))udp UNCONN 0 0 *:8472 *:*
udp UNCONN 0 0 127.0.0.1:323 *:*
users:(("chronyd",pid=4678,fd=5))udp UNCONN 0 0 ::1:323 :::*
users:(("chronyd",pid=4678,fd=6))tcp LISTEN 0 20480 127.0.0.1:10248 *:*
users:(("kubelet",pid=4659,fd=28))tcp LISTEN 0 20480 127.0.0.1:10249 *:*
users:(("kube-proxy",pid=7373,fd=13))tcp LISTEN 0 20480 172.200.1.200:2379 *:*
users:(("etcd",pid=6708,fd=6))tcp LISTEN 0 20480 127.0.0.1:2379 *:*
users:(("etcd",pid=6708,fd=5))tcp LISTEN 0 20480 172.200.1.200:2380 *:*
users:(("etcd",pid=6708,fd=3))tcp LISTEN 0 20480 127.0.0.1:2381 *:*
users:(("etcd",pid=6708,fd=11))tcp LISTEN 0 20480 127.0.0.1:10257 *:*
users:(("kube-controller",pid=6593,fd=6))tcp LISTEN 0 20480 127.0.0.1:10259 *:*
users:(("kube-scheduler",pid=6659,fd=6))tcp LISTEN 0 128 *:22 *:*
users:(("sshd",pid=5129,fd=3))tcp LISTEN 0 20480 127.0.0.1:17369 *:*
users:(("kubelet",pid=4659,fd=9))tcp LISTEN 0 20480 :::10250 :::*
users:(("kubelet",pid=4659,fd=23))tcp LISTEN 0 20480 :::30443 :::*
users:(("kube-proxy",pid=7373,fd=10))tcp LISTEN 0 20480 :::10251 :::*
users:(("kube-scheduler",pid=6659,fd=5))tcp LISTEN 0 20480 :::6443 :::*
users:(("kube-apiserver",pid=6595,fd=5))tcp LISTEN 0 20480 :::10252 :::*
users:(("kube-controller",pid=6593,fd=5))tcp LISTEN 0 20480 :::10256 :::*
users:(("kube-proxy",pid=7373,fd=14))tcp LISTEN 0 128 :::22 :::*
users:(("sshd",pid=5129,fd=4))tcp LISTEN 0 20480 :::30080 :::*
users:(("kube-proxy",pid=7373,fd=8))[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# ss -untlp
三.查看服务端和客户端时间是否同步完成
1>.以交互式方式(支持命令补全)查看时间同步资源
[root@master200.yinzhengjie.org.cn ~]#
[root@master200.yinzhengjie.org.cn ~]# chronyc
chrony version 3.4
Copyright (C) 1997-2003, 2007, 2009-2018 Richard P. Curnow and others
chrony comes with ABSOLUTELY NO WARRANTY. This is free software, and
you are welcome to redistribute it under certain conditions. See the
GNU General Public License version 2 for details.
chronyc>
chronyc> sources
210 Number of sources = 1
MS Name/IP address Stratum Poll Reach LastRx Last sample
===============================================================================
^* master200.yinzhengjie.or> 10 10 377 15h -180ns[-2930ns] +/- 7588ns
chronyc>
chronyc>
chronyc> sources
2>.以交互式方式(支持命令补全)查看时间同步正常是否正常
[root@node201.yinzhengjie.org.cn ~]# chronyc
chrony version 3.4
Copyright (C) 1997-2003, 2007, 2009-2018 Richard P. Curnow and others
chrony comes with ABSOLUTELY NO WARRANTY. This is free software, and
you are welcome to redistribute it under certain conditions. See the
GNU General Public License version 2 for details.
chronyc>
chronyc> sourcestats
210 Number of sources = 1
Name/IP Address NP NR Span Frequency Freq Skew Offset Std Dev
==============================================================================
master200.yinzhengjie.or> 64 34 14h -0.000 0.001 -1ns 52us
chronyc>
chronyc>
[root@node201.yinzhengjie.org.cn ~]# chronyc
3>.以非交互式方式(注意,不支持命令补全哟)查看时间同步资源详细信息
[root@node201.yinzhengjie.org.cn ~]# chronyc sources -v
210 Number of sources = 1
.-- 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
===============================================================================
^* master200.yinzhengjie.or> 11 10 377 8 +383ns[ +554ns] +/- 117ms
[root@node201.yinzhengjie.org.cn ~]#
[root@node201.yinzhengjie.org.cn ~]# chronyc sources -v
4>.通过chronyc交互式接口配置chrony访问可参考帮助信息(不推荐使用,建议直接修改"/etc/chrony.conf"配置文件)
[root@master200.yinzhengjie.org.cn ~]# chronyc
chrony version 3.4
Copyright (C) 1997-2003, 2007, 2009-2018 Richard P. Curnow and others
chrony comes with ABSOLUTELY NO WARRANTY. This is free software, and
you are welcome to redistribute it under certain conditions. See the
GNU General Public License version 2 for details.
chronyc> help
System clock:
tracking Display system time information
makestep Correct clock by stepping immediately
makestep <threshold> <updates>
Configure automatic clock stepping
maxupdateskew <skew> Modify maximum valid skew to update frequency
waitsync [<max-tries> [<max-correction> [<max-skew> [<interval>]]]]
Wait until synchronised in specified limits
Time sources:
sources [-v] Display information about current sources
sourcestats [-v] Display statistics about collected measurements
reselect Force reselecting synchronisation source
reselectdist <dist> Modify reselection distance
NTP sources:
activity Check how many NTP sources are online/offline
ntpdata [<address>] Display information about last valid measurement
add server <address> [options]
Add new NTP server
add peer <address> [options]
Add new NTP peer
delete <address> Remove server or peer
burst <n-good>/<n-max> [<mask>/<address>]
Start rapid set of measurements
maxdelay <address> <delay> Modify maximum valid sample delay
maxdelayratio <address> <ratio>
Modify maximum valid delay/minimum ratio
maxdelaydevratio <address> <ratio>
Modify maximum valid delay/deviation ratio
minpoll <address> <poll> Modify minimum polling interval
maxpoll <address> <poll> Modify maximum polling interval
minstratum <address> <stratum>
Modify minimum stratum
offline [<mask>/<address>] Set sources in subnet to offline status
online [<mask>/<address>] Set sources in subnet to online status
onoffline Set all sources to online or offline status
according to network configuration
polltarget <address> <target>
Modify poll target
refresh Refresh IP addresses
Manual time input:
manual off|on|reset Disable/enable/reset settime command
manual list Show previous settime entries
manual delete <index> Delete previous settime entry
settime <time> Set daemon time
(e.g. Sep 25, 2015 16:30:05 or 16:30:05)
NTP access:
accheck <address> Check whether address is allowed
clients Report on clients that have accessed the server
serverstats Display statistics of the server
allow [<subnet>] Allow access to subnet as a default
allow all [<subnet>] Allow access to subnet and all children
deny [<subnet>] Deny access to subnet as a default
deny all [<subnet>] Deny access to subnet and all children
local [options] Serve time even when not synchronised
local off Don't serve time when not synchronised
smoothtime reset|activate Reset/activate time smoothing
smoothing Display current time smoothing state
Monitoring access:
cmdaccheck <address> Check whether address is allowed
cmdallow [<subnet>] Allow access to subnet as a default
cmdallow all [<subnet>] Allow access to subnet and all children
cmddeny [<subnet>] Deny access to subnet as a default
cmddeny all [<subnet>] Deny access to subnet and all children
Real-time clock:
rtcdata Print current RTC performance parameters
trimrtc Correct RTC relative to system clock
writertc Save RTC performance parameters to file
Other daemon commands:
cyclelogs Close and re-open log files
dump Dump all measurements to save files
rekey Re-read keys from key file
shutdown Stop daemon
Client commands:
dns -n|+n Disable/enable resolving IP addresses to hostnames
dns -4|-6|-46 Resolve hostnames only to IPv4/IPv6/both addresses
timeout <milliseconds> Set initial response timeout
retries <retries> Set maximum number of retries
keygen [<id> [<type> [<bits>]]]
Generate key for key file
exit|quit Leave the program
help Generate this help
chronyc>
chronyc> help