aboutsummaryrefslogtreecommitdiff
path: root/modules/apps/memcached/default.nix
blob: e963518652a9bcd2fe229eaddaee663af6c9bfca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
{ config, lib, pkgs, ... }:

let

  inherit (builtins)
    elem filter isBool isList ;

  inherit (lib)
    concatMapStringsSep concatStringsSep filterAttrs flatten foldAttrs foldl
    mapAttrsToList mkOption optionalString ;

  inherit (lib.types)
    attrsOf submodule ;

  concatMapAttrsSep = s: f: attrs: concatStringsSep s (mapAttrsToList f attrs);

  explicit = filterAttrs (n: v: n != "_module" && v != null);
  instances = explicit config.nixsap.apps.memcached;
  users = mapAttrsToList (_: i: i.user) instances;


  mkService = name: cfg:
    let

      show = n: v:
        if isList v then map (s: "-${n} '${toString s}'") v
        else if isBool v then (optionalString v "-${n}")
        else "-${n} '${toString v}'";

      args = flatten (mapAttrsToList show (explicit cfg.args));

      start = pkgs.writeBashScriptBin "memcached-${name}-start" ''
        set -euo pipefail
        umask 0027

        exec ${cfg.package}/bin/memcached \
        ${concatStringsSep " \\\n" args}
      '';

    in {
      "memcached-${name}" = {
        description = "memcached (${name})";
        wantedBy = [ "multi-user.target" ];
        after = [ "keys.target" "network.target" "local-fs.target" ];
        serviceConfig = {
          ExecStart = "${start}/bin/memcached-${name}-start";
          Restart = "always";
          User = cfg.user;
        };
      };
    };

in {

  options.nixsap.apps.memcached = mkOption {
    description = "Memcached instances";
    default = {};
    type = attrsOf (submodule (import ./instance.nix pkgs));
  };

  config = {
    systemd.services = foldl (a: b: a//b) {} (mapAttrsToList mkService instances);
    nixsap.system.users.daemons = users;
  };

}