aboutsummaryrefslogtreecommitdiff
path: root/hosts/tower/postgres.nix
blob: 31fab498ca3dd614c4537bd79979f8cd9613dde3 (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
{
  pkgs,
  lib,
  config,
  ...
}:
let
  newPostgres = pkgs.postgresql_18_jit;
  cfg = config.services.postgresql;
  upgrade-pg-cluster = pkgs.writeScriptBin "upgrade-pg-cluster" ''
    set -eux
    systemctl stop postgresql

    export NEWDATA="/var/lib/postgresql/${newPostgres.psqlSchema}"
    export NEWBIN="${newPostgres}/bin"

    export OLDDATA="${cfg.dataDir}"
    export OLDBIN="${cfg.finalPackage}/bin"

    install -d -m 0700 -o postgres -g postgres "$NEWDATA"
    cd "$NEWDATA"
    sudo -u postgres "$NEWBIN/initdb" -D "$NEWDATA" ${lib.escapeShellArgs cfg.initdbArgs}

    sudo -u postgres "$NEWBIN/pg_upgrade" \
      --old-datadir "$OLDDATA" --new-datadir "$NEWDATA" \
      --old-bindir "$OLDBIN" --new-bindir "$NEWBIN" \
      "$@"
  '';
in
{
  services.postgresql = {
    enable = true;
    package = pkgs.postgresql_18_jit;
    enableTCPIP = true;
    enableJIT = true;

    settings = {
      password_encryption = "scram-sha-256";
    };

    authentication = ''
      # TYPE  DATABASE  USER        ADDRESS  METHOD
      local   all       all                  peer
      host    all       postgres    all      reject
      host    all       all         all      scram-sha-256
    '';
  }; # end of services.postgreslq

  environment.systemPackages = [ upgrade-pg-cluster ];

  systemd.services.backup-postgres = lib.mkIf cfg.enable {
    serviceConfig = {
      Type = "exec";
      User = "postgres";
      Group = "postgres";
      StateDirectory = "backups/postgres";
      StateDirectoryMode = "0700";
      Umask = "077";
    };
    description = "Back up postgres data";
    path = [ cfg.finalPackage ];
    enableStrictShellChecks = true;
    script = ''
      #!/usr/bin/env bash
      set -euo pipefail

      TIMESTAMP="$(date +%Y%m%d%H%M%S)"
      BACKUP_PATH="$STATE_DIRECTORY/$TIMESTAMP.sql"
      echo "Backing up postgresql to $BACKUP_PATH" >&2

      pg_dumpall --file="$BACKUP_PATH" --verbose
      chmod u=r,go-rwx "$BACKUP_PATH"

      find "$STATE_DIRECTORY" -type f -name '*.sql' -print0 |
        sort --zero-terminated --reverse |
        tail --zero-terminated --lines=+6 |
        xargs --null --no-run-if-empty rm --
    '';
  };

  systemd.timers.backup-postgres = lib.mkIf cfg.enable {
    description = "Back up postgres data every morning";
    timerConfig.OnCalendar = "*-*-* 05:00:00";
    wantedBy = [ "timers.target" ];
  };
}