blob: 742e3d436c51bd2ffc485718986f2c3df828255e [file] [log] [blame]
Skyler Greya78aa672023-05-20 13:48:18 +02001{ lib, config, pkgs, ... }: {
2 services.postgresql = {
3 enable = true;
4
5 package = pkgs.postgresql;
6 settings = {
7 log_connections = true;
Skyler Greya78aa672023-05-20 13:48:18 +02008 logging_collector = true;
9 log_disconnections = true;
10 log_destination = lib.mkForce "syslog";
11 };
12
13 ensureUsers = [
14 {
15 name = "clicks_grafana";
16 ensurePermissions = {
17 "ALL TABLES IN SCHEMA public" = "SELECT";
18 "SCHEMA public" = "USAGE";
19 };
20 }
21 {
Skyler Grey8e32c832023-05-20 22:54:30 +020022 name = "synapse";
Skyler Greya78aa672023-05-20 13:48:18 +020023 ensurePermissions = {
Skyler Grey8e32c832023-05-20 22:54:30 +020024 "DATABASE synapse" = "ALL PRIVILEGES";
Skyler Greya78aa672023-05-20 13:48:18 +020025 };
26 }
27 ] ++ (map
28 (name: (
29 {
30 inherit name;
31 ensurePermissions = { "ALL TABLES IN SCHEMA public" = "ALL PRIVILEGES"; };
32 }
33 )) [ "minion" "coded" "pinea" ]);
34
Skyler Greya78aa672023-05-20 13:48:18 +020035 };
36
Skyler Grey8e32c832023-05-20 22:54:30 +020037 systemd.services.postgresql.postStart = lib.mkMerge [
38 (
39 let
40 database = "synapse";
41 cfg = config.services.postgresql;
42 in
43 lib.mkBefore (
44 ''
45 PSQL="psql --port=${toString cfg.port}"
46
47 while ! $PSQL -d postgres -c "" 2> /dev/null; do
48 if ! kill -0 "$MAINPID"; then exit 1; fi
49 sleep 0.1
50 done
51
52 $PSQL -tAc "SELECT 1 FROM pg_database WHERE datname = '${database}'" | grep -q 1 || $PSQL -tAc 'CREATE DATABASE "${database}" WITH LC_CTYPE="C" LC_COLLATE="C" TEMPLATE="template0"'
53 ''
54 ) # synapse needs C collation, so we can't use ensureDatabases for it
55 )
56 (lib.mkAfter (lib.pipe [
57 { user = "clicks_grafana"; passwordFile = config.sops.secrets.clicks_grafana_db_password.path; }
58 ] [
59 (map (userData: ''
60 $PSQL -tAc "ALTER USER ${userData.user} PASSWORD '$(cat ${userData.passwordFile})';"
61 ''))
62 (lib.concatStringsSep "\n")
63 ]))
64 ];
Skyler Greya78aa672023-05-20 13:48:18 +020065
66 sops.secrets = lib.pipe [
67 "clicks_grafana_db_password"
Skyler Greya78aa672023-05-20 13:48:18 +020068 ] [
69 (map (name: {
70 inherit name;
71 value = {
72 mode = "0400";
73 owner = config.services.postgresql.superUser;
74 group = config.users.users.${config.services.postgresql.superUser}.group;
75 sopsFile = ../secrets/postgres.json;
76 format = "json";
77 };
78 }))
79 builtins.listToAttrs
80 ];
81}