zfs-backup/backup.sh

87 lines
2.1 KiB
Bash
Raw Normal View History

2022-11-19 08:34:22 +00:00
#!/usr/bin/env sh
2022-11-19 08:49:50 +00:00
### nodes.txt
# localhost 22 <this host's root zfs> <this host's user>
# <remote host 1 address> <host 1 port> <host 1 root zfs>
# <remote host 2 address> <host 2 port> <host 2 root zfs>
2022-11-19 08:36:40 +00:00
# ...
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:49:50 +00:00
if [ ! -f nodes.txt ]; then echo "No nodes specified."; exit 2; fi
2022-11-19 08:34:22 +00:00
2022-11-19 08:49:50 +00:00
read BR_HOST BR_PORT BR_ROOT BR_USER < nodes.txt
2022-11-19 08:37:36 +00:00
2022-11-19 08:34:22 +00:00
list_filesets()
{
2022-11-19 08:49:50 +00:00
zfs list | tail -n +2 | cut -d' ' -f1|grep ${BR_ROOT}
2022-11-19 08:34:22 +00:00
}
get_latest_snapshot()
{
zfs list -t snapshot |
2022-11-19 08:49:50 +00:00
grep ${BR_ROOT} |
2022-11-19 08:34:22 +00:00
tail -n1 |
cut -d'@' -f2 |
cut -d' ' -f 1
}
setup_aggregator()
{
2022-11-19 08:49:50 +00:00
zfs allow -u ${BR_USER} send,snapshot,hold ${BR_ROOT}
2022-11-19 08:34:22 +00:00
for dataset in `cat datasets.txt`; do
zfs create $dataset
done
}
setup_mirror()
{
2022-11-19 08:49:50 +00:00
zfs allow -u ${BR_USER} send,snapshot,hold ${BR_ROOT}
zfs allow -du ${BR_USER} \
compression,mountpoint,receive,create,mount ${BR_ROOT}
2022-11-19 08:34:22 +00:00
}
create_snapshot()
{
id="`date -I`-`date +%s`"
2022-11-19 08:49:50 +00:00
zfs snapshot -r ${BR_ROOT}@${id}
2022-11-19 08:34:22 +00:00
}
send_single_snapshot()
{
2022-11-19 08:49:50 +00:00
BR_NEW_SNAPSHOT=`get_latest_snapshot`
while read BR_REMOTE_ADDR BR_REMOTE_PORT BR_REMOTE_ROOT BR_REMOTE_USER; do
zfs send -R ${BR_ROOT}@${BR_NEW_SNAPSHOT} |
ssh -i ~/.ssh/id_rsa -o port=${BR_REMOTE_PORT} \
${BR_REMOTE_USER}@${BR_REMOTE_ADDR} \
zfs receive -dvu ${BR_REMOTE_ROOT}@${BR_NEW_SNAPSHOT}
2022-11-19 08:34:22 +00:00
done
2022-11-19 08:49:50 +00:00
echo $BR_NEW_SNAPSHOT > "old-snapshot.txt"
2022-11-19 08:34:22 +00:00
}
2022-11-19 08:51:26 +00:00
send_incremental_snapshot()
2022-11-19 08:34:22 +00:00
{
2022-11-19 08:49:50 +00:00
BR_NEW_SNAPSHOT=`get_latest_snapshot`
while read BR_REMOTE_ADDR BR_REMOTE_PORT BR_REMOTE_ROOT BR_REMOTE_USER; do
zfs send -R -i `cat old-snapshot.txt` ${BR_ROOT}@${BR_NEW_SNAPSHOT} |
ssh -i ~/.ssh/id_rsa -o port=${BR_REMOTE_PORT} \
${BR_REMOTE_USER}@${BR_REMOTE_ADDR} \
zfs receive -dvu ${BR_REMOTE_ROOT}@${BR_NEW_SNAPSHOT}
2022-11-19 08:34:22 +00:00
done
2022-11-19 08:49:50 +00:00
echo $BR_NEW_SNAPSHOT > "old-snapshot.txt"
2022-11-19 08:34:22 +00:00
}
2022-11-19 08:51:06 +00:00
create_snapshot
2022-11-19 08:34:22 +00:00
2022-11-19 08:49:50 +00:00
if [ -f "old-snapshot.txt" ]; then
2022-11-19 08:51:26 +00:00
send_incremental_snapshot
2022-11-19 08:34:22 +00:00
else
send_single_snapshot
fi