borg-backup.sh (2651B)
1 #!/bin/bash 2 3 export BORG_REPO='{{ BORG_REPO }}' 4 export BORG_PASSPHRASE='{{ BORG_PASSPHRASE }}' 5 6 # some helpers and error handling: 7 info() { printf "\n%s %s\n\n" "$( date )" "$*" >&2; } 8 trap 'echo $( date ) Backup interrupted >&2; exit 2' INT TERM 9 10 info "Dumping database" 11 12 sudo -u postgres pg_dumpall > postgres-backup.sql 13 db_exit=$? 14 15 # Note: I actually benchmarked (!) this on *out* SQL data. 16 # zstd was fastest, but gzip was smallest 17 # (tested: gzip, bzip, zstd, lzip, xz) 18 gzip postgres-backup.sql || exit 1 19 20 echo "Database snapshot created:" 21 ls -al postgres-backup.sql.gz 22 23 info "Starting backup" 24 25 # Backup the most important directories into an archive named after 26 # the machine this script is currently running on: 27 28 borg create \ 29 --verbose \ 30 --filter AME \ 31 --list \ 32 --stats \ 33 --show-rc \ 34 --compression lz4 \ 35 --exclude-caches \ 36 --exclude 'home/*/.cache/*' \ 37 --exclude 'var/tmp/*' \ 38 --exclude 'var/lib/taler-exchange/secmod-*/*' \ 39 \ 40 ::'{hostname}-{now}' \ 41 /etc \ 42 /root \ 43 /var/lib/libeufin-nexus \ 44 /var/lib/taler-exchange 45 46 backup_exit=$? 47 48 info "Removing database dump" 49 50 rm postgres-backup.sql.gz 51 52 53 info "Pruning repository" 54 55 # Use the `prune` subcommand to maintain 7 daily, 4 weekly and 6 monthly 56 # archives of THIS machine. The '{hostname}-*' matching is very important to 57 # limit prune's operation to this machine's archives and not apply to 58 # other machines' archives also: 59 60 borg prune \ 61 --list \ 62 --glob-archives '{hostname}-*' \ 63 --show-rc \ 64 --keep-daily 7 \ 65 --keep-weekly 4 \ 66 --keep-monthly 6 67 68 prune_exit=$? 69 70 # actually free repo disk space by compacting segments 71 72 info "Compacting repository" 73 74 borg compact 75 76 compact_exit=$? 77 78 # use highest exit code as global exit code 79 global_exit=$(( backup_exit > prune_exit ? backup_exit : prune_exit )) 80 global_exit=$(( compact_exit > global_exit ? compact_exit : global_exit )) 81 global_exit=$(( db_exit > global_exit ? db_exit : global_exit )) 82 83 if [ ${global_exit} -eq 0 ]; then 84 info "Backup, Prune, and Compact finished successfully" 85 elif [ ${global_exit} -eq 1 ]; then 86 info "Backup, Prune, and/or Compact finished with warnings" 87 else 88 info "Backup, Prune, and/or Compact finished with errors" 89 fi 90 91 exit ${global_exit}