1 { config, lib, pkgs, ... }:
6 cfg = config.services.redis;
9 if value == true then "yes"
10 else if value == false then "no"
11 else generators.mkValueStringDefault { } value;
13 redisConfig = settings: pkgs.writeText "redis.conf" (generators.toKeyValue {
14 listsAsDuplicateKeys = true;
15 mkKeyValue = generators.mkKeyValueDefault { inherit mkValueString; } " ";
18 redisName = name: "redis" + optionalString (name != "") ("-"+name);
19 enabledServers = filterAttrs (name: conf: conf.enable) config.services.redis.servers;
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" ])
60 defaultText = "pkgs.redis";
61 description = "Which Redis derivation to use.";
64 vmOverCommit = mkEnableOption ''
65 setting of vm.overcommit_memory to 1
66 (Suggested for Background Saving: http://redis.io/topics/faq)
70 type = with types; attrsOf (submodule ({config, name, ...}@args: {
72 enable = mkEnableOption ''
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).
83 default = redisName name;
84 defaultText = "\"redis\" or \"redis-\${name}\" if name != \"\"";
85 description = "The username and groupname for redis-server.";
91 description = "The port for Redis to listen to.";
94 openFirewall = mkOption {
98 Whether to open ports in the firewall for the server.
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 != \"\"";
107 The IP interface to bind to.
108 <literal>null</literal> means "all interfaces".
110 example = "192.0.2.1";
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.";
120 unixSocketPerm = mkOption {
123 description = "Change permissions for the socket";
127 logLevel = mkOption {
129 default = "notice"; # debug, verbose, notice, warning
131 description = "Specify the server verbosity level, options: debug, verbose, notice, warning.";
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";
144 description = "Enable logging to the system logger.";
147 databases = mkOption {
150 description = "Set the number of databases.";
153 maxclients = mkOption {
156 description = "Set the max number of connected clients at the same time.";
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] ];
167 type = with types; nullOr (submodule ({ ... }: {
171 description = "IP of the Redis master";
172 example = "192.168.1.100";
177 description = "port of the Redis master";
184 description = "IP and port to which this redis instance acts as a slave.";
185 example = { ip = "192.168.1.100"; port = 6379; };
188 masterAuth = mkOption {
189 type = with types; nullOr str;
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)'';
197 requirePass = mkOption {
198 type = with types; nullOr str;
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.
204 example = "letmein!";
207 requirePassFile = mkOption {
208 type = with types; nullOr path;
210 description = "File with password for the database.";
211 example = "/run/keys/redis-password";
214 appendOnly = mkOption {
217 description = "By default data is only periodically persisted to disk, enable this option to use an append-only file for improved persistence.";
220 appendFsync = mkOption {
222 default = "everysec"; # no, always, everysec
223 description = "How often to fsync the append-only log, options: no, always, everysec.";
226 slowLogLogSlowerThan = mkOption {
229 description = "Log queries whose execution take longer than X in milliseconds.";
233 slowLogMaxLen = mkOption {
236 description = "Maximum number of items to keep in slow log.";
239 settings = mkOption {
240 # TODO: this should be converted to freeformType
241 type = with types; attrsOf (oneOf [ bool int str (listOf str) ]);
244 Redis configuration. Refer to
245 <link xlink:href="https://redis.io/topics/config"/>
246 for details on supported values.
248 example = literalExample ''
250 loadmodule = [ "/path/to/my_module.so" "/path/to/other_module.so" ];
255 config.settings = mkMerge [
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;
273 (mkIf (config.bind != null) { bind = config.bind; })
274 (mkIf (config.unixSocket != null) {
275 unixsocket = config.unixSocket;
276 unixsocketperm = toString config.unixSocketPerm;
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; })
283 description = "Configuration of multiple <literal>redis-server</literal> instances.";
291 ###### implementation
293 config = mkIf (enabledServers != {}) {
295 assertions = attrValues (mapAttrs (name: conf: {
296 assertion = conf.requirePass != null -> conf.requirePassFile == null;
298 You can only set one services.redis.servers.${name}.requirePass
299 or services.redis.servers.${name}.requirePassFile
303 boot.kernel.sysctl = mkMerge [
304 { "vm.nr_hugepages" = "0"; }
305 ( mkIf cfg.vmOverCommit { "vm.overcommit_memory" = "1"; } )
308 networking.firewall.allowedTCPPorts = concatMap (conf:
309 optional conf.openFirewall conf.port
310 ) (attrValues enabledServers);
312 environment.systemPackages = [ cfg.package ];
314 users.users = mapAttrs' (name: conf: nameValuePair (redisName name) {
315 description = "System user for the redis-server instance ${name}";
318 users.groups = mapAttrs' (name: conf: nameValuePair (redisName name) {
321 systemd.services = mapAttrs' (name: conf: nameValuePair (redisName name) {
322 description = "Redis Server - ${redisName name}";
324 wantedBy = [ "multi-user.target" ];
325 after = [ "network.target" ];
328 ExecStart = "${cfg.package}/bin/redis-server /run/${redisName name}/redis.conf";
329 ExecStartPre = [("+"+pkgs.writeShellScript "${redisName name}-credentials" (''
330 install -o '${conf.user}' -m 600 ${redisConfig conf.settings} /run/${redisName name}/redis.conf
331 '' + optionalString (conf.requirePassFile != null) ''
333 printf requirePass' '
334 cat ${escapeShellArg conf.requirePassFile}
335 } >>/run/${redisName name}/redis.conf
342 # Runtime directory and mode
343 RuntimeDirectory = redisName name;
344 RuntimeDirectoryMode = "0750";
345 # State directory and mode
346 StateDirectory = redisName name;
347 StateDirectoryMode = "0700";
348 # Access write directories
351 CapabilityBoundingSet = "";
353 NoNewPrivileges = true;
355 LimitNOFILE = mkDefault "${toString (conf.maxclients + 32)}";
357 ProtectSystem = "strict";
360 PrivateDevices = true;
363 ProtectHostname = true;
364 ProtectKernelLogs = true;
365 ProtectKernelModules = true;
366 ProtectKernelTunables = true;
367 ProtectControlGroups = true;
368 RestrictAddressFamilies =
369 optionals (conf.bind != null) ["AF_INET" "AF_INET6"] ++
370 optional (conf.unixSocket != null) "AF_UNIX";
371 RestrictNamespaces = true;
372 LockPersonality = true;
373 MemoryDenyWriteExecute = true;
374 RestrictRealtime = true;
375 RestrictSUIDSGID = true;
376 PrivateMounts = true;
377 # System Call Filtering
378 SystemCallArchitectures = "native";
379 SystemCallFilter = "~@cpu-emulation @debug @keyring @memlock @mount @obsolete @privileged @resources @setuid";