Skip to content

Instantly share code, notes, and snippets.

@flexoid
Created May 5, 2020 19:42
Show Gist options
  • Save flexoid/ca545e2764f61ffacf7a0c1f1c6e6b41 to your computer and use it in GitHub Desktop.
Save flexoid/ca545e2764f61ffacf7a0c1f1c6e6b41 to your computer and use it in GitHub Desktop.
Borg backup script for Raspberry Pi
#!/bin/sh
# This script is inspired by the automated backup script example from borg site.
# https://borgbackup.readthedocs.io/en/stable/quickstart.html#automating-backups
export BORG_REPO=/var/local/borgbackups/full
export BORG_PASSPHRASE='<***>'
export RSYNC_DEST="backblaze:raspberry-hass"
export TEXTFILE_COLLECTOR_DIR=/var/lib/node_exporter/textfile_collector
info() { printf "\n%s %s\n\n" "$( date )" "$*" >&2; }
trap 'echo $( date ) Backup interrupted >&2; exit 2' INT TERM
info "Starting backup"
backup_started=$(date +%s)
hostname=$(hostname)
borg create --stats --verbose --show-rc \
--exclude-caches \
--exclude '/proc' \
--exclude '/sys' \
--exclude '/dev' \
--exclude '/mnt' \
--exclude '/media' \
--exclude '/run' \
--exclude '/tmp' \
--exclude '/var/run' \
--exclude '/var/lock' \
--exclude '/var/lock' \
--exclude '/var/swap' \
--exclude '/root/.cache' \
--exclude '/home/*/.cache/*' \
--exclude '/var/cache/*' \
--exclude '/root/tmp' \
--exclude '/home/*/tmp' \
--exclude '/var/tmp/*' \
--exclude '/var/local/borgbackups' \
\
::'{hostname}-{now}' \
/ /boot
backup_exit=$?
info "Pruning repository"
borg prune \
--list \
--prefix '{hostname}-' \
--show-rc \
--keep-daily 7 \
--keep-weekly 4 \
--keep-monthly 6 \
prune_exit=$?
global_exit=$(( backup_exit > prune_exit ? backup_exit : prune_exit ))
if [ ${global_exit} -eq 0 ]; then
info "Backup and Prune finished successfully"
elif [ ${global_exit} -eq 1 ]; then
info "Backup and/or Prune finished with warnings"
else
info "Backup and/or Prune finished with errors"
exit ${global_exit}
fi
borg with-lock ${BORG_REPO} rclone sync -v ${BORG_REPO} ${RSYNC_DEST}
rclone_exit=$?
if [ "$rclone_exit" -ne 0 ]; then
info "Rclone sync failed with error code $rclone_exit"
exit $rclone_exit
fi
# Run this to export borg repository stats to prometheus.
# https://github.com/OVYA/prometheus-borg-exporter
# /root/borg_exporter.sh
backup_completed=$(date +%s)
prom_file=$TEXTFILE_COLLECTOR_DIR/backup_stats.prom
prom_file_tmp=$PROM_FILE.$$
[ -e $prom_file_tmp ] && rm -f $prom_file_tmp
cat <<EOT >> $prom_file_tmp
# TYPE host_backup_started_time gauge
host_backup_started_time{host="${hostname}"} ${backup_started}
# TYPE host_backup_completed_time gauge
host_backup_completed_time{host="${hostname}"} ${backup_completed}
EOT
mv $prom_file_tmp $prom_file
exit ${global_exit}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment