forked from django-extensions/django-extensions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backup.py
141 lines (123 loc) · 5.03 KB
/
backup.py
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
from __future__ import print_function
from optparse import make_option
import datetime
import re
import socket
import subprocess
import sys
import os
import django
from django.core.management.base import CommandError, BaseCommand
from django.conf import settings
from django_extensions.management.commands.mysql import MysqlCommand
from django_extensions.management.commands.rackspace import RackspaceCommand
class BackupCommand(object):
def __init__(self, router, container_name, verbose=False):
self.mysql = MysqlCommand(router, verbose)
self.rackspace = RackspaceCommand(container_name, verbose)
self.verbose = verbose
self.start_time = datetime.datetime.now()
def _run_cmd(self, cmd, filepath, ext=None):
if self.verbose:
print(cmd)
subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
if ext is not None:
filepath += ext
filesize = os.stat(filepath).st_size
if filesize == 0:
raise baku_exception.BadFileSize('Bad filesize for "%s"' % (filepath))
return filepath, filesize
def tar_directory(self, directory, prefix=None):
root, name = os.path.split(directory)
name = '%s.%s-%s.tar.bz2' % \
(name, self.start_time.strftime('%Y%m%d_%H%M%S'), socket.gethostname())
if prefix is not None:
backup_dir = '%s/%s' % (settings.BACKUP_DIR, prefix)
else:
backup_dir = settings.BACKUP_DIR
if not os.path.exists(backup_dir):
os.mkdir(backup_dir)
filepath = '%s/%s' % (backup_dir, name)
cmd = '/bin/tar cfj %s %s -C %s' % (filepath, directory, root)
return self._run_cmd(cmd, filepath)
def cull(self):
culled = []
files = os.listdir(settings.BACKUP_DIR)
for filename in files:
for date in self.rackspace.culls:
if self.verbose:
print('Checking %s %s' % (date, filename))
search = re.search('\.%s_' % (date), filename)
if search is not None:
filepath = '%s/%s/' % (settings.BACKUP_DIR, filename)
if self.verbose:
print('Deleting %s' % (filepath))
if not self.dry_run:
os.unlink(filepath)
culled.append(filepath)
return culled
def backup_database(self):
dbfile = self.mysql.dump()
uploaded = self.rackspace.upload(dbfile, 'db')
if self.verbose:
print(uploaded.name)
return uploaded
def backup_site(self):
filepath, filesize = self.tar_directory(settings.SITE_ROOT, 'site')
if self.verbose:
print('%s %s' % (filepath, filesize))
uploaded = self.rackspace.upload(filepath, 'site')
if self.verbose:
print(uploaded.name)
return uploaded
def backup_all(self):
db_upload = self.backup_database()
site_upload = self.backup_site()
deletes = self.rackspace.cull()
if self.verbose:
for deleted in deletes:
print('Deleted: %s' % (deleted.name))
deletes = self.cull()
if self.verbose:
for deleted in deletes:
print('Deleted: %s' % (deleted.name))
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('-D', '--db', action='store_true',
dest='db', default=False,
help='Backup the database.'),
make_option('-C', '--contianer', action='store',
dest='container',
default=settings.RACKSPACE_BACKUP_CONTAINER,
help='The container to use.'),
make_option('--cull', action='store_true',
dest='cull', default=False,
help='Cull the backup files.'),
make_option('-R', '--router', action='store',
dest='router', default='default',
help='Use this router and not the default.'),
make_option('-S', '--site', action='store_true',
dest='site', default=False,
help='Backup the site directory.'),
make_option('-U', '--upload', action='store',
dest='upload', help='Upload the file to rackspace.'),
make_option('-V', '--verbose', action='store_true',
dest='verbose', default=False,
help='Be verbose.'),
)
help = """Backups the database and the site directory."""
requires_model_validation = False
can_import_settings = True
def handle(self, *args, **options):
backup = BackupCommand(
options.get('router'),
options.get('container'),
options.get('verbose'))
if options.get('cull'):
backup = backup.cull()
elif options.get('db'):
backup = backup.backup_database()
elif options.get('site'):
backup = backup.backup_site()
else:
backup.backup_all()