Difference between revisions of "Network Time Protocol"

From ArchWiki
Jump to navigation Jump to search
(Updated section 1.2 and improved formatting)
(Split the article in "Network Time Protocol daemon" and "OpenNTPD")
Line 1: Line 1:
[[Category:Networking (English)]]
#REDIRECT [[Network Time Protocol daemon]]
[[Category:Daemons and system services (English)]]
[[Category:HOWTOs (English)]]
{{i18n|Network Time Protocol}}
This article describes two different methods to synchronize the Linux software clock (system clock) to internet time servers. For more information on computer timekeeping, see [[Time]]. Traditional ntpd is explained first and then OpenNTPD (part of the OpenBSD project) is explained. Both daemons can sync the local clock and act as a time server if needed. OpenNTPD is designed to be simple and secure, while ntpd has a larger set of features. '''Note that OpenNTPD is not currently maintained for Linux (see [http://bbs.archlinux.org/viewtopic.php?id=68627 this thread]).
[http://www.ntp.org/ ntp] is available from [extra]:
{{cli|# pacman -S ntp{{cursor}}}}
The first thing you define in your {{Filename|/etc/ntp.conf}} is the servers your machine will synchronize to.
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. Tipically, stratum 2 servers are used for general synchronization purposes: if you don't already know the servers you're going to connect to, you should use the [http://www.pool.ntp.org/ pool.ntp.org] servers ([http://support.ntp.org/bin/view/Servers/NTPPoolServers alternate link]) and choose the server pool that is closest to your location.
The following lines are just an example:
server 0.it.pool.ntp.org iburst
server 1.it.pool.ntp.org iburst
server 2.it.pool.ntp.org iburst
server 3.it.pool.ntp.org iburst
The ''iburst'' option is recommended, and sends a burst of packets if it cannot obtain a connection with the first attempt. The ''burst'' option should never be used without explicit permission and will likely result in blacklisting.
If you're setting up a ntp server, you need to add ''localhost'' as a server, so that, in case it loses internet access, it won't stop serving time to the network; add ''localhost'' as a stratum 10 server (using the ''fudge'' command) so that it will never be used unless internet access is lost:
fudge stratum 10
The next thing you have to do is add the drift file (which keeps track of your clock's time deviation) and optionally the log file location:
driftfile /var/lib/ntp/ntp.drift
logfile /var/log/ntp.log
Now all that's left to do is 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:
restrict default nomodify nopeer
This restricts everyone from modifying anything and prevents everyone from querying your time server.
You can also add other options:
restrict default kod nomodify notrap nopeer noquery
In the past, ''notrust'' option was used too, but its function has changed to mean that authentication with a key is required.
Following this line, you need to tell ''ntpd'' what to allow through into your server; the following line is enough if you're not configuring a ntp server:
Otherwise you can add more clients like in this example:
restrict nomodify
restrict mask nomodify notrap
This tells ''ntpd'' that and all IP addresses from the range will be allowed to synchronize on this server, but they will not be allowed to modify anything. All other IP addresses in the world will still obey the default restrictions (the first line in the {{Filename|ntp.conf}}).
In the end, for the most basic configuration, the complete file will look like this ('''all comments have been stripped out for clarity'''):
server 0.it.pool.ntp.org iburst
server 1.it.pool.ntp.org iburst
server 2.it.pool.ntp.org iburst
server 3.it.pool.ntp.org iburst
driftfile /var/lib/ntp/ntp.drift
logfile /var/log/ntp.log
restrict default nomodify nopeer
Actually, defining the log file is not mandatory, but it's always a good idea to have a feedback for ''ntpd'' operations.
Lastly, never forget man pages: {{Codeline|man ntp.conf}} is likely to answer any doubts you could still have.
===Running as a daemon===
====Starting ntpd====
Add ''ntpd'' to the DAEMONS array in {{Filename|/etc/rc.conf}} to have it start at boot:
DAEMONS=(syslog-ng network '''@ntpd''' ...)
''ntpd'' can be brought up/down along with a network connection through the use of [[NetworkManager#Network Services with NetworkManager Dispatcher|NetworkManager's dispatcher scripts]]. You can install the needed script from [community]:
{{cli|# pacman -S networkmanager-dispatcher-ntpd{{cursor}}}}
====Running as non-root user====
When compiled with ''--enable-linux-caps'', ntp can be run as a non-root user for increased security (the vanilla Arch Linux package has this enabled).
{{Note|Before attempting this, make sure ntp has already created {{Filename|/var/lib/ntp/ntp.drift}}.}}
Create ''ntp'' group and ''ntp'' user:
{{cli|# groupadd ntp<br><br>
<nowiki>#</nowiki> useradd -r -d /var/lib/ntp -g ntp -s /bin/false ntp{{cursor}}}}
Change ownership of ntp directory to the ntp user/group:
{{cli|# chown -R ntp:ntp /var/lib/ntp{{cursor}}}}
Edit {{Filename|/etc/conf.d/ntp-client.conf}} and change
NTPD_ARGS="-g -u ntp:ntp"
===Syncing the clock without running the daemon===
If what you want is just synchronize your system clock at boot time without running ''ntpd'' as a daemon, you can add this line to your {{Filename|/etc/rc.local}}:
ntpd -qg &
* In order for this method to work you have to make sure that, when {{Filename|rc.local}} is executed, the network connection has already been initialized (for example you shouldn't background essential network-related daemons in {{Filename|/etc/rc.conf}})
* The hardware clock is already automatically realigned with the system clock each time you halt the computer, through a command in {{Filename|/etc/rc.shutdown}}
* Using this method is highly discouraged on servers and in general on machines that need to run continuously for more than 2 or 3 days, as the system clock will be updated only once at boot time.
* Running "ntpd -qg" as a ''cron'' event is to be completely avoided, unless you are perfectly aware of how your running applications would react to instantaneous system time changes.
== OpenNTPD ==
=== Installation ===
[http://www.openntpd.org/ OpenNTPD] can be installed from [community]:
# pacman -S openntpd
The default configuration is actually usable if all you want is to sync the time of the local computer. For more detailed settings, the {{Filename|/etc/ntpd.conf}} file must be edited:
To sync to a particular server, uncomment and edit the "server" directive. You can find the server's URL in your area at [http://www.pool.ntp.org/zone/@ www.pool.ntp.org/zone/@].
server ntp.example.org
The "servers" directive works the same as the "server" directive, however, if the DNS name resolves to multiple IP address, ALL of them will be synced to.  The default, "pool.ntp.org" is working and should be acceptable in most cases.
Any number of "server" or "servers" directives may be used.
If you want the computer you run OpenNTPD on to also be a time server, simply uncomment and edit the "listen" directive.
For example:
listen on *
will listen on all interfaces, and
listen on
will only listen on the loopback interface.
Your time server will only begin to serve time after it has synchronized itself to a high resolution. This may take hours, or days, depending on the accuracy of your system.
If you would like to run OpenNTPD at boot, add {{Codeline|openntpd}} the DAEMONS variable in your {{Filename|/etc/rc.conf}} following your network daemon.
DAEMONS=(syslog-ng network '''openntpd''' ...)
If openntpd is being used to set local system time only, it may be safely backgrounded.
DAEMONS=(syslog-ng network '''@openntpd''' ...)
To see the status of NTP syncing, visit {{Filename|/var/log/daemon.log}} and look for entries with "ntpd".
OpenNTPD adjusts the clock by small amounts at a time. It is designed this way to prevent sudden, large time fluctuations in your system, which could adversely affect system services (e.g., cron jobs). Thus, it can take some time to correct the time.
If your clock is off by more than 180 seconds you can try "{{Codeline|ntpd -s -d}}" in the console. If ntpd is already running, you can simply restart it with {{Codeline|sudo /etc/rc.d/openntpd restart}}, as the Arch openntpd package uses the "-s" flag by default. See {{Codeline|man ntpd}} for more info. You can also set the [[Time#Time_Set|system clock]] to as close to possible to the actual time and then let OpenNTPD fine tune the time.
=== Making openntpd dependent upon network access ===
If you have intermittent network access (you roam around on a laptop, you use dial-up, etc), it does not make sense to have {{Codeline|openntpd}} running as a system daemon on start up. Here are a few ways you can control {{Codeline|openntpd}} based on the presence of a network connection. These instructions should also work for {{Codeline|ntpd}} found further below. 
==== Using netcfg ====
If you are using netcfg, you can also start/stop openntpd as a POST_UP/PRE_DOWN command in your network profile:
POST_UP="/etc/rc.d/openntpd start || true"
PRE_DOWN="/etc/rc.d/openntpd stop || true"
Of course, you will have to specify this manually for each network profile.
==== Using NetworkManager dispatcher ====
OpenNTPD can be brought up/down along with a network connection through the use of [[NetworkManager#Network Services with NetworkManager Dispatcher|NetworkManager's dispatcher scripts]]. You can install the needed script from [community]:
# pacman -S networkmanager-dispatcher-openntpd
==== Using wicd ====
These instructions require wicd 1.7.0 or later, which is available in the standard Arch repository.
You will also need write access to {{Filename|/etc/wicd/scripts}}.
{{Note|Remember to make these two scripts executable using {{Codeline|chmod}} }}
Make one shell script inside {{Filename|/etc/wicd/scripts/postconnect/openntpd-start.sh}} with the following:
/etc/rc.d/openntpd start
Similarly, make another shell script inside {{Filename|/etc/wicd/scripts/predisconnect/openntpd-stop.sh}} with the following:
/etc/rc.d/openntpd stop
==== Using dhcpcd hooks ====
Another possibility is to use dhcpcd hooks to start and stop openntpd.
When dhcpcd detects a change in state it will run the following scripts: <br>
{{Filename|/etc/dhcpcd.enter-hook}} <br>
{{Filename|/usr/lib/dhcpcd/dhcpcd-hooks/*}} <br>
{{Filename|/etc/dhcpcd.exit-hook}} <br>
The following example uses {{Filename|/etc/dhcpcd.exit-hook}} to start and stop openntpd depending on dhcp status:
[ "$interface" != "eth0" ] && exit 0
if $if_up; then
    pgrep ntpd &> /dev/null || /etc/rc.d/openntpd start
elif $if_down; then
    pgrep ntpd &> /dev/null && /etc/rc.d/openntpd stop
====Error adjusting time====
If you find your time set incorrectly and in log you see:
openntpd adjtime failed: Invalid argument
ntpd -s -d
This is also how you would manually sync your system.
====Increasing time shift====
Starting ''openntpd'' in the background could lead to synchronization errors between the actual time and the time stored on your computer. If you recognize an increasing time difference between your desktop clock and the actual time, try to start the ''openntpd'' daemon normal and not in the background.
====Initialization Failure====
Openntpd may fail to initialize properly if it is started before the network is fully configured. In some cases you may want to remove {{Codeline|openntpd}} from the DAEMONS array in {{Filename|/etc/rc.conf}} and add the following line to {{Filename|/etc/rc.local}}:
(sleep 300 && /etc/rc.d/openntpd start) &
{{Note|This method is an alternative to the four methods listed [[#Making openntpd dependent upon network access|above]]. The other three methods are preferred and work better. Use this as a last resort.}}
This will wait 5 minutes before starting openntpd, which should give the system sufficient time to set up the network properly. If your network settings change often, you may also consider restarting the daemon regularly with cron.
==External links==
* http://www.ntp.org/
* http://twiki.ntp.org/bin/view/Main/WebHome
* http://www.eecis.udel.edu/~mills/ntp/html/index.html
* http://www.openntpd.org

Revision as of 20:58, 11 February 2011