-
Notifications
You must be signed in to change notification settings - Fork 31
/
default.nix
352 lines (328 loc) · 12.2 KB
/
default.nix
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
# Based on https://github.com/cachix/devenv/blob/main/src/modules/services/postgres.nix
{ name, config, pkgs, lib, ... }:
with lib.types; let
inherit (lib) types;
in
{
options = {
enable = lib.mkEnableOption name;
package = lib.mkOption {
type = types.package;
description = "Which package of postgresql to use";
default = pkgs.postgresql;
defaultText = lib.literalExpression "pkgs.postgresql";
apply = postgresPkg:
if config.extensions != null then
if builtins.hasAttr "withPackages" postgresPkg
then postgresPkg.withPackages config.extensions
else
builtins.throw ''
Cannot add extensions to the PostgreSQL package.
`services.postgres.package` is missing the `withPackages` attribute. Did you already add extensions to the package?
''
else postgresPkg;
};
extensions = lib.mkOption {
type = with types; nullOr (functionTo (listOf package));
default = null;
example = lib.literalExpression ''
extensions: [
extensions.pg_cron
extensions.postgis
extensions.timescaledb
];
'';
description = ''
Additional PostgreSQL extensions to install.
The available extensions are:
${lib.concatLines (builtins.map (x: "- " + x) (builtins.attrNames pkgs.postgresql.pkgs))}
'';
};
dataDir = lib.mkOption {
type = lib.types.str;
default = "./data/${name}";
description = "The DB data directory";
};
socketDir = lib.mkOption {
type = lib.types.str;
default = "";
description = "The DB socket directory";
defaultText = ''
An empty value specifies not listening on any Unix-domain sockets, in which case only TCP/IP sockets can be used to connect to the server.
See: https://www.postgresql.org/docs/current/runtime-config-connection.html#GUC-UNIX-SOCKET-DIRECTORIES
'';
};
# Based on: https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING-URIS
connectionURI = lib.mkOption {
type = lib.types.functionTo lib.types.str;
readOnly = true;
default = { dbName, ... }: "postgres://${config.listen_addresses}:${builtins.toString config.port}/${dbName}";
description = ''
A function that accepts an attrset overriding the connection parameters
and returns the [postgres connection URI](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING-URIS)
'';
};
hbaConf =
let
hbaConfSubmodule = lib.types.submodule {
options = {
type = lib.mkOption { type = lib.types.str; };
database = lib.mkOption { type = lib.types.str; };
user = lib.mkOption { type = lib.types.str; };
address = lib.mkOption { type = lib.types.str; };
method = lib.mkOption { type = lib.types.str; };
};
};
in
lib.mkOption {
type = lib.types.listOf hbaConfSubmodule;
default = [ ];
description = ''
A list of objects that represent the entries in the pg_hba.conf file.
Each object has sub-options for type, database, user, address, and method.
See the official PostgreSQL documentation for more information:
https://www.postgresql.org/docs/current/auth-pg-hba-conf.html
'';
example = [
{ type = "local"; database = "all"; user = "postgres"; address = ""; method = "md5"; }
{ type = "host"; database = "all"; user = "all"; address = "0.0.0.0/0"; method = "md5"; }
];
};
hbaConfFile =
let
# Default pg_hba.conf entries
defaultHbaConf = [
{ type = "local"; database = "all"; user = "all"; address = ""; method = "trust"; }
{ type = "host"; database = "all"; user = "all"; address = "127.0.0.1/32"; method = "trust"; }
{ type = "host"; database = "all"; user = "all"; address = "::1/128"; method = "trust"; }
{ type = "local"; database = "replication"; user = "all"; address = ""; method = "trust"; }
{ type = "host"; database = "replication"; user = "all"; address = "127.0.0.1/32"; method = "trust"; }
{ type = "host"; database = "replication"; user = "all"; address = "::1/128"; method = "trust"; }
];
# Merge the default pg_hba.conf entries with the user-defined entries
hbaConf = defaultHbaConf ++ config.hbaConf;
# Convert the pgHbaConf array to a string
hbaConfString = ''
# Generated by Nix
${"# TYPE\tDATABASE\tUSER\tADDRESS\tMETHOD\n"}
${lib.concatMapStrings (cnf: " ${cnf.type}\t${cnf.database}\t${cnf.user}\t${cnf.address}\t${cnf.method}\n") hbaConf}
'';
in
lib.mkOption {
type = lib.types.package;
internal = true;
readOnly = true;
description = "The `pg_hba.conf` file.";
default = pkgs.writeText "pg_hba.conf" hbaConfString;
};
listen_addresses = lib.mkOption {
type = lib.types.str;
description = "Listen address";
default = "127.0.0.1";
example = "127.0.0.1";
};
port = lib.mkOption {
type = lib.types.port;
default = 5432;
description = ''
The TCP port to accept connections.
'';
};
superuser = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
description = ''
Name of superuser.
null defaults to $USER
'';
};
createDatabase = lib.mkOption {
type = types.bool;
default = true;
description = ''
Create a database named like current user on startup. Only applies when initialDatabases is an empty list.
'';
};
initdbArgs = lib.mkOption {
type = types.listOf types.lines;
default = [ "--locale=C" "--encoding=UTF8" ];
example = [ "--data-checksums" "--allow-group-access" ];
description = ''
Additional arguments passed to `initdb` during data dir
initialisation.
'';
};
defaultSettings =
lib.mkOption {
type = with lib.types; attrsOf (oneOf [ bool float int str ]);
internal = true;
readOnly = true;
description = ''
Default configuration for `postgresql.conf`. `settings` can override these values.
'';
default = {
listen_addresses = config.listen_addresses;
port = config.port;
unix_socket_directories = config.socketDir;
hba_file = "${config.hbaConfFile}";
};
};
settings =
lib.mkOption {
type = with lib.types; attrsOf (oneOf [ bool float int str ]);
default = { };
description = ''
PostgreSQL configuration. Refer to
<https://www.postgresql.org/docs/11/config-setting.html#CONFIG-SETTING-CONFIGURATION-FILE>
for an overview of `postgresql.conf`.
String values will automatically be enclosed in single quotes. Single quotes will be
escaped with two single quotes as described by the upstream documentation linked above.
'';
default = {
listen_addresses = config.listen_addresses;
port = config.port;
unix_socket_directories = lib.mkDefault config.socketDir;
hba_file = "${config.hbaConfFile}";
};
example = lib.literalExpression ''
{
log_connections = true;
log_statement = "all";
logging_collector = true
log_disconnections = true
log_destination = lib.mkForce "syslog";
}
'';
};
initialDatabases = lib.mkOption {
type = types.listOf (types.submodule {
options = {
name = lib.mkOption {
type = types.str;
description = ''
The name of the database to create.
'';
};
schemas = lib.mkOption {
type = types.nullOr (types.listOf types.path);
default = null;
description = ''
The initial list of schemas for the database; if null (the default),
an empty database is created.
'';
};
};
});
default = [ ];
description = ''
List of database names and their initial schemas that should be used to create databases on the first startup
of Postgres. The schema attribute is optional: If not specified, an empty database is created.
'';
example = lib.literalExpression ''
[
{
name = "foodatabase";
schemas = [ ./fooschemas ./bar.sql ];
}
{ name = "bardatabase"; }
]
'';
};
initialScript = lib.mkOption {
type = types.submodule ({ config, ... }: {
options = {
before = lib.mkOption {
type = types.nullOr types.str;
default = null;
description = ''
SQL commands to run before the database initialization.
'';
example = lib.literalExpression ''
CREATE USER postgres SUPERUSER;
CREATE USER bar;
'';
};
after = lib.mkOption {
type = types.nullOr types.str;
default = null;
description = ''
SQL commands to run after the database initialization.
'';
example = lib.literalExpression ''
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL UNIQUE
);
'';
};
};
});
default = { before = null; after = null; };
description = ''
Initial SQL commands to run during database initialization. This can be multiple
SQL expressions separated by a semi-colon.
'';
};
outputs.settings = lib.mkOption {
type = types.deferredModule;
internal = true;
readOnly = true;
default =
{
processes = {
# DB initialization
"${name}-init" =
let
setupScript = import ./setup-script.nix { inherit config pkgs lib; };
in
{
command = setupScript;
namespace = name;
};
# DB process
${name} =
let
startScript = pkgs.writeShellApplication {
name = "start-postgres";
runtimeInputs = [ config.package pkgs.coreutils ];
text = ''
set -euo pipefail
PGDATA=$(readlink -f "${config.dataDir}")
export PGDATA
${ if config.socketDir != "" then ''
PGSOCKETDIR=$(readlink -f "${config.socketDir}")
postgres -k "$PGSOCKETDIR"
'' else ''
postgres
''}
'';
};
pg_isreadyArgs = [
(if config.socketDir != "" then "-h $(readlink -f \"${config.socketDir}\")" else "-h ${config.listen_addresses}")
"-p ${toString config.port}"
"-d template1"
] ++ (lib.optional (config.superuser != null) "-U ${config.superuser}");
in
{
command = startScript;
# SIGINT (= 2) for faster shutdown: https://www.postgresql.org/docs/current/server-shutdown.html
shutdown.signal = 2;
readiness_probe = {
exec.command = "${config.package}/bin/pg_isready ${lib.concatStringsSep " " pg_isreadyArgs}";
initial_delay_seconds = 2;
period_seconds = 10;
timeout_seconds = 4;
success_threshold = 1;
failure_threshold = 5;
};
namespace = name;
depends_on."${name}-init".condition = "process_completed_successfully";
# https://github.com/F1bonacc1/process-compose#-auto-restart-if-not-healthy
availability.restart = "on_failure";
};
};
};
};
};
}