b0rged/b0rged.sh

84 lines
2.5 KiB
Bash
Raw Normal View History

2024-12-03 13:47:27 +00:00
#!/usr/bin/env bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
set -o allexport
eval $(cat ${DIR}'/.env' | sed -e '/^#/d;/^\s*$/d' -e 's/\(\w*\)[ \t]*=[ \t]*\(.*\)/\1=\2/' -e "s/=['\"]\(.*\)['\"]/=\1/g" -e "s/'/'\\\''/g" -e "s/=\(.*\)/='\1'/g")
set +o allexport
info() { printf "\n%s %s\n\n" "$( date )" "$*" >&2; }
trap 'echo $( date ) Backup interrupted >&2; exit 2' INT TERM
if [ -z ${BORG_REPO+x} ]; then info "BORG_REPO must be set, check your .env"; exit 1; fi
if [ -z ${BORG_PASSPHRASE+x} ]; then info "BORG_PASSPHRASE must be set, check your .env"; exit 1; fi
node_metrics_enabled=${NODE_METRICS_ENABLED:-1}
node_metrics_path=${NODE_METRICS_PATH:-/usr/local/lib/prom}
start=$(date +%s)
exec {lock_fd}>/var/lock/borg-backup.lock || exit 1
flock -n "$lock_fd" || { echo "ERROR: flock() failed." >&2; exit 1; }
patternfile=$(mktemp)
cat patterns.* > $patternfile
if [ ${DOCKER_VOLUMES_ENABLED} -eq 1 ]; then
info "Collecting docker volumes..."
: ${DOCKER_COMMAND:=/usr/bin/docker}
volumes=$(${DOCKER_COMMAND} volume ls -f label=org.zknt.backup -f driver=local --format "{{.Name}}")
dockerpatterns=$(mktemp)
for volume in ${volumes}; do
mountpoint=$(${DOCKER_COMMAND} volume inspect ${volume} --format "{{.Mountpoint}}")
echo "R $(dirname ${mountpoint})" >> $dockerpatterns
done
cat $dockerpatterns >> $patternfile
rm $dockerpatterns
fi
info "Starting borg..."
borg create \
--warning \
--filter AME \
--list \
--stats \
--show-rc \
--compression lz4 \
--exclude-caches \
--exclude '/home/*/.cache/*' \
--exclude '/var/tmp/*' \
::'{hostname}-{now}' \
--patterns-from $patternfile
backup_exit=$?
rm $patternfile
borg prune \
--list \
--prefix '{hostname}-' \
--show-rc \
--keep-daily ${BORG_PRUNE_KEEP_DAILY:-14} \
--keep-weekly ${BORG_PRUNE_KEEP_WEEKLY:-4} \
--keep-monthly ${BORG_PRUNE_KEEP_MONTHLY:-6}
prune_exit=$?
global_exit=$(( backup_exit > prune_exit ? backup_exit : prune_exit ))
if [ ${global_exit} -eq 0 ]; then
info "Backup, Prune, and Compact finished successfully"
elif [ ${global_exit} -eq 1 ]; then
info "Backup, Prune, and/or Compact finished with warnings"
else
info "Backup, Prune, and/or Compact finished with errors"
fi
end=$(date +%s)
if [ ${node_metrics_enabled} -eq 1 ]; then
echo "borg_last_run ${end}" > ${node_metrics_path}/borg_backup.prom.$$
echo "borg_last_duration $(($end - $start))" >> ${node_metrics_path}/borg_backup.prom.$$
mv ${node_metrics_path}/borg_backup.prom{.$$,}
fi
flock -u "$lock_fd"