]> Git — Sourcephile - sourcephile-nix.git/blob - nixos/modules/services/databases/redis.nix
logrotate: rotate /var/log/{b,w}tmp and nginx
[sourcephile-nix.git] / nixos / modules / services / databases / redis.nix
1 { config, lib, pkgs, ... }:
2
3 with lib;
4
5 let
6 cfg = config.services.redis;
7
8 mkValueString = value:
9 if value == true then "yes"
10 else if value == false then "no"
11 else generators.mkValueStringDefault { } value;
12
13 redisConfig = settings: pkgs.writeText "redis.conf" (generators.toKeyValue {
14 listsAsDuplicateKeys = true;
15 mkKeyValue = generators.mkKeyValueDefault { inherit mkValueString; } " ";
16 } settings);
17
18 redisName = name: "redis" + optionalString (name != "") ("-"+name);
19 enabledServers = filterAttrs (name: conf: conf.enable) config.services.redis.servers;
20
21 in {
22 imports = [
23 (mkRemovedOptionModule [ "services" "redis" "user" ] "The redis module now is hardcoded to the redis user.")
24 (mkRemovedOptionModule [ "services" "redis" "dbpath" ] "The redis module now uses /var/lib/redis as data directory.")
25 (mkRemovedOptionModule [ "services" "redis" "dbFilename" ] "The redis module now uses /var/lib/redis/dump.rdb as database dump location.")
26 (mkRemovedOptionModule [ "services" "redis" "appendOnlyFilename" ] "This option was never used.")
27 (mkRemovedOptionModule [ "services" "redis" "pidFile" ] "This option was removed.")
28 (mkRemovedOptionModule [ "services" "redis" "extraConfig" ] "Use services.redis.settings instead.")
29 (mkRenamedOptionModule [ "services" "redis" "enable"] [ "services" "redis" "servers" "" "enable" ])
30 (mkRenamedOptionModule [ "services" "redis" "port"] [ "services" "redis" "servers" "" "port" ])
31 (mkRenamedOptionModule [ "services" "redis" "openFirewall"] [ "services" "redis" "servers" "" "openFirewall" ])
32 (mkRenamedOptionModule [ "services" "redis" "bind"] [ "services" "redis" "servers" "" "bind" ])
33 (mkRenamedOptionModule [ "services" "redis" "unixSocket"] [ "services" "redis" "servers" "" "unixSocket" ])
34 (mkRenamedOptionModule [ "services" "redis" "unixSocketPerm"] [ "services" "redis" "servers" "" "unixSocketPerm" ])
35 (mkRenamedOptionModule [ "services" "redis" "logLevel"] [ "services" "redis" "servers" "" "logLevel" ])
36 (mkRenamedOptionModule [ "services" "redis" "logfile"] [ "services" "redis" "servers" "" "logfile" ])
37 (mkRenamedOptionModule [ "services" "redis" "syslog"] [ "services" "redis" "servers" "" "syslog" ])
38 (mkRenamedOptionModule [ "services" "redis" "databases"] [ "services" "redis" "servers" "" "databases" ])
39 (mkRenamedOptionModule [ "services" "redis" "maxclients"] [ "services" "redis" "servers" "" "maxclients" ])
40 (mkRenamedOptionModule [ "services" "redis" "save"] [ "services" "redis" "servers" "" "save" ])
41 (mkRenamedOptionModule [ "services" "redis" "slaveOf"] [ "services" "redis" "servers" "" "slaveOf" ])
42 (mkRenamedOptionModule [ "services" "redis" "masterAuth"] [ "services" "redis" "servers" "" "masterAuth" ])
43 (mkRenamedOptionModule [ "services" "redis" "requirePass"] [ "services" "redis" "servers" "" "requirePass" ])
44 (mkRenamedOptionModule [ "services" "redis" "requirePassFile"] [ "services" "redis" "servers" "" "requirePassFile" ])
45 (mkRenamedOptionModule [ "services" "redis" "appendOnly"] [ "services" "redis" "servers" "" "appendOnly" ])
46 (mkRenamedOptionModule [ "services" "redis" "appendFsync"] [ "services" "redis" "servers" "" "appendFsync" ])
47 (mkRenamedOptionModule [ "services" "redis" "slowLogLogSlowerThan"] [ "services" "redis" "servers" "" "slowLogLogSlowerThan" ])
48 (mkRenamedOptionModule [ "services" "redis" "slowLogMaxLen"] [ "services" "redis" "servers" "" "slowLogMaxLen" ])
49 (mkRenamedOptionModule [ "services" "redis" "settings"] [ "services" "redis" "servers" "" "settings" ])
50 ];
51
52 ###### interface
53
54 options = {
55
56 services.redis = {
57 package = mkOption {
58 type = types.package;
59 default = pkgs.redis;
60 defaultText = "pkgs.redis";
61 description = "Which Redis derivation to use.";
62 };
63
64 vmOverCommit = mkEnableOption ''
65 setting of vm.overcommit_memory to 1
66 (Suggested for Background Saving: http://redis.io/topics/faq)
67 '';
68
69 servers = mkOption {
70 type = with types; attrsOf (submodule ({config, name, ...}@args: {
71 options = {
72 enable = mkEnableOption ''
73 Redis server.
74
75 Note that the NixOS module for Redis disables kernel support
76 for Transparent Huge Pages (THP),
77 because this features causes major performance problems for Redis,
78 e.g. (https://redis.io/topics/latency).
79 '';
80
81 user = mkOption {
82 type = types.str;
83 default = redisName name;
84 defaultText = "\"redis\" or \"redis-\${name}\" if name != \"\"";
85 description = "The username and groupname for redis-server.";
86 };
87
88 port = mkOption {
89 type = types.port;
90 default = 6379;
91 description = "The port for Redis to listen to.";
92 };
93
94 openFirewall = mkOption {
95 type = types.bool;
96 default = false;
97 description = ''
98 Whether to open ports in the firewall for the server.
99 '';
100 };
101
102 bind = mkOption {
103 type = with types; nullOr str;
104 default = if name == "" then "127.0.0.1" else null;
105 defaultText = "127.0.0.1 or null if name != \"\"";
106 description = ''
107 The IP interface to bind to.
108 <literal>null</literal> means "all interfaces".
109 '';
110 example = "192.0.2.1";
111 };
112
113 unixSocket = mkOption {
114 type = with types; nullOr path;
115 default = "/run/${redisName name}/redis.sock";
116 defaultText = "\"/run/redis/redis.sock\" or \"/run/redis-\${name}/redis.sock\" if name != \"\"";
117 description = "The path to the socket to bind to.";
118 };
119
120 unixSocketPerm = mkOption {
121 type = types.int;
122 default = 660;
123 description = "Change permissions for the socket";
124 example = 600;
125 };
126
127 logLevel = mkOption {
128 type = types.str;
129 default = "notice"; # debug, verbose, notice, warning
130 example = "debug";
131 description = "Specify the server verbosity level, options: debug, verbose, notice, warning.";
132 };
133
134 logfile = mkOption {
135 type = types.str;
136 default = "/dev/null";
137 description = "Specify the log file name. Also 'stdout' can be used to force Redis to log on the standard output.";
138 example = "/var/log/redis.log";
139 };
140
141 syslog = mkOption {
142 type = types.bool;
143 default = true;
144 description = "Enable logging to the system logger.";
145 };
146
147 databases = mkOption {
148 type = types.int;
149 default = 16;
150 description = "Set the number of databases.";
151 };
152
153 maxclients = mkOption {
154 type = types.int;
155 default = 10000;
156 description = "Set the max number of connected clients at the same time.";
157 };
158
159 save = mkOption {
160 type = with types; listOf (listOf int);
161 default = [ [900 1] [300 10] [60 10000] ];
162 description = "The schedule in which data is persisted to disk, represented as a list of lists where the first element represent the amount of seconds and the second the number of changes.";
163 example = [ [900 1] [300 10] [60 10000] ];
164 };
165
166 slaveOf = mkOption {
167 type = with types; nullOr (submodule ({ ... }: {
168 options = {
169 ip = mkOption {
170 type = str;
171 description = "IP of the Redis master";
172 example = "192.168.1.100";
173 };
174
175 port = mkOption {
176 type = port;
177 description = "port of the Redis master";
178 default = 6379;
179 };
180 };
181 }));
182
183 default = null;
184 description = "IP and port to which this redis instance acts as a slave.";
185 example = { ip = "192.168.1.100"; port = 6379; };
186 };
187
188 masterAuth = mkOption {
189 type = with types; nullOr str;
190 default = null;
191 description = ''If the master is password protected (using the requirePass configuration)
192 it is possible to tell the slave to authenticate before starting the replication synchronization
193 process, otherwise the master will refuse the slave request.
194 (STORED PLAIN TEXT, WORLD-READABLE IN NIX STORE)'';
195 };
196
197 requirePass = mkOption {
198 type = with types; nullOr str;
199 default = null;
200 description = ''
201 Password for database (STORED PLAIN TEXT, WORLD-READABLE IN NIX STORE).
202 Use requirePassFile to store it outside of the nix store in a dedicated file.
203 '';
204 example = "letmein!";
205 };
206
207 requirePassFile = mkOption {
208 type = with types; nullOr path;
209 default = null;
210 description = "File with password for the database.";
211 example = "/run/keys/redis-password";
212 };
213
214 appendOnly = mkOption {
215 type = types.bool;
216 default = false;
217 description = "By default data is only periodically persisted to disk, enable this option to use an append-only file for improved persistence.";
218 };
219
220 appendFsync = mkOption {
221 type = types.str;
222 default = "everysec"; # no, always, everysec
223 description = "How often to fsync the append-only log, options: no, always, everysec.";
224 };
225
226 slowLogLogSlowerThan = mkOption {
227 type = types.int;
228 default = 10000;
229 description = "Log queries whose execution take longer than X in milliseconds.";
230 example = 1000;
231 };
232
233 slowLogMaxLen = mkOption {
234 type = types.int;
235 default = 128;
236 description = "Maximum number of items to keep in slow log.";
237 };
238
239 settings = mkOption {
240 # TODO: this should be converted to freeformType
241 type = with types; attrsOf (oneOf [ bool int str (listOf str) ]);
242 default = {};
243 description = ''
244 Redis configuration. Refer to
245 <link xlink:href="https://redis.io/topics/config"/>
246 for details on supported values.
247 '';
248 example = literalExample ''
249 {
250 loadmodule = [ "/path/to/my_module.so" "/path/to/other_module.so" ];
251 }
252 '';
253 };
254 };
255 config.settings = mkMerge [
256 {
257 port = if config.bind == null then 0 else config.port;
258 daemonize = false;
259 supervised = "systemd";
260 loglevel = config.logLevel;
261 logfile = config.logfile;
262 syslog-enabled = config.syslog;
263 databases = config.databases;
264 maxclients = config.maxclients;
265 save = map (d: "${toString (builtins.elemAt d 0)} ${toString (builtins.elemAt d 1)}") config.save;
266 dbfilename = "dump.rdb";
267 dir = "/var/lib/${redisName name}";
268 appendOnly = config.appendOnly;
269 appendfsync = config.appendFsync;
270 slowlog-log-slower-than = config.slowLogLogSlowerThan;
271 slowlog-max-len = config.slowLogMaxLen;
272 }
273 (mkIf (config.bind != null) { bind = config.bind; })
274 (mkIf (config.unixSocket != null) {
275 unixsocket = config.unixSocket;
276 unixsocketperm = toString config.unixSocketPerm;
277 })
278 (mkIf (config.slaveOf != null) { slaveof = "${config.slaveOf.ip} ${toString config.slaveOf.port}"; })
279 (mkIf (config.masterAuth != null) { masterauth = config.masterAuth; })
280 (mkIf (config.requirePass != null) { requirepass = config.requirePass; })
281 ];
282 }));
283 description = "Configuration of multiple <literal>redis-server</literal> instances.";
284 default = {};
285 };
286 };
287
288 };
289
290
291 ###### implementation
292
293 config = mkIf (enabledServers != {}) {
294
295 assertions = attrValues (mapAttrs (name: conf: {
296 assertion = conf.requirePass != null -> conf.requirePassFile == null;
297 message = ''
298 You can only set one services.redis.servers.${name}.requirePass
299 or services.redis.servers.${name}.requirePassFile
300 '';
301 }) enabledServers);
302
303 boot.kernel.sysctl = mkMerge [
304 { "vm.nr_hugepages" = "0"; }
305 ( mkIf cfg.vmOverCommit { "vm.overcommit_memory" = "1"; } )
306 ];
307
308 networking.firewall.allowedTCPPorts = concatMap (conf:
309 optional conf.openFirewall conf.port
310 ) (attrValues enabledServers);
311
312 environment.systemPackages = [ cfg.package ];
313
314 users.users = mapAttrs' (name: conf: nameValuePair (redisName name) {
315 description = "System user for the redis-server instance ${name}";
316 isSystemUser = true;
317 group = redisName name;
318 }) enabledServers;
319 users.groups = mapAttrs' (name: conf: nameValuePair (redisName name) {
320 }) enabledServers;
321
322 systemd.services = mapAttrs' (name: conf: nameValuePair (redisName name) {
323 description = "Redis Server - ${redisName name}";
324
325 wantedBy = [ "multi-user.target" ];
326 after = [ "network.target" ];
327
328 serviceConfig = {
329 ExecStart = "${cfg.package}/bin/redis-server /run/${redisName name}/redis.conf";
330 ExecStartPre = [("+"+pkgs.writeShellScript "${redisName name}-credentials" (''
331 install -o '${conf.user}' -m 600 ${redisConfig conf.settings} /run/${redisName name}/redis.conf
332 '' + optionalString (conf.requirePassFile != null) ''
333 {
334 printf requirePass' '
335 cat ${escapeShellArg conf.requirePassFile}
336 } >>/run/${redisName name}/redis.conf
337 '')
338 )];
339 Type = "notify";
340 # User and group
341 User = conf.user;
342 Group = conf.user;
343 # Runtime directory and mode
344 RuntimeDirectory = redisName name;
345 RuntimeDirectoryMode = "0750";
346 # State directory and mode
347 StateDirectory = redisName name;
348 StateDirectoryMode = "0700";
349 # Access write directories
350 UMask = "0077";
351 # Capabilities
352 CapabilityBoundingSet = "";
353 # Security
354 NoNewPrivileges = true;
355 # Process Properties
356 LimitNOFILE = mkDefault "${toString (conf.maxclients + 32)}";
357 # Sandboxing
358 ProtectSystem = "strict";
359 ProtectHome = true;
360 PrivateTmp = true;
361 PrivateDevices = true;
362 PrivateUsers = true;
363 ProtectClock = true;
364 ProtectHostname = true;
365 ProtectKernelLogs = true;
366 ProtectKernelModules = true;
367 ProtectKernelTunables = true;
368 ProtectControlGroups = true;
369 RestrictAddressFamilies =
370 optionals (conf.bind != null) ["AF_INET" "AF_INET6"] ++
371 optional (conf.unixSocket != null) "AF_UNIX";
372 RestrictNamespaces = true;
373 LockPersonality = true;
374 MemoryDenyWriteExecute = true;
375 RestrictRealtime = true;
376 RestrictSUIDSGID = true;
377 PrivateMounts = true;
378 # System Call Filtering
379 SystemCallArchitectures = "native";
380 SystemCallFilter = "~@cpu-emulation @debug @keyring @memlock @mount @obsolete @privileged @resources @setuid";
381 };
382 }) enabledServers;
383
384 };
385 }