Backup databases

This commit is contained in:
Ruud
2014-03-07 11:18:14 +01:00
parent 89e561c991
commit 2d28cb6897
+34 -3
View File
@@ -7,6 +7,7 @@ from couchpotato.core.event import fireEventAsync, fireEvent
from couchpotato.core.helpers.encoding import toUnicode
from couchpotato.core.helpers.variable import getDataDir, tryInt
from logging import handlers
from scandir import scandir
from tornado.httpserver import HTTPServer
from tornado.web import Application, StaticFileHandler, RedirectHandler
from uuid import uuid4
@@ -17,6 +18,8 @@ import sys
import time
import traceback
import warnings
import re
import tarfile
def getOptions(base_path, args):
@@ -88,13 +91,41 @@ def runCouchPotato(options, base_path, args, data_dir = None, log_dir = None, En
db = ThreadSafeDatabase(db_path)
db_exists = db.exists()
if db_exists:
# Backup before start and cleanup old backups
backup_path = toUnicode(os.path.join(data_dir, 'db_backup'))
backup_count = 5
existing_backups = []
if not os.path.isdir(backup_path): os.makedirs(backup_path)
for root, dirs, files in scandir.walk(backup_path):
for file in files:
ints = re.findall('\d+', file)
# Delete non zip files
if len(ints) != 1:
os.remove(os.path.join(backup_path, file))
else:
existing_backups.append((int(ints[0]), file))
# Remove all but the last 5
for eb in existing_backups[:-backup_count]:
os.remove(os.path.join(backup_path, eb[1]))
# Create new backup
new_backup = toUnicode(os.path.join(backup_path, '%s.tar.gz' % int(time.time())))
zipf = tarfile.open(new_backup, 'w:gz')
for root, dirs, files in scandir.walk(db_path):
for file in files:
zipf.add(os.path.join(root, file), arcname = 'database/%s' % os.path.join(root[len(db_path)+1:], file))
zipf.close()
# Open last
db.open()
db.compact()
else:
db.create()
# TODO:Backup before start and cleanup old databases
# Register environment settings
Env.set('app_dir', toUnicode(base_path))
Env.set('data_dir', toUnicode(data_dir))