summaryrefslogtreecommitdiff
path: root/modules/pgbackrest.nix
blob: cc865bca44170890a83ddf90fc861412483e7660 (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
{ config, pkgs, lib, utils, ... }:

with utils;
with lib;

let
  cfg = config.services.pgbackrest;
  settingsFormat = pkgs.formats.ini {
    listsAsDuplicateKeys = true;
    mkKeyValue = lib.generators.mkKeyValueDefault {
      mkValueString = v: with builtins;
        let err = t: v: abort
              ("mkValueString: " +
               "${t} not supported: ${toPretty {} v}");
        in   if isInt      v then toString v
        # convert derivations to store paths
        else if lib.isDerivation v then toString v
        # we default to not quoting strings
        else if isString   v then v
        # isString returns "1", which is not a good default
        else if true  ==   v then "y"
        # here it returns to "", which is even less of a good default
        else if false ==   v then "n"
        else if null  ==   v then "null"
        # if you have lists you probably want to replace this
        else if isList     v then err "lists" v
        # same as for lists, might want to replace
        else if isAttrs    v then err "attrsets" v
        # functions can’t be printed of course
        else if isFunction v then err "functions" v
        # Floats currently can't be converted to precise strings,
        # condition warning on nix version once this isn't a problem anymore
        # See https://github.com/NixOS/nix/pull/3480
        else if isFloat    v then libStr.floatToString v
        else err "this value is" (toString v);
    } "=";
  };

  loglevelType = types.enum ["off" "error" "warn" "info" "detail" "debug" "trace"];
  inherit (utils.systemdUtils.unitOptions) unitOption;
in {
  options = {
    services.pgbackrest = {
      enable = mkEnableOption "pgBackRest";

      package = mkPackageOption pkgs "pgbackrest" {};

      configurePostgresql = {
        enable = mkEnableOption "configuring PostgreSQL for sending WAL to pgBackRest" // {
          default = config.services.postgresql.enable;
          defaultText = literalExpression "config.systemd.services.postgresql.enable";
        };

        stanza = mkOption {
          type = types.str;
          default = config.networking.hostName;
          defaultText = literalExpression "config.networking.hostName";
        };
      };

      settings = mkOption {
        type = types.submodule {
          freeformType = settingsFormat.type;

          options = {
            global.log-level-console = mkOption {
              type = loglevelType;
              default = "detail";
            };
            global.log-level-file = mkOption {
              type = loglevelType;
              default = "off";
            };
            global.log-level-stderr = mkOption {
              type = loglevelType;
              default = "warn";
            };

            global.log-subprocess = mkOption {
              type = types.bool;
              default = true;
            };
            global.log-timestamp = mkOption {
              type = types.bool;
              default = false;
            };
          };
        };
        default = {};
        description = ''
          Configuration for pgBackRest
        '';
      };

      tlsServer = {
        enable = mkEnableOption "pgBackRest TLS Server";

        user = mkOption {
          type = types.str;
          default = "postgres";
        };
        group = mkOption {
          type = types.str;
          default = "postgres";
        };
      };

      backups = mkOption {
        type = types.attrsOf (types.submodule ({ name, ... }: {
          options = {
            type = mkOption {
              type = types.enum ["full" "incr" "diff"];
              default = "full";
            };

            stanza = mkOption {
              type = types.str;
              default = cfg.configurePostgresql.stanza;
              defaultText = literalExpression "config.services.pgbackrest.configurePostgresql.stanza";
            };
            repo = mkOption {
              type = types.nullOr (types.strMatching "^[0-9]+$");
            };

            user = mkOption {
              type = types.str;
              default = "postgres";
            };
            group = mkOption {
              type = types.str;
              default = "postgres";
            };

            timerConfig = mkOption {
              type = types.attrsOf unitOption;
            };
          };
        }));
        default = {};
      };
    };
  };

  config = mkIf cfg.enable {
    environment.systemPackages = [ cfg.package ];

    services.postgresql.settings = mkIf cfg.configurePostgresql.enable {
      archive_command = "pgbackrest --stanza ${escapeSystemdExecArg cfg.configurePostgresql.stanza} archive-push %p";
      archive_mode = true;
      max_wal_senders = mkDefault 3;
      wal_level = "replica";
    };

    systemd.services = {
      postgresql.path = mkIf cfg.configurePostgresql.enable [ cfg.package ];
      pgbackrest-tls-server = mkIf cfg.tlsServer.enable {
        description = "pgBackRest TLS-Server";
        wantedBy = [ "multi-user.target" ];
        after = [ "network.target" ];

        restartTriggers = [ config.environment.etc."pgbackrest/pgbackrest.conf".source ];

        unitConfig = {
          StartLimitIntervalSec = 0;
        };

        serviceConfig = {
          Type = "simple";
          Restart = "always";
          RestartSec = 1;
          User = cfg.tlsServer.user;
          Group = cfg.tlsServer.group;
          ExecStart = "${cfg.package}/bin/pgbackrest server";
          ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";

          Environment = [
            "LD_PRELOAD=${pkgs.libdscp}/lib/libdscp.so"
            "DSCP=8"
          ];
        };
      };
    } // mapAttrs' (name: backupCfg: nameValuePair "pgbackrest-backup@${escapeSystemdPath name}" {
      description = "Perform pgBackRest Backup (${name}${optionalString (!(isNull backupCfg.repo)) " repo${backupCfg.repo}"})";
      serviceConfig = {
        Type = "oneshot";
        ExecStart = "${cfg.package}/bin/pgbackrest --type ${escapeSystemdExecArg backupCfg.type} --stanza ${escapeSystemdExecArg backupCfg.stanza}${optionalString (!(isNull backupCfg.repo)) " --repo ${backupCfg.repo}"} backup";
        User = backupCfg.user;
        Group = backupCfg.group;
        Restart = "on-failure";
        RestartSec = "5min";

        Environment = [
          "LD_PRELOAD=${pkgs.libdscp}/lib/libdscp.so"
          "DSCP=8"
        ];
      };
    }) cfg.backups;

    systemd.timers = mapAttrs' (name: backupCfg: nameValuePair "pgbackrest-backup@${escapeSystemdPath name}" {
      wantedBy = [ "timers.target" ];
      inherit (backupCfg) timerConfig;
    }) cfg.backups;

    environment.etc."pgbackrest/pgbackrest.conf".source = settingsFormat.generate "pgbackrest.conf" cfg.settings;
  };
}