- Network Time Protocol daemon (Русский)
- Contents
- Установка
- Настройка
- Запуск демона
- Запуск ntpd
- NetworkManager
- Использование не root-пользователем
- Синхронизация часов без запуска демона
- Альтернативы
- Network Time Protocol daemon
- Contents
- Installation
- Configuration
- Connection to NTP servers
- NTP server mode
- Usage
- Start ntpd at boot
- Synchronize time once per boot
- Tips and tricks
- Start ntpd on network connection
- Using ntpd with GPS
- Running in a chroot
- Restrict listening sockets
- System time
- Contents
- Hardware clock
- Read hardware clock
- Set hardware clock from system clock
- System clock
- Read clock
- Set system clock
- Time standard
- UTC in Microsoft Windows
- Historical notes
- UTC in Ubuntu
- Time zone
- Setting based on geolocation
- Update timezone every time NetworkManager connects to a network
- Time skew
- Time synchronization
- Per-user/session or temporary settings
- Troubleshooting
- Clock shows a value that is neither UTC nor local time
- Tips and tricks
- fake-hwclock
Network Time Protocol daemon (Русский)
Перевод этой статьи или раздела не отражает оригинальное содержание.
Эта статья описывает, как установить и настроить NTPd (Network Time Protocol daemon), наиболее распространенный способ синхронизации часов в системе GNU/Linux с серверами в сети Интернет при помощи NTP. Если все настроено правильно, Ваш компьютер тоже может выступать в роли сервера синхронизации времени.
Contents
Установка
Пакет ntp доступен в репозитории [extra]:
Настройка
Самая первая строка в вашем файле /etc/ntp.conf определяет серверы, с которыми планируется синхронизироваться. NTP использует иерархическую систему «часовых уровней». Уровень 1 синхронизован с высокоточными часами, например, с системой GPS, ГЛОНАСС (Единая Государственная шкала времени РФ) или атомным эталоном времени. Уровень 2 синхронизируется с одной из машин уровня 1, и так далее.
Однако следует учитывать, что уровни не всегда являются показателями точности. Обычно для синхронизации пользовательских машин используются серверы третьего уровня. Если Вы не знаете серверов NTP в Вашем регионе, используйте pool.ntp.org и выберите сервер в Вашем регионе. Например,
Опция ‘iburst’ рекомендуется, с ее помощью посылается шквал пакетов, если не удается установить соединение с сервером с первого раза. Напротив, опцию ‘burst’ не используйте никогда без особого разрешения, так как Вы можете попасть в «черный список».
При настройке своего NTP сервера, нужно добавить localhost в список серверов, так как в случае потери соединения с сетью Интернет, сервер продолжит синхрозировать время в сети. Для этого добавьте localhost как сервер десятого уровня при помощи команды fudge , чтобы синхронизация не происходила, пока соединение с Интернет доступно:
Затем, определите правила, по которым к Вашему серверу смогут подключаться клиенты (localhost — это тоже клиент) при помощи команды restrict. Также добавьте в файл конфигурации:
Эти настройки не позволят пользователям изменять что-либо. Можете также добавить следующие опции:
Теперь нужно указать ntpd, какие подключения к Вашему серверу разрешены; если Вы не конфигурируете сервер NTP, следующей строки будет достаточно:
В противном случае, можно добавить больше клиентов:
Эти строки укажут ntpd, что адресам 1.2.3.4, а также всем адресам подсети 192.168.0.0/24 позволено синхронизировать время с Вашим сервером, но не позволено ничего изменять.
Если Вы желаете принудительно определить адреса по протоколу IPv6, напишите -6 перед IP-адресом или именем хоста (-4 принудительно устанавливает протокол IPv4), например:
Наконец, установите файл-буфер (в котором будет находиться погрешность часов системы) и журнал (лог):
Примерная конфигурация выглядит так:
Вообще, журнал (лог) устанавливать необязательно, но рекомендуется для того, чтобы знать, какие изменения проводит ntpd.
В заключении, никогда не забывайте читать man: ntp.conf(5) . Это ответит на многие Ваши вопросы. Также можно посмотреть man
Запуск демона
Запуск ntpd
Если Вы используете sysvinit:
Поместите ntpd в массив DAEMONS в файле /etc/rc.conf , чтобы он загружался при старте системы:
Если Вы используете systemd:
systemctl start ntpd
Для загрузки при старте системы
systemctl enable ntpd
NetworkManager
ntpd можно включать/выключать вместе со стартом сетевого соединения с помощью networkmanager-dispatcher-ntpd:
Использование не root-пользователем
Если программа скомпилирована с флагом —enable-linux-caps, ntpd может запустить не root-пользователь (стандартный пакет в Arch Linux имеет эту опцию).
Создайте группу ntp и пользователя ntp:
Смените владельца директории ntp на пользователя ntp:
Отредактируйте /etc/conf.d/ntp-client.conf и измените
Наконец, перезапустите демона:
Синхронизация часов без запуска демона
Если Вы просто хотите синхронизировать часы без запуска демона ntpd, добавьте в файл /etc/rc.local следующее:
Альтернативы
Доступная альтернатива ntpd — это OpenNTPD, часть проекта OpenBSD (не поддерживается сообществом Linux).
Источник
Network Time Protocol daemon
Network Time Protocol is the most common method to synchronize the software clock of a GNU/Linux system with internet time servers. It is designed to mitigate the effects of variable network latency and can usually maintain time to within tens of milliseconds over the public Internet. The accuracy on local area networks is even better, up to one millisecond.
The NTP Project provides a reference implementation of the protocol called simply NTP. This article further describes how to set up and run the NTP daemon, both as a client and as a server.
See System time#Time synchronization for other NTP implementations.
Contents
Installation
Install the ntp package. By default, ntpd works in client mode without further configuration. You can skip to #Usage, if you want to use the Arch Linux default configuration file for it. For server configuration, see #NTP server mode.
Configuration
The main daemon is ntpd, which is configured in /etc/ntp.conf . Refer to ntp.conf(5) for detail.
Connection to NTP servers
NTP servers are classified in a hierarchical system with many levels called strata: the devices which are considered independent time sources are classified as stratum 0 sources; the servers directly connected to stratum 0 devices are classified as stratum 1 sources; servers connected to stratum 1 sources are then classified as stratum 2 sources and so on.
It has to be understood that a server’s stratum cannot be taken as an indication of its accuracy or reliability. Typically, stratum 2 servers are used for general synchronization purposes: if you do not already know the servers you are going to connect to, you should choose a server pool close to your location from the pool.ntp.org servers (alternative link).
Since ntp version 4.2.7.p465-2, Arch Linux uses its own default vendor pool of NTP servers provided by the NTP Pool Project (see FS#41700). Modify those to suit your needs, e.g. if you want to use your country’s servers with an option:
The iburst option is recommended, and sends a burst of packets only if it cannot obtain a connection with the first attempt. The burst option always does this, even on the first attempt, and should never be used without explicit permission and may result in blacklisting.
NTP server mode
If setting up an NTP server, check that you have orphan mode enabled, so that, in case it loses internet access, it will continue serving time to the network; enable orphan mode using the tos configuration parameter (you can set up to stratum 15) so that it will never be used unless internet access is lost:
Next, define the rules that will allow clients to connect to your service (localhost is considered a client too) using the restrict command; you should already have a line like this in your file:
This restricts everyone from modifying anything and prevents everyone from querying the status of your time server: nomodify prevents reconfiguring ntpd (with ntpq or ntpdc), and noquery is important to prevent dumping status data from ntpd (also with ntpq or ntpdc).
You can also add other options:
If you want to change any of these, see the full docs for the «restrict» option in ntp.conf(5) , the detailed ntp instructions [dead link 2021-05-17 ⓘ] and #Usage.
Following this line, you need to tell ntpd what to allow through into your server; the following line is enough if you are not configuring an NTP server:
If you want to force DNS resolution to the IPv6 namespace, write -6 before the IP address or host name ( -4 forces IPv4 instead), for example:
Lastly, specify the drift file (which keeps track of your clock’s time deviation) and optionally the log file location:
A very basic configuration file will look like this:
Usage
The package has a default client-mode configuration and its own user and group to drop root privileges after starting. If you start it from the console, you should always do so with the -u option:
The -u option is employed by the two included systemd services. These services also use the -g option, which disables a threshold (so-called panic-gate). Hence, they will synchonize time even in case the ntp-server’s time exceeds the threshold deviation from the system clock.
Both services are tied to the system’s resolver, and will start synchronizing when an active network connection is detected.
Start ntpd at boot
Enable the daemon with ntpd.service . See also #Running in a chroot.
Use ntpq to see the list of configured peers and status of synchronization:
The delay, offset and jitter columns should be non-zero. The servers ntpd is synchronizing with are prefixed by an asterisk. It can take several minutes before ntpd selects a server to synchronize with; try checking after 17 minutes (1024 seconds).
Synchronize time once per boot
Alternatively, enable ntpdate.service to synchronize time once (option -q ) and non-forking (option -n ) per boot, instead of running the daemon in the background. This method is discouraged on servers, and in general on machines that run without rebooting for more than a few days.
If the synchronized time should be written to the hardware clock as well, configure the provided unit as described in systemd#Editing provided units before starting it:
Tips and tricks
Start ntpd on network connection
ntpd can be started by your network manager, so that the daemon only runs when the computer is online.
This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.
Append the following lines to your netctl profile:
The ntpd daemon can be brought up/down along with a network connection through the use of NetworkManager’s dispatcher scripts. The networkmanager-dispatcher-ntpd AUR package installs one, pre-configured to start and stop the ntpd service with a connection.
For Wicd, create a start script in the postconnect directory and a stop script in the predisconnect directory. Remember to make them executable:
KDE can use NTP (ntp must be installed) by right clicking the clock and selecting Adjust date/time. However, this requires the ntp daemon to be disabled before configuring KDE to use NTP. [2]
Using ntpd with GPS
Most of the articles online about configuring ntpd to receive time from a GPS suggest to use the SHM (shared memory) method. However, at least since ntpd version 4.2.8 a much better method is available. It connects directly to gpsd, so gpsd needs to be installed.
Add these lines to your /etc/ntp.conf :
This will work as long as you have gpsd working. It connects to gpsd via the local socket and queries the «gpsd_json» object that is returned.
To test the setup, first ensure that gpsd is working by running:
Then wait a few minutes and run ntpq -p . This will show if ntpd is talking to gpsd:
Running in a chroot
Create a new directory /etc/systemd/system/ntpd.service.d/ if it does not exist and a file named customexec.conf inside with the following content:
Then, edit /etc/ntp.conf to change the driftfile path such that it is relative to the chroot directory, rather than to the real system root. Change:
Create a suitable chroot environment so that getaddrinfo() will work by creating pertinent directories and files (as root):
and by bind-mounting the aformentioned files:
Finally, restart ntpd daemon again. Once it restarted you can verify that the daemon process is chrooted by checking where /proc/
should now link to /var/lib/ntp instead of / .
It is relatively difficult to be sure that your driftfile configuration is actually working without waiting a while, as ntpd does not read or write it very often. If you get it wrong, it will log an error; if you get it right, it will update the timestamp. If you do not see any errors about it after a full day of running, and the timestamp is updated, you should be confident of success.
Restrict listening sockets
You can limit sockets ntpd is listening to using the interface option:
Источник
System time
This article or section needs expansion.
In an operating system, the time (clock) is determined by three parts: time value, whether it is local time or UTC or something else, time zone, and Daylight Saving Time (DST) if applicable. This article explains what they are and how to read/set them. Two clocks are present on systems: a hardware clock and a system clock which are also detailed in this article.
Standard behavior of most operating systems is:
- Set the system clock from the hardware clock on boot.
- Keep accurate time of the system clock, see #Time synchronization.
- Set the hardware clock from the system clock on shutdown.
Contents
Hardware clock
The hardware clock (a.k.a. the Real Time Clock (RTC) or CMOS clock) stores the values of: Year, Month, Day, Hour, Minute, and Seconds. Only 2016, or later, UEFI firmware has the ability to store the timezone, and whether DST is used.
Read hardware clock
Set hardware clock from system clock
The following sets the hardware clock from the system clock. Additionally it updates /etc/adjtime or creates it if not present. See hwclock(8) section «The Adjtime File» for more information on this file as well as the #Time skew section.
System clock
The system clock (a.k.a. the software clock) keeps track of: time, time zone, and DST if applicable. It is calculated by the Linux kernel as the number of seconds since midnight January 1st 1970, UTC. The initial value of the system clock is calculated from the hardware clock, dependent on the contents of /etc/adjtime . After boot-up has completed, the system clock runs independently of the hardware clock. The Linux kernel keeps track of the system clock by counting timer interrupts.
Read clock
To check the current system clock time (presented both in local time and UTC) as well as the RTC (hardware clock):
Set system clock
To set the local time of the system clock directly:
sets the time to May 26th, year 2014, 11:13 and 54 seconds.
Time standard
There are two time standards: localtime and Coordinated Universal Time (UTC). The localtime standard is dependent on the current time zone, while UTC is the global time standard and is independent of time zone values. Though conceptually different, UTC is also known as GMT (Greenwich Mean Time).
The standard used by the hardware clock (CMOS clock, the BIOS time) is set by the operating system. By default, Windows uses localtime, macOS uses UTC, other UNIX and UNIX-like systems vary. An OS that uses the UTC standard will generally consider the hardware clock as UTC and make an adjustment to it to set the OS time at boot according to the time zone.
If multiple operating systems are installed on a machine, they will all derive the current time from the same hardware clock: it is recommended to adopt a unique standard for the hardware clock to avoid conflicts across systems and set it to UTC. Otherwise, if the hardware clock is set to localtime, more than one operating system may adjust it after a DST change for example, thus resulting in an over-correction; problems may also arise when traveling between different time zones and using one of the operating systems to reset the system/hardware clock.
The hardware clock can be queried and set with the timedatectl command. You can see the current hardware clock time standard of the Arch system using:
To change the hardware clock time standard to localtime, use:
To revert to the hardware clock being in UTC, type:
These generate /etc/adjtime automatically and update the RTC accordingly; no further configuration is required.
During kernel startup, at the point when the RTC driver is loaded, the system clock may be set from the hardware clock. Whether this occurs depends on the hardware platform, the version of the kernel and kernel build options. If this does occur, at this point in the boot sequence, the hardware clock time is assumed to be UTC and the value of /sys/class/rtc/rtcN/hctosys (N=0,1,2. ) will be set to 1.
Later, the system clock is set again from the hardware clock by systemd, dependent on values in /etc/adjtime . Hence, having the hardware clock using localtime may cause some unexpected behavior during the boot sequence; e.g system time going backwards, which is always a bad idea (there is a lot more to it). To avoid it systemd will only synchronize back, if the hardware clock is set to UTC and keep the kernel uninformed about the local timezone. As a consequence timestamps on a FAT filesystem touched by the Linux system will be in UTC.
UTC in Microsoft Windows
To dual boot with Windows it is recommended to configure Windows to use UTC, rather than Linux to use localtime. (Windows by default uses localtime [1].)
It can be done by a simple registry fix: Open regedit and add a DWORD value with hexadecimal value 1 to the registry:
You can do this from an Administrator Command Prompt running:
Alternatively, create a *.reg file (on the desktop) with the following content and double-click it to import it into registry:
Should Windows ask to update the clock due to DST changes, let it. It will leave the clock in UTC as expected, only correcting the displayed time.
The #Hardware clock and #System clock time may need to be updated after setting this value.
If you are having issues with the offset of the time, try reinstalling tzdata and then setting your time zone again:
Historical notes
For really old Windows, the above method fails, due to Windows bugs. More precisely,
- For 64-bit versions of Windows 7 and older builds of Windows 10, there was a bug that made it necessary to have a QWORD value with hexadecimal value of 1 instead of a DWORD value. This bug has been fixed in newer builds and now only DWORD works.
- Before Vista SP2, there is a bug that resets the clock to localtime after resuming from the suspend/hibernation state.
- For XP and older, there is a bug related to the daylight saving time. See [2] for details.
- For even older versions of Windows, you might want to read https://www.cl.cam.ac.uk/
mgk25/mswish/ut-rtc.html — the functionality was not even documented nor officially supported then.
For these operating systems, it is recommended to use localtime.
UTC in Ubuntu
Ubuntu and its derivatives have the hardware clock set to be interpreted as in «localtime» if Windows was detected on any disk during Ubuntu installation. This is apparently done deliberately to allow new Linux users to try out Ubuntu on their Windows computers without editing the registry.
For changing this behavior, see above.
Time zone
To check the current zone defined for the system:
To list available zones:
To set your time zone:
This will create an /etc/localtime symlink that points to a zoneinfo file under /usr/share/zoneinfo/ . In case you choose to create the link manually (for example during chroot where timedatectl will not work), keep in mind that it must be a symbolic link, as specified in archlinux(7) [dead link 2021-02-08] :
Setting based on geolocation
To set the timezone automatically based on the IP address location, one can use a geolocation API to retrieve the timezone, for example curl https://ipapi.co/timezone , and pass the output to timedatectl set-timezone for automatic setting. Some geo-IP APIs that provide free or partly free services are listed below:
Update timezone every time NetworkManager connects to a network
Alternatively, the tool tzupdate AUR automatically sets the timezone based on the geolocation of the IP address. This comparison of the most popular IP geolocation apis may be helpful in deciding which API to use in production.
Time skew
Every clock has a value that differs from real time (the best representation of which being International Atomic Time); no clock is perfect. A quartz-based electronic clock keeps imperfect time, but maintains a consistent inaccuracy. This base ‘inaccuracy’ is known as ‘time skew’ or ‘time drift’.
When the hardware clock is set with hwclock , a new drift value is calculated in seconds per day. The drift value is calculated by using the difference between the new value set and the hardware clock value just before the set, taking into account the value of the previous drift value and the last time the hardware clock was set. The new drift value and the time when the clock was set is written to the file /etc/adjtime overwriting the previous values. The hardware clock can therefore be adjusted for drift when the command hwclock —adjust is run; this also occurs on shutdown but only if the hwclock daemon is enabled, hence for Arch systems which use systemd, this does not happen.
If the hardware clock keeps losing or gaining time in large increments, it is possible that an invalid drift has been recorded (but only applicable, if the hwclock daemon is running). This can happen if you have set the hardware clock time incorrectly or your time standard is not synchronized with a Windows or macOS install. The drift value can be removed by first removing the file /etc/adjtime , then setting the correct hardware clock and system clock time. You should then check if your time standard is correct.
The software clock is very accurate but like most clocks is not perfectly accurate and will drift as well. Though rarely, the system clock can lose accuracy if the kernel skips interrupts. There are some tools to improve software clock accuracy:
Time synchronization
The Network Time Protocol (NTP) is a protocol for synchronizing the clocks of computer systems over packet-switched, variable-latency data networks. The following are implementations of NTP available for Arch Linux:
- Chrony — A client and server that is roaming friendly and designed specifically for systems that are not online all the time.
https://chrony.tuxfamily.org/ || chrony
- ConnMan — A lightweight network manager with NTP support.
https://01.org/connman (waybackmachine) || connman
- Network Time Protocol daemon — The reference implementation of the protocol, especially recommended to be used on time servers. It can also adjust the interrupt frequency and the number of ticks per second to decrease system clock drift, and will cause the hardware clock to be re-synchronised every 11 minutes.
https://www.ntp.org/ || ntp
- ntpclient — A simple command-line NTP client.
http://doolittle.icarus.com/ntpclient/ || ntpclientAUR
- NTPsec — A fork of NTPd, focused on security.
https://ntpsec.org/ || ntpsecAUR
- OpenNTPD — Part of the OpenBSD project and implements both a client and a server.
https://www.openntpd.org/ || openntpd
- sntp — An SNTP client that comes with NTPd. It supersedes ntpdate and is recommended in non-server environments.
https://www.ntp.org/ || ntp
- systemd-timesyncd — A simple SNTP daemon that only implements a client side, focusing only on querying time from one remote server. It should be more than appropriate for most installations.
https://www.freedesktop.org/wiki/Software/systemd/ || systemd
Per-user/session or temporary settings
For some use cases it may be useful to change the time settings without touching the global system values. For example to test applications relying on the time during development or adjusting the system time zone when logging into a server remotely from another zone.
To make an application «see» a different date/time than the system one, you can use the faketime(1) utility (from libfaketime ).
If instead you want an application to «see» a different time zone than the system one, set the TZ environment variable, for example:
This is different than just setting the time, as for example it allows to test the behavior of a program with positive or negative UTC offset values, or the effects of DST changes when developing on systems in a non-DST time zone.
Another use case is having different time zones set for different users of the same system: this can be accomplished by setting the TZ variable in the shell’s configuration file, see Environment variables#Defining variables.
Troubleshooting
Clock shows a value that is neither UTC nor local time
This might be caused by a number of reasons. For example, if your hardware clock is running on local time, but timedatectl is set to assume it is in UTC, the result would be that your timezone’s offset to UTC effectively gets applied twice, resulting in wrong values for your local time and UTC.
To force your clock to the correct time, and to also write the correct UTC to your hardware clock, follow these steps:
- Setup ntpd (enabling it as a service is not necessary).
- Set your time zone correctly.
- Run ntpd -qg to manually synchronize your clock with the network, ignoring large deviations between local UTC and network UTC.
- Run hwclock —systohc to write the current software UTC time to the hardware clock.
Tips and tricks
fake-hwclock
alarm-fake-hwclock designed especially for system without battery backed up RTC, it includes a systemd service which on shutdown saves the current time and on startup restores the saved time, thus avoiding strange time travel errors.
Источник