├── ebt_jobs ├── __init__.py ├── rsync.py ├── mysql.py ├── amazon.py ├── btrfs.py ├── s3.py └── vm.py ├── ebt_db ├── __init__.py └── mysql.py ├── setup.cfg ├── ebt_virt ├── __init__.py └── libvirt_helper.py ├── ebt_cloud ├── __init__.py └── amazon.py ├── ebt_cleaner ├── __init__.py └── cleaner.py ├── ebt_cli ├── __init__.py ├── __version__.py ├── ebt.spec ├── ddd.py ├── log.py └── cli.py ├── ebt_system ├── __init__.py ├── lvm.py ├── system.py └── btrfs.py ├── ebt_files ├── __init__.py ├── dd.py ├── archive.py ├── rsync.py └── ddd.py ├── plans.py ├── ebt.conf ├── .gitignore ├── setup.py ├── README.md └── LICENSE /ebt_jobs/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ebt_db/__init__.py: -------------------------------------------------------------------------------- 1 | from ebt_db.mysql import Mysql 2 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | -------------------------------------------------------------------------------- /ebt_virt/__init__.py: -------------------------------------------------------------------------------- 1 | from ebt_virt.libvirt_helper import Libvirt 2 | -------------------------------------------------------------------------------- /ebt_cloud/__init__.py: -------------------------------------------------------------------------------- 1 | from ebt_cloud.amazon import AmazonGlacier, S3 2 | -------------------------------------------------------------------------------- /ebt_cleaner/__init__.py: -------------------------------------------------------------------------------- 1 | from ebt_cleaner.cleaner import filter_list, last_backup, get_dir_name 2 | -------------------------------------------------------------------------------- /ebt_cli/__init__.py: -------------------------------------------------------------------------------- 1 | from ebt_cli.cli import ebt_cli 2 | from ebt_cli.ddd import ddd_cli 3 | 4 | -------------------------------------------------------------------------------- /ebt_system/__init__.py: -------------------------------------------------------------------------------- 1 | from ebt_system.system import popen, rm, makedirs 2 | import ebt_system.btrfs as btrfs 3 | import ebt_system.lvm as lvm 4 | 5 | -------------------------------------------------------------------------------- /ebt_files/__init__.py: -------------------------------------------------------------------------------- 1 | import ebt_files.rsync as rsync 2 | import ebt_files.dd as dd 3 | import ebt_files.archive as archive 4 | import ebt_files.ddd as ddd 5 | 6 | -------------------------------------------------------------------------------- /plans.py: -------------------------------------------------------------------------------- 1 | import ebt_jobs 2 | 3 | # Put your jobs here: 4 | """ 5 | def test_job(): 6 | backup = ebt_jobs.btrfs.BTRFSBackupFull(source='/', snap_dir='/.snap', dest_dir='/mnt/backup', day_exp=None, store_last=5) 7 | backup.start() 8 | """ 9 | -------------------------------------------------------------------------------- /ebt.conf: -------------------------------------------------------------------------------- 1 | [Config] 2 | logmethod = syslog, file 3 | loglevel = debug 4 | logfile = /var/log/ebt.log 5 | 6 | [MailConfig] 7 | from = ebt 8 | server = smtp.gmail.com 9 | port = 587 10 | login = login@gmail.com 11 | password = PaSSworD 12 | recipients = mymail@gmail.com, 13 | tls = True 14 | -------------------------------------------------------------------------------- /ebt_cli/__version__.py: -------------------------------------------------------------------------------- 1 | __name__ = "ebt" 2 | __version__ = "2.0.93" 3 | __author__ = "larrabee" 4 | __email__ = "kafatron@gmail.com" 5 | __description__ = "Flexible backup framework" 6 | __long_description__ = "Backup framework with rsync, mysql, libvirt, btrfs, lvm and amazon glacier plugins." 7 | __url__ = "https://github.com/larrabee/ebt" 8 | __license__ = "GPLv3" 9 | -------------------------------------------------------------------------------- /ebt_cli/ebt.spec: -------------------------------------------------------------------------------- 1 | [Config] 2 | logmethod = string_list(default=list('','')) 3 | loglevel = option('debug', 'info', 'warn', 'error', 'crit', default=info) 4 | logfile = string(default=/var/log/ebt.log) 5 | max_log_size = float(default=4194304) 6 | 7 | [MailConfig] 8 | from = string 9 | subject = string(default=ebt report) 10 | server = string 11 | port = string(default=25) 12 | login = string 13 | password = string 14 | recipients = string_list 15 | tls = boolean(default=True) 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /ebt_files/dd.py: -------------------------------------------------------------------------------- 1 | from ebt_system import popen as __popen 2 | import logging 3 | import sys 4 | from multiprocessing import cpu_count 5 | 6 | 7 | log = logging.getLogger('__main__') 8 | 9 | 10 | def create(source, dest, bs='8M', compress_level=0, compress_threads=cpu_count(), passwd=None): 11 | assert isinstance(source, str), '{1}.{2}: variable "{0}" has wrong type.' \ 12 | .format('source', __name__, sys._getframe().f_code.co_name) 13 | assert isinstance(dest, str), '{1}.{2}: variable "{0}" has wrong type.' \ 14 | .format('dest', __name__, sys._getframe().f_code.co_name) 15 | assert isinstance(bs, str), '{1}.{2}: variable "{0}" has wrong type.' \ 16 | .format('bs', __name__, sys._getframe().f_code.co_name) 17 | 18 | 19 | if compress_level > 0: 20 | command = 'dd if={0} bs={1} |pigz -c -{2} -p {3}'.format(source, bs, compress_level, compress_threads) 21 | else: 22 | command = 'dd if={0} bs={1}'.format(source, bs) 23 | 24 | if passwd is not None: 25 | command = '{0} |openssl enc -aes-256-cbc -k "{1}"'.format(command, passwd) 26 | 27 | command = '{0} |dd of={1} bs={2}'.format(command, dest, bs) 28 | 29 | __popen(command, shell=True) 30 | log.info('Successful create copy of {0} to {1}'.format(source, dest)) 31 | -------------------------------------------------------------------------------- /ebt_files/archive.py: -------------------------------------------------------------------------------- 1 | from ebt_system import popen as _popen 2 | import logging 3 | import sys 4 | 5 | log = logging.getLogger('__main__') 6 | 7 | 8 | def create7z(source, dest, level=5, password=None, options=None): 9 | assert isinstance(source, str), '{1}.{2}: variable "{0}" has wrong type.' \ 10 | .format('source', __name__, sys._getframe().f_code.co_name) 11 | assert isinstance(dest, str), '{1}.{2}: variable "{0}" has wrong type.' \ 12 | .format('dest', __name__, sys._getframe().f_code.co_name) 13 | assert isinstance(level, int), '{1}.{2}: variable "{0}" has wrong type.' \ 14 | .format('full', __name__, sys._getframe().f_code.co_name) 15 | assert isinstance(password, str) or (password is None), '{1}.{2}: variable "{0}" has wrong type.' \ 16 | .format('full', __name__, sys._getframe().f_code.co_name) 17 | assert isinstance(options, str) or (options is None), '{1}.{2}: variable "{0}" has wrong type.' \ 18 | .format('full', __name__, sys._getframe().f_code.co_name) 19 | command = '7za a -mhe=on -t7z -mx={0}'.format(str(level)) 20 | if password is not None: 21 | command += ' -p{0}'.format(password) 22 | if options is not None: 23 | command += ' {0}'.format(options) 24 | command += ' {0} {1}'.format(dest, source) 25 | _popen(command, logging_commands=False) 26 | log.info('Successful create 7z archive from {1} to {0}'.format(dest, source)) 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | 103 | # PyCharm service dirs 104 | .idea/ 105 | 106 | test.py -------------------------------------------------------------------------------- /ebt_files/rsync.py: -------------------------------------------------------------------------------- 1 | from ebt_system import popen as _popen 2 | import logging 3 | import sys 4 | 5 | 6 | log = logging.getLogger('__main__') 7 | 8 | 9 | def __list_to_string(file_list, mode): 10 | line = '' 11 | if len(file_list) > 0: 12 | for item in file_list: 13 | line += ' --{0}=\'{1}\''.format(mode, item) 14 | return line 15 | 16 | 17 | def full_copy(source, dest, rsync_options='aAX', include=list(), exclude=list()): 18 | assert isinstance(source, str), '{1}.{2}: variable "{0}" has wrong type.'\ 19 | .format('source', __name__, sys._getframe().f_code.co_name) 20 | assert isinstance(dest, str), '{1}.{2}: variable "{0}" has wrong type.'\ 21 | .format('dest', __name__, sys._getframe().f_code.co_name) 22 | assert isinstance(rsync_options, str), '{1}.{2}: variable "{0}" has wrong type.'\ 23 | .format('rsync_options', __name__, sys._getframe().f_code.co_name) 24 | command = 'rsync -{0}{1}{2} {3} {4}'.format(rsync_options, __list_to_string(include, 'include'), __list_to_string(exclude, 'exclude'), source, dest) 25 | _popen(command) 26 | log.info('Successful create full copy of {0} to {1}'.format(source, dest)) 27 | 28 | 29 | def diff_copy(source, full, dest, include=list(), exclude=list()): 30 | assert isinstance(source, str), '{1}.{2}: variable "{0}" has wrong type.'.format('source', __name__, sys._getframe().f_code.co_name) 31 | assert isinstance(full, str), '{1}.{2}: variable "{0}" has wrong type.'.format('full', __name__, sys._getframe().f_code.co_name) 32 | assert isinstance(dest, str), '{1}.{2}: variable "{0}" has wrong type.'.format('dest', __name__, sys._getframe().f_code.co_name) 33 | command = 'rsync -a{0}{1} --inplace --delete --backup --link-dest={2} {3} {4}'.format( 34 | __list_to_string(include, 'include'), __list_to_string(exclude, 'exclude'), full, source, dest) 35 | _popen(command) 36 | log.info('Successful create diff copy of {0} with full {1} to {2}'.format(source, full, dest)) 37 | -------------------------------------------------------------------------------- /ebt_jobs/rsync.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import ebt_cleaner 3 | import ebt_system 4 | import ebt_files 5 | import os 6 | 7 | log = logging.getLogger('__main__') 8 | 9 | 10 | class RsyncBackupFull(object): 11 | def __init__(self, source, dest_dir, day_exp, store_last, exclude=list(), include=list()): 12 | self.include = include 13 | self.exclude = exclude 14 | self.store_last = store_last 15 | self.day_exp = day_exp 16 | self.dest_dir = dest_dir 17 | self.source = source 18 | 19 | def _set_backup_dest(self): 20 | self.backup_date = ebt_cleaner.get_dir_name() 21 | self.dest = "{0}/{1}".format(self.dest_dir, self.backup_date) 22 | 23 | def _cleanup_old_backups(self): 24 | old_backups = ebt_cleaner.filter_list(path=self.dest_dir, dayexp=self.day_exp, store_last=self.store_last) 25 | ebt_system.rm(old_backups) 26 | 27 | def _pre_backup(self): 28 | pass 29 | 30 | def _post_backup(self): 31 | pass 32 | 33 | def _create_instance_backup(self): 34 | os.makedirs(self.dest) 35 | ebt_files.rsync.full_copy(source=self.source, dest=self.dest, exclude=self.exclude, include=self.include) 36 | 37 | def start(self): 38 | self._set_backup_dest() 39 | self._cleanup_old_backups() 40 | self._pre_backup() 41 | self._create_instance_backup() 42 | self._post_backup() 43 | 44 | 45 | class RsyncBackupDiff(RsyncBackupFull): 46 | def _set_backup_dest(self): 47 | self.backup_date = ebt_cleaner.get_dir_name() 48 | self.full = ebt_cleaner.last_backup(self.dest_dir) 49 | self.dest = "{0}/{1}%{2}".format(self.dest_dir, self.backup_date, str(self.full).split('/')[-1]) 50 | 51 | def _cleanup_old_backups(self): 52 | old_backups = ebt_cleaner.filter_list(path=self.dest_dir, dayexp=self.day_exp, store_last=self.store_last, fmt='%date%%%fdate') 53 | ebt_system.rm(old_backups) 54 | 55 | def _create_instance_backup(self): 56 | os.makedirs(self.dest) 57 | ebt_files.rsync.diff_copy(source=self.source, full=self.full, dest=self.dest, exclude=self.exclude, include=self.include) 58 | -------------------------------------------------------------------------------- /ebt_cli/ddd.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from ebt_files import ddd 3 | 4 | 5 | def ddd_cli(): 6 | import sys 7 | import argparse 8 | 9 | cli_parser = argparse.ArgumentParser() 10 | cli_parser.add_argument('-i', '--if', type=str, default=sys.stdin, help='Input File (Full copy)') 11 | cli_parser.add_argument('-d', '--df', type=str, default=sys.stdin, 12 | help='Diff File. For backup mode: changed file. For restore mode: binary diff file') 13 | cli_parser.add_argument('-o', '--of', type=str, default=sys.stdout, 14 | help='Output File. For backup mode: binary diff. For restore mode: restored file') 15 | cli_parser.add_argument('-m', '--mode', choices=['backup', 'restore'], default='backup', type=str, required=False, 16 | help='Working mode') 17 | cli_parser.add_argument('-b', '--block-size', type=int, default=8192, help='Block size') 18 | cli = cli_parser.parse_args() 19 | 20 | if (vars(cli)['if'] == sys.stdin) and (vars(cli)['df'] == sys.stdin) and (sys.stdin.isatty() is True): 21 | sys.stderr.write("--if and --df files should be specified\n") 22 | exit(1) 23 | elif (vars(cli)['if'] == sys.stdin) and (vars(cli)['df'] == sys.stdin) and (sys.stdin.isatty() is False): 24 | sys.stderr.write("Can not read both (--if and --df) files from stdin.\nYou should specify at least one\n") 25 | exit(1) 26 | 27 | if vars(cli)['if'] == sys.stdin: 28 | iffd = sys.stdin 29 | else: 30 | iffd = open(vars(cli)['if'], 'rb') 31 | if vars(cli)['df'] == sys.stdin: 32 | dffd = sys.stdin 33 | else: 34 | dffd = open(vars(cli)['df'], 'rb') 35 | if vars(cli)['of'] == sys.stdout: 36 | offd = sys.stdout 37 | else: 38 | offd = open(vars(cli)['of'], 'wb') 39 | 40 | if cli.mode == 'backup': 41 | differ = ddd.CreateDiff(iffd=iffd, dffd=dffd, offd=offd, block_size=cli.block_size) 42 | differ.start() 43 | elif cli.mode == 'restore': 44 | differ_restore = ddd.RestoreDiff(iffd=iffd, dffd=dffd, offd=offd, block_size=cli.block_size) 45 | differ_restore.start() 46 | -------------------------------------------------------------------------------- /ebt_system/lvm.py: -------------------------------------------------------------------------------- 1 | from ebt_system import popen as _popen 2 | import os 3 | import sys 4 | import logging 5 | 6 | log = logging.getLogger('__main__') 7 | 8 | 9 | def create_snapshot(source, size='10G', snap_suff='-snap'): 10 | assert isinstance(source, str), '{1}.{2}: variable "{0}" has wrong type.' \ 11 | .format('source', __name__, sys._getframe().f_code.co_name) 12 | assert isinstance(snap_suff, str), '{1}.{2}: variable "{0}" has wrong type.' \ 13 | .format('snap_suff', __name__, sys._getframe().f_code.co_name) 14 | assert isinstance(size, str), '{1}.{2}: variable "{0}" has wrong type.' \ 15 | .format('size', __name__, sys._getframe().f_code.co_name) 16 | snap_name = source + snap_suff 17 | command = 'lvcreate --size {0} -A y --snapshot --name {1} {2}'.format(size, snap_name, source) 18 | log.info('Create snapshot of {0} with name {1} and size {2}'.format(source, snap_name, size)) 19 | _popen(command=command) 20 | 21 | 22 | def remove_snap_if_exist(source, snap_suff='-snap'): 23 | assert isinstance(source, str), '{1}.{2}: variable "{0}" has wrong type.' \ 24 | .format('source', __name__, sys._getframe().f_code.co_name) 25 | assert isinstance(snap_suff, str), '{1}.{2}: variable "{0}" has wrong type.' \ 26 | .format('snap_suff', __name__, sys._getframe().f_code.co_name) 27 | snap_name = source + snap_suff 28 | if os.path.exists(snap_name): 29 | command = 'lvremove -A y {0} --force'.format(snap_name) 30 | log.info('Remove snapshot {0} of volume {1}'.format(snap_name, source)) 31 | _popen(command=command) 32 | else: 33 | log.info('Snapshot with name {0} not found. Skipping remove.'.format(snap_name)) 34 | 35 | 36 | def remove_snap(source, snap_suff='-snap'): 37 | assert isinstance(source, str), '{1}.{2}: variable "{0}" has wrong type.' \ 38 | .format('source', __name__, sys._getframe().f_code.co_name) 39 | assert isinstance(snap_suff, str), '{1}.{2}: variable "{0}" has wrong type.' \ 40 | .format('snap_suff', __name__, sys._getframe().f_code.co_name) 41 | snap_name = source + snap_suff 42 | command = 'lvremove -A y {0} --force'.format(snap_name) 43 | log.info('Remove snapshot {0} of volume {1}'.format(snap_name, source)) 44 | _popen(command=command) 45 | -------------------------------------------------------------------------------- /ebt_jobs/mysql.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import ebt_cleaner 3 | from ebt_system import rm 4 | import ebt_db 5 | import os 6 | 7 | log = logging.getLogger('__main__') 8 | 9 | 10 | class MySQLDump(object): 11 | def __init__(self, instances, dest_dir, day_exp=None, store_last=None): 12 | self.instances = instances 13 | self.dest_dir = dest_dir 14 | self.day_exp = day_exp 15 | self.store_last = store_last 16 | 17 | def _set_backup_dest(self): 18 | backup_date = ebt_cleaner.get_dir_name() 19 | self.dest = "{0}/{1}".format(self.dest_dir, backup_date) 20 | 21 | def _cleanup_old_backups(self): 22 | old_backups = ebt_cleaner.filter_list(path=self.dest_dir, dayexp=self.day_exp, store_last=self.store_last) 23 | rm(old_backups) 24 | 25 | def _pre_backup(self): 26 | pass 27 | 28 | def _post_backup(self): 29 | pass 30 | 31 | def _create_instance_backup(self, instance): 32 | instance['dest'] = "{0}/{1}".format(self.dest, instance['name']) 33 | client = ebt_db.Mysql(instance) 34 | log.info('Stop slave on server {0}'.format(instance['name'])) 35 | client.slave_stop() 36 | log.info('Create dest dir: {0}'.format(instance['dest'])) 37 | os.makedirs(instance['dest']) 38 | log.info('Start backup databases {0} from {1}'.format(instance['db'], instance['name'])) 39 | client.slave_status_to_file() 40 | client.mysqldump() 41 | log.info('Backup databases {0} from {1} finished'.format(instance['db'], instance['name'])) 42 | log.info('Start slave on server {0}'.format(instance['name'])) 43 | client.slave_start() 44 | 45 | def start(self): 46 | self._set_backup_dest() 47 | self._cleanup_old_backups() 48 | self._pre_backup() 49 | for instance in self.instances: 50 | self._create_instance_backup(instance) 51 | self._post_backup() 52 | 53 | 54 | class InnoBackupEX(MySQLDump): 55 | def _create_instance_backup(self, instance): 56 | instance['dest'] = "{0}/{1}".format(self.dest, instance['name']) 57 | client = ebt_db.Mysql(instance) 58 | log.info('Create dest dir: {0}'.format(instance['dest'])) 59 | os.makedirs(instance['dest']) 60 | log.info('Start backup databases from {0}'.format(instance['name'])) 61 | client.innobackupex() 62 | log.info('Backup databases from {0} finished'.format(instance['name'])) 63 | -------------------------------------------------------------------------------- /ebt_jobs/amazon.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from datetime import datetime, timedelta 3 | import ebt_cloud 4 | import os 5 | 6 | 7 | log = logging.getLogger('__main__') 8 | 9 | 10 | class CleanUpGlacier(object): 11 | def __init__(self, aws_access_key_id, aws_secret_access_key, region_name, vault, dayexp=365): 12 | self.dayexp = dayexp 13 | self.vault = vault 14 | self.glacier = ebt_cloud.AmazonGlacier(aws_access_key_id=aws_access_key_id, 15 | aws_secret_access_key=aws_secret_access_key, 16 | region_name=region_name) 17 | 18 | def _check_archive_expiration(self, archive): 19 | archive_id = archive['ArchiveId'] 20 | creation_date = datetime.strptime(archive['CreationDate'], "%Y-%m-%dT%H:%M:%SZ") 21 | description = archive['ArchiveDescription'] 22 | size_gb = int(archive['Size'] / (1024 * 1024 * 1024)) 23 | if creation_date + timedelta(days=self.dayexp) <= datetime.now(): 24 | log.info('Remove archive. ID: "{0}", Description: "{1}", Creation date: "{2}", Size in GB: "{3}"'.format( 25 | archive_id, description, creation_date, size_gb 26 | )) 27 | return True 28 | else: 29 | log.info('Skip archive. ID: "{0}", Description: "{1}", Creation date: "{2}", Size in GB: "{3}"'.format( 30 | archive_id, description, creation_date, size_gb 31 | )) 32 | return False 33 | pass 34 | 35 | def start(self): 36 | log.info('Cleanup vault "{0}"'.format(self.vault)) 37 | inventory = self.glacier.get_inventory(self.vault) 38 | for archive in inventory['ArchiveList']: 39 | if self._check_archive_expiration(archive) is True: 40 | self.glacier.delete_archive(vault_name=self.vault, archive_id=archive['ArchiveId']) 41 | 42 | 43 | class RetrieveArchive(object): 44 | def __init__(self, aws_access_key_id, aws_secret_access_key, region_name, vault, dest_dir): 45 | self.dest_dir = dest_dir 46 | self.vault = vault 47 | self.glacier = ebt_cloud.AmazonGlacier(aws_access_key_id=aws_access_key_id, 48 | aws_secret_access_key=aws_secret_access_key, 49 | region_name=region_name) 50 | 51 | def get_file(self, archive_id, filename=None): 52 | if filename is None: 53 | dest = os.path.join(self.dest_dir, archive_id) 54 | else: 55 | dest = os.path.join(self.dest_dir, filename) 56 | log.info("Download archive {0} to {1}".format(archive_id, dest)) 57 | self.glacier.download_file(self.vault, archive_id, dest) 58 | 59 | -------------------------------------------------------------------------------- /ebt_system/system.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import sys 3 | import shutil 4 | import os 5 | import subprocess 6 | import errno 7 | 8 | log = logging.getLogger('__main__') 9 | 10 | 11 | def popen(command, logging_commands=True, shell=False, executable='/bin/bash', cwd='./', valid_exitcodes=None): 12 | if valid_exitcodes is None: 13 | valid_exitcodes = [0, ] 14 | assert isinstance(command, str), '{1}.{2}: variable "{0}" has wrong type.' \ 15 | .format('command', __name__, sys._getframe().f_code.co_name) 16 | assert isinstance(logging_commands, bool), '{1}.{2}: variable "{0}" has wrong type.' \ 17 | .format('command', __name__, sys._getframe().f_code.co_name) 18 | if logging_commands: 19 | log.debug('Exec command: {0}'.format(command)) 20 | if shell: 21 | process = subprocess.Popen(command, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=shell, 22 | executable=executable, cwd=cwd) 23 | else: 24 | process = subprocess.Popen(command.split(), stderr=subprocess.STDOUT, stdout=subprocess.PIPE, cwd=cwd) 25 | output = process.communicate()[0] 26 | log.debug('Exit code: {0}, output: {1}'.format(process.returncode, output)) 27 | if process.returncode not in valid_exitcodes: 28 | log.error('External program exit with invalid exit code.') 29 | if logging_commands: 30 | raise RuntimeError('Error code:', str(process.returncode), 'Output: ', output, 'Command: ', command) 31 | else: 32 | raise RuntimeError('Error code:', str(process.returncode), 'Output: ', output) 33 | return process.returncode, output 34 | 35 | 36 | def rm(path): 37 | assert isinstance(path, str) or isinstance(path, list), '{1}.{2}: variable "{0}" has wrong type.' \ 38 | .format('path', __name__, sys._getframe().f_code.co_name) 39 | if type(path) is str: 40 | if os.path.isdir(path): 41 | shutil.rmtree(path) 42 | log.info('Remove directory: {0}'.format(path)) 43 | elif os.path.isfile(path): 44 | os.remove(path) 45 | log.info('Remove file: {0}'.format(path)) 46 | else: 47 | for item in path: 48 | if os.path.isdir(item): 49 | shutil.rmtree(item) 50 | log.info('Remove directory: {0}'.format(item)) 51 | elif os.path.isfile(item): 52 | os.remove(item) 53 | log.info('Remove file: {0}'.format(item)) 54 | 55 | 56 | def makedirs(path, exist_ok=False): 57 | if exist_ok is True: 58 | try: 59 | os.makedirs(path) 60 | except OSError as exc: 61 | if exc.errno == errno.EEXIST and os.path.isdir(path): 62 | pass 63 | else: 64 | raise 65 | else: 66 | os.makedirs(path) -------------------------------------------------------------------------------- /ebt_jobs/btrfs.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import ebt_cleaner 3 | import ebt_system 4 | 5 | log = logging.getLogger('__main__') 6 | 7 | 8 | class BTRFSBackupFull(object): 9 | def __init__(self, source, snap_dir, dest_dir, day_exp, store_last): 10 | self.store_last = store_last 11 | self.day_exp = day_exp 12 | self.dest_dir = dest_dir 13 | self.snap_dir = snap_dir 14 | self.source = source 15 | 16 | def _set_backup_dest(self): 17 | self.backup_date = ebt_cleaner.get_dir_name() 18 | self.dest = "{0}/{1}".format(self.dest_dir, self.backup_date) 19 | self.snap = "{0}/{1}".format(self.snap_dir, self.backup_date) 20 | 21 | def _cleanup_old_backups(self): 22 | old_backups = ebt_cleaner.filter_list(path=self.dest_dir, dayexp=self.day_exp, store_last=self.store_last) 23 | ebt_system.rm(old_backups) 24 | 25 | def _cleanup_old_snapshots(self): 26 | old_snapshots = ebt_cleaner.filter_list(path=self.snap_dir, dayexp=self.day_exp, store_last=self.store_last) 27 | ebt_system.btrfs.subvolume_delete(old_snapshots) 28 | 29 | def _pre_backup(self): 30 | pass 31 | 32 | def _post_backup(self): 33 | pass 34 | 35 | def _create_instance_backup(self): 36 | ebt_system.btrfs.subvolume_create_snapshot(source=self.source, dest=self.snap, readonly=True) 37 | ebt_system.btrfs.subvolume_send(source=self.snap, dest=self.dest, compress_level=6) 38 | 39 | def start(self): 40 | self._set_backup_dest() 41 | self._cleanup_old_backups() 42 | self._cleanup_old_snapshots() 43 | self._pre_backup() 44 | self._create_instance_backup() 45 | self._post_backup() 46 | 47 | 48 | class BTRFSBackupDiff(BTRFSBackupFull): 49 | def _set_backup_dest(self): 50 | self.backup_date = ebt_cleaner.get_dir_name() 51 | self.full = ebt_cleaner.last_backup(self.dest_dir) 52 | self.snap_full = "{0}/{1}".format(self.snap_dir, str(self.full).split('/')[-1]) 53 | self.dest = "{0}/{1}%{2}".format(self.dest_dir, self.backup_date, str(self.full).split('/')[-1]) 54 | self.snap = "{0}/{1}%{2}".format(self.snap_dir, self.backup_date, str(self.full).split('/')[-1]) 55 | 56 | def _cleanup_old_backups(self): 57 | old_backups = ebt_cleaner.filter_list(path=self.dest_dir, dayexp=self.day_exp, store_last=self.store_last, fmt='%date%%%fdate') 58 | ebt_system.rm(old_backups) 59 | 60 | def _cleanup_old_snapshots(self): 61 | old_snapshots = ebt_cleaner.filter_list(path=self.snap_dir, dayexp=self.day_exp, store_last=self.store_last, fmt='%date%%%fdate') 62 | ebt_system.btrfs.subvolume_delete(old_snapshots) 63 | 64 | def _create_instance_backup(self): 65 | ebt_system.btrfs.subvolume_create_snapshot(source=self.source, dest=self.snap, readonly=True) 66 | ebt_system.btrfs.subvolume_send(source=self.snap, dest=self.dest, parent_path=self.snap_full, compress_level=6) 67 | -------------------------------------------------------------------------------- /ebt_cleaner/cleaner.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import os 3 | import re 4 | import sys 5 | from datetime import datetime, timedelta 6 | 7 | 8 | def __sort_by_date(string): 9 | return string[6:10] + string[3:5] + string[0:2] + string[11:13] + string[14:16] 10 | 11 | 12 | def filter_list(path, fmt='%date', dayexp=None, store_last=None): 13 | """ 14 | fmt принимает текст и символы в формате Python regex, а так-же параметры в формате %parameter 15 | Список параметров: 16 | %date - заменяется на regex даты в формате "%d-%m-%Y_%H:%M" (обозначает текущую дату) 17 | %fdate - заменяется на regex даты в формате "%d-%m-%Y_%H:%M" (обозначает дату полного бэкапа) 18 | %% заменяется на % (используется как разделитель) 19 | 20 | dayexp - кол-во дней, по проществии которых необходимо удалять бэкап 21 | store_last - сколько необходимо хранить копий 22 | path - директория, в которой необходимо искать бэкапы 23 | Возвращает список бэкапов на удаление. 24 | Если dayexp и store_last не указанны, то возвращает список всех найденных бэкапов. 25 | """ 26 | assert isinstance(path, str), '{1}.{2}: variable "{0}" has wrong type.'.format('path', __name__, sys._getframe().f_code.co_name) 27 | assert isinstance(fmt, str), '{1}.{2}: variable "{0}" has wrong type.'.format('format', __name__, sys._getframe().f_code.co_name) 28 | assert isinstance(dayexp, int) or (dayexp is None), '{1}.{2}: variable "{0}" has wrong type.'.format('dayexp', __name__, sys._getframe().f_code.co_name) 29 | assert isinstance(store_last, int) or (store_last is None), '{1}.{2}: variable "{0}" has wrong type.'.format('store_last', __name__, sys._getframe().f_code.co_name) 30 | formated_list = list() 31 | filtered_list = list() 32 | full_list = list() 33 | fmt = str(fmt).replace('%date', '([\d]{2}[-][\d]{2}[-][\d]{4}[_][\d]{2}[:][\d]{2})') 34 | fmt = str(fmt).replace('%fdate', '([\d]{2}[-][\d]{2}[-][\d]{4}[_][\d]{2}[:][\d]{2})') 35 | fmt = fmt.replace('%%', '[%%]') 36 | regex = '\A' + fmt + '\Z' 37 | comp_regex = re.compile(regex) 38 | dirs = os.listdir(path) 39 | for directory in dirs: 40 | if re.match(comp_regex, directory) is not None: 41 | formated_list.append(directory) 42 | formated_list.sort(reverse=True, key=__sort_by_date) 43 | 44 | if (dayexp is None) and (store_last is None): 45 | filtered_list = formated_list 46 | if dayexp is not None: 47 | dayexp_delta = timedelta(days=dayexp) 48 | for backup in formated_list: 49 | if datetime.strptime(backup.split('%')[0], '%d-%m-%Y_%H:%M') + dayexp_delta <= datetime.now(): 50 | if backup not in filtered_list: 51 | filtered_list.append(backup) 52 | if store_last is not None: 53 | for backup in formated_list[store_last:]: 54 | if backup not in filtered_list: 55 | filtered_list.append(backup) 56 | 57 | for element in filtered_list: 58 | full_list.append(path + '/' + element) 59 | return full_list 60 | 61 | 62 | def last_backup(path, fmt='%date'): 63 | backup = filter_list(path=path, fmt=fmt) 64 | return backup[0] 65 | 66 | 67 | def get_dir_name(fdate=None): 68 | if fdate is None: 69 | name = datetime.now().strftime('%d-%m-%Y_%H:%M') 70 | else: 71 | name = '{0}%{1}'.format(fdate, datetime.now().strftime('%d-%m-%Y_%H:%M')) 72 | return name 73 | -------------------------------------------------------------------------------- /ebt_files/ddd.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import struct 4 | 5 | 6 | class CreateDiff: 7 | def __init__(self, iffd, dffd, offd, block_size=8192): 8 | self.block_size = block_size 9 | self.iffd = iffd 10 | self.dffd = dffd 11 | self.offd = offd 12 | self.ifgen = self.__read_file_generator(self.iffd) 13 | self.dfgen = self.__read_file_generator(self.dffd) 14 | self.header = '' 15 | 16 | def __read_file_generator(self, fd): 17 | while True: 18 | chunk = fd.read(self.block_size) 19 | if chunk: 20 | yield chunk 21 | else: 22 | break 23 | 24 | def __write_file(self, block_number, data): 25 | block_number_bytes = struct.pack('@Q', block_number) 26 | self.offd.write(block_number_bytes) 27 | self.offd.write(data) 28 | 29 | # Reserved header for further use 30 | def __write_header(self, header_string): 31 | data = struct.pack('@32768s', header_string.encode()) 32 | self.offd.write(data) 33 | 34 | def start(self): 35 | self.__write_header(self.header) 36 | block_counter = 0 37 | while True: 38 | try: 39 | ifdata = next(self.ifgen) 40 | except StopIteration: 41 | ifdata = None 42 | try: 43 | dfdata = next(self.dfgen) 44 | except StopIteration: 45 | dfdata = None 46 | if dfdata is None: 47 | self.__write_file(block_counter, bytes()) 48 | break 49 | elif ifdata == dfdata: 50 | block_counter += 1 51 | continue 52 | else: 53 | self.__write_file(block_counter, dfdata) 54 | block_counter += 1 55 | 56 | 57 | class RestoreDiff: 58 | def __init__(self, iffd, dffd, offd, block_size=8192): 59 | self.block_size = block_size 60 | self.iffd = iffd 61 | self.dffd = dffd 62 | self.offd = offd 63 | self.ifgen = self.__read_file_generator(self.iffd, block_size=self.block_size) 64 | self.dfgen = self.__read_file_generator(self.dffd, block_size=self.block_size + 8) 65 | self.header = self.__read_header() 66 | 67 | @staticmethod 68 | def __read_file_generator(fd, block_size): 69 | while True: 70 | chunk = fd.read(block_size) 71 | if chunk: 72 | yield chunk 73 | else: 74 | break 75 | 76 | def __write_file(self, data): 77 | self.offd.write(data) 78 | 79 | def __read_header(self): 80 | header_bin = self.dffd.read(32768) 81 | header = (struct.unpack('@32768s', header_bin)[0]).decode() 82 | return header 83 | 84 | def start(self): 85 | block_counter = 0 86 | dfdata = next(self.dfgen) 87 | dfdata_block_number = struct.unpack('@Q', dfdata[0:8])[0] 88 | dfdata_data = dfdata[8:] 89 | while True: 90 | try: 91 | ifdata = next(self.ifgen) 92 | except StopIteration: 93 | ifdata = None 94 | if (len(dfdata_data) == 0) and (dfdata_block_number == block_counter): 95 | break 96 | elif dfdata_block_number == block_counter: 97 | data = dfdata_data 98 | dfdata = next(self.dfgen) 99 | dfdata_block_number = struct.unpack('@Q', dfdata[0:8])[0] 100 | dfdata_data = dfdata[8:] 101 | else: 102 | data = ifdata 103 | self.__write_file(data) 104 | block_counter += 1 105 | 106 | -------------------------------------------------------------------------------- /ebt_cli/log.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import logging.handlers 3 | import smtplib 4 | from email.utils import formatdate 5 | 6 | 7 | class BufferingSMTPHandler(logging.handlers.SMTPHandler): 8 | def __init__(self, mailhost, fromaddr, toaddrs, subject, credentials=None, 9 | secure=None, capacity=1024 * 1000): 10 | logging.handlers.SMTPHandler.__init__(self, mailhost, fromaddr, 11 | toaddrs, subject, 12 | credentials, secure) 13 | 14 | self.capacity = capacity 15 | self.buffer = list() 16 | 17 | def emit(self, record): 18 | try: 19 | self.buffer.append(record) 20 | 21 | if len(self.buffer) >= self.capacity: 22 | self.flush() 23 | except (KeyboardInterrupt, SystemExit): 24 | raise 25 | except: 26 | self.handleError(record) 27 | 28 | def flush(self): 29 | if not self.buffer: 30 | return 31 | 32 | try: 33 | port = self.mailport 34 | if not port: 35 | port = smtplib.SMTP_PORT 36 | smtp = smtplib.SMTP(self.mailhost, port) 37 | msg = "From: {0}\nTo: {1}\nSubject: {2}\nDate: {3}\n\n".format( 38 | self.fromaddr, 39 | ",".join(self.toaddrs), 40 | self.getSubject(self.buffer[0]), 41 | formatdate()) 42 | for record in self.buffer: 43 | msg = msg + self.format(record) + "\r\n" 44 | 45 | if self.username: 46 | if self.secure is not None: 47 | smtp.ehlo() 48 | smtp.starttls(*self.secure) 49 | smtp.ehlo() 50 | smtp.login(self.username, self.password) 51 | smtp.sendmail(self.fromaddr, self.toaddrs, msg) 52 | smtp.quit() 53 | self.buffer = [] 54 | except (KeyboardInterrupt, SystemExit): 55 | raise 56 | except: 57 | self.handleError(self.buffer[0]) 58 | 59 | 60 | class Configurator: 61 | def __init__(self): 62 | self.msg_format = "%(asctime)s %(levelname)s: %(message)s" 63 | self.date_format = "%d-%m-%Y %H:%M:%S" 64 | self.formatter = logging.Formatter(fmt=self.msg_format, datefmt=self.date_format) 65 | logging.basicConfig(format=self.msg_format, datefmt=self.date_format, level=logging.DEBUG) 66 | self.log = logging.getLogger("__main__") 67 | 68 | def get_logger(self): 69 | return self.log 70 | 71 | def set_level(self, severity): 72 | log_levels = {'debug': logging.DEBUG, 'info': logging.INFO, 'warn': logging.WARN, 'error': logging.ERROR, 73 | 'crit': logging.CRITICAL} 74 | self.log.setLevel(log_levels[severity]) 75 | 76 | def add_syslog_handler(self, address='/dev/log', facility='user'): 77 | syslog_handler = logging.handlers.SysLogHandler(address=address, facility=facility) 78 | self.log.addHandler(syslog_handler) 79 | self.log.debug('Syslog handler successfully added') 80 | 81 | def add_file_handler(self, path, max_size): 82 | file_handler = logging.handlers.RotatingFileHandler(path, maxBytes=max_size) 83 | file_handler.setFormatter(self.formatter) 84 | self.log.addHandler(file_handler) 85 | self.log.debug('File handler successfully added') 86 | 87 | def add_smtp_handler(self, fromaddr, mailhost, toaddrs, subject, secure, credentials): 88 | smtp_handler = BufferingSMTPHandler(fromaddr=fromaddr, mailhost=mailhost, toaddrs=toaddrs, subject=subject, 89 | secure=secure, credentials=credentials) 90 | smtp_handler.setFormatter(self.formatter) 91 | self.log.addHandler(smtp_handler) 92 | self.log.debug('SMTP handler successfully added') 93 | -------------------------------------------------------------------------------- /ebt_system/btrfs.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import sys 3 | from ebt_system import popen as _popen 4 | from multiprocessing import cpu_count 5 | 6 | log = logging.getLogger('__main__') 7 | 8 | 9 | def subvolume_list(path): 10 | assert isinstance(path, str), '{1}.{2}: variable "{0}" has wrong type.' \ 11 | .format('path', __name__, sys._getframe().f_code.co_name) 12 | command = 'btrfs subvolume list {0}'.format(str(path)) 13 | raw_output = _popen(command)[0] 14 | form_output = raw_output.decode() 15 | output = list() 16 | for string in form_output.split(sep='\n'): 17 | string = string.split(sep=' ') 18 | if len(string) > 1: 19 | output_element = {'id': string[1], 'gen': string[3], 'parrent': string[6], 'path': string[8]} 20 | output.append(output_element) 21 | return output 22 | 23 | 24 | def subvolume_delete(path): 25 | assert isinstance(path, str) or isinstance(path, list), '{1}.{2}: variable "{0}" has wrong type.' \ 26 | .format('path', __name__, sys._getframe().f_code.co_name) 27 | if type(path) is str: 28 | command = 'btrfs subvolume delete {0}'.format(path) 29 | _popen(command) 30 | log.info('Delete btrfs subvolume {0}'.format(path)) 31 | else: 32 | for subvolume in path: 33 | command = 'btrfs subvolume delete {0}'.format(subvolume) 34 | _popen(command) 35 | log.info('Delete btrfs subvolume {0}'.format(subvolume)) 36 | 37 | 38 | def subvolume_create_snapshot(source, dest, readonly=True): 39 | assert isinstance(source, str), '{1}.{2}: variable "{0}" has wrong type.' \ 40 | .format('source', __name__, sys._getframe().f_code.co_name) 41 | assert isinstance(dest, str), '{1}.{2}: variable "{0}" has wrong type.' \ 42 | .format('dest', __name__, sys._getframe().f_code.co_name) 43 | assert isinstance(readonly, bool), '{1}.{2}: variable "{0}" has wrong type.' \ 44 | .format('readonly', __name__, sys._getframe().f_code.co_name) 45 | command = 'btrfs subvolume snapshot' 46 | if readonly: 47 | command = '{0} -r'.format(command) 48 | command = "{0} {1} {2}".format(command, source, dest) 49 | _popen(command) 50 | log.info('Create snapshot of {0} to {1} , readonly: {2}'.format(source, dest, str(readonly))) 51 | 52 | 53 | def file_create_snapshot(source, dest): 54 | assert isinstance(source, str), '{1}.{2}: variable "{0}" has wrong type.' \ 55 | .format('source', __name__, sys._getframe().f_code.co_name) 56 | assert isinstance(dest, str), '{1}.{2}: variable "{0}" has wrong type.' \ 57 | .format('dest', __name__, sys._getframe().f_code.co_name) 58 | command = 'cp --reflink {0} {1}'.format(source, dest) 59 | _popen(command) 60 | log.info('Create snapshot of file {0} to {1}'.format(source, dest)) 61 | 62 | 63 | def subvolume_send(source, dest, parent_path=None, compress_level=0, compress_threads=cpu_count()): 64 | assert isinstance(source, str), '{1}.{2}: variable "{0}" has wrong type.' \ 65 | .format('source', __name__, sys._getframe().f_code.co_name) 66 | assert isinstance(dest, str), '{1}.{2}: variable "{0}" has wrong type.' \ 67 | .format('dest', __name__, sys._getframe().f_code.co_name) 68 | assert (compress_level is None) or (isinstance(compress_level, int) and (compress_level in range(0, 9))), \ 69 | '{1}.{2}: variable "{0}" has wrong type.'.format('compress', __name__, sys._getframe().f_code.co_name) 70 | assert isinstance(parent_path, str) or (parent_path is None), '{1}.{2}: variable "{0}" has wrong type.' \ 71 | .format('parent_path', __name__, sys._getframe().f_code.co_name) 72 | if parent_path is not None: 73 | command = 'btrfs send -p {0} {1}'.format(parent_path, source) 74 | else: 75 | command = 'btrfs send {0}'.format(source) 76 | if compress_level > 0: 77 | command = "{0} |pigz -c -{1} -p {2}".format(command, compress_level, compress_threads) 78 | command = "{0} > {1}".format(command, dest) 79 | _popen(command, shell=True) 80 | log.info('Send subvolume {0} to {1} , parrent: {2}'.format(source, dest, str(parent_path))) 81 | 82 | 83 | -------------------------------------------------------------------------------- /ebt_cli/cli.py: -------------------------------------------------------------------------------- 1 | def ebt_cli(): 2 | import argparse 3 | import sys 4 | import traceback 5 | from configobj import ConfigObj 6 | from validate import Validator 7 | import os 8 | import ebt_cli.log 9 | import inspect 10 | from ebt_cli.__version__ import __version__ 11 | 12 | getfunctions = lambda func: [x[0] for x in inspect.getmembers(func, inspect.isfunction)] 13 | 14 | # Base vars 15 | config_spec_filename = os.path.dirname(os.path.realpath(__file__)) + '/ebt.spec' 16 | 17 | # Command line parser 18 | cli_parser = argparse.ArgumentParser() 19 | cli_parser.add_argument('-j', '--jobs', nargs='+', help='List of jobs to run') 20 | cli_parser.add_argument('-p', '--plan', default='/etc/ebt/plans.py', type=str, help='Custom path to plans file') 21 | cli_parser.add_argument('-c', '--config', default='/etc/ebt/ebt.conf', type=str, help='Custom path to config file') 22 | cli_parser.add_argument('-v', '--version', default=False, action='store_true', 23 | help='Display program version and exit') 24 | cli = cli_parser.parse_args() 25 | 26 | # Import plans file 27 | sys.path.append(os.path.dirname(cli.plan)) 28 | plans = __import__(os.path.splitext(os.path.basename(cli.plan))[0]) 29 | 30 | # Base logging 31 | log_configurator = ebt_cli.log.Configurator() 32 | log = log_configurator.get_logger() 33 | 34 | # Config Parser 35 | cfg_parser = ConfigObj(cli.config, configspec=config_spec_filename) 36 | validator = Validator() 37 | result = cfg_parser.validate(validator) 38 | if result is not True: 39 | log.critical('Config validation failed.') 40 | log.debug('Validation result: {0}'.format(result)) 41 | exit(1) 42 | config = cfg_parser['Config'] 43 | 44 | if cli.version: 45 | print('Version: {0}'.format(__version__)) 46 | exit(0) 47 | 48 | if cli.jobs is None: 49 | print('Nothing to do') 50 | exit(0) 51 | 52 | # Logging 53 | log_configurator.set_level(severity=config['loglevel']) 54 | 55 | if 'file' in config['logmethod']: 56 | try: 57 | log_configurator.add_file_handler(path=config['logfile'], max_size=config['max_log_size']) 58 | except Exception: 59 | log.error('Cannot add file handler') 60 | if 'syslog' in config['logmethod']: 61 | try: 62 | log_configurator.add_syslog_handler() 63 | except Exception: 64 | log.error('Cannot add syslog handler') 65 | if 'smtp' in config['logmethod']: 66 | try: 67 | mail_config = cfg_parser['MailConfig'] 68 | if mail_config['tls']: 69 | secure = tuple() 70 | else: 71 | secure = None 72 | log_configurator.add_smtp_handler(fromaddr=mail_config['from'], 73 | mailhost=(mail_config['server'], mail_config['port']), 74 | toaddrs=mail_config['recipients'], subject=mail_config['subject'], 75 | credentials=(mail_config['login'], mail_config['password']), 76 | secure=secure) 77 | except Exception: 78 | log.error('Cannot add SMTP handler') 79 | 80 | log.info('=' * 30 + 'Program started' + '=' * 30) 81 | exit_code = 0 82 | for job in cli.jobs: 83 | if job not in getfunctions(plans): 84 | log.error('Job "{0}" not found in "{1}"'.format(job, cli.plan)) 85 | exit_code = 1 86 | break 87 | log.info('-' * 30 + 'Job "{0}" started'.format(job) + '-' * 30) 88 | try: 89 | getattr(plans, job)() 90 | except AssertionError as e: 91 | log.error('Assertion Error: {0}'.format(e)) 92 | _, _, tb = sys.exc_info() 93 | log.debug(traceback.format_tb(tb)) 94 | exit_code = 1 95 | except Exception as e: 96 | log.error(e) 97 | log.debug(traceback.format_exc()) 98 | exit_code = 1 99 | log.info('-' * 30 + 'Job "{0}" finished'.format(job) + '-' * 30) 100 | log.info('=' * 30 + 'Program halted' + '=' * 30) 101 | exit(exit_code) 102 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """A setuptools based setup module. 2 | See: 3 | https://packaging.python.org/en/latest/distributing.html 4 | https://github.com/pypa/sampleproject 5 | """ 6 | 7 | # Always prefer setuptools over distutils 8 | from setuptools import setup, find_packages 9 | from shutil import copyfile 10 | import os 11 | # To use a consistent encoding 12 | from os import path 13 | import ebt_cli.__version__ 14 | 15 | here = path.abspath(path.dirname(__file__)) 16 | 17 | 18 | setup( 19 | name=ebt_cli.__version__.__name__, 20 | 21 | # Versions should comply with PEP440. For a discussion on single-sourcing 22 | # the version across setup.py and the project code, see 23 | # https://packaging.python.org/en/latest/single_source_version.html 24 | version=ebt_cli.__version__.__version__, 25 | 26 | description=ebt_cli.__version__.__description__, 27 | long_description=ebt_cli.__version__.__long_description__, 28 | 29 | # The project's main homepage. 30 | url=ebt_cli.__version__.__url__, 31 | 32 | # Author details 33 | author=ebt_cli.__version__.__author__, 34 | author_email=ebt_cli.__version__.__email__, 35 | 36 | # Choose your license 37 | license=ebt_cli.__version__.__license__, 38 | 39 | # See https://pypi.python.org/pypi?%3Aaction=list_classifiers 40 | classifiers=[ 41 | 'Development Status :: 5 - Production/Stable', 42 | 'Environment :: Console', 43 | 'Intended Audience :: System Administrators', 44 | 'Operating System :: POSIX :: Linux', 45 | 'Operating System :: Unix', 46 | 'Topic :: Utilities', 47 | 'Topic :: System :: Archiving :: Backup', 48 | 49 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 50 | 51 | # Specify the Python versions you support here. In particular, ensure 52 | # that you indicate whether you support Python 2, Python 3 or both. 53 | 'Programming Language :: Python :: 2.7', 54 | 'Programming Language :: Python :: 3', 55 | ], 56 | 57 | # What does your project relate to? 58 | keywords='diff-dd diff disk dump tool', 59 | 60 | # You can just specify the packages manually here if your project is 61 | # simple. Or you can use find_packages(). 62 | packages=find_packages(), 63 | 64 | # Alternatively, if you want to distribute just a my_module.py, uncomment 65 | # this: 66 | # py_modules=["my_module"], 67 | 68 | # List run-time dependencies here. These will be installed by pip when 69 | # your project is installed. For an analysis of "install_requires" vs pip's 70 | # requirements files see: 71 | # https://packaging.python.org/en/latest/requirements.html 72 | install_requires=["configobj", "boto>=2,<3", "mysqlclient==1.4.6", "lxml", 'multiprocess'], 73 | 74 | # List additional groups of dependencies here (e.g. development 75 | # dependencies). You can install these using the following syntax, 76 | # for example: 77 | # $ pip install -e .[dev,test] 78 | extras_require={}, 79 | 80 | # If there are data files included in your packages that need to be 81 | # installed, specify them here. If using Python 2.6 or less, then these 82 | # have to be included in MANIFEST.in as well. 83 | package_data={ 84 | # If any package contains *.txt or *.rst files, include them: 85 | '': ['*.spec', ], 86 | }, 87 | 88 | # Although 'package_data' is the preferred approach, in some case you may 89 | # need to place data files outside of your packages. See: 90 | # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa 91 | # In this case, 'data_file' will be installed into '/my_data' 92 | 93 | # To provide executable scripts, use entry points in preference to the 94 | # "scripts" keyword. Entry points provide cross-platform support and allow 95 | # pip to create the appropriate form of executable for the target platform. 96 | entry_points={ 97 | 'console_scripts': [ 98 | 'ddd=ebt_cli:ddd_cli', 99 | 'ebt=ebt_cli:ebt_cli', 100 | ], 101 | }, 102 | ) 103 | 104 | config_dir = '/etc/ebt/' 105 | config_files = [ 106 | (config_dir, 'ebt.conf'), 107 | (config_dir, 'plans.py'), 108 | ] 109 | 110 | for config in config_files: 111 | if not path.exists(config[0]): 112 | os.makedirs(config[0]) 113 | if not path.exists(path.join(config[0], config[1])): 114 | copyfile(config[1], path.join(config[0], config[1])) 115 | -------------------------------------------------------------------------------- /ebt_db/mysql.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import MySQLdb 3 | from ebt_system import popen as _popen 4 | from multiprocessing import cpu_count 5 | 6 | 7 | class Mysql: 8 | def __init__(self, params): 9 | self.log = logging.getLogger('__main__') 10 | self.params = params 11 | 12 | def exec_command(self, sql_command): 13 | if 'unix_socket' in self.params: 14 | if self.params['passwd'] is None: 15 | db = MySQLdb.connect(unix_socket=self.params['unix_socket'], user=self.params['user'], charset='utf8') 16 | else: 17 | db = MySQLdb.connect(unix_socket=self.params['unix_socket'], user=self.params['user'], 18 | passwd=self.params['passwd'], 19 | charset='utf8') 20 | else: 21 | if self.params['passwd'] is None: 22 | db = MySQLdb.connect(host=self.params['host'], port=self.params['port'], user=self.params['user'], 23 | charset='utf8') 24 | else: 25 | db = MySQLdb.connect(host=self.params['host'], port=self.params['port'], user=self.params['user'], 26 | passwd=self.params['passwd'], charset='utf8') 27 | cursor = db.cursor(MySQLdb.cursors.DictCursor) 28 | self.log.debug('Mysql exec command: {0}'.format(sql_command)) 29 | cursor.execute(sql_command) 30 | data = cursor.fetchall() 31 | db.commit() 32 | return data 33 | 34 | def slave_start(self): 35 | self.exec_command('start slave') 36 | 37 | def slave_stop(self): 38 | self.exec_command('stop slave') 39 | 40 | def slave_status(self): 41 | return self.exec_command('SHOW SLAVE STATUS')[0] 42 | 43 | def slave_status_to_file(self, file_name='slave_data'): 44 | slave_data_file = open('{0}/{1}'.format(self.params['dest'], file_name), 'w') 45 | slave_status = self.slave_status() 46 | slave_data_file.write( 47 | 'CHANGE MASTER TO MASTER_HOST="{0}", MASTER_PORT={1}, MASTER_USER="{2}", MASTER_LOG_FILE="{3}", MASTER_LOG_POS={4};\n'.format( 48 | slave_status['Master_Host'], slave_status['Master_Port'], slave_status['Master_User'], 49 | slave_status['Master_Log_File'], slave_status['Exec_Master_Log_Pos'])) 50 | for key, value in slave_status.iteritems(): 51 | slave_data_file.write('#\t{0}: {1}\n'.format(key, value)) 52 | slave_data_file.close() 53 | 54 | def mysqldump(self): 55 | for database in self.params['db']: 56 | command = 'mysqldump' 57 | if 'unix_socket' in self.params: 58 | command += ' -S{0}'.format(self.params['unix_socket']) 59 | else: 60 | command += ' -h{0} -P{1}'.format(self.params['host'], self.params['port']) 61 | if self.params['passwd'] is not None: 62 | command += ' -p{0}'.format(self.params['passwd']) 63 | command += ' -u{0} {1} {2}'.format(self.params['user'], self.params['dump_args'], database) 64 | if self.params['compress_level'] > 0: 65 | compress_threads = self.params['compress-threads'] if ( 66 | 'compress-threads' in self.params) else cpu_count() 67 | command += ' |pigz -c -{2} -p {3} > {0}/{1}.sql.gz'.format(self.params['dest'], database, 68 | self.params['compress_level'], 69 | compress_threads) 70 | else: 71 | command += ' > {0}/{1}.sql'.format(self.params['dest'], database) 72 | self.log.debug('Mysql dump command: {0}'.format(command)) 73 | _popen(command=command, shell=True) 74 | 75 | def innobackupex(self): 76 | command = 'innobackupex --no-timestamp' 77 | if 'unix_socket' in self.params: 78 | command += ' -S{0}'.format(self.params['unix_socket']) 79 | else: 80 | command += ' -h{0} -P{1}'.format(self.params['host'], self.params['port']) 81 | if self.params['passwd'] is not None: 82 | command += ' -p{0}'.format(self.params['passwd']) 83 | command += ' -u{0} {1}'.format(self.params['user'], self.params['dump_args']) 84 | if self.params['compress']: 85 | command += ' --compress --compress-threads={0}'.format(self.params['compress-threads']) 86 | if self.params['db']: 87 | command += ' --databases {0}'.format(' '.join(self.params['db'])) 88 | command += ' {0}'.format(self.params['dest']) 89 | self.log.debug('Innobackupex command: {0}'.format(command)) 90 | _popen(command=command, shell=True) 91 | -------------------------------------------------------------------------------- /ebt_cloud/amazon.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from boto.glacier.layer2 import Layer2 3 | from boto import connect_s3 4 | import boto.s3.connection 5 | import time 6 | import datetime 7 | import ebt_system 8 | import os 9 | import multiprocess as mp 10 | from functools import partial 11 | from contextlib import contextmanager 12 | 13 | 14 | class AmazonGlacier: 15 | def __init__(self, aws_access_key_id, aws_secret_access_key, region_name): 16 | self.log = logging.getLogger('__main__') 17 | logging.getLogger('boto').setLevel(logging.CRITICAL) 18 | self.glacier_client = Layer2(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, 19 | region_name=region_name) 20 | 21 | def upload_file(self, vault_name, description, path): 22 | if self.is_vault_exist(vault_name): 23 | vault = self.glacier_client.get_vault(vault_name) 24 | else: 25 | vault = self.create_vault(vault_name) 26 | archive_id = vault.concurrent_create_archive_from_file(path, description, part_size=4194304) 27 | self.log.debug('File "{0}" upload successful. Archive id: "{1}"'.format(path, archive_id)) 28 | return archive_id 29 | 30 | def create_vault(self, vault_name): 31 | vault = self.glacier_client.create_vault(name=vault_name) 32 | return vault 33 | 34 | def is_vault_exist(self, vault_name): 35 | vaults = [i.name for i in self.glacier_client.list_vaults()] 36 | if vault_name in vaults: 37 | return True 38 | else: 39 | return False 40 | 41 | def get_inventory(self, vault_name, sleep_interval=1200): 42 | vault = self.glacier_client.get_vault(vault_name) 43 | inventory_job_id = vault.retrieve_inventory() 44 | job = vault.get_job(inventory_job_id) 45 | while not job.completed: 46 | time.sleep(sleep_interval) 47 | job = vault.get_job(inventory_job_id) 48 | inventory = job.get_output() 49 | return inventory 50 | 51 | def download_file(self, vault_name, archive_id, dest, sleep_interval=1200): 52 | vault = self.glacier_client.get_vault(vault_name) 53 | job = vault.retrieve_archive(archive_id) 54 | job_id = job.id 55 | while not job.completed: 56 | time.sleep(sleep_interval) 57 | job = vault.get_job(job_id) 58 | download_result = job.download_to_file(dest) 59 | return download_result 60 | 61 | def delete_archive(self, vault_name, archive_id): 62 | vault = self.glacier_client.get_vault(vault_name) 63 | vault.delete_archive(archive_id) 64 | self.log.debug('Successfully remove archive "{0}" from vault "{1}"'.format(archive_id, vault.name)) 65 | 66 | 67 | class S3(object): 68 | def __init__(self, aws_access_key_id, aws_secret_access_key, **kwargs): 69 | self.s3_client = connect_s3(aws_access_key_id=aws_access_key_id, 70 | aws_secret_access_key=aws_secret_access_key, 71 | calling_format=boto.s3.connection.OrdinaryCallingFormat(), **kwargs) 72 | logging.getLogger('boto').setLevel(logging.CRITICAL) 73 | 74 | @staticmethod 75 | def _is_dir(path): 76 | if path == "{0}/".format(os.path.dirname(path)): 77 | return True 78 | else: 79 | return False 80 | 81 | def _get_bucket_by_name(self, bucket_name): 82 | return self.s3_client.get_bucket(bucket_name) 83 | 84 | def list_bucket(self, bucket_name, max_keys): 85 | bucket = self._get_bucket_by_name(bucket_name) 86 | more_results = True 87 | k = None 88 | marker = '' 89 | while more_results: 90 | rs = bucket.get_all_keys(marker=marker, max_keys=max_keys) 91 | for k in rs: 92 | k.last_modified_dt = datetime.datetime.strptime(k.last_modified, '%Y-%m-%dT%H:%M:%S.%fZ') - (datetime.datetime.utcnow() - datetime.datetime.now()) 93 | yield k 94 | if k: 95 | marker = rs.next_marker or k.name 96 | more_results = rs.is_truncated 97 | 98 | @staticmethod 99 | @contextmanager 100 | def poolcontext(*args, **kwargs): 101 | pool = mp.Pool(*args, **kwargs) 102 | yield pool 103 | pool.terminate() 104 | 105 | @staticmethod 106 | def _dump_file(file, dest_dir): 107 | dest = os.path.join(dest_dir, file.name) 108 | ebt_system.makedirs(os.path.dirname(dest), exist_ok=True) 109 | file.get_contents_to_filename(dest) 110 | 111 | def dump_files(self, files, dest_dir, workers=48): 112 | with self.poolcontext(processes=workers) as pool: 113 | pool.map(partial(self._dump_file, dest_dir=dest_dir), files) 114 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Enhanced Backup Tool 2 | 3 | ## Overview 4 | This is backup framework for creating flexible backup scripts. 5 | 6 | ## Features 7 | 1. Module for upload backups to Amazon Glacier and remove old Glacier backups. 8 | 2. MySQL module support creating backup with mysqldump and InnoBackupEx. 9 | 3. LVM module for snapshots. 10 | 4. Full/Diff backups of files backups with rsync. 11 | 5. Full/Diff backups of btrfs with btrfs send/receive. 12 | 6. Full/Diff backups of any binary files or block devices with diff-dd. 13 | 7. Full/Diff backups of Libvirt VM's. 14 | 8. Full/Diff backups of Libvirt VM's with external snapshots (works with qcow, qcow2, and raw file block devices). 15 | 9. Full/Diff backups of S3 buckets (beta, can work with Amazon S3, Ceph and other S3 storage) 16 | 10. Predefined jobs for popular cases. 17 | 18 | ## Install 19 | 1. Install following dependency with your OS package manager: 20 | For CentOS: 21 | ``` 22 | http://www.percona.com/downloads/percona-release/redhat/0.1-4/percona-release-0.1-4.noarch.rpm (Percona repo) 23 | libvirt-python 24 | python-pip 25 | rsync 26 | lvm2 27 | p7zip 28 | btrfs-progs 29 | pigz 30 | Percona-Server-client-57 31 | percona-xtrabackup-24 32 | ``` 33 | For Debian/Ubuntu: 34 | ``` 35 | https://repo.percona.com/apt/percona-release_0.1-4.$(lsb_release -sc)_all.deb (Percona repo) 36 | python-libvirt 37 | python-setuptools 38 | python-pip 39 | rsync 40 | lvm2 41 | p7zip 42 | btrfs-progs 43 | pigz 44 | Percona-Server-client-57 45 | percona-xtrabackup-24 46 | ``` 47 | 2. Install python package from pip: 48 | ``` 49 | pip install ebt 50 | ``` 51 | 52 | ## Configure 53 | Configuration files stored in `/etc/ebt/` directory. 54 | File `/etc/ebt/ebt.conf` contain logging configuration. 55 | 56 | File `/etc/ebt/plans.py` contains your backups jobs. Few examples of `plans.py`: 57 | 58 | ```python 59 | import ebt_jobs.btrfs 60 | 61 | 62 | def btrfs_root_full(): 63 | backup = ebt_jobs.btrfs.BTRFSBackupFull(source='/', snap_dir='/.snap', dest_dir='/mnt/backup', day_exp=None, store_last=1) 64 | backup.start() 65 | 66 | def btrfs_root_diff(): 67 | backup = ebt_jobs.btrfs.BTRFSBackupDiff(source='/', snap_dir='/.snap', dest_dir='/mnt/backup', day_exp=None, store_last=5) 68 | backup.start() 69 | ``` 70 | This example of using predefined job `ebt_jobs.btrfs.BTRFSBackupDiff`. You can see all jobs in `ebt_jobs/` directory. 71 | 72 | Next example. You can inheritance your own class from base class: 73 | ```python 74 | import ebt_jobs.btrfs 75 | import ebt_system 76 | 77 | class BTRFSBackupFullWithRsync(ebt_jobs.btrfs.BTRFSBackupFull): 78 | def _post_backup(self): 79 | ebt_system.popen(command="rsync /usr/bin/rsync {0} remote:/mnt/backup/archive/".format(self.dest), shell=True) 80 | 81 | class BTRFSBackupDiffWithRsync(ebt_jobs.btrfs.BTRFSBackupDiff, BTRFSBackupFullWithRsync): 82 | pass 83 | 84 | def btrfs_root_full(): 85 | backup = BTRFSBackupFullWithRsync(source='/', snap_dir='/.snap', dest_dir='/mnt/backup', day_exp=None, store_last=1) 86 | backup.start() 87 | 88 | def btrfs_root_diff(): 89 | backup = BTRFSBackupDiffWithRsync(source='/', snap_dir='/.snap', dest_dir='/mnt/backup', day_exp=None, store_last=5) 90 | backup.start() 91 | ``` 92 | You can write your own jobs from primitives that can be found in `ebt_*` dirs. 93 | 94 | ## EBT cli Usage 95 | ``` 96 | root » ebt --help 97 | usage: ebt [-h] [-j JOBS [JOBS ...]] [-p PLAN] [-c CONFIG] [-v] 98 | 99 | optional arguments: 100 | -h, --help show this help message and exit 101 | -j JOBS [JOBS ...], --jobs JOBS [JOBS ...] 102 | List of jobs to run 103 | -p PLAN, --plan PLAN Custom path to plans file 104 | -c CONFIG, --config CONFIG 105 | Custom path to config file 106 | -v, --version Display program version and exit 107 | ``` 108 | Where `-j or --jobs` is the functions names from your `plans.py` file. Example: `ebt -j btrfs_root_full btrfs_root_diff` 109 | If you specified few jobs they will be executed in sequential order. 110 | 111 | ## Diff-dd cli Usage 112 | You can use for restoring diff backups of Libvirt VM's or for creating diff backups from external scripts. 113 | 114 | Backup examples: 115 | ``` 116 | ddd --if /backup/full_disk_copy.raw --df /dev/lvm/changed_disk_snapshot --of /backup/diff_disk_copy.ddd 117 | ddd --if /backup/full_disk_copy.raw --df /dev/lvm/changed_disk_snapshot > /backup/diff_disk_copy.ddd 118 | ddd --if /backup/full_disk_copy.raw --df /dev/lvm/changed_disk_snapshot | gzip > /backup/diff_disk_copy.ddd.gz 119 | ddd --if <(zcat /backup/full_disk_copy.raw.gz) --df /dev/lvm/changed_disk_snapshot --of /backup/diff_disk_copy.ddd 120 | zcat /backup/full_disk_copy.raw.gz | ddd --df /dev/lvm/changed_disk_snapshot --of /backup/diff_disk_copy.ddd 121 | cat /dev/lvm/changed_disk_snapshot | ddd --if <(zcat /backup/full_disk_copy.raw.gz) --of /backup/diff_disk_copy.ddd 122 | ddd --if <(ssh remotehost cat /backup/full_disk_copy.raw) --df <(ssh remote2host cat /dev/lvm/changed_disk_snapshot) | ssh remote3host dd of=/backup/diff_disk_copy.ddd 123 | ``` 124 | 125 | Restore examples: 126 | ``` 127 | ddd --mode restore --if /backup/full_disk_copy.raw --df /backup/diff_disk_copy.ddd --of /dev/lvm/disk 128 | ddd --mode restore --if <(zcat /backup/full_disk_copy.raw.gz) --df <(zcat /backup/diff_disk_copy.ddd.gz) > /dev/lvm/disk 129 | zcat /backup/full_disk_copy.raw.gz | ddd --mode restore --df <(ssh remotehost cat /backup/diff_disk_copy.ddd.gz) | ssh remote2host dd of=/dev/lvm/disk 130 | ``` 131 | 132 | ## Diff-dd API Usage 133 | Backup: 134 | ``` 135 | import ebt_files 136 | import gzip 137 | iffd = gzip.open('/backup/full_disk_copy.raw.gz', 'rb') 138 | dffd = open('/dev/lvm/changed_disk_snapshot', 'rb') 139 | offd = gzip.open('/backup/diff_disk_copy.ddd', 'wb') 140 | 141 | differ = ebt_files.ddd.CreateDiff(iffd=iffd, dffd=dffd, offd=offd, block_size=16384) 142 | differ.start() 143 | ``` 144 | 145 | Restore: 146 | ``` 147 | import ebt_files 148 | iffd = gzip.open('/backup/full_disk_copy.raw.gz', 'rb') 149 | dffd = gzip.open('/backup/diff_disk_copy.ddd', 'rb') 150 | offd = open('/dev/lvm/disk', 'wb') 151 | 152 | differ_restore = ebt_files.ddd.RestoreDiff(iffd=iffd, dffd=dffd, offd=offd, block_size=16384) 153 | differ_restore.start() 154 | ``` 155 | 156 | ## License 157 | GPLv3 158 | -------------------------------------------------------------------------------- /ebt_virt/libvirt_helper.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import libvirt 3 | from xml.etree import ElementTree 4 | import time 5 | import ebt_system 6 | 7 | 8 | class Libvirt(object): 9 | def __init__(self, uri='qemu:///system'): 10 | self.conn = libvirt.open(uri) 11 | 12 | def list_domains(self): 13 | return self.conn.listAllDomains() 14 | 15 | @staticmethod 16 | def get_domain_disks(domain): 17 | assert isinstance(domain, libvirt.virDomain), '{1}.{2}: variable "{0}" has wrong type.' \ 18 | .format('domain', __name__, sys._getframe().f_code.co_name) 19 | domain_xml = domain.XMLDesc(0) 20 | root = ElementTree.fromstring(domain_xml) 21 | disks = root.findall('./devices/disk') 22 | disks_list = list() 23 | for disk in disks: 24 | disk_info = {} 25 | if disk.attrib['device'] in ('disk',): 26 | if (disk.find('source') is not None) and (disk.find('source').get('dev') is not None): 27 | disk_info['path'] = disk.find('source').get('dev') 28 | disk_info['target'] = disk.find('target').get('dev') 29 | disk_info['source_type'] = 'dev' 30 | disk_info['snapshot_path'] = None 31 | disks_list.append(disk_info) 32 | elif (disk.find('source') is not None) and (disk.find('source').get('file') is not None): 33 | disk_info['path'] = disk.find('source').get('file') 34 | disk_info['target'] = disk.find('target').get('dev') 35 | disk_info['source_type'] = 'file' 36 | disk_info['snapshot_path'] = None 37 | disks_list.append(disk_info) 38 | return disks_list 39 | 40 | def filter_domain_list(self, domains, include=list(), exclude=list()): 41 | assert isinstance(include, list), '{1}.{2}: variable "{0}" has wrong type.' \ 42 | .format('include', __name__, sys._getframe().f_code.co_name) 43 | assert isinstance(exclude, list), '{1}.{2}: variable "{0}" has wrong type.' \ 44 | .format('exclude', __name__, sys._getframe().f_code.co_name) 45 | assert isinstance(domains, list) and isinstance(domains[0], 46 | libvirt.virDomain), '{1}.{2}: variable "{0}" has wrong type.' \ 47 | .format('domains', __name__, sys._getframe().f_code.co_name) 48 | filtered_list = list() 49 | for domain in domains: 50 | if (domain.name() in include) or (('all' not in exclude) and (domain.name() not in exclude)): 51 | filtered_list.append(domain) 52 | return filtered_list 53 | 54 | @staticmethod 55 | def export_xml(domain, path): 56 | domain_xml = domain.XMLDesc(0) 57 | xml_file = open(path, mode='w') 58 | xml_file.write(domain_xml) 59 | xml_file.close() 60 | 61 | @staticmethod 62 | def device_size(domain, path): 63 | return int(domain.blockInfo(path)[0]) 64 | 65 | def restore(self, path): 66 | self.conn.restore(path) 67 | 68 | @staticmethod 69 | def create_snapshot_xml(disks, memory_path=None): 70 | assert isinstance(disks, list) and isinstance(disks[0], dict), '{1}.{2}: variable "{0}" has wrong type.' \ 71 | .format('disks', __name__, sys._getframe().f_code.co_name) 72 | assert (memory_path is None) or isinstance(memory_path, str), '{1}.{2}: variable "{0}" has wrong type.' \ 73 | .format('memory_path', __name__, sys._getframe().f_code.co_name) 74 | snap_xml = ElementTree.Element('domainsnapshot') 75 | disks_xml = ElementTree.SubElement(snap_xml, 'disks') 76 | if memory_path is None: 77 | ElementTree.SubElement(snap_xml, 'memory', {'snapshot': 'no'}) 78 | else: 79 | ElementTree.SubElement(snap_xml, 'memory', {'snapshot': 'external', 'file': memory_path}) 80 | for disk in disks: 81 | if disk['snapshot_path'] is None: 82 | ElementTree.SubElement(disks_xml, 'disk', {'name': disk['target'], 'snapshot': 'no'}) 83 | else: 84 | disk_xml = ElementTree.SubElement(disks_xml, 'disk', {'name': disk['target'], 'snapshot': 'external'}) 85 | ElementTree.SubElement(disk_xml, 'source', {'file': disk['snapshot_path']}) 86 | snap_xml_str = ElementTree.tostring(snap_xml, encoding='utf8', method='xml') 87 | return snap_xml_str 88 | 89 | def create_vm_snapshot(self, domain, disks, memory_path=None, atomic=True, quiesce=False): 90 | assert isinstance(domain, libvirt.virDomain), '{1}.{2}: variable "{0}" has wrong type.' \ 91 | .format('domain', __name__, sys._getframe().f_code.co_name) 92 | assert isinstance(disks, list) and isinstance(disks[0], dict), '{1}.{2}: variable "{0}" has wrong type.' \ 93 | .format('disks', __name__, sys._getframe().f_code.co_name) 94 | assert (memory_path is None) or isinstance(memory_path, str), '{1}.{2}: variable "{0}" has wrong type.' \ 95 | .format('memory_path', __name__, sys._getframe().f_code.co_name) 96 | assert isinstance(atomic, bool), '{1}.{2}: variable "{0}" has wrong type.' \ 97 | .format('atomic', __name__, sys._getframe().f_code.co_name) 98 | assert isinstance(quiesce, bool), '{1}.{2}: variable "{0}" has wrong type.' \ 99 | .format('quiesce', __name__, sys._getframe().f_code.co_name) 100 | flags = 0 101 | if memory_path is None: 102 | flags |= libvirt.VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY 103 | else: 104 | flags |= libvirt.VIR_DOMAIN_SNAPSHOT_CREATE_LIVE 105 | if atomic: 106 | flags |= libvirt.VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC 107 | if quiesce: 108 | flags |= libvirt.VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE 109 | snap_xml = self.create_snapshot_xml(disks, memory_path) 110 | snap = domain.snapshotCreateXML(snap_xml, flags) 111 | return snap 112 | 113 | @staticmethod 114 | def remove_vm_snapshot(domain, disks): 115 | assert isinstance(domain, libvirt.virDomain), '{1}.{2}: variable "{0}" has wrong type.' \ 116 | .format('domain', __name__, sys._getframe().f_code.co_name) 117 | assert isinstance(disks, list) and isinstance(disks[0], dict), '{1}.{2}: variable "{0}" has wrong type.' \ 118 | .format('disks', __name__, sys._getframe().f_code.co_name) 119 | flags = libvirt.VIR_DOMAIN_BLOCK_COMMIT_ACTIVE 120 | for disk in disks: 121 | if disk['snapshot_path'] is not None: 122 | domain.blockCommit(disk=disk['target'], base=None, top=None, flags=flags) 123 | while True: 124 | status = domain.blockJobInfo(disk['target']) 125 | if status['cur'] == status['end']: 126 | domain.blockJobAbort(disk=disk['target'], flags=libvirt.VIR_DOMAIN_BLOCK_JOB_ABORT_PIVOT) 127 | ebt_system.rm(disk['snapshot_path']) 128 | break 129 | else: 130 | time.sleep(3) 131 | 132 | -------------------------------------------------------------------------------- /ebt_jobs/s3.py: -------------------------------------------------------------------------------- 1 | from ebt_cloud import S3 2 | import logging 3 | import ebt_cleaner 4 | import ebt_system 5 | import re 6 | import datetime 7 | 8 | log = logging.getLogger('__main__') 9 | 10 | 11 | class S3BackupFull(object): 12 | def __init__(self, aws_access_key_id, aws_secret_access_key, bucket, dest_dir, day_exp, store_last, exclude=[], **kwargs): 13 | self.s3 = S3(aws_access_key_id=aws_access_key_id, 14 | aws_secret_access_key=aws_secret_access_key, 15 | **kwargs 16 | ) 17 | self.dest_dir = dest_dir 18 | self.bucket = bucket 19 | self.exclude = exclude 20 | self.day_exp = day_exp 21 | self.store_last = store_last 22 | self.workers = 64 23 | self.queue_length = 65536 24 | self.max_keys = 10000 25 | 26 | def _set_backup_dest(self): 27 | backup_date = ebt_cleaner.get_dir_name() 28 | self.dest = "{0}/{1}".format(self.dest_dir, backup_date) 29 | 30 | def _cleanup_old_backups(self): 31 | old_backups = ebt_cleaner.filter_list(path=self.dest_dir, dayexp=self.day_exp, store_last=self.store_last) 32 | ebt_system.rm(old_backups) 33 | 34 | def _pre_backup(self): 35 | pass 36 | 37 | def _post_backup(self): 38 | pass 39 | 40 | def _exclude_file_by_regex(self, file): 41 | if len(self.exclude) == 0: 42 | return False 43 | for regex in self.exclude: 44 | if re.match(regex, file.name) is not None: 45 | return True 46 | return False 47 | 48 | def _exclude_files_by_time(self, file): 49 | return False 50 | 51 | def _create_backup(self): 52 | log.info('Starting backup of bucket "{0}"'.format(self.bucket)) 53 | files = [] 54 | files_count = 0 55 | for file in self.s3.list_bucket(self.bucket, max_keys=self.max_keys): 56 | if self._exclude_files_by_time(file) is True: 57 | continue 58 | elif self._exclude_file_by_regex(file) is True: 59 | continue 60 | if len(files) < self.queue_length: 61 | files.append(file) 62 | files_count += 1 63 | else: 64 | files.append(file) 65 | files_count += 1 66 | self.s3.dump_files(files, self.dest, workers=self.workers) 67 | files = [] 68 | self.s3.dump_files(files, self.dest, workers=self.workers) 69 | log.info('Backup of bucket "{0}" successfully completed. Backuped {1} files.'.format(self.bucket, files_count)) 70 | 71 | def start(self): 72 | self._set_backup_dest() 73 | self._cleanup_old_backups() 74 | self._pre_backup() 75 | self._create_backup() 76 | self._post_backup() 77 | 78 | 79 | class S3BackupDiff(S3BackupFull): 80 | def _set_backup_dest(self): 81 | self.backup_date = ebt_cleaner.get_dir_name() 82 | self.full = ebt_cleaner.last_backup(self.dest_dir) 83 | self.dest = "{0}/{1}%{2}".format(self.dest_dir, self.backup_date, str(self.full).split('/')[-1]) 84 | self.full_backup_date = datetime.datetime.strptime(str(self.full).split('/')[-1], '%d-%m-%Y_%H:%M') 85 | 86 | def _cleanup_old_backups(self): 87 | old_backups = ebt_cleaner.filter_list(path=self.dest_dir, dayexp=self.day_exp, store_last=self.store_last, fmt='%date%%%fdate') 88 | ebt_system.rm(old_backups) 89 | 90 | def _exclude_files_by_time(self, file): 91 | if file.last_modified_dt > self.full_backup_date: 92 | return False 93 | return True 94 | 95 | 96 | class S3BackupFullS3sync(object): 97 | def __init__(self, aws_access_key_id, aws_secret_access_key, bucket, dest_dir, day_exp, store_last, endpoint, prefix="", onfail="fatal"): 98 | self.aws_access_key_id = aws_access_key_id 99 | self.aws_secret_access_key = aws_secret_access_key 100 | self.dest_dir = dest_dir 101 | self.bucket = bucket 102 | self.endpoint = endpoint 103 | self.day_exp = day_exp 104 | self.store_last = store_last 105 | self.prefix = prefix 106 | self.onfail = onfail 107 | self.workers = 128 108 | self.ratelimit_objects = 0 109 | self.ratelimit_bandwidth = None 110 | self.retry = 5 111 | self.retry_interval = 1 112 | self.disable_http2 = False 113 | self.debug = False 114 | self.filter_extensions = [] 115 | self.filter_contenttype = [] 116 | self.filter_revert_extensions = [] 117 | self.filter_revert_contenttype = [] 118 | 119 | def _set_backup_dest(self): 120 | backup_date = ebt_cleaner.get_dir_name() 121 | self.dest = "{0}/{1}".format(self.dest_dir, backup_date) 122 | 123 | def _cleanup_old_backups(self): 124 | old_backups = ebt_cleaner.filter_list(path=self.dest_dir, dayexp=self.day_exp, store_last=self.store_last) 125 | ebt_system.rm(old_backups) 126 | 127 | def _pre_backup(self): 128 | pass 129 | 130 | def _post_backup(self): 131 | pass 132 | 133 | def _create_backup(self): 134 | log.info('Starting backup of bucket "{0}" with s3sync'.format(self.bucket)) 135 | command = 's3sync --sk {aws_access_key_id} --ss {aws_secret_access_key} --se {endpoint} -w {workers} -f {onfail} --s3-retry {retry} --s3-retry-sleep {retry_interval} s3://{bucket}{prefix} fs://{dest}'.format( 136 | aws_access_key_id=self.aws_access_key_id, 137 | aws_secret_access_key=self.aws_secret_access_key, 138 | endpoint=self.endpoint, 139 | workers=self.workers, 140 | onfail=self.onfail, 141 | retry=self.retry, 142 | bucket=self.bucket, 143 | prefix=self.prefix, 144 | dest=self.dest, 145 | retry_interval=self.retry_interval 146 | ) 147 | if self.disable_http2: 148 | command = "{cmd} --disable-http2".format(cmd=command) 149 | if self.debug: 150 | command = "{cmd} --debug".format(cmd=command) 151 | if self.ratelimit_objects > 0: 152 | command = "{cmd} --ratelimit-objects {limit}".format(cmd=command, limit=self.ratelimit_objects) 153 | if self.ratelimit_bandwidth is not None: 154 | command = "{cmd} --ratelimit-bandwidth {limit}".format(cmd=command, limit=self.ratelimit_bandwidth) 155 | for item in self.filter_extensions: 156 | command = "{cmd} --filter-ext {fe}".format(cmd=command, fe=item) 157 | for item in self.filter_revert_extensions: 158 | command = "{cmd} --filter-not-ext {fre}".format(cmd=command, fre=item) 159 | for item in self.filter_contenttype: 160 | command = "{cmd} --filter-ct {fct}".format(cmd=command, fct=item) 161 | for item in self.filter_revert_contenttype: 162 | command = "{cmd} --filter-not-ct {frct}".format(cmd=command, frct=item) 163 | 164 | exitcode, output = ebt_system.popen(command) 165 | log.info(output) 166 | log.info('Backup of bucket "{0}" successfully completed.'.format(self.bucket)) 167 | 168 | def start(self): 169 | self._set_backup_dest() 170 | self._cleanup_old_backups() 171 | self._pre_backup() 172 | self._create_backup() 173 | self._post_backup() 174 | 175 | 176 | class S3BackupDiffS3sync(S3BackupFullS3sync): 177 | def _set_backup_dest(self): 178 | self.backup_date = ebt_cleaner.get_dir_name() 179 | self.full = ebt_cleaner.last_backup(self.dest_dir) 180 | self.dest = "{0}/{1}%{2}".format(self.dest_dir, self.backup_date, str(self.full).split('/')[-1]) 181 | self.full_backup_date = datetime.datetime.strptime(str(self.full).split('/')[-1], '%d-%m-%Y_%H:%M') 182 | 183 | def _cleanup_old_backups(self): 184 | old_backups = ebt_cleaner.filter_list(path=self.dest_dir, dayexp=self.day_exp, store_last=self.store_last, fmt='%date%%%fdate') 185 | ebt_system.rm(old_backups) 186 | 187 | def _exclude_files_by_time(self, file): 188 | if file.last_modified_dt > self.full_backup_date: 189 | return False 190 | return True 191 | 192 | def _create_backup(self): 193 | log.info('Starting backup of bucket "{0}" with s3sync'.format(self.bucket)) 194 | command = 's3sync --sk {aws_access_key_id} --ss {aws_secret_access_key} --se {endpoint} -w {workers} -f {onfail} --s3-retry {retry} --s3-retry-sleep {retry_interval} --filter-after-mtime {timestamp} s3://{bucket}{prefix} fs://{dest}'.format( 195 | aws_access_key_id=self.aws_access_key_id, 196 | aws_secret_access_key=self.aws_secret_access_key, 197 | endpoint=self.endpoint, 198 | workers=self.workers, 199 | onfail=self.onfail, 200 | retry=self.retry, 201 | bucket=self.bucket, 202 | prefix=self.prefix, 203 | dest=self.dest, 204 | retry_interval=self.retry_interval, 205 | timestamp=self.full_backup_date.strftime("%s") 206 | ) 207 | 208 | if self.disable_http2: 209 | command = "{cmd} --disable-http2".format(cmd=command) 210 | if self.debug: 211 | command = "{cmd} --debug".format(cmd=command) 212 | if self.ratelimit_objects > 0: 213 | command = "{cmd} --ratelimit-objects {limit}".format(cmd=command, limit=self.ratelimit_objects) 214 | if self.ratelimit_bandwidth is not None: 215 | command = "{cmd} --ratelimit-bandwidth {limit}".format(cmd=command, limit=self.ratelimit_bandwidth) 216 | for item in self.filter_extensions: 217 | command = "{cmd} --filter-ext {fe}".format(cmd=command, fe=item) 218 | for item in self.filter_revert_extensions: 219 | command = "{cmd} --filter-not-ext {fre}".format(cmd=command, fre=item) 220 | for item in self.filter_contenttype: 221 | command = "{cmd} --filter-ct {fct}".format(cmd=command, fct=item) 222 | for item in self.filter_revert_contenttype: 223 | command = "{cmd} --filter-not-ct {frct}".format(cmd=command, frct=item) 224 | 225 | 226 | exitcode, output = ebt_system.popen(command) 227 | log.info(output) 228 | log.info('Backup of bucket "{0}" successfully completed.'.format(self.bucket)) 229 | -------------------------------------------------------------------------------- /ebt_jobs/vm.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import ebt_cleaner 3 | import ebt_system 4 | import ebt_files 5 | import ebt_virt 6 | import ebt_cloud 7 | import os 8 | import gzip 9 | from multiprocessing import cpu_count 10 | 11 | log = logging.getLogger('__main__') 12 | 13 | 14 | class LibvirtBackup(object): 15 | def __init__(self, dest_dir, day_exp=None, store_last=5, exclude_vm=list(), include_vm=list(), exclude_disks=list(), 16 | dump_memory=True): 17 | self.dump_memory = dump_memory 18 | self.exclude_disks = exclude_disks 19 | self.store_last = store_last 20 | self.dest_dir = dest_dir 21 | self.day_exp = day_exp 22 | self.libvirt_client = ebt_virt.Libvirt() 23 | self.exclude_vm = exclude_vm 24 | self.include_vm = include_vm 25 | self.compress_level = 5 26 | self.lvm_snap_size = '10G' 27 | self.compress_threads = cpu_count() 28 | self.passwd=None 29 | 30 | def _set_backup_dest(self): 31 | self.backup_date = ebt_cleaner.get_dir_name() 32 | self.dest = "{0}/{1}".format(self.dest_dir, self.backup_date) 33 | 34 | def _cleanup_old_backups(self): 35 | old_backups = ebt_cleaner.filter_list(path=self.dest_dir, dayexp=self.day_exp, store_last=self.store_last) 36 | ebt_system.rm(old_backups) 37 | 38 | def _pre_backup(self): 39 | pass 40 | 41 | def _post_backup(self): 42 | pass 43 | 44 | def _create_instance_backup(self, domain): 45 | log.info('Start backup domain {0}'.format(domain.name())) 46 | os.makedirs('{0}/{1}'.format(self.dest, domain.name())) 47 | log.info('Export domain XML to {0}/{1}/{1}.xml'.format(self.dest, domain.name())) 48 | self.libvirt_client.export_xml(domain=domain, path='{0}/{1}/{1}.xml'.format(self.dest, domain.name())) 49 | if (self.dump_memory is True) and (domain.isActive() == 1): 50 | log.debug('Save memory image to {0}/{1}/memory.save'.format(self.dest, domain.name())) 51 | domain.save(to='{0}/{1}/memory.save'.format(self.dest, domain.name())) 52 | elif (self.dump_memory is False) and (domain.isActive() == 1): 53 | log.debug('Suspending domain {0}'.format(domain.name())) 54 | domain.suspend() 55 | domain_disks = self.libvirt_client.get_domain_disks(domain) 56 | for disk in domain_disks: 57 | if (disk['source_type'] == 'dev') and (disk['path'] not in self.exclude_disks): 58 | log.info('Create snapshot of disk {0}'.format(disk['path'])) 59 | ebt_system.lvm.remove_snap_if_exist(source=disk['path']) 60 | ebt_system.lvm.create_snapshot(source=disk['path'], size=self.lvm_snap_size) 61 | elif (disk['source_type'] == 'file') and (disk['path'] not in self.exclude_disks): 62 | log.info( 63 | 'Create copy of disk {3} to {0}/{1}/{2}'.format(self.dest, domain.name(), 64 | os.path.basename(disk['path']), 65 | disk['path'])) 66 | ebt_files.dd.create(source=disk['path'], dest='{0}/{1}/{2}.img.gz'.format(self.dest, domain.name(), 67 | os.path.basename( 68 | disk['path'])), 69 | compress_level=self.compress_level, compress_threads=self.compress_threads, passwd=self.passwd) 70 | if (self.dump_memory is True) and (domain.isActive() == 0) and ( 71 | os.path.isfile("{0}/{1}/memory.save".format(self.dest, domain.name())) is True): 72 | log.info('Restore memory from file {0}/{1}/memory.save'.format(self.dest, domain.name())) 73 | self.libvirt_client.restore('{0}/{1}/memory.save'.format(self.dest, domain.name())) 74 | elif (self.dump_memory is False) and (domain.isActive() == 1): 75 | log.debug('Resuming domain {0}'.format(domain.name())) 76 | domain.resume() 77 | for disk in domain_disks: 78 | if (disk['source_type'] == 'dev') and (disk['path'] not in self.exclude_disks): 79 | log.info('Create copy of snapshot {3}-snap to {0}/{1}/{2}.img.gz'.format(self.dest, domain.name(), 80 | os.path.basename(disk['path']), 81 | disk['path'])) 82 | ebt_files.dd.create(source='{0}-snap'.format(disk['path']), 83 | dest='{0}/{1}/{2}.img.gz'.format(self.dest, domain.name(), 84 | os.path.basename(disk['path'])), 85 | compress_level=self.compress_level, compress_threads=self.compress_threads, passwd=self.passwd) 86 | open('{0}/{1}/{2}.img.size'.format(self.dest, domain.name(), os.path.basename(disk['path'])), 87 | mode='w').write( 88 | str(self.libvirt_client.device_size(domain, disk['target']))) 89 | log.info('Remove snapshot {0}-snap'.format(disk['path'])) 90 | ebt_system.lvm.remove_snap(disk['path']) 91 | 92 | def start(self): 93 | self._set_backup_dest() 94 | self._cleanup_old_backups() 95 | self._pre_backup() 96 | domains = self.libvirt_client.filter_domain_list(self.libvirt_client.list_domains(), include=self.include_vm, exclude=self.exclude_vm) 97 | for domain in domains: 98 | self._create_instance_backup(domain) 99 | self._post_backup() 100 | 101 | 102 | class LibvirtBackupDiff(LibvirtBackup): 103 | def _set_backup_dest(self): 104 | self.backup_date = ebt_cleaner.get_dir_name() 105 | self.full = ebt_cleaner.last_backup(self.dest_dir) 106 | self.dest = "{0}/{1}%{2}".format(self.dest_dir, self.backup_date, str(self.full).split('/')[-1]) 107 | 108 | def _cleanup_old_backups(self): 109 | old_backups = ebt_cleaner.filter_list(path=self.dest_dir, dayexp=self.day_exp, store_last=self.store_last, 110 | fmt='%date%%%fdate') 111 | ebt_system.rm(old_backups) 112 | 113 | def _create_instance_backup(self, domain): 114 | log.info('Start diff backup domain {0}'.format(domain.name())) 115 | os.makedirs('{0}/{1}'.format(self.dest, domain.name())) 116 | log.info('Export domain XML to {0}/{1}/{1}.xml'.format(self.dest, domain.name())) 117 | self.libvirt_client.export_xml(domain=domain, path='{0}/{1}/{1}.xml'.format(self.dest, domain.name())) 118 | if (self.dump_memory is True) and (domain.isActive() == 1): 119 | log.debug('Save memory image to {0}/{1}/memory.save'.format(self.dest, domain.name())) 120 | domain.save(to='{0}/{1}/memory.save'.format(self.dest, domain.name())) 121 | elif (self.dump_memory is False) and (domain.isActive() == 1): 122 | log.debug('Suspending domain {0}'.format(domain.name())) 123 | domain.suspend() 124 | domain_disks = self.libvirt_client.get_domain_disks(domain) 125 | for disk in domain_disks: 126 | if (disk['source_type'] == 'dev') and (disk['path'] not in self.exclude_disks): 127 | log.info('Create snapshot of disk {0}'.format(disk['path'])) 128 | ebt_system.lvm.remove_snap_if_exist(source=disk['path']) 129 | ebt_system.lvm.create_snapshot(source=disk['path'], size=self.lvm_snap_size) 130 | elif (disk['source_type'] == 'file') and (disk['path'] not in self.exclude_disks): 131 | log.info( 132 | 'Create copy of disk {3} to {0}/{1}/{2}'.format(self.dest, domain.name(), 133 | os.path.basename(disk['path']), 134 | disk['path'])) 135 | iffd = gzip.open('{0}/{1}/{2}.img.gz'.format(self.full, domain.name(), os.path.basename(disk['path'])), 'rb') 136 | dffd = open(disk['path'], 'rb') 137 | offd = gzip.open('{0}/{1}/{2}.img.ddd.gz'.format(self.dest, domain.name(), os.path.basename(disk['path'])), 138 | 'wb', compresslevel=self.compress_level) 139 | differ = ebt_files.ddd.CreateDiff(iffd=iffd, dffd=dffd, offd=offd, block_size=8192) 140 | differ.start() 141 | iffd.close() 142 | dffd.close() 143 | offd.close() 144 | if (self.dump_memory is True) and (domain.isActive() == 0) and ( 145 | os.path.isfile("{0}/{1}/memory.save".format(self.dest, domain.name())) is True): 146 | log.info('Restore memory from file {0}/{1}/memory.save'.format(self.dest, domain.name())) 147 | self.libvirt_client.restore('{0}/{1}/memory.save'.format(self.dest, domain.name())) 148 | elif (self.dump_memory is False) and (domain.isActive() == 1): 149 | log.debug('Resuming domain {0}'.format(domain.name())) 150 | domain.resume() 151 | for disk in domain_disks: 152 | if (disk['source_type'] == 'dev') and (disk['path'] not in self.exclude_disks): 153 | log.info('Create copy of snapshot {3}-snap to {0}/{1}/{2}.img.ddd.gz'.format(self.dest, domain.name(), 154 | os.path.basename( 155 | disk['path']), 156 | disk['path'])) 157 | iffd = gzip.open('{0}/{1}/{2}.img.gz'.format(self.full, domain.name(), os.path.basename(disk['path'])), 158 | 'rb') 159 | dffd = open('{0}-snap'.format(disk['path']), 'rb') 160 | offd = gzip.open( 161 | '{0}/{1}/{2}.img.ddd.gz'.format(self.dest, domain.name(), os.path.basename(disk['path'])), 'wb', 162 | compresslevel=self.compress_level) 163 | differ = ebt_files.ddd.CreateDiff(iffd=iffd, dffd=dffd, offd=offd, block_size=8192) 164 | differ.start() 165 | iffd.close() 166 | dffd.close() 167 | offd.close() 168 | open('{0}/{1}/{2}.img.size'.format(self.dest, domain.name(), os.path.basename(disk['path'])), 169 | mode='w').write( 170 | str(self.libvirt_client.device_size(domain, disk['target']))) 171 | log.info('Remove snapshot {0}-snap'.format(disk['path'])) 172 | ebt_system.lvm.remove_snap(disk['path']) 173 | 174 | 175 | class LibvirtBackupToGlacier(LibvirtBackup): 176 | def __init__(self, aws_access_key_id, aws_secret_access_key, region_name, vault, archive_pass, *args, **kwargs): 177 | super(LibvirtBackupToGlacier, self).__init__(*args, **kwargs) 178 | self.glacier = ebt_cloud.AmazonGlacier(aws_access_key_id=aws_access_key_id, 179 | aws_secret_access_key=aws_secret_access_key, 180 | region_name=region_name) 181 | self.archive_pass = archive_pass 182 | self.vault = vault 183 | 184 | def _upload_to_glacier(self, domain): 185 | log.info('Compressing "{0}/{1}" to "{0}/{1}.7z"'.format(self.dest, domain.name())) 186 | ebt_files.archive.create7z(source="{0}/{1}".format(self.dest, domain.name()), 187 | dest="{0}/{1}.7z".format(self.dest, domain.name()), password=self.archive_pass, 188 | options="-sdel -mmt2", level=1) 189 | log.info('Upload file "{0}/{1}.7z" to vault "{2}"'.format(self.dest, domain.name(), self.vault)) 190 | archive_id = self.glacier.upload_file(vault_name=self.vault, description=domain.name(), 191 | path="{0}/{1}.7z".format(self.dest, domain.name())) 192 | log.info('Archive uploaded successfully. Archive id: "{0}"'.format(archive_id)) 193 | log.info('Remove file "{0}/{1}.7z"'.format(self.dest, domain.name())) 194 | ebt_system.rm("{0}/{1}.7z".format(self.dest, domain.name())) 195 | 196 | def start(self): 197 | self._set_backup_dest() 198 | self._cleanup_old_backups() 199 | self._pre_backup() 200 | domains = self.libvirt_client.filter_domain_list(self.libvirt_client.list_domains(), include=self.include_vm, exclude=self.exclude_vm) 201 | for domain in domains: 202 | self._create_instance_backup(domain) 203 | for domain in domains: 204 | self._upload_to_glacier(domain) 205 | self._post_backup() 206 | 207 | 208 | class LibvirtBackupExternalSnapshot(LibvirtBackup): 209 | def __init__(self, snap_dir, *args, **kwargs): 210 | super(LibvirtBackupExternalSnapshot, self).__init__(*args, **kwargs) 211 | self.snap_dir = snap_dir 212 | 213 | def _set_backup_dest(self): 214 | super(LibvirtBackupExternalSnapshot, self)._set_backup_dest() 215 | self.snap = "{0}/{1}".format(self.snap_dir, self.backup_date) 216 | 217 | def _cleanup_old_backups(self): 218 | super(LibvirtBackupExternalSnapshot, self)._cleanup_old_backups() 219 | if self.dest != self.snap: 220 | old_backups = ebt_cleaner.filter_list(path=self.snap_dir, dayexp=self.day_exp, store_last=self.store_last) 221 | ebt_system.rm(old_backups) 222 | 223 | def _create_instance_backup(self, domain): 224 | log.info('Start backup domain {0}'.format(domain.name())) 225 | os.makedirs('{0}/{1}'.format(self.dest, domain.name())) 226 | if self.dest != self.snap: 227 | os.makedirs('{0}/{1}'.format(self.snap, domain.name())) 228 | log.info('Export domain XML to {0}/{1}/{1}.xml'.format(self.dest, domain.name())) 229 | self.libvirt_client.export_xml(domain=domain, path='{0}/{1}/{1}.xml'.format(self.dest, domain.name())) 230 | if (self.dump_memory is True) and (domain.isActive() == 1): 231 | memory_path = '{0}/{1}/memory.save'.format(self.dest, domain.name()) 232 | else: 233 | memory_path = None 234 | domain_disks = self.libvirt_client.get_domain_disks(domain) 235 | for index, disk in enumerate(domain_disks): 236 | if disk['path'] not in self.exclude_disks: 237 | domain_disks[index]['snapshot_path'] = '{0}/{1}/snapshot_{2}.qcow2'.format(self.snap, domain.name(), 238 | disk['target']) 239 | log.info('Create snapshot of domain {0}'.format(domain.name())) 240 | self.libvirt_client.create_vm_snapshot(domain, domain_disks, memory_path=memory_path) 241 | for disk in domain_disks: 242 | if disk['path'] not in self.exclude_disks: 243 | log.info('Create copy of {3} to {0}/{1}/{2}.img.gz'.format(self.dest, domain.name(), 244 | os.path.basename(disk['path']), 245 | disk['path'])) 246 | ebt_files.dd.create(source=disk['path'], dest='{0}/{1}/{2}.img.gz'.format(self.dest, domain.name(), 247 | os.path.basename( 248 | disk['path'])), 249 | compress_level=self.compress_level, compress_threads=self.compress_threads, passwd=self.passwd) 250 | open('{0}/{1}/{2}.img.size'.format(self.dest, domain.name(), os.path.basename(disk['path'])), 251 | mode='w').write( 252 | str(self.libvirt_client.device_size(domain, disk['target']))) 253 | log.info('Remove snapshot of domain {0}'.format(domain.name())) 254 | self.libvirt_client.remove_vm_snapshot(domain, domain_disks) 255 | 256 | 257 | class LibvirtBackupExternalSnapshotDiff(LibvirtBackupDiff): 258 | def __init__(self, snap_dir, *args, **kwargs): 259 | super(LibvirtBackupExternalSnapshotDiff, self).__init__(*args, **kwargs) 260 | self.snap_dir = snap_dir 261 | 262 | def _set_backup_dest(self): 263 | super(LibvirtBackupExternalSnapshotDiff, self)._set_backup_dest() 264 | self.snap = "{0}/{1}%{2}".format(self.snap_dir, self.backup_date, str(self.full).split('/')[-1]) 265 | 266 | def _cleanup_old_backups(self): 267 | super(LibvirtBackupExternalSnapshotDiff, self)._cleanup_old_backups() 268 | if self.dest != self.snap: 269 | old_backups = ebt_cleaner.filter_list(path=self.snap_dir, dayexp=self.day_exp, store_last=self.store_last, 270 | fmt='%date%%%fdate') 271 | ebt_system.rm(old_backups) 272 | 273 | def _create_instance_backup(self, domain): 274 | log.info('Start backup domain {0}'.format(domain.name())) 275 | os.makedirs('{0}/{1}'.format(self.dest, domain.name())) 276 | if self.dest != self.snap: 277 | os.makedirs('{0}/{1}'.format(self.snap, domain.name())) 278 | log.info('Export domain XML to {0}/{1}/{1}.xml'.format(self.dest, domain.name())) 279 | self.libvirt_client.export_xml(domain=domain, path='{0}/{1}/{1}.xml'.format(self.dest, domain.name())) 280 | if (self.dump_memory is True) and (domain.isActive() == 1): 281 | memory_path = '{0}/{1}/memory.save'.format(self.dest, domain.name()) 282 | else: 283 | memory_path = None 284 | domain_disks = self.libvirt_client.get_domain_disks(domain) 285 | for index, disk in enumerate(domain_disks): 286 | if disk['path'] not in self.exclude_disks: 287 | domain_disks[index]['snapshot_path'] = '{0}/{1}/snapshot_{2}.qcow2'.format(self.snap, domain.name(), 288 | disk['target']) 289 | log.info('Create snapshot of domain {0}'.format(domain.name())) 290 | self.libvirt_client.create_vm_snapshot(domain, domain_disks, memory_path=memory_path) 291 | for disk in domain_disks: 292 | if disk['path'] not in self.exclude_disks: 293 | log.info('Create Diff copy of {3} to {0}/{1}/{2}.img.gz'.format(self.dest, domain.name(), 294 | os.path.basename(disk['path']), 295 | disk['path'])) 296 | iffd = gzip.open('{0}/{1}/{2}.img.gz'.format(self.full, domain.name(), os.path.basename(disk['path'])), 297 | 'rb') 298 | dffd = open(disk['path'], 'rb') 299 | offd = gzip.open( 300 | '{0}/{1}/{2}.img.ddd.gz'.format(self.dest, domain.name(), os.path.basename(disk['path'])), 'wb', 301 | compresslevel=self.compress_level) 302 | differ = ebt_files.ddd.CreateDiff(iffd=iffd, dffd=dffd, offd=offd, block_size=8192) 303 | differ.start() 304 | iffd.close() 305 | dffd.close() 306 | offd.close() 307 | open('{0}/{1}/{2}.img.size'.format(self.dest, domain.name(), os.path.basename(disk['path'])), 308 | mode='w').write( 309 | str(self.libvirt_client.device_size(domain, disk['target']))) 310 | log.info('Remove snapshot of domain {0}'.format(domain.name())) 311 | self.libvirt_client.remove_vm_snapshot(domain, domain_disks) 312 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------