nixos_forgejo/backup.nix

68 lines
2.3 KiB
Nix
Raw Normal View History

{config, pkgs, lib, ... }:
2024-02-17 02:42:35 +01:00
2024-02-20 04:41:48 +01:00
# NOTE: For this to work you should use MariaDB as your Forgejo-Database running on the same host. If this is not the case, update this script accordingly.
2024-02-17 02:42:35 +01:00
let
makeBackupForRepo = repo: lib.getExe (pkgs.writeShellScriptBin "forgejo-borgbackup" ''
2024-02-17 02:42:35 +01:00
#!/bin/sh
set -e
#stop forgejo
systemctl stop forgejo.service
2024-02-20 04:41:48 +01:00
# Dump Forgejo DB
2024-02-17 02:42:35 +01:00
MYSQL_DATABASE="forgejodb"
2024-02-17 05:44:04 +01:00
${pkgs.mariadb}/bin/mysqldump -u root ''${MYSQL_DATABASE} > /borgbackupcache/forgejobackup.sql
2024-02-17 02:42:35 +01:00
# BorgBackup
2024-02-17 05:44:04 +01:00
export BORG_PASSCOMMAND="cat /etc/nixos/borgpassword"
export BORG_REPO=${repo}
2024-02-20 04:41:48 +01:00
export BACKUP_NAME="forgejo-$(date +%Y-%m-%d-%H-%M)"
2024-02-17 02:42:35 +01:00
# Add everything to be backed up
${pkgs.borgbackup}/bin/borg create --verbose --filter AME --list --stats --show-rc --compression lz4 --exclude-caches \
$BORG_REPO::$BACKUP_NAME \
/var/lib/forgejo/repositories/ \
/var/lib/forgejo/data/ \
/borgbackupcache/forgejobackup.sql \
/etc/nixos/
2024-02-20 04:41:48 +01:00
# Delete DB dump
2024-02-17 02:42:35 +01:00
rm /borgbackupcache/forgejobackup.sql
# Start Forgejo again
systemctl start forgejo.service
# Prune old backups
${pkgs.borgbackup}/bin/borg prune --list $BORG_REPO --prefix 'forgejo-' --show-rc --keep-daily=7 --keep-weekly=4 --keep-monthly=6
'');
repos = repolistfile: lib.pipe repolistfile [
builtins.readFile
(lib.splitString "\n")
(lib.filter (s: s != ""))
];
backups = repolistfile: builtins.map makeBackupForRepo (repos repolistfile);
2024-02-17 03:11:14 +01:00
in
{
environment.systemPackages = [ pkgs.borgbackup ];
# Create folders
systemd.tmpfiles.rules = [
"d /borgbackupcache 700 root root"
];
# Backup timer
systemd.services.borg-backup = {
2024-02-20 04:41:48 +01:00
description = "Borg Backup for Forgejo and the Forgejo MySQL Database";
2024-02-17 03:11:14 +01:00
serviceConfig = {
ExecStart = lib.getExe (pkgs.writeShellScriptBin "doBackups" (lib.concatStringsSep ";" (backups config._module.args.borgrepolistfile)));
2024-02-17 03:11:14 +01:00
User = "root";
};
requires= ["mysql.service"];
after = ["forgejo.service" "mysql.service" "network-online.target"];
wants = ["network-online.target"];
2024-02-17 03:11:14 +01:00
wantedBy = [ "multi-user.target" ];
};
systemd.timers.borg-backup = {
description = "Daily Borg Backup Timer";
wantedBy = [ "timers.target" ];
timerConfig = {
OnActiveSec = "30s";
2024-02-17 03:11:14 +01:00
OnCalendar = "daily";
Persistent = true;
};
};
2024-02-17 05:44:04 +01:00
}