server-scripts/zfs_backup.sh

67 lines
1.4 KiB
Bash
Raw Normal View History

#!/bin/sh
### Arguments ###
DATASET=$1
if test -z "$DATASET"; then
echo "Missing dataset argument"
exit 1
fi
NAME=$2
if test -z "$NAME"; then
echo "Missing snapshot name argument"
exit 1
fi
PREVIOUS_NAME=$3
if test -z "$NAME"; then
echo "Missing previous snapshot name argument"
exit 1
fi
TARGET=$4
if test -z "$TARGET"; then
echo "Missing target"
exit 1
fi
TARGET_PATH=$5
if test -z "$TARGET_PATH"; then
echo "Missing target path"
exit 1
fi
SNAPSHOT="$DATASET@$NAME"
PREVIOUS_SNAPSHOT="$DATASET@$PREVIOUS_NAME"
REMOTE_NAME="$TARGET_PATH/"$(echo -e $DATASET | sed -r "s/\//_/g")
LOCK_NAME="${0}_"$(echo -e $DATASET | sed -r "s/\//_/g")
### LOCK ###
if ! lockfile-create -p -r 2 $LOCK_NAME; then
echo "Another backup is running, aborting"
exit 49
fi
# Create snapshot
exists=$(zfs list -H -t snapshot -o name $SNAPSHOT)
if [ "$exists" = "$SNAPSHOT" ]; then
echo "Snapshot $SNAPSHOT already exists, skip create."
else
echo "Creating $SNAPSHOT snapshot..."
zfs snapshot $SNAPSHOT || exit 1
echo "Snapshot created."
fi
# Send snapshot
echo "Sending snapshot ($PREVIOUS_SNAPSHOT --- $SNAPSHOT) to $REMOTE_NAME ..."
if test ! -z "$PREVIOUS_NAME"; then
incr="-I $PREVIOUS_SNAPSHOT"
fi
zfs send -v -p $incr $SNAPSHOT | ssh $TARGET zfs receive -F -s $REMOTE_NAME || exit 1
echo "Snapshot sent."
### UNLOCK ###
echo "Backup of $DATASET dataset finished. Removing lock..."
lockfile-remove $LOCK_NAME