summary refs log tree commit diff
path: root/nixos/modules/services/backup/postgresql-backup.nix
blob: 2ec78ce6f2cfa2e2ab43d81bc87289a5a35c276b (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
{ config, lib, pkgs, ... }:

with lib;

let

  cfg = config.services.postgresqlBackup;

  postgresqlBackupService = db :
    {
      enable = true;

      description = "Backup of database ${db}";

      requires = [ "postgresql.service" ];

      preStart = ''
        mkdir -m 0700 -p ${cfg.location}
        chown postgres ${cfg.location}
      '';

      script = ''
        if [ -e ${cfg.location}/${db}.sql.gz ]; then
          ${pkgs.coreutils}/bin/mv ${cfg.location}/${db}.sql.gz ${cfg.location}/${db}.prev.sql.gz
        fi

        ${config.services.postgresql.package}/bin/pg_dump ${cfg.pgdumpOptions} ${db} | \
          ${pkgs.gzip}/bin/gzip -c > ${cfg.location}/${db}.sql.gz
      '';

      serviceConfig = {
        Type = "oneshot";
        PermissionsStartOnly = "true";
        User = "postgres";
      };

      startAt = cfg.startAt;
    };

in {

  options = {

    services.postgresqlBackup = {

      enable = mkOption {
        default = false;
        description = ''
          Whether to enable PostgreSQL dumps.
        '';
      };

      startAt = mkOption {
        default = "*-*-* 01:15:00";
        description = ''
          This option defines (see <literal>systemd.time</literal> for format) when the
          databases should be dumped.
          The default is to update at 01:15 (at night) every day.
        '';
      };

      databases = mkOption {
        default = [];
        description = ''
          List of database names to dump.
        '';
      };

      location = mkOption {
        default = "/var/backup/postgresql";
        description = ''
          Location to put the gzipped PostgreSQL database dumps.
        '';
      };

      pgdumpOptions = mkOption {
        type = types.string;
        default = "-Cbo";
        description = ''
          Command line options for pg_dump.
        '';
      };
    };

  };

  config = mkIf config.services.postgresqlBackup.enable {

    systemd.services = listToAttrs (map (db : {
          name = "postgresqlBackup-${db}";
          value = postgresqlBackupService db; } ) cfg.databases);
  };

}