Skip to content

Instantly share code, notes, and snippets.

@cnrd
Created March 8, 2018 00:19
Show Gist options
  • Save cnrd/44352eadc141a2175e3390811f74e810 to your computer and use it in GitHub Desktop.
Save cnrd/44352eadc141a2175e3390811f74e810 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
mountSnapshots () {
mkdir -p "/mnt/$ZFSSNAPSHOTNAME"
mount -t zfs "$ZFSSNAPSHOTBASE@$ZFSSNAPSHOTNAME" "/mnt/$ZFSSNAPSHOTNAME"
while read -r line
do
MOUNTPATH=$(echo "$line" | sed "s/$ESCAPEDZFSSNAPSHOTBASE\///" | sed "s/@$ZFSSNAPSHOTNAME//")
if [ -d "/mnt/$ZFSSNAPSHOTNAME/$MOUNTPATH" ]; then
mount -t zfs "$line" "/mnt/$ZFSSNAPSHOTNAME/$MOUNTPATH"
fi
done < <(zfs list -t snapshot | grep "$ZFSSNAPSHOTNAME" | grep "$ZFSSNAPSHOTBASE" | grep -v "$ZFSSNAPSHOTBASE/\." | grep -o "$ZFSSNAPSHOTBASE/[0-9,a-z,A-Z,/,[:space:]]*@$ZFSSNAPSHOTNAME" | sed 's/[[:space:]]*$//')
}
unmountSnapshots () {
while read -r line
do
MOUNTPATH=$(echo "$line" | sed "s/$ESCAPEDZFSSNAPSHOTBASE\///" | sed "s/@$ZFSSNAPSHOTNAME//")
if [ -d "/mnt/$ZFSSNAPSHOTNAME/$MOUNTPATH" ]; then
umount "/mnt/$ZFSSNAPSHOTNAME/$MOUNTPATH"
fi
done < <(zfs list -t snapshot | grep "$ZFSSNAPSHOTNAME" | grep "$ZFSSNAPSHOTBASE" | grep -v "$ZFSSNAPSHOTBASE/\." | grep -o "$ZFSSNAPSHOTBASE/[0-9,a-z,A-Z,/,[:space:]]*@$ZFSSNAPSHOTNAME" | sed 's/[[:space:]]*$//' | tail -r)
umount "/mnt/$ZFSSNAPSHOTNAME"
rmdir "/mnt/$ZFSSNAPSHOTNAME"
}
exitCleanup () {
trap SIGINT
unmountSnapshots
zfs destroy -r "$ZFSSNAPSHOTBASE@$ZFSSNAPSHOTNAME"
rm $PIDFILE
exit
}
if [ $# -eq 2 ]
then
BASENAME=$(basename $1)
RUNNAME=rclone-$BASENAME
ZFSSNAPSHOTBASE=$(zfs list | grep "$BASENAME" | grep -v "$BASENAME/" | awk '{print $1}')
ESCAPEDZFSSNAPSHOTBASE=$(echo "$ZFSSNAPSHOTBASE" | sed 's/\//\\\//')
PIDFILE=/var/lock/$RUNNAME.pid
ISOTIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
YEAR=$(date -u +"%Y")
ZFSSNAPSHOTNAME="rclone"
if [ -f $PIDFILE ]
then
PID=$(cat $PIDFILE)
ps -p $PID > /dev/null 2>&1
if [ $? -eq 0 ]
then
echo "Process already running"
exit 1
else
## Process not found assume not running
echo $$ > $PIDFILE
if [ $? -ne 0 ]
then
echo "Could not create PID file"
exit 1
fi
fi
else
echo $$ > $PIDFILE
if [ $? -ne 0 ]
then
echo "Could not create PID file"
exit 1
fi
fi
zfs snapshot -r "$ZFSSNAPSHOTBASE@$ZFSSNAPSHOTNAME"
trap "exitCleanup" INT
mountSnapshots
# Do tha backup dance!
rclone --config /root/rclone.conf sync "/mnt/$ZFSSNAPSHOTNAME" "$2:$BASENAME/current" --backup-dir "$2:$BASENAME/$YEAR/$ISOTIME" --transfers 10 --log-file /var/log/$RUNNAME.log --log-level INFO
unmountSnapshots
zfs destroy -r "$ZFSSNAPSHOTBASE@$ZFSSNAPSHOTNAME"
rm $PIDFILE
else
echo "Argument should be: path remote"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment