about summary refs log tree commit diff
path: root/nixos/modules/services/web-apps/pretalx.nix
blob: b062a8b7eeeac59e455ae19d48bb0734464b7a42 (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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
{ config
, lib
, pkgs
, utils
, ...
}:

let
  cfg = config.services.pretalx;
  format = pkgs.formats.ini { };

  configFile = format.generate "pretalx.cfg" cfg.settings;

  extras = cfg.package.optional-dependencies.redis
    ++ lib.optionals (cfg.settings.database.backend == "mysql") cfg.package.optional-dependencies.mysql
    ++ lib.optionals (cfg.settings.database.backend == "postgresql") cfg.package.optional-dependencies.postgres;

  pythonEnv = cfg.package.python.buildEnv.override {
    extraLibs = [ (cfg.package.python.pkgs.toPythonModule cfg.package) ]
      ++ (with cfg.package.python.pkgs; [ gunicorn ]
      ++ lib.optional cfg.celery.enable celery) ++ extras;
  };
in

{
  meta = with lib; {
    maintainers = teams.c3d2.members;
  };

  options.services.pretalx = {
    enable = lib.mkEnableOption "pretalx";

    package = lib.mkPackageOptionMD pkgs "pretalx" {};

    group = lib.mkOption {
      type = lib.types.str;
      default = "pretalx";
      description = "Group under which pretalx should run.";
    };

    user = lib.mkOption {
      type = lib.types.str;
      default = "pretalx";
      description = "User under which pretalx should run.";
    };

    gunicorn.extraArgs = lib.mkOption {
      type = with lib.types; listOf str;
      default = [
        "--name=pretalx"
      ];
      example = [
        "--name=pretalx"
        "--workers=4"
        "--max-requests=1200"
        "--max-requests-jitter=50"
        "--log-level=info"
      ];
      description = ''
        Extra arguments to pass to gunicorn.
        See <https://docs.pretalx.org/administrator/installation.html#step-6-starting-pretalx-as-a-service> for details.
      '';
      apply = lib.escapeShellArgs;
    };

    celery = {
      enable = lib.mkOption {
        type = lib.types.bool;
        default = true;
        example = false;
        description = ''
          Whether to set up celery as an asynchronous task runner.
        '';
      };

      extraArgs = lib.mkOption {
        type = with lib.types; listOf str;
        default = [ ];
        description = ''
          Extra arguments to pass to celery.

          See <https://docs.celeryq.dev/en/stable/reference/cli.html#celery-worker> for more info.
        '';
        apply = utils.escapeSystemdExecArgs;
      };
    };

    nginx = {
      enable = lib.mkOption {
        type = lib.types.bool;
        default = true;
        example = false;
        description = ''
          Whether to set up an nginx virtual host.
        '';
      };

      domain = lib.mkOption {
        type = lib.types.str;
        example = "talks.example.com";
        description = ''
          The domain name under which to set up the virtual host.
        '';
      };
    };

    database.createLocally = lib.mkOption {
      type = lib.types.bool;
      default = true;
      example = false;
      description = ''
        Whether to automatically set up the database on the local DBMS instance.

        Currently only supported for PostgreSQL. Not required for sqlite.
      '';
    };

    settings = lib.mkOption {
      type = lib.types.submodule {
        freeformType = format.type;
        options = {
          database = {
            backend = lib.mkOption {
              type = lib.types.enum [
                "postgresql"
              ];
              default = "postgresql";
              description = ''
                Database backend to use.

                Currently only PostgreSQL gets tested, and as such we don't support any other DBMS.
              '';
              readOnly = true; # only postgres supported right now
            };

            host = lib.mkOption {
              type = with lib.types; nullOr types.path;
              default = if cfg.settings.database.backend == "postgresql" then "/run/postgresql"
                else if cfg.settings.database.backend == "mysql" then "/run/mysqld/mysqld.sock"
                else null;
              defaultText = lib.literalExpression ''
                if config.services.pretalx.settings..database.backend == "postgresql" then "/run/postgresql"
                else if config.services.pretalx.settings.database.backend == "mysql" then "/run/mysqld/mysqld.sock"
                else null
              '';
              description = ''
                Database host or socket path.
              '';
            };

            name = lib.mkOption {
              type = lib.types.str;
              default = "pretalx";
              description = ''
                Database name.
              '';
            };

            user = lib.mkOption {
              type = lib.types.str;
              default = "pretalx";
              description = ''
                Database username.
              '';
            };
          };

          filesystem = {
            data = lib.mkOption {
              type = lib.types.path;
              default = "/var/lib/pretalx";
              description = ''
                Base path for all other storage paths.
              '';
            };
            logs = lib.mkOption {
              type = lib.types.path;
              default = "/var/log/pretalx";
              description = ''
                Path to the log directory, that pretalx logs message to.
              '';
            };
            static = lib.mkOption {
              type = lib.types.path;
              default = "${cfg.package.static}/";
              defaultText = lib.literalExpression "\${config.services.pretalx.package}.static}/";
              readOnly = true;
              description = ''
                Path to the directory that contains static files.
              '';
            };
          };

          celery = {
            backend = lib.mkOption {
              type = with lib.types; nullOr str;
              default = lib.optionalString cfg.celery.enable "redis+socket://${config.services.redis.servers.pretalx.unixSocket}?virtual_host=1";
              defaultText = lib.literalExpression ''
                optionalString config.services.pretalx.celery.enable "redis+socket://''${config.services.redis.servers.pretalx.unixSocket}?virtual_host=1"
              '';
              description = ''
                URI to the celery backend used for the asynchronous job queue.
              '';
            };

            broker = lib.mkOption {
              type = with lib.types; nullOr str;
              default = lib.optionalString cfg.celery.enable "redis+socket://${config.services.redis.servers.pretalx.unixSocket}?virtual_host=2";
              defaultText = lib.literalExpression ''
                optionalString config.services.pretalx.celery.enable "redis+socket://''${config.services.redis.servers.pretalx.unixSocket}?virtual_host=2"
              '';
              description = ''
                URI to the celery broker used for the asynchronous job queue.
              '';
            };
          };

          redis = {
            location = lib.mkOption {
              type = with lib.types; nullOr str;
              default = "unix://${config.services.redis.servers.pretalx.unixSocket}?db=0";
              defaultText = lib.literalExpression ''
                "unix://''${config.services.redis.servers.pretalx.unixSocket}?db=0"
              '';
              description = ''
                URI to the redis server, used to speed up locking, caching and session storage.
              '';
            };

            session = lib.mkOption {
              type = lib.types.bool;
              default = true;
              example = false;
              description = ''
                Whether to use redis as the session storage.
              '';
            };
          };

          site = {
            url = lib.mkOption {
              type = lib.types.str;
              default = "https://${cfg.nginx.domain}";
              defaultText = lib.literalExpression "https://\${config.services.pretalx.nginx.domain}";
              example = "https://talks.example.com";
              description = ''
                The base URI below which your pretalx instance will be reachable.
              '';
            };
          };
        };
      };
      default = { };
      description = ''
        pretalx configuration as a Nix attribute set. All settings can also be passed
        from the environment.

        See <https://docs.pretalx.org/administrator/configure.html> for possible options.
      '';
    };
  };

  config = lib.mkIf cfg.enable {
    # https://docs.pretalx.org/administrator/installation.html

    environment.systemPackages = [
      (pkgs.writeScriptBin "pretalx-manage" ''
        cd ${cfg.settings.filesystem.data}
        sudo=exec
        if [[ "$USER" != ${cfg.user} ]]; then
          sudo='exec /run/wrappers/bin/sudo -u ${cfg.user} --preserve-env=PRETALX_CONFIG_FILE'
        fi
        export PRETALX_CONFIG_FILE=${configFile}
        $sudo ${lib.getExe' pythonEnv "pretalx-manage"} "$@"
      '')
    ];

    services = {
      nginx = lib.mkIf cfg.nginx.enable {
        enable = true;
        recommendedGzipSettings = lib.mkDefault true;
        recommendedOptimisation = lib.mkDefault true;
        recommendedProxySettings = lib.mkDefault true;
        recommendedTlsSettings = lib.mkDefault true;
        upstreams.pretalx.servers."unix:/run/pretalx/pretalx.sock" = { };
        virtualHosts.${cfg.nginx.domain} = {
          # https://docs.pretalx.org/administrator/installation.html#step-7-ssl
          extraConfig = ''
            more_set_headers "Referrer-Policy: same-origin";
            more_set_headers "X-Content-Type-Options: nosniff";
          '';
          locations = {
            "/".proxyPass = "http://pretalx";
            "/media/" = {
              alias = "${cfg.settings.filesystem.data}/media/";
              extraConfig = ''
                access_log off;
                more_set_headers 'Content-Disposition: attachment; filename="$1"';
                expires 7d;
              '';
            };
            "/static/" = {
              alias = cfg.settings.filesystem.static;
              extraConfig = ''
                access_log off;
                more_set_headers Cache-Control "public";
                expires 365d;
              '';
            };
          };
        };
      };

      postgresql = lib.mkIf (cfg.database.createLocally && cfg.settings.database.backend == "postgresql") {
        enable = true;
        ensureUsers = [ {
          name = cfg.settings.database.user;
          ensureDBOwnership = true;
        } ];
        ensureDatabases = [ cfg.settings.database.name ];
      };

      redis.servers.pretalx.enable = true;
    };

    systemd.services = let
      commonUnitConfig = {
        environment.PRETALX_CONFIG_FILE = configFile;
        serviceConfig = {
          User = "pretalx";
          Group = "pretalx";
          StateDirectory = [ "pretalx" "pretalx/media" ];
          LogsDirectory = "pretalx";
          WorkingDirectory = cfg.settings.filesystem.data;
          SupplementaryGroups = [ "redis-pretalx" ];
        };
      };
    in {
      pretalx-web = lib.recursiveUpdate commonUnitConfig {
        description = "pretalx web service";
        after = [
          "network.target"
          "redis-pretalx.service"
        ] ++ lib.optionals (cfg.settings.database.backend == "postgresql") [
          "postgresql.service"
        ] ++ lib.optionals (cfg.settings.database.backend == "mysql") [
          "mysql.service"
        ];
        wantedBy = [ "multi-user.target" ];
        preStart = ''
          versionFile="${cfg.settings.filesystem.data}/.version"
          version=$(cat "$versionFile" 2>/dev/null || echo 0)

          if [[ $version != ${cfg.package.version} ]]; then
            ${lib.getExe' pythonEnv "pretalx-manage"} migrate

            echo "${cfg.package.version}" > "$versionFile"
          fi
        '';
        serviceConfig = {
          ExecStart = "${lib.getExe' pythonEnv "gunicorn"} --bind unix:/run/pretalx/pretalx.sock ${cfg.gunicorn.extraArgs} pretalx.wsgi";
          RuntimeDirectory = "pretalx";
        };
      };

      pretalx-periodic = lib.recursiveUpdate commonUnitConfig {
        description = "pretalx periodic task runner";
        # every 15 minutes
        startAt = [ "*:3,18,33,48" ];
        serviceConfig = {
          Type = "oneshot";
          ExecStart = "${lib.getExe' pythonEnv "pretalx-manage"} runperiodic";
        };
      };

      pretalx-clear-sessions = lib.recursiveUpdate commonUnitConfig {
        description = "pretalx session pruning";
        startAt = [ "monthly" ];
        serviceConfig = {
          Type = "oneshot";
          ExecStart = "${lib.getExe' pythonEnv "pretalx-manage"} clearsessions";
        };
      };

      pretalx-worker = lib.mkIf cfg.celery.enable (lib.recursiveUpdate commonUnitConfig {
        description = "pretalx asynchronous job runner";
        after = [
          "network.target"
          "redis-pretalx.service"
        ] ++ lib.optionals (cfg.settings.database.backend == "postgresql") [
          "postgresql.service"
        ] ++ lib.optionals (cfg.settings.database.backend == "mysql") [
          "mysql.service"
        ];
        wantedBy = [ "multi-user.target" ];
        serviceConfig.ExecStart = "${lib.getExe' pythonEnv "celery"} -A pretalx.celery_app worker ${cfg.celery.extraArgs}";
      });
    };

    systemd.sockets.pretalx-web.socketConfig = {
      ListenStream = "/run/pretalx/pretalx.sock";
      SocketUser = "nginx";
    };

    users = {
      groups."${cfg.group}" = {};
      users."${cfg.user}" = {
        isSystemUser = true;
        createHome = true;
        home = cfg.settings.filesystem.data;
        inherit (cfg) group;
      };
    };
  };
}