summaryrefslogtreecommitdiffstats
path: root/nixos/modules/services/backup/pgbackrest.nix
blob: 7d39abc1975b69fac5cd74f0eba1336a97afe04a (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
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
{
  config,
  lib,
  pkgs,
  ...
}:

let
  cfg = config.services.pgbackrest;

  settingsFormat = pkgs.formats.ini {
    listsAsDuplicateKeys = true;
  };

  # pgBackRest "options"
  settingsType =
    with lib.types;
    attrsOf (oneOf [
      bool
      ints.unsigned
      str
      (attrsOf str)
      (listOf str)
    ]);

  # Applied to both repoNNN-* and pgNNN-* options in global and stanza sections.
  flattenWithIndex =
    attrs: prefix:
    lib.concatMapAttrs (
      name:
      let
        index = lib.lists.findFirstIndex (n: n == name) null (lib.attrNames attrs);
        index1 = index + 1;
      in
      lib.mapAttrs' (option: lib.nameValuePair "${prefix}${toString index1}-${option}")
    ) attrs;

  # Remove nulls, turn attrsets into lists and bools into y/n
  normalize =
    x:
    lib.pipe x [
      (lib.filterAttrs (_: v: v != null))
      (lib.mapAttrs (_: v: if lib.isAttrs v then lib.mapAttrsToList (n': v': "${n'}=${v'}") v else v))
      (lib.mapAttrs (
        _: v:
        if v == true then
          "y"
        else if v == false then
          "n"
        else
          v
      ))
    ];

  fullConfig = {
    global = normalize (cfg.settings // flattenWithIndex cfg.repos "repo");
  }
  // lib.mapAttrs' (
    cmd: settings: lib.nameValuePair "global:${cmd}" (normalize settings)
  ) cfg.commands
  // lib.mapAttrs (
    _: cfg': normalize (cfg'.settings // flattenWithIndex cfg'.instances "pg")
  ) cfg.stanzas;

  namedJobs = lib.listToAttrs (
    lib.flatten (
      lib.mapAttrsToList (
        stanza:
        { jobs, ... }:
        lib.mapAttrsToList (
          job: attrs: lib.nameValuePair "pgbackrest-${stanza}-${job}" (attrs // { inherit stanza job; })
        ) jobs
      ) cfg.stanzas
    )
  );

  disabledOption = lib.mkOption {
    default = null;
    readOnly = true;
    internal = true;
  };

  secretPathOption =
    with lib.types;
    lib.mkOption {
      type = nullOr externalPath;
      default = null;
      internal = true;
    };
in

{
  # TODO: Add enableServer option and corresponding pgBackRest TLS server service.
  # TODO: Write wrapper around pgbackrest to turn --repo=<name> into --repo=<number>
  # The following two are dependent on improvements upstream:
  #   https://github.com/pgbackrest/pgbackrest/issues/2621
  # TODO: Add support for more repository types
  # TODO: Support passing encryption key safely
  options.services.pgbackrest = {
    enable = lib.mkEnableOption "pgBackRest";

    repos = lib.mkOption {
      type =
        with lib.types;
        attrsOf (
          submodule (
            { config, name, ... }:
            let
              setHostForType =
                type:
                if name == "localhost" then
                  null
                # "posix" is the default repo type, which uses the -host option.
                # Other types use prefixed options, for example -sftp-host.
                else if config.type or "posix" != type then
                  null
                else
                  name;
            in
            {
              freeformType = settingsType;

              options.host = lib.mkOption {
                type = nullOr str;
                default = setHostForType "posix";
                defaultText = lib.literalExpression "name";
                description = "Repository host when operating remotely";
              };

              options.sftp-host = lib.mkOption {
                type = nullOr str;
                default = setHostForType "sftp";
                defaultText = lib.literalExpression "name";
                description = "SFTP repository host";
              };

              options.sftp-private-key-file = lib.mkOption {
                type = nullOr externalPath;
                default = null;
                description = ''
                  SFTP private key file.

                  The file must be accessible by both the pgbackrest and the postgres users.
                '';
              };

              # The following options should not be used; they would store secrets in the store.
              options.azure-key = disabledOption;
              options.cipher-pass = disabledOption;
              options.s3-key = disabledOption;
              options.s3-key-secret = disabledOption;
              options.s3-kms-key-id = disabledOption; # unsure whether that's a secret or not
              options.s3-sse-customer-key = disabledOption; # unsure whether that's a secret or not
              options.s3-token = disabledOption;
              options.sftp-private-key-passphrase = disabledOption;

              # The following options are not fully supported / tested, yet, but point to files with secrets.
              # Users can already set those options, but we'll force non-store paths.
              options.gcs-key = secretPathOption;
              options.host-cert-file = secretPathOption;
              options.host-key-file = secretPathOption;
            }
          )
        );
      default = { };
      description = ''
        An attribute set of repositories as described in:
        <https://pgbackrest.org/configuration.html#section-repository>

        Each repository defaults to set `repo-host` to the attribute's name.
        The special value "localhost" will unset `repo-host`.

        ::: {.note}
        The prefix `repoNNN-` is added automatically.
        Example: Use `path` instead of `repo1-path`.
        :::
      '';
      example = lib.literalExpression ''
        {
          localhost.path = "/var/lib/backup";
          "backup.example.com".host-type = "tls";
        }
      '';
    };

    stanzas = lib.mkOption {
      type =
        with lib.types;
        attrsOf (submodule {
          options = {
            jobs = lib.mkOption {
              type = lib.types.attrsOf (
                lib.types.submodule {
                  options.schedule = lib.mkOption {
                    type = lib.types.str;
                    description = ''
                      When or how often the backup should run.
                      Must be in the format described in {manpage}`systemd.time(7)`.
                    '';
                  };

                  options.type = lib.mkOption {
                    type = lib.types.str;
                    description = ''
                      Backup type as described in:
                      <https://pgbackrest.org/command.html#command-backup/category-command/option-type>
                    '';
                  };
                }
              );
              default = { };
              description = ''
                Backups jobs to schedule for this stanza as described in:
                <https://pgbackrest.org/user-guide.html#quickstart/schedule-backup>
              '';
              example = lib.literalExpression ''
                {
                  weekly = { schedule = "Sun, 6:30"; type = "full"; };
                  daily = { schedule = "Mon..Sat, 6:30"; type = "diff"; };
                }
              '';
            };

            instances = lib.mkOption {
              type =
                with lib.types;
                attrsOf (
                  submodule (
                    { name, ... }:
                    {
                      freeformType = settingsType;
                      options.host = lib.mkOption {
                        type = nullOr str;
                        default = if name == "localhost" then null else name;
                        defaultText = lib.literalExpression ''if name == "localhost" then null else name'';
                        description = "PostgreSQL host for operating remotely.";
                      };

                      # The following options are not fully supported / tested, yet, but point to files with secrets.
                      # Users can already set those options, but we'll force non-store paths.
                      options.host-cert-file = secretPathOption;
                      options.host-key-file = secretPathOption;
                    }
                  )
                );
              default = { };
              description = ''
                An attribute set of database instances as described in:
                <https://pgbackrest.org/configuration.html#section-stanza>

                Each instance defaults to set `pg-host` to the attribute's name.
                The special value "localhost" will unset `pg-host`.

                ::: {.note}
                The prefix `pgNNN-` is added automatically.
                Example: Use `user` instead of `pg1-user`.
                :::
              '';
              example = lib.literalExpression ''
                {
                  localhost.database = "app";
                  "postgres.example.com".port = "5433";
                }
              '';
            };

            settings = lib.mkOption {
              type = lib.types.submodule {
                freeformType = settingsType;

                # The following options are not fully supported / tested, yet, but point to files with secrets.
                # Users can already set those options, but we'll force non-store paths.
                options.tls-server-cert-file = secretPathOption;
                options.tls-server-key-file = secretPathOption;
              };
              default = { };
              description = ''
                An attribute set of options as described in:
                <https://pgbackrest.org/configuration.html>

                All options can be used.
                Repository options should be set via [`repos`](#opt-services.pgbackrest.repos) instead.
                Stanza options should be set via [`instances`](#opt-services.pgbackrest.stanzas._name_.instances) instead.
              '';
              example = lib.literalExpression ''
                {
                  process-max = 2;
                }
              '';
            };
          };
        });
      default = { };
      description = ''
        An attribute set of stanzas as described in:
        <https://pgbackrest.org/user-guide.html#quickstart/configure-stanza>
      '';
    };

    settings = lib.mkOption {
      type = lib.types.submodule {
        freeformType = settingsType;

        # The following options are not fully supported / tested, yet, but point to files with secrets.
        # Users can already set those options, but we'll force non-store paths.
        options.tls-server-cert-file = secretPathOption;
        options.tls-server-key-file = secretPathOption;
      };
      default = { };
      description = ''
        An attribute set of options as described in:
        <https://pgbackrest.org/configuration.html>

        All globally available options, i.e. all except stanza options, can be used.
        Repository options should be set via [`repos`](#opt-services.pgbackrest.repos) instead.
      '';
      example = lib.literalExpression ''
        {
          process-max = 2;
        }
      '';
    };

    commands =
      lib.genAttrs
        [
          # List of commands from https://pgbackrest.org/command.html:
          "annotate"
          "archive-get"
          "archive-push"
          "backup"
          "check"
          "expire"
          "help"
          "info"
          "repo-get"
          "repo-ls"
          "restore"
          "server"
          "server-ping"
          "stanza-create"
          "stanza-delete"
          "stanza-upgrade"
          "start"
          "stop"
          "verify"
          "version"
        ]
        (
          command:
          lib.mkOption {
            type = lib.types.submodule {
              freeformType = settingsType;

              # The following options are not fully supported / tested, yet, but point to files with secrets.
              # Users can already set those options, but we'll force non-store paths.
              options.tls-server-cert-file = secretPathOption;
              options.tls-server-key-file = secretPathOption;
            };
            default = { };
            description = ''
              Options for the '${command}' command.

              An attribute set of options as described in:
              <https://pgbackrest.org/configuration.html>

              All globally available options, i.e. all except stanza options, can be used.
              Repository options should be set via [`repos`](#opt-services.pgbackrest.repos) instead.
            '';
          }
        );
  };

  config = lib.mkIf cfg.enable (
    lib.mkMerge [
      {
        services.pgbackrest.settings = {
          log-level-console = lib.mkDefault "info";
          log-level-file = lib.mkDefault "off";
          cmd-ssh = lib.getExe pkgs.openssh;
        };

        environment.systemPackages = [ pkgs.pgbackrest ];
        environment.etc."pgbackrest/pgbackrest.conf".source =
          settingsFormat.generate "pgbackrest.conf" fullConfig;

        users.users.pgbackrest = {
          name = "pgbackrest";
          group = "pgbackrest";
          description = "pgBackRest service user";
          isSystemUser = true;
          useDefaultShell = true;
          createHome = true;
          home = cfg.repos.localhost.path or "/var/lib/pgbackrest";
        };
        users.groups.pgbackrest = { };

        systemd.services = lib.mapAttrs (
          _:
          {
            stanza,
            job,
            type,
            ...
          }:
          {
            description = "pgBackRest job ${job} for stanza ${stanza}";

            serviceConfig = {
              User = "pgbackrest";
              Group = "pgbackrest";
              Type = "oneshot";
              # stanza-create is idempotent, so safe to always run
              ExecStartPre = "${lib.getExe pkgs.pgbackrest} --stanza='${stanza}' stanza-create";
              ExecStart = "${lib.getExe pkgs.pgbackrest} --stanza='${stanza}' backup --type='${type}'";
            };
          }
        ) namedJobs;

        systemd.timers = lib.mapAttrs (
          name:
          {
            stanza,
            job,
            schedule,
            ...
          }:
          {
            description = "pgBackRest job ${job} for stanza ${stanza}";
            wantedBy = [ "timers.target" ];
            after = [ "network-online.target" ];
            wants = [ "network-online.target" ];
            timerConfig = {
              OnCalendar = schedule;
              Persistent = true;
              Unit = "${name}.service";
            };
          }
        ) namedJobs;
      }

      # The default stanza is set up for the local postgresql instance.
      # It does not backup automatically, the systemd timer still needs to be set.
      (lib.mkIf config.services.postgresql.enable {
        services.pgbackrest.stanzas.default = {
          settings.cmd = lib.getExe pkgs.pgbackrest;
          instances.localhost = {
            path = config.services.postgresql.dataDir;
            user = "postgres";
          };
        };
        # If PostgreSQL runs on the same machine, any restore will have to be done with that user.
        # Keeping the lock file in a directory writeable by the postgres user prevents errors.
        services.pgbackrest.commands.restore.lock-path = "/tmp/postgresql";
        services.postgresql.identMap = ''
          postgres pgbackrest postgres
        '';
        services.postgresql.initdbArgs = [ "--allow-group-access" ];
        users.users.pgbackrest.extraGroups = [ "postgres" ];

        services.postgresql.settings = {
          archive_command = ''${lib.getExe pkgs.pgbackrest} --stanza=default archive-push "%p"'';
          archive_mode = lib.mkDefault "on";
        };
        users.groups.pgbackrest.members = [ "postgres" ];
      })
    ]
  );
}