Skip to content

Instantly share code, notes, and snippets.

@juris
Last active March 21, 2023 14:27
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save juris/53c8674c427ba17ace0a561ef9d58b30 to your computer and use it in GitHub Desktop.
Save juris/53c8674c427ba17ace0a561ef9d58b30 to your computer and use it in GitHub Desktop.
Redis Cluster backup script
#!/bin/sh
readonly cluster_topology=$(redis-cli -h redis-cluster cluster nodes)
readonly slaves=$(echo "${cluster_topology}" | grep slave | cut -d' ' -f2,4 | tr ' ' ',')
readonly backup_dir="/opt/redis-backup"
mkdir -p ${backup_dir}
for slave in ${slaves}; do
master_id=$(echo "${slave}" | cut -d',' -f2)
slave_ip=$(echo "${slave}" | cut -d':' -f1)
slots=$(echo "${cluster_topology}" | grep "${master_id}" | grep "master" | cut -d' ' -f9)
if [ -z "$slave_ip" ] || [ -z "$slots" ]; then
echo "Can not find redis slave or slots in topology:\n${cluster_topology}\n"
exit 1
fi
# Get last dump.rdb
redis-cli --rdb dump.rdb -h ${slave_ip}
# Check rdb file for consistency
rdb_check=$(redis-check-rdb dump.rdb)
echo ${rdb_check} | grep "Checksum OK" | grep "RDB looks OK!"
# If rdb is consistent, compress it and move to backup directory. Fail otherwise.
if [ $? -eq 0 ]; then
backup_file=dump-${slots}-$(date '+%Y-%m-%d-%H%M').rdb.gz
gzip dump.rdb
mv dump.rdb.gz ${backup_dir}/${backup_file}
else
failed_dump=dump-failed-${slots}-$(date '+%Y-%m-%d-%H%M').rdb
echo "RDB check failed!"
mv dump.rdb ${backup_dir}/${failed_dump}
fi
done
# Cleanup backups older than 5 days
find ${backup_dir} -mindepth 1 -mtime +5 -delete
@fanlifei
Copy link

In redis 5.0.8 versions, an error is reported here:
slots=$(echo "${cluster_topology}" | grep "${master_id}" | grep "master" | cut -d' ' -f9)

@juris
Copy link
Author

juris commented Oct 21, 2021

what kind of error?

@gee456
Copy link

gee456 commented Mar 21, 2023

Great Script , Do you have a script for restoration?

@juris
Copy link
Author

juris commented Mar 21, 2023

Thanks @gee456. I don't have a restoration script. When I need to restore something, I check what slots were affected, pick the file with the corresponding slots, upload it to the affected server and follow the standard recovery procedure.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment