Skip to content

Backup Restore Cassandra.

nodetool is being used for backups (snapshots) and restoring.

  • Bash for export cassandra

Create export.sh

Bash
#!/bin/bash

keyspace=$1
bkp_name="bkp-$$"
data_dir="/var/lib/cassandra/data/"

if [ -z "${keyspace}" ]; then
    echo "Usage export.sh [keyspace]"
    exit 1
fi

echo "Create snapshot named: ${bkp_name}"
nodetool snapshot "${keyspace}" -t "${bkp_name}"

echo "Preparing backup file"
for name in $(find  "${data_dir}/${keyspace}/"*"/snapshots/${bkp_name}" -type f); do
        new=$(echo "$name" | sed -e "s#${data_dir}/##g" -e "s#\([^/]\+\)/\([^-]\+\).\+/snapshots/${bkp_name}/\([^/]\+\)\$#\1/\2/\3#g")
        mkdir -p "${bkp_name}/$(dirname $new)"
        cp "$name" "${bkp_name}/$new"
done

echo "Remove snapshot named: ${bkp_name}"
nodetool clearsnapshot -t "${bkp_name}" "${keyspace}"

echo "Dump keyspace and table creation instruction"
cqlsh -e "desc \"${keyspace}\";" cassandra1 > "${bkp_name}/${keyspace}.sql"

echo "Create tar file: ${keyspace}-$(date +%Y%m%d).tar.gz"
cd "${bkp_name}"
tar -czf "../${keyspace}-$(date +%Y%m%d).tar.gz" .
cd -

echo "Remove temporary files"
rm -rf "${bkp_name}"
  • Import

Create import.sh

Bash
#!/bin/bash

tar_file=$1
cassandra_server=$2
bkp_name="bkp-$$"

if [ -z "${tar_file}" ]; then
    echo "Usage import.sh [tar file]"
    exit 1
fi

keyspace=$(basename "${tar_file}" ".tar.gz")

mkdir -p "${bkp_name}"

tar -xvzf "${tar_file}" -C "${bkp_name}"

echo "Drop keyspace ${keyspace}"
cqlsh -e "drop keyspace \"${keyspace}\";" ${cassandra_server}

echo "Create empty keyspace: ${keyspace}"
cat "${bkp_name}/${keyspace}.sql" | cqlsh ${cassandra_server}

for dir in "${bkp_name}/${keyspace}/"*; do
    sstableloader -d ${cassandra_server} "${dir}"
done
Back to top