zfs-backup/backup.sh

95 lines
2.3 KiB
Bash
Raw Normal View History

2022-11-19 08:34:22 +00:00
#!/usr/bin/env sh
2022-11-19 08:36:40 +00:00
## Data Format
### user.txt
# <username>
### hosts.txt
# <host 1 address> <host 1 port> <host 1 root zfs>
# <host 2 address> <host 2 port> <host 2 root zfs>
# ...
### rootzfs.txt
# <root zfs>
2022-11-19 08:37:36 +00:00
### datasets.txt (Only required for aggregator setup.)
2022-11-19 08:36:40 +00:00
# <dataset 1>
# <dataset 1>/<dataset 1a>
# <dataset 1>/<dataset 1b>
# <dataset 2>
# <dataset 2>/<dataset 2a>
# <dataset 3>
# ...
2022-11-19 08:34:22 +00:00
if [ ! -f user.txt ]; then echo "No user specified."; exit 2; fi
if [ ! -f hosts.txt ]; then echo "No hosts specified."; exit 2; fi
if [ ! -f rootzfs.txt ]; then echo "No rootzfs specified."; exit 2; fi
2022-11-19 08:37:36 +00:00
BAKRNG_ROOT=`cat rootzfs.txt`
2022-11-19 08:34:22 +00:00
list_filesets()
{
zfs list | tail -n +2 | cut -d' ' -f1|grep ${BAKRNG_ROOT}
}
get_latest_snapshot()
{
zfs list -t snapshot |
grep ${BAKRNG_ROOT} |
tail -n1 |
cut -d'@' -f2 |
cut -d' ' -f 1
}
setup_aggregator()
{
zfs allow -u `cat user.txt` send,snapshot,hold ${BAKRNG_ROOT}
for dataset in `cat datasets.txt`; do
zfs create $dataset
done
}
setup_mirror()
{
zfs allow -u `cat user.txt` send,snapshot,hold ${BAKRNG_ROOT}
zfs allow -du `cat user.txt` \
compression,mountpoint,receive,create,mount ${BAKRNG_ROOT}
}
create_snapshot()
{
id="`date -I`-`date +%s`"
2022-11-19 08:38:20 +00:00
zfs snapshot -r ${BAKRNG_ROOT}@${id}
2022-11-19 08:34:22 +00:00
}
send_single_snapshot()
{
BAKRNG_SEND_SNAPSHOT=`get_latest_snapshot`
while read BAKRNG_REMOTE_ADDR BAKRNG_REMOTE_PORT BAKRNG_REMOTE_ROOT; do
2022-11-19 08:38:20 +00:00
zfs send -R ${BAKRNG_ROOT}@${BAKRNG_SEND_SNAPSHOT} |
2022-11-19 08:34:22 +00:00
ssh -i ~/.ssh/id_rsa \
-o port=${BAKRNG_REMOTE_PORT} ${BAKRNG_REMOTE_ADDR} \
2022-11-19 08:38:20 +00:00
zfs receive -dvu ${BAKRNG_REMOTE_ROOT}@${BAKRNG_SEND_SNAPSHOT}
2022-11-19 08:34:22 +00:00
done
2022-11-19 08:38:20 +00:00
echo $BAKRNG_SEND_SNAPSHOT > "last-snapshot.txt"
2022-11-19 08:34:22 +00:00
}
send_incremental_snapshop()
{
BAKRNG_SEND_SNAPSHOT=`get_latest_snapshot`
while read BAKRNG_REMOTE_ADDR BAKRNG_REMOTE_PORT BAKRNG_REMOTE_ROOT; do
2022-11-19 08:38:20 +00:00
zfs send -R -i `cat last-snapshot.txt` \
2022-11-19 08:34:22 +00:00
${BAKRNG_ROOT}@${BAKRNG_SEND_SNAPSHOT} | ssh -i ~/.ssh/id_rsa \
-o port=${BAKRNG_REMOTE_PORT} ${BAKRNG_REMOTE_ADDR} \
2022-11-19 08:38:20 +00:00
zfs receive -dvu ${BAKRNG_REMOTE_ROOT}@${BAKRNG_SEND_SNAPSHOT}
2022-11-19 08:34:22 +00:00
done
2022-11-19 08:38:20 +00:00
echo $BAKRNG_SEND_SNAPSHOT > "last-snapshot.txt"
2022-11-19 08:34:22 +00:00
}
if [ -f "last-snapshot.txt" ]; then
send_incremental_snapshop
else
send_single_snapshot
fi