prune backups older than 3 days

This commit is contained in:
Joseph Hanson 2024-09-26 09:39:21 -05:00
parent eb182bb1e7
commit 00494736d1
Signed by: jahanson
SSH key fingerprint: SHA256:vy6dKBECV522aPAwklFM3ReKAVB086rT3oWwiuiFG7o
3 changed files with 48 additions and 1 deletions

View file

@ -1,5 +1,5 @@
{ pkgs, ... }: { { pkgs, ... }: {
imports = [ ]; imports = [ ./resources/prune-backup.nix ];
networking.hostId = "cdab8473"; networking.hostId = "cdab8473";
networking.hostName = "varda"; # Define your hostname. networking.hostName = "varda"; # Define your hostname.
@ -22,6 +22,7 @@
swapDevices = [ ]; swapDevices = [ ];
# System settings and services. # System settings and services.
mySystem = { mySystem = {
purpose = "Production"; purpose = "Production";

View file

@ -0,0 +1,24 @@
{ pkgs, ... }:
let
cleanupScript = pkgs.writeScript "cleanup-backups.sh" (builtins.readFile ./prune-backups.sh);
in
{
systemd.timers.cleanup-backups = {
wantedBy = [ "timers.target" ];
timerConfig = {
OnCalendar = "daily";
Persistent = true;
};
};
systemd.services.cleanup-backups = {
script = "${cleanupScript}";
serviceConfig = {
Type = "oneshot";
User = "forgejo";
StandardOutput = "journal+console";
StandardError = "journal+console";
};
};
}

View file

@ -0,0 +1,22 @@
#!/usr/bin/env bash
# Set the backup directory
BACKUP_DIR="/var/lib/forgejo/dump"
# Keep the 3 most recent backups
KEEP_NUM=3
echo "Starting backup cleanup process..."
echo "Keeping the $KEEP_NUM most recent backups in $BACKUP_DIR"
# Find all backup files, sort by modification time (newest first),
# skip the first 3, and delete the rest
find "$BACKUP_DIR" -type f -name "forgejo-dump-*" -print0 |
sort -z -t_ -k2 -r |
tail -z -n +$((KEEP_NUM + 1)) |
while IFS= read -r -d '' file; do
echo "Deleting: $file"
rm -f "$file"
done
echo "Cleanup complete. Deleted all but the $KEEP_NUM most recent backups."