lvm-backup/backupscript.sh

117 lines
2.6 KiB
Bash
Raw Permalink Normal View History

2017-08-24 23:27:49 +02:00
#!/bin/bash
# dir to backup
cd $(dirname $0)
usage() {
echo "backup script with snapshots"
echo "$0 [-x exclude dir] [-k N] <backup dir>"
echo
echo " -x excludes sub directory"
echo " -k defines how many snapshots to keep (default 7)"
echo " -q supress verbose output"
echo
}
# read configuration variables
source config.sh
BDIR=""
EXCLUDE=""
#### READ PARAMETERS
while getopts ":x:hqk:" opt; do
case $opt in
x)
EXCLUDE="${EXCLUDE} --exclude ${SNAPSHOTDIR}/${OPTARG}"
;;
h)
usage
exit 0
;;
q)
QUIET="--quiet"
;;
k)
KEEPLAST="${OPTARG}"
;;
\?)
echo "ERROR: Invalid option: -$OPTARG" >&2
usage
exit 1
;;
:)
echo "ERROR: Option -$OPTARG requires an argument." >&2
usage
exit 1
;;
esac
done
shift $((OPTIND-1))
BDIR=${1}
if [ -z "$BDIR" ]; then
echo "ERROR: Missing backup directory!" >&2
usage
exit 2
fi
#### END READ PARAMETERS
# umount and close everything if it is mounted before
uuid=$(cat /proc/sys/kernel/random/uuid)
if ! ./lock.sh haslock; then
2017-10-28 11:02:48 +02:00
echo "###" BEGIN EXPECTED ERRORS >&2
2017-08-24 23:27:49 +02:00
umount -v $SNAPSHOTDIR
cryptsetup close snapshot-decrypt
lvremove -f vg01/crypt-snapshot
2017-10-28 11:02:48 +02:00
echo "###" END EXPECTED ERRORS >&2
2017-08-24 23:27:49 +02:00
mkdir -p $SNAPSHOTDIR
# create snapshot of data volume
sync
lvcreate -l100%FREE -s -n crypt-snapshot /dev/vg01/data-crypt || exit 1
# decrypt snapshot with key on unencrypted partition
echo mounting snapshot
cryptsetup open --type luks --key-file /data/_lukskeyfile /dev/vg01/crypt-snapshot snapshot-decrypt || exit 2
# mount the freshly decrypted backup
mount -o ro /dev/mapper/snapshot-decrypt $SNAPSHOTDIR || exit 3
fi
./lock.sh lock $uuid
export RESTIC_PASSWORD=${BACKUP_PASSWORD}
2017-10-28 10:53:29 +02:00
SNAPSHOTPATH=$SNAPSHOTDIR
if [[ -n "$BDIR" && "$BDIR" != "." ]]; then
SNAPSHOTPATH=$SNAPSHOTDIR/$BDIR
fi
echo "Backup path: $SNAPSHOTPATH"
2017-08-25 20:27:54 +02:00
# backup the snapshot (without freezing the filesystem)
2017-08-24 23:27:49 +02:00
# use -q for quiet mode (when run as a cron job)
2017-10-28 10:53:29 +02:00
ionice -c 3 $RESTIC --repo $URI $EXCLUDE $QUIET backup "$SNAPSHOTPATH"
2017-08-24 23:27:49 +02:00
./lock.sh unlock $uuid
if ! ./lock.sh haslock; then
# at this point we no longer need the snapshot and can unmount it
umount $SNAPSHOTDIR
cryptsetup close snapshot-decrypt
lvremove -f vg01/crypt-snapshot
fi
# delete everything older than the last X snapshots
2017-10-28 10:53:29 +02:00
$RESTIC --repo $URI $QUIET forget --keep-last $KEEPLAST --path "$SNAPSHOTPATH"
2017-08-24 23:27:49 +02:00
unset RESTIC_PASSWORD
exit 0