about summary refs log tree commit diff
path: root/nixos/modules/services/cluster/patroni/default.nix
blob: 5ab016a9f59f0ad031ab67e2a55d25cabfffa8d9 (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
{ config, lib, pkgs, ... }:
with lib;
let
  cfg = config.services.patroni;
  defaultUser = "patroni";
  defaultGroup = "patroni";
  format = pkgs.formats.yaml { };

  configFileName = "patroni-${cfg.scope}-${cfg.name}.yaml";
  configFile = format.generate configFileName cfg.settings;
in
{
  options.services.patroni = {

    enable = mkEnableOption (lib.mdDoc "Patroni");

    postgresqlPackage = mkOption {
      type = types.package;
      example = literalExpression "pkgs.postgresql_14";
      description = mdDoc ''
        PostgreSQL package to use.
        Plugins can be enabled like this `pkgs.postgresql_14.withPackages (p: [ p.pg_safeupdate p.postgis ])`.
      '';
    };

    postgresqlDataDir = mkOption {
      type = types.path;
      defaultText = literalExpression ''"/var/lib/postgresql/''${config.services.patroni.postgresqlPackage.psqlSchema}"'';
      example = "/var/lib/postgresql/14";
      default = "/var/lib/postgresql/${cfg.postgresqlPackage.psqlSchema}";
      description = mdDoc ''
        The data directory for PostgreSQL. If left as the default value
        this directory will automatically be created before the PostgreSQL server starts, otherwise
        the sysadmin is responsible for ensuring the directory exists with appropriate ownership
        and permissions.
      '';
    };

    postgresqlPort = mkOption {
      type = types.port;
      default = 5432;
      description = mdDoc ''
        The port on which PostgreSQL listens.
      '';
    };

    user = mkOption {
      type = types.str;
      default = defaultUser;
      example = "postgres";
      description = mdDoc ''
        The user for the service. If left as the default value this user will automatically be created,
        otherwise the sysadmin is responsible for ensuring the user exists.
      '';
    };

    group = mkOption {
      type = types.str;
      default = defaultGroup;
      example = "postgres";
      description = mdDoc ''
        The group for the service. If left as the default value this group will automatically be created,
        otherwise the sysadmin is responsible for ensuring the group exists.
      '';
    };

    dataDir = mkOption {
      type = types.path;
      default = "/var/lib/patroni";
      description = mdDoc ''
        Folder where Patroni data will be written, used by Raft as well if enabled.
      '';
    };

    scope = mkOption {
      type = types.str;
      example = "cluster1";
      description = mdDoc ''
        Cluster name.
      '';
    };

    name = mkOption {
      type = types.str;
      example = "node1";
      description = mdDoc ''
        The name of the host. Must be unique for the cluster.
      '';
    };

    namespace = mkOption {
      type = types.str;
      default = "/service";
      description = mdDoc ''
        Path within the configuration store where Patroni will keep information about the cluster.
      '';
    };

    nodeIp = mkOption {
      type = types.str;
      example = "192.168.1.1";
      description = mdDoc ''
        IP address of this node.
      '';
    };

    otherNodesIps = mkOption {
      type = types.listOf types.str;
      example = [ "192.168.1.2" "192.168.1.3" ];
      description = mdDoc ''
        IP addresses of the other nodes.
      '';
    };

    restApiPort = mkOption {
      type = types.port;
      default = 8008;
      description = mdDoc ''
        The port on Patroni's REST api listens.
      '';
    };

    raft = mkOption {
      type = types.bool;
      default = false;
      description = mdDoc ''
        This will configure Patroni to use its own RAFT implementation instead of using a dedicated DCS.
      '';
    };

    raftPort = mkOption {
      type = types.port;
      default = 5010;
      description = mdDoc ''
        The port on which RAFT listens.
      '';
    };

    softwareWatchdog = mkOption {
      type = types.bool;
      default = false;
      description = mdDoc ''
        This will configure Patroni to use the software watchdog built into the Linux kernel
        as described in the [documentation](https://patroni.readthedocs.io/en/latest/watchdog.html#setting-up-software-watchdog-on-linux).
      '';
    };

    settings = mkOption {
      type = format.type;
      default = { };
      description = mdDoc ''
        The primary patroni configuration. See the [documentation](https://patroni.readthedocs.io/en/latest/SETTINGS.html)
        for possible values.
        Secrets should be passed in by using the `environmentFiles` option.
      '';
    };

    environmentFiles = mkOption {
      type = with types; attrsOf (nullOr (oneOf [ str path package ]));
      default = { };
      example = {
        PATRONI_REPLICATION_PASSWORD = "/secret/file";
        PATRONI_SUPERUSER_PASSWORD = "/secret/file";
      };
      description = mdDoc "Environment variables made available to Patroni as files content, useful for providing secrets from files.";
    };
  };

  config = mkIf cfg.enable {

    services.patroni.settings = {
      scope = cfg.scope;
      name = cfg.name;
      namespace = cfg.namespace;

      restapi = {
        listen = "${cfg.nodeIp}:${toString cfg.restApiPort}";
        connect_address = "${cfg.nodeIp}:${toString cfg.restApiPort}";
      };

      raft = mkIf cfg.raft {
        data_dir = "${cfg.dataDir}/raft";
        self_addr = "${cfg.nodeIp}:5010";
        partner_addrs = map (ip: ip + ":5010") cfg.otherNodesIps;
      };

      postgresql = {
        listen = "${cfg.nodeIp}:${toString cfg.postgresqlPort}";
        connect_address = "${cfg.nodeIp}:${toString cfg.postgresqlPort}";
        data_dir = cfg.postgresqlDataDir;
        bin_dir = "${cfg.postgresqlPackage}/bin";
        pgpass = "${cfg.dataDir}/pgpass";
      };

      watchdog = mkIf cfg.softwareWatchdog {
        mode = "required";
        device = "/dev/watchdog";
        safety_margin = 5;
      };
    };


    users = {
      users = mkIf (cfg.user == defaultUser) {
        patroni = {
          group = cfg.group;
          isSystemUser = true;
        };
      };
      groups = mkIf (cfg.group == defaultGroup) {
        patroni = { };
      };
    };

    systemd.services = {
      patroni = {
        description = "Runners to orchestrate a high-availability PostgreSQL";

        wantedBy = [ "multi-user.target" ];
        after = [ "network.target" ];

        script = ''
          ${concatStringsSep "\n" (attrValues (mapAttrs (name: path: ''export ${name}="$(< ${escapeShellArg path})"'') cfg.environmentFiles))}
          exec ${pkgs.patroni}/bin/patroni ${configFile}
        '';

        serviceConfig = mkMerge [
          {
            User = cfg.user;
            Group = cfg.group;
            Type = "simple";
            Restart = "on-failure";
            TimeoutSec = 30;
            ExecReload = "${pkgs.coreutils}/bin/kill -s HUP $MAINPID";
            KillMode = "process";
          }
          (mkIf (cfg.postgresqlDataDir == "/var/lib/postgresql/${cfg.postgresqlPackage.psqlSchema}" && cfg.dataDir == "/var/lib/patroni") {
            StateDirectory = "patroni patroni/raft postgresql postgresql/${cfg.postgresqlPackage.psqlSchema}";
            StateDirectoryMode = "0750";
          })
        ];
      };
    };

    boot.kernelModules = mkIf cfg.softwareWatchdog [ "softdog" ];

    services.udev.extraRules = mkIf cfg.softwareWatchdog ''
      KERNEL=="watchdog", OWNER="${cfg.user}", GROUP="${cfg.group}", MODE="0600"
    '';

    environment.systemPackages = [
      pkgs.patroni
      cfg.postgresqlPackage
      (mkIf cfg.raft pkgs.python310Packages.pysyncobj)
    ];

    environment.etc."${configFileName}".source = configFile;

    environment.sessionVariables = {
      PATRONICTL_CONFIG_FILE = "/etc/${configFileName}";
    };
  };

  meta.maintainers = [ maintainers.phfroidmont ];
}