Tutorials
goetia
Software
0x53.net

Time synchronization

A computers internal clock is always skewed by some amount. To fix this it has to contact another machine with more precise timekeeping to fix its own time. The usual protocol for this is the network time protocol (NTP) and the server contacted to get a precise time is called an NTP server.

Ideally, the time server would only be contacted a handful of times, the local skew computed and automatically corrected. This approach is not yet part of this tutorial. Instead, the clock will be corrected periodically when using the approach shown here.

Using only s6-networking and s6-dns, very simple time synchronization via the network time protocol is possible. This synchronization can then easily periodically done using snooze.

Create a source directory for a longrun service called clockadd-@SERVER@-srv. @SERVER@ should be replaced with a descriptive name for the timeserver.

clockadd-@SERVER@-srv
├── dependencies.d
│   └── networking    # empty/arbitrary
├── producer-for      # clockadd-@SERVER@-log
├── run               # see below
└── type              # longrun
        

The run script looks as follows. Replace @TIMESERVERADDRESS@ with the address of of the NTP server desired.

#!/bin/execlineb -P

fdmove -c 2 1
if {
	pipeline {
		s6-setuidgid time
		backtick -E IP { s6-dnsip @TIMESERVERADDRESS@ }
		s6-sntpclock
			-v3
			-T 50000
			${IP}
	}
	s6-clockadd -f
}

snooze -H *

exit 0
		

The script does roughly the following: every hour, it querries the ip address of the NTP server, fetches the time and adjusts the system clock. Everything but the adjustment is done with reduced privileges of the user time.

Some useful NTP server providers are: