-
Notifications
You must be signed in to change notification settings - Fork 163
/
cassandra_backup.j2
68 lines (58 loc) · 2.59 KB
/
cassandra_backup.j2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/env python3
# Author: Rajesh Rajendran <[email protected]>
'''
Create a snapshot and create tar ball in targetdirectory name
usage: script snapshot_name
eg: ./cassandra_backup.py my_snapshot
'''
from os import path, walk, sep, system, getcwd, makedirs
from argparse import ArgumentParser
from shutil import rmtree, ignore_patterns, copytree
from re import match, compile
from sys import exit
from tempfile import mkdtemp
parser = ArgumentParser(description="Create a snapshot and create tar ball inside tardirectory")
parser.add_argument("-d","--datadirectory", metavar="datadir", default='/var/lib/cassandra/data', help="path to create the tarball. Default /var/lib/cassadra/data")
parser.add_argument("snapshotname", help="name in which you want to take the snapshot")
parser.add_argument("-t","--tardirectory", metavar="tardir", default=getcwd(), help="path to create the tarball. Default {}".format(getcwd()))
args = parser.parse_args()
# Create temporary directory to copy data
tmpdir=mkdtemp()
makedirs(tmpdir+sep+"cassandra_backup")
def copy():
'''
Copying the data sanpshots to the target directory
'''
root_levels = args.datadirectory.count(sep)
ignore_list = compile(tmpdir+sep+"cassandra_backup"+sep+'(system|system|systemtauth|system_traces|system_schema|system_distributed)')
try:
for root, dirs, files in walk(args.datadirectory):
root_target_dir=tmpdir+sep+"cassandra_backup"+sep+sep.join(root.split(sep)[root_levels+1:-2])
if match(ignore_list, root_target_dir):
continue
if root.split(sep)[-1] == args.snapshotname:
copytree(src=root, dst=root_target_dir, ignore=ignore_patterns('.*'))
except Exception as e:
print(e)
# Creating schema
command = "cqlsh -e 'DESC SCHEMA' > {}/cassandra_backup/db_schema.cql".format(tmpdir)
rc = system(command)
if rc != 0:
print("Couldn't backup schema, exiting...")
exit(1)
print("Schema backup completed. saved in {}/cassandra_backup/db_schema.sql".format(tmpdir))
# Cleaning all old snapshots
command = "nodetool clearsnapshot"
system(command)
# Creating snapshots
command = "nodetool snapshot -t {}".format(args.snapshotname)
rc = system(command)
if rc == 0:
print("Snapshot taken.")
copy()
print("Making a tarball: {}.tar.gz".format(args.snapshotname))
command = "cd {} && tar -czvf {}/{}.tar.gz *".format(tmpdir, args.tardirectory, args.snapshotname)
system(command)
# Cleaning up backup directory
rmtree(tmpdir)
print("Cassandra backup completed and stored in {}/{}.tar.gz".format(args.tardirectory,args.snapshotname))