nixos postgresql-backup: add compression option

This option allows basic configuration of the compression technique
used in the backup script. Specifically it adds `none` and `zstd` as
new alternatives, keeping `gzip` as the default.
This commit is contained in:
Robert Helgesson
2021-08-03 23:04:48 +02:00
parent 4393d15463
commit bcc7a902d5
2 changed files with 67 additions and 14 deletions

View File

@@ -7,28 +7,49 @@ let
cfg = config.services.postgresqlBackup;
postgresqlBackupService = db: dumpCmd:
{
let
compressSuffixes = {
"none" = "";
"gzip" = ".gz";
"zstd" = ".zstd";
};
compressSuffix = getAttr cfg.compression compressSuffixes;
compressCmd = getAttr cfg.compression {
"none" = "cat";
"gzip" = "${pkgs.gzip}/bin/gzip -c";
"zstd" = "${pkgs.zstd}/bin/zstd -c";
};
mkSqlPath = prefix: suffix: "${cfg.location}/${db}${prefix}.sql${suffix}";
curFile = mkSqlPath "" compressSuffix;
prevFile = mkSqlPath ".prev" compressSuffix;
prevFiles = map (mkSqlPath ".prev") (attrValues compressSuffixes);
inProgressFile = mkSqlPath ".in-progress" compressSuffix;
in {
enable = true;
description = "Backup of ${db} database(s)";
requires = [ "postgresql.service" ];
path = [ pkgs.coreutils pkgs.gzip config.services.postgresql.package ];
path = [ pkgs.coreutils config.services.postgresql.package ];
script = ''
set -e -o pipefail
umask 0077 # ensure backup is only readable by postgres user
if [ -e ${cfg.location}/${db}.sql.gz ]; then
mv ${cfg.location}/${db}.sql.gz ${cfg.location}/${db}.prev.sql.gz
if [ -e ${curFile} ]; then
rm -f ${toString prevFiles}
mv ${curFile} ${prevFile}
fi
${dumpCmd} | \
gzip -c > ${cfg.location}/${db}.in-progress.sql.gz
${dumpCmd} \
| ${compressCmd} \
> ${inProgressFile}
mv ${cfg.location}/${db}.in-progress.sql.gz ${cfg.location}/${db}.sql.gz
mv ${inProgressFile} ${curFile}
'';
serviceConfig = {
@@ -87,7 +108,7 @@ in {
default = "/var/backup/postgresql";
type = types.path;
description = ''
Location to put the gzipped PostgreSQL database dumps.
Path of directory where the PostgreSQL database dumps will be placed.
'';
};
@@ -101,6 +122,14 @@ in {
when no databases where specified.
'';
};
compression = mkOption {
type = types.enum ["none" "gzip" "zstd"];
default = "gzip";
description = ''
The type of compression to use on the generated database dump.
'';
};
};
};