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