|
| 1 | +"""Import and export data for the OpenBazaar server.""" |
| 2 | +__author__ = 'marc' |
| 3 | +from constants import DATA_FOLDER |
| 4 | +import db.datastore as db |
| 5 | +import os |
| 6 | +import sqlite3 as lite |
| 7 | +import tarfile |
| 8 | +import time |
| 9 | + |
| 10 | +BACKUP_FOLDER = 'backup' |
| 11 | + |
| 12 | +def _getdatabase(): |
| 13 | + """Retrieves the OpenBazaar database file.""" |
| 14 | + database = db.Database() |
| 15 | + return database.DATABASE |
| 16 | + |
| 17 | +def backupfiles(output_name=None): |
| 18 | + """Archives OpenBazaar files in a single tar archive.""" |
| 19 | + os.chdir(DATA_FOLDER) |
| 20 | + if not os.path.exists(BACKUP_FOLDER): |
| 21 | + os.makedirs(BACKUP_FOLDER) |
| 22 | + if not output_name: |
| 23 | + output_name = 'backup_{0}.tar.gz'.format(time.strftime('%Y-%m-%d')) |
| 24 | + if not os.path.isabs(output_name): |
| 25 | + output = BACKUP_FOLDER + os.sep + output_name |
| 26 | + if os.path.isfile(output): |
| 27 | + raise IOError(output + ' already exists.') |
| 28 | + |
| 29 | + # Lock the database |
| 30 | + db_file = _getdatabase() |
| 31 | + db_connection = lite.connect(db_file) |
| 32 | + db_connection.commit() |
| 33 | + |
| 34 | + # Archive files |
| 35 | + files = os.listdir(DATA_FOLDER) |
| 36 | + with tarfile.open(output, 'w:gz') as tar: |
| 37 | + for fil in files: |
| 38 | + if fil != BACKUP_FOLDER: |
| 39 | + tar.add(fil) |
| 40 | + tar.close() |
| 41 | + |
| 42 | + # Unlock database |
| 43 | + db_connection.rollback() |
| 44 | + db_connection.close() |
| 45 | + |
| 46 | + return True |
| 47 | + |
| 48 | + |
| 49 | +def restorefiles(input_file): |
| 50 | + """Restores files of given archive to OpenBazaar folder.""" |
| 51 | + os.chdir(DATA_FOLDER) |
| 52 | + if not os.path.isabs(input_file): |
| 53 | + input_file = BACKUP_FOLDER + os.sep + input_file |
| 54 | + |
| 55 | + if not os.path.isfile(input_file): |
| 56 | + raise IOError(input_file + ' does not exist.') |
| 57 | + |
| 58 | + # Unarchive files |
| 59 | + with tarfile.open(input_file, 'r:gz') as tar: |
| 60 | + tar.extractall() |
| 61 | + |
| 62 | + return True |
0 commit comments