Linux Time Synchronization: NTP, Chrony and systemd-timesyncd

Linux Time Synchronization: NTP, Chrony and systemd-timesyncd
Most people keep track of time. We get up on time to complete our morning rituals and go to work, take a lunch break, meet project deadlines, celebrate birthdays and holidays, board a plane, and so on.

Moreover: some of us are obsessed with time. My watch is powered by solar energy and gets accurate time from the National Institute of Standards and Technology (NIST) to Fort Collins, Colorado via longwave radio WWVB. The time signals are synchronized with the atomic clock, also located at Fort Collins. My Fitbit is syncing with my phone which is syncing with the server NTP, which eventually synchronizes with the atomic clock.

Devices keep track of time too

There are many reasons why our devices and computers need accurate time. For example, in banking, stock markets, and other financial businesses, transactions must be carried out in the proper order, and accurate time sequences are critical to this.

Our phones, tablets, cars, GPS systems and computers all require accurate time and date settings. I want the clock on my computer's desktop to show the correct time. I want reminders to appear on my local calendar at the right time. The correct time also ensures that the cron and systemd jobs run at the correct time.

Date and time are also important for logging, so it's a little easier to find certain logs based on date and time. For example, I once worked in DevOps (it was not called that at the time) and was setting up an email system in the state of North Carolina. We used to process over 20 million emails a day. Tracking e-mail through a series of servers, or determining the exact sequence of events using log files on geographically dispersed hosts, can be much easier if the respective computers are synchronized in time.

One time - many hours

Linux hosts must take into account that there is a system time and an RTC time. RTC (Real Time Clock) is a slightly strange and not very accurate name for a hardware clock.

The hardware clock runs continuously even when the computer is turned off, using the battery on the system motherboard. The main function of the RTC is to store time when a connection to a time server is not available. In the days when it was impossible to connect to a time server over the Internet, every computer had to have an accurate internal clock. Operating systems had to access the RTC at boot time and the user had to manually set the system time using the BIOS hardware configuration interface to make sure it was correct.

Hardware clocks don't understand the concept of time zones; RTC only stores the time, not the time zone or offset from UTC (Coordinated Universal Time, also known as GMT or Greenwich Mean Time). You can install RTC using a tool that I will cover later in this article.

The system time is the time that the OS displays on the GUI clock on your desktop, in the output of the date command, in the timestamps of the logs. This also applies to when files are created, modified, and opened.

On page man for rtc there is a full description of the RTC and the system clock.

What's with NTP?

Computers all over the world use NTP (Network Time Protocol) to synchronize their time with standard reference clocks over the Internet using a hierarchy of NTP servers. The main time servers are at layer 1 and they are directly connected to various national time services at layer 0 via satellite, radio or even modems over telephone lines. Layer 0 time services can be an atomic clock, a radio receiver that is tuned to signals transmitted by atomic clocks, or a GPS receiver that uses highly accurate clock signals transmitted by GPS satellites.

The vast majority of the reference servers have several thousand public NTP stratum 2 servers open to the public. Many organizations and users (myself included) with a lot of hosts who need an NTP server choose to set up their own time servers so only one local host accesses stratum 2 or 3. They then configure the remaining nodes on the network to use the local time server . In the case of my home network, this is a layer 3 server.

Various implementations of NTP

The original implementation of NTP is ntpd. It was then joined by two newer ones, chronyd and systemd-timesyncd. All three synchronize the local host time with an NTP time server. The systemd-timesyncd service is not as reliable as chronyd, but it's good enough for most purposes. If the RTC is out of sync, it can gradually adjust the system time to synchronize with the NTP server when the local system time drifts slightly. The systemd-timesync service cannot be used as a time server.

Chrony is an implementation of NTP that contains two programs: the chronyd daemon and a command-line interface called chronyc. Chrony has some features that are indispensable in many cases:

  • Chrony can synchronize with a time server much faster than the old ntpd service. This is good for laptops or desktops that don't work all the time.
  • It can compensate for clock fluctuations, such as when the host goes to sleep or enters sleep mode, or when the clock changes due to frequency hopping, which slows down clocks at low loads.
  • It solves time problems related to unstable network connection or network congestion.
  • It regulates network delays.
  • After the initial time sync, Chrony never stops the clock. This provides stable and consistent timeslots for many system services and applications.
  • Chrony can work even without a network connection. In this case, the local host or server can be updated manually.
  • Chrony can act as an NTP server.

Once again, NTP is a protocol that can be implemented on a Linux host using Chrony or systemd-timesyncd.

The NTP, Chrony, and systemd-timesyncd RPMs are available in the standard Fedora repositories. The systemd-udev RPM is a kernel event manager that is installed by default on Fedora, but is optional.

You can install all three and switch between them, but this will create an extra headache. So it's better not to. Modern releases of Fedora, CentOS, and RHEL have moved to Chrony as the default implementation, and they also have systemd-timesyncd. I find Chrony to work well, provide a better interface than the NTP service, provide much more information and control, which system administrators will certainly enjoy.

Disabling NTP Services

The NTP service may already be running on your host. If so, you need to disable it before switching to something else. I had chronyd running so I used the following commands to stop and disable it. Run the appropriate commands for any NTP daemon you are running on your host:

[root@testvm1 ~]# systemctl disable chronyd ; systemctl stop chronyd
Removed /etc/systemd/system/multi-user.target.wants/chronyd.service.
[root@testvm1 ~]#

Check that the service is stopped and disabled:

[root@testvm1 ~]# systemctl status chronyd
● chronyd.service - NTP client/server
     Loaded: loaded (/usr/lib/systemd/system/chronyd.service; disabled; vendor preset: enabled)
     Active: inactive (dead)
       Docs: man:chronyd(8)
             man:chrony.conf(5)
[root@testvm1 ~]#

Status check before launch

The system clock synchronization status allows you to determine if the NTP service is running. Since you haven't started NTP yet, the timesync-status command will hint at this:

[root@testvm1 ~]# timedatectl timesync-status
Failed to query server: Could not activate remote peer.

A direct status request provides important information. For example, the timedatectl command with no argument or options executes the status subcommand by default:

[root@testvm1 ~]# timedatectl status
           Local time: Fri 2020-05-15 08:43:10 EDT  
           Universal time: Fri 2020-05-15 12:43:10 UTC  
                 RTC time: Fri 2020-05-15 08:43:08      
                Time zone: America/New_York (EDT, -0400)
System clock synchronized: no                          
              NTP service: inactive                    
          RTC in local TZ: yes                    

Warning: The system is configured to read the RTC time in the local time zone.
         This mode cannot be fully supported. It will create various problems
         with time zone changes and daylight saving time adjustments. The RTC
         time is never updated, it relies on external facilities to maintain it.
         If at all possible, use RTC in UTC by calling
         'timedatectl set-local-rtc 0'.
[root@testvm1 ~]#

This will give you the local time for your host, UTC time, and RTC time. In this case, the system time is set to the America / New_York (TZ) time zone, the RTC is set to the time in the local time zone, and the NTP service is not active. The RTC time has started to deviate slightly from the system time. This is normal for systems whose clocks have not been synchronized. The amount of offset on the host depends on the time that has passed since the system was last synchronized.

We also received a warning about using local time for RTC - this applies to time zone changes and DST settings. If the computer is turned off when changes need to be made, the RTC will not change. But for servers or other hosts that run around the clock, this is not a problem at all. In addition, any service that provides NTP time synchronization will adjust the host's time during the initial startup phase, so the time will be correct again after startup is complete.

Setting the time zone

Usually, you specify the time zone during the installation procedure and you do not have the task of changing it later. However, there are times when you need to change the time zone. There are several tools that can help. Linux uses timezone files to determine the local timezone of a host. These files are in the directory /usr/share/zoneinfo. By default, for my time zone, the system prescribes this: /etc/localtime -> ../usr/share/zoneinfo/America/New_York. But you don't need to know such subtleties to change the time zone.

The main thing is to know the official time zone name for your location and the corresponding command. Let's say you want to change the time zone to Los Angeles:


[root@testvm2 ~]# timedatectl list-timezones | column
<SNIP>
America/La_Paz                  Europe/Budapest
America/Lima                    Europe/Chisinau
America/Los_Angeles             Europe/Copenhagen
America/Maceio                  Europe/Dublin
America/Managua                 Europe/Gibraltar
America/Manaus                  Europe/Helsinki
<SNIP>

Now you can set the timezone. I used the date command to check for changes, but you can also use timedatectl:

[root@testvm2 ~]# date
Tue 19 May 2020 04:47:49 PM EDT
[root@testvm2 ~]# timedatectl set-timezone America/Los_Angeles
[root@testvm2 ~]# date
Tue 19 May 2020 01:48:23 PM PDT
[root@testvm2 ~]#

Now you can change your host's time zone back to local time.

systemd-timesyncd

The systemd timesync daemon provides an NTP implementation that is easy to manage in the systemd context. It is installed by default on Fedora and Ubuntu. However, it only starts by default on Ubuntu. I'm not sure about other distributions. You can check for yourself:

[root@testvm1 ~]# systemctl status systemd-timesyncd

Configuring systemd-timesyncd

The configuration file for systemd-timesyncd is /etc/systemd/timesyncd.conf. This is a simple file with fewer options enabled than the old NTP and chronyd services. Here is the contents of this file (without further modifications) on my Fedora VM:

#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.
#
# Entries in this file show the compile time defaults.
# You can change settings by editing this file.
# Defaults can be restored by simply deleting this file.
#
# See timesyncd.conf(5) for details.

[Time]
#NTP=
#FallbackNTP=0.fedora.pool.ntp.org 1.fedora.pool.ntp.org 2.fedora.pool.ntp.org 3.fedora.pool.ntp.org
#RootDistanceMaxSec=5
#PollIntervalMinSec=32
#PollIntervalMaxSec=2048

The only section it contains, besides comments, is [Time]. All other lines are commented out. These are the default values ​​and should not be changed (unless you have a reason to). If you do not have an NTP time server defined in the NTP= line, Fedora defaults to a fallback Fedora time server. I usually add my time server:

NTP=myntpserver

Running timesync

You can start and make systemd-timesyncd active like this:

[root@testvm2 ~]# systemctl enable systemd-timesyncd.service
Created symlink /etc/systemd/system/dbus-org.freedesktop.timesync1.service β†’ /usr/lib/systemd/system/systemd-timesyncd.service.
Created symlink /etc/systemd/system/sysinit.target.wants/systemd-timesyncd.service β†’ /usr/lib/systemd/system/systemd-timesyncd.service.
[root@testvm2 ~]# systemctl start systemd-timesyncd.service
[root@testvm2 ~]#

Setting the hardware clock

Here is what the situation looks like after running timesyncd:

[root@testvm2 systemd]# timedatectl
               Local time: Sat 2020-05-16 14:34:54 EDT  
           Universal time: Sat 2020-05-16 18:34:54 UTC  
                 RTC time: Sat 2020-05-16 14:34:53      
                Time zone: America/New_York (EDT, -0400)
System clock synchronized: yes                          
              NTP service: active                      
          RTC in local TZ: no    

Initially, the difference between RTC and local time (EDT) is less than a second, and the discrepancy increases by another couple of seconds over the next few days. Since there is no concept of time zones in RTC, the timedatectl command must perform a comparison to determine the correct time zone. If the RTC time does not exactly match the local time, then it does not match the local time zone either.

Looking for more information, I checked the status of systemd-timesync and found this:

[root@testvm2 systemd]# systemctl status systemd-timesyncd.service
● systemd-timesyncd.service - Network Time Synchronization
     Loaded: loaded (/usr/lib/systemd/system/systemd-timesyncd.service; enabled; vendor preset: disabled)
     Active: active (running) since Sat 2020-05-16 13:56:53 EDT; 18h ago
       Docs: man:systemd-timesyncd.service(8)
   Main PID: 822 (systemd-timesyn)
     Status: "Initial synchronization to time server 163.237.218.19:123 (2.fedora.pool.ntp.org)."
      Tasks: 2 (limit: 10365)
     Memory: 2.8M
        CPU: 476ms
     CGroup: /system.slice/systemd-timesyncd.service
             └─822 /usr/lib/systemd/systemd-timesyncd

May 16 09:57:24 testvm2.both.org systemd[1]: Starting Network Time Synchronization...
May 16 09:57:24 testvm2.both.org systemd-timesyncd[822]: System clock time unset or jumped backwards, restoring from recorded timestamp: Sat 2020-05-16 13:56:53 EDT
May 16 13:56:53 testvm2.both.org systemd[1]: Started Network Time Synchronization.
May 16 13:57:56 testvm2.both.org systemd-timesyncd[822]: Initial synchronization to time server 163.237.218.19:123 (2.fedora.pool.ntp.org).
[root@testvm2 systemd]#

Notice the log message that says the system time has not been set or has been reset. The Timesync service sets the system time based on the timestamp. Timestamps are maintained by the timesync daemon and are created on every successful sync.

The timedatectl command has no way to take the value of the hardware clock from the system clock. It can only set the time and date from the value entered on the command line. You can set the RTC to the same value as the system time using the hwclock command:

[root@testvm2 ~]# /sbin/hwclock --systohc --localtime
[root@testvm2 ~]# timedatectl
               Local time: Mon 2020-05-18 13:56:46 EDT  
           Universal time: Mon 2020-05-18 17:56:46 UTC  
                 RTC time: Mon 2020-05-18 13:56:46      
                Time zone: America/New_York (EDT, -0400)
System clock synchronized: yes                          
              NTP service: active                      
          RTC in local TZ: yes

The --localtime option tells the hardware clock to show local time, not UTC.

Why do you need RTC at all?

Any implementation of NTP will set the system clock at startup time. And why then RTC? This is not entirely true: this will only happen if you have a network connection to the time server. However, many systems don't always have access to a network connection, so a hardware clock is useful for Linux to use to set the system time. This is better than manually setting the time, even though it may deviate from real time.

Conclusion

This article has reviewed some tools for manipulating date, time, and time zones. The systemd-timesyncd tool provides an NTP client that can synchronize the time on the local host with an NTP server. However, systemd-timesyncd does not provide a server service, so if you need an NTP server on your network, you must use something else, such as Chrony, to act as a server.

I prefer to have a single implementation for any service on my network, so I use Chrony. If you don't need a local NTP server, or if you don't mind using Chrony as the server and systemd-timesyncd as the SNTP client. After all, there is no need to use the additional features of Chrony as a client if you are satisfied with the functionality of systemd-timesyncd.

Another note: you are not required to use the systemd tools to implement NTP. You can use an older version of ntpd, Chrony, or another NTP implementation. After all, systemd consists of a large number of services; many of them are optional, so you can turn them off and use something else instead. This is not a huge monolithic monster. You may not like systemd or parts of it, but you should make an informed decision.

I like systemd's implementation of NTP, but I prefer Chrony because it suits my needs better. It's Linux, baby -)

As advertising

VDSina offers servers for any task, a huge selection of operating systems for automatic installation, it is possible to install any OS from your own ISO, comfortable Control Panel own development and daily payment. Recall that we have eternal servers that are definitely timeless πŸ˜‰

Linux Time Synchronization: NTP, Chrony and systemd-timesyncd

Source: habr.com

Add a comment