aboutsummaryrefslogtreecommitdiff
path: root/modules/apps/php-fpm.nix
blob: 98628b9c963567e70a09319bf249b2f38ccd5133 (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
{ config, pkgs, lib, ... }:

let

  inherit (builtins)
    filter isAttrs isBool ;

  inherit (lib)
    concatStringsSep filterAttrs hasPrefix mapAttrs' mapAttrsToList
    mkDefault mkIf mkOption ;

  inherit (lib.types)
    attrsOf bool either enum int nullOr package path str submodule ;


  explicit = filterAttrs (n: v: n != "_module" && v != null);
  concatNonEmpty = sep: list: concatStringsSep sep (filter (s: s != "") list);

  default = d: t: mkOption { type = t; default = d; };
  readonly = d: t: mkOption { type = t; default = d; readOnly = true; };
  mandatory = t: mkOption { type = t; };
  optional = t: mkOption { type = nullOr t; default = null; };

  instances = explicit (config.nixsap.apps.php-fpm);

  users = mapAttrsToList (_: v: v.user) instances;

  mkLogRotate = name: cfg:
    let instance = "php-fpm-${name}";
    in {
      name = instance;
      value = {
        files = [ "${cfg.logDir}/*.log" ];
        directives = {
          delaycompress = mkDefault true;
          missingok = mkDefault true;
          notifempty = mkDefault true;
          rotate = mkDefault 14;
          sharedscripts = true;
          daily = mkDefault true;
          create = mkDefault "0640 ${cfg.user} ${cfg.user}";
          postrotate = pkgs.writeBashScript "logrotate-${instance}-postrotate"
            "systemctl kill -s SIGUSR1 --kill-who=main '${instance}.service'";
        };
      };
    };

  mkService = name: cfg:
    let
      show = v: if isBool v then (if v then "yes" else "no") else toString v;

      mkGroup = group: opts: main:
        let f = k: v: if k == main
                      then "${group} = ${show v}"
                      else "${group}.${k} = ${show v}";
        in concatNonEmpty "\n" (mapAttrsToList f (explicit opts));

      mkEnv = t: k: v: "${t}[${k}] = ${show v}";

      mkPool = k: v:
        if k == "listen" then mkGroup k v "socket"
        else if k == "env" || hasPrefix "php_" k then concatNonEmpty "\n" (mapAttrsToList (mkEnv k) v)
        else if k == "pm" then mkGroup k v "strategy"
        else if isAttrs v then mkGroup k v ""
        else "${k} = ${show v}";

      mkGlobal = k: v:
        if isAttrs v then mkGroup k v ""
        else "${k} = ${show v}";

      conf = pkgs.writeText "php-fpm-${name}.conf" ''
        [global]
        daemonize = no
        ${concatNonEmpty "\n" (mapAttrsToList mkGlobal (explicit cfg.global))}

        [pool]
        listen.mode = 0660
        ${concatNonEmpty "\n" (mapAttrsToList mkPool (explicit cfg.pool))}
      '';
      exec = "${cfg.package}/bin/php-fpm --fpm-config ${conf} "
           + ( if cfg.php-ini != null
               then "--php-ini ${cfg.php-ini}"
               else "--no-php-ini" );
    in {
      name = "php-fpm-${name}";
      value = {
        description = "PHP FastCGI Process Manager (${name})";
        after = [ "local-fs.target" ];
        wantedBy = [ "multi-user.target" ];
        preStart = ''
          mkdir -p -- '${cfg.home}' '${cfg.logDir}'
          rm -f    -- '${cfg.pool.listen.socket}'
          chown -Rc '${cfg.user}:${cfg.user}' -- '${cfg.home}'
          chmod -Rc u=rwX,g=rX,o= -- '${cfg.home}'
        '';
        serviceConfig = {
          ExecStart = exec;
          KillMode = "mixed";
          PermissionsStartOnly = true;
          Restart = "always";
          User = cfg.user;
        };
      };
    };

in {

  options.nixsap.apps.php-fpm = default {}
    (attrsOf (submodule( { config, name, ... }: {
      options = {
        home = mkOption {
          description = "Directory with logs and the socket";
          type = path;
          default = "/php-fpm/${name}";
        };
        logDir = mkOption {
          description = "Directory with logs. This is convenient read-only option";
          type = path;
          readOnly = true;
          default = "${config.home}/log";
        };
        user = mkOption {
          description = "User to run as";
          type = str;
          default = "php-fpm-${name}";
        };
        package = mkOption {
          description = "PHP package to use FPM from";
          type = package;
          default = pkgs.php;
        };
        php-ini = mkOption {
          description = "php.ini file to pass to php-fpm";
          type = nullOr path;
          default = null;
        };


        global = {
          emergency_restart_interval = optional int;
          emergency_restart_threshold = optional int;
          error_log = readonly "${config.logDir}/error.log" path;
          log_level = optional (enum ["alert" "error" "warning" "notice" "debug"]);
          process_control_timeout = optional int;
          rlimit_core = optional int;
          rlimit_files = optional int;

          process = {
            max      = optional int;
            priority = optional int;
          };
        };

        pool = {
          catch_workers_output      = optional bool;
          chdir                     = optional path;
          clear_env                 = optional bool;
          env                       = default {} (attrsOf str);
          php_admin_flag            = default {} (attrsOf bool);
          php_admin_value           = default {} (attrsOf (either str int));
          php_flag                  = default {} (attrsOf bool);
          php_value                 = default {} (attrsOf (either str int));
          request_terminate_timeout = optional int;
          rlimit_core               = optional int;
          rlimit_files              = optional int;
          listen = {
            acl_groups = optional str;
            backlog    = optional int;
            socket     = readonly "${config.home}/sock" path;
          };
          pm = {
            max_children      = mandatory int;
            max_requests      = optional int;
            max_spare_servers = optional int;
            min_spare_servers = optional int;
            start_servers     = optional int;
            status_path       = optional path;
            strategy          = mandatory (enum ["static" "ondemand" "dynamic"]);
          };
          ping = {
            path     = optional path;
            response = optional str;
          };
        };
      };
    })));

  config = mkIf ({} != instances) {
    nixsap.apps.logrotate.conf = mapAttrs' mkLogRotate instances;
    nixsap.system.users.daemons = users;
    systemd.services = mapAttrs' mkService instances;
  };
}