aboutsummaryrefslogtreecommitdiff
path: root/systems/eldiron/websites/cloud/farm.nix
blob: df24cba995a81c1cd0271663ed4d1f91d5bea76e (plain) (blame)
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
{ lib, pkgs, config, ... }:
let
  scfg = config.secrets.fullPaths;
  cfg = config.myServices.tools.cloud.farm;
  apacheUser = config.services.websites.env.production.user;
  apacheGroup = config.services.websites.env.production.group;
  additionalConfs = icfg: lib.attrsets.mapAttrs (n: v: pkgs.writeText "${n}.json" (builtins.toJSON v)) icfg.rootDir.otherConfig;
  overrideConfig = icfg: pkgs.writeText "override.config.php" ''
    <?php
    $CONFIG = json_decode(file_get_contents("${icfg.configOverride}"), TRUE);
  '';
  toVhost = icfg: ''
    SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
    SetEnv NEXTCLOUD_CONFIG_DIR "${icfg.varDir}/config"
    <Directory ${icfg.rootDir}>
      AcceptPathInfo On
      DirectoryIndex index.php
      Options FollowSymlinks
      Require all granted
      AllowOverride all

      <IfModule mod_headers.c>
        Header always set Strict-Transport-Security "max-age=15552000; includeSubDomains; preload"
      </IfModule>
      <FilesMatch "\.php$">
        CGIPassAuth on
        SetHandler "proxy:unix:${config.services.phpfpm.pools.${icfg.phpPoolName}.socket}|fcgi://localhost"
      </FilesMatch>

    </Directory>
    '';
in
{
  options.myServices.tools.cloud.farm = {
    instances = lib.mkOption {
      description = "Instances names for the nextcloud Farm";
      default = {};
      type = lib.types.attrsOf (lib.types.submodule ({ name, config, ... }: {
        options = {
          nextcloud = lib.mkOption {
            description = "Nextcloud version to use";
            default = pkgs.webapps-nextcloud_27;
            type = lib.types.package;
          };
          apps = lib.mkOption {
            description = "Applications to use";
            default = a: [];
            #type = functionTo (listOf packages)
            type = lib.types.unspecified;
          };
          config = lib.mkOption {
            description = "Config keys";
            default = {};
            type = lib.types.attrsOf lib.types.unspecified;
          };
          secretsPath = lib.mkOption {
            description = "Path in secrets to nextcloud config file";
            default = "websites/${name}/nextcloud";
            type = lib.types.str;
          };
          configOverride = lib.mkOption {
            description = "Path to config override";
            readOnly = true;
            default = scfg."${config.secretsPath}";
            type = lib.types.path;
          };
          phpPackage = lib.mkOption {
            description = "PHP package to use";
            default = pkgs.php81;
            type = lib.types.package;
            apply = v: (v.withExtensions({ enabled, all }: enabled ++ [ all.redis all.apcu all.opcache all.imagick all.sysvsem ])).override { extraConfig = ''
              apc.enable_cli = 1
              apc.enabled = 1
            '';
            };
          };
          rootDir = lib.mkOption {
            description = "Instance root dirs";
            readOnly = true;
            type = lib.types.package;
            default = config.nextcloud.withApps config.apps;
          };
          phpPoolName = lib.mkOption {
            description = "Php pool name for the instance";
            readOnly = true;
            type = lib.types.str;
            default = "nextcloud_farm_" + name;
          };
          phpBaseDir = lib.mkOption {
            description = "Php basedir for the instance";
            readOnly = true;
            type = lib.types.str;
            default = builtins.concatStringsSep ":" (
              [ config.rootDir config.varDir ]
              ++ config.rootDir.apps
              ++ [ config.configOverride (overrideConfig config) ]
              ++ (builtins.attrValues (additionalConfs config))
            );
          };
          varDir = lib.mkOption {
            description = "Instance var dir";
            type = lib.types.path;
            default = "/var/lib/nextcloud_farm/${name}";
          };
          vhost = lib.mkOption {
            description = "Instance vhost config";
            readOnly = true;
            type = lib.types.str;
            default = toVhost config;
          };
        };
      }));
    };
  };

  config = lib.mkIf (builtins.length (builtins.attrNames cfg.instances) > 0) {
    systemd.services = lib.mapAttrs' (k: v: lib.nameValuePair ("phpfpm-" + v.phpPoolName) {
      after = lib.mkAfter [ "postgresql.service" ];
      wants = [ "postgresql.service" ];
      serviceConfig.ExecStartPre =
        "+${pkgs.writeScript "phpfpm-nextcloud-${k}-pre-start" ''
          #!${pkgs.stdenv.shell}

          install -m 0755 -o wwwrun -g wwwrun -d ${v.varDir} -d ${v.varDir}/config
          ${builtins.concatStringsSep "\n" (lib.attrsets.mapAttrsToList (n: f:
            "ln -sf ${f} ${v.varDir}/config/${n}.json"
            ) (additionalConfs v))}
          ln -sf ${overrideConfig v} ${v.varDir}/config/override.config.php
        ''}";
    }) cfg.instances;
    services.phpfpm.pools = lib.mapAttrs' (k: v: lib.nameValuePair v.phpPoolName {
      user = apacheUser;
      group = apacheGroup;
      settings = {
        "listen.owner" = apacheUser;
        "listen.group" = apacheGroup;
        "pm" = "dynamic";
        "pm.max_children" = "60";
        "pm.start_servers" = "3";
        "pm.min_spare_servers" = "3";
        "pm.max_spare_servers" = "3";
        "pm.process_idle_timeout" = "60";

        "php_admin_value[output_buffering]" = "0";
        "php_admin_value[max_execution_time]" = "1800";
        "php_admin_value[zend_extension]" = "opcache";
        "php_value[apc.enable_cli]" = "1";
        "php_value[apc.enabled]" = "1";
        #already enabled by default?
        #"php_value[opcache.enable]" = "1";
        "php_value[opcache.enable_cli]" = "1";
        "php_value[opcache.interned_strings_buffer]" = "32";
        "php_value[opcache.max_accelerated_files]" = "10000";
        "php_value[opcache.memory_consumption]" = "128";
        "php_value[opcache.save_comments]" = "1";
        "php_value[opcache.revalidate_freq]" = "1";
        "php_admin_value[memory_limit]" = "512M";

        "php_admin_value[open_basedir]" = "/run/wrappers/bin/sendmail:${v.phpBaseDir}:/proc/cpuinfo:/proc/meminfo:/dev/urandom:/proc/self/fd:/tmp";
        "php_admin_value[session.save_handler]" = "redis";
        "php_admin_value[session.save_path]" = "'unix:///run/redis-php-sessions/redis.sock?persistent=1&prefix=Tools:NextcloudFarm:${k}:'";
      };
      phpPackage = v.phpPackage;
    }) cfg.instances;
    environment.systemPackages = let
      toOcc = name: icfg: pkgs.writeScriptBin "nextcloud-occ-${name}" ''
        #! ${pkgs.stdenv.shell}
        cd ${icfg.rootDir}
        NEXTCLOUD_CONFIG_DIR="${icfg.varDir}/config" \
          exec \
          sudo -E -u wwwrun ${icfg.phpPackage}/bin/php \
          -d memory_limit=512M \
          -c ${icfg.phpPackage}/etc/php.ini \
          occ $*
        '';
      in lib.mapAttrsToList toOcc cfg.instances;
    services.cron = {
      enable = true;
      systemCronJobs = let
        toScript = name: icfg: pkgs.writeScriptBin "nextcloud-cron" ''
          #! ${pkgs.stdenv.shell}
          export LOCALE_ARCHIVE=/run/current-system/sw/lib/locale/locale-archive
          export PATH=/run/wrappers/bin:$PATH
          export NEXTCLOUD_CONFIG_DIR="${icfg.varDir}/config"
          ${icfg.phpPackage}/bin/php -c ${icfg.phpPackage}/etc/php.ini -d memory_limit=512M -f ${icfg.rootDir}/cron.php
          '';
        toLine = name: icfg: ''
          */5 * * * * wwwrun ${toScript name icfg}/bin/nextcloud-cron
          '';
        in lib.mapAttrsToList toLine cfg.instances;
    };

    secrets.keys = lib.mapAttrs' (name: v: lib.nameValuePair "${v.secretsPath}" {
      user = "wwwrun";
      group = "wwwrun";
      permissions = "0600";
      # Be careful when editing that: config from this file takes
      # precedence over the regular one, but if a key got removed, it my
      # still exist in the default config file
      text = builtins.toJSON ( {
        "datadirectory" = if name == "immae" then v.varDir else "${v.varDir}/data";

        "appstoreenabled" = false;
        "integrity.check.disabled" = true;
        "updater.release.channel" = "stable";
        "upgrade.disable-web" = true;

        "memcache.local" = "\\OC\\Memcache\\APCu";

        "htaccess.RewriteBase" = "/";

        "loglevel" = 2;
        "logtimezone" = "Europe/Paris";

        "default_phone_region" = "FR";
        "skeletondirectory" = "";
        "theme" = "";
      } // v.config);
    }) cfg.instances;
  };
}