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