1{ config, lib, pkgs, ... }:
2
3with lib;
4
5let
6
7 inherit (pkgs) ntp;
8
9 cfg = config.services.ntp;
10
11 stateDir = "/var/lib/ntp";
12
13 ntpUser = "ntp";
14
15 configFile = pkgs.writeText "ntp.conf" ''
16 driftfile ${stateDir}/ntp.drift
17
18 restrict 127.0.0.1
19 restrict -6 ::1
20
21 ${toString (map (server: "server " + server + " iburst\n") cfg.servers)}
22 '';
23
24 ntpFlags = "-c ${configFile} -u ${ntpUser}:nogroup ${toString cfg.extraFlags}";
25
26in
27
28{
29
30 ###### interface
31
32 options = {
33
34 services.ntp = {
35
36 enable = mkOption {
37 default = !config.boot.isContainer;
38 description = ''
39 Whether to synchronise your machine's time using the NTP
40 protocol.
41 '';
42 };
43
44 servers = mkOption {
45 default = [
46 "0.nixos.pool.ntp.org"
47 "1.nixos.pool.ntp.org"
48 "2.nixos.pool.ntp.org"
49 "3.nixos.pool.ntp.org"
50 ];
51 description = ''
52 The set of NTP servers from which to synchronise.
53 '';
54 };
55
56 extraFlags = mkOption {
57 type = types.listOf types.str;
58 description = "Extra flags passed to the ntpd command.";
59 default = [];
60 };
61
62 };
63
64 };
65
66
67 ###### implementation
68
69 config = mkIf config.services.ntp.enable {
70
71 # Make tools such as ntpq available in the system path.
72 environment.systemPackages = [ pkgs.ntp ];
73
74 users.extraUsers = singleton
75 { name = ntpUser;
76 uid = config.ids.uids.ntp;
77 description = "NTP daemon user";
78 home = stateDir;
79 };
80
81 systemd.services.ntpd =
82 { description = "NTP Daemon";
83
84 wantedBy = [ "multi-user.target" ];
85
86 preStart =
87 ''
88 mkdir -m 0755 -p ${stateDir}
89 chown ${ntpUser} ${stateDir}
90 '';
91
92 serviceConfig = {
93 ExecStart = "@${ntp}/bin/ntpd ntpd -g ${ntpFlags}";
94 Type = "forking";
95 };
96 };
97
98 };
99
100}