django-cloud-backup 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
cloud_backup/apps.py ADDED
@@ -0,0 +1,5 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class CloudBackupConfig(AppConfig):
5
+ name = 'cloud_backup'
cloud_backup/backup.py ADDED
@@ -0,0 +1,109 @@
1
+ import logging
2
+ from tempfile import gettempdir
3
+
4
+ from django.conf import settings
5
+ from .backup_db import BackupDb
6
+ from .backup_local_files import BackupLocal
7
+ from .config import BackupConfig, CHANGED_PROTECT, get_config
8
+ from .sql_functions import get_schemas
9
+ from .storages import get_storage
10
+
11
+ try:
12
+ from .backup_s3 import BackupS3
13
+ except ImportError:
14
+ # Allow for not using S3 and not installing boto3
15
+ BackupS3 = None
16
+
17
+
18
+ class ChangedFilesError(Exception):
19
+ """Source files no longer match their existing backups while
20
+ BACKUP_CHANGED_FILES = 'protect' - possible ransomware or corruption. The rest of
21
+ the backup completed before this was raised."""
22
+
23
+
24
+ class Backup:
25
+
26
+ def __init__(self, logger=None, config=None):
27
+ """config: a BACKUP_CONFIGS name, a BackupConfig instance, or None for the
28
+ default config (the legacy global settings when BACKUP_CONFIGS is not used)"""
29
+ self.logger = logger if logger else logging.getLogger(__name__)
30
+ self.config = config if isinstance(config, BackupConfig) else get_config(config)
31
+ self._storage = None
32
+
33
+ @property
34
+ def storage(self):
35
+ if self._storage is None:
36
+ self._storage = get_storage(self.config.storage_settings)
37
+ return self._storage
38
+
39
+ def get_backup_db(self, schema=None, table=None, sub_folder=None):
40
+ backup_directory = self.config.db_dir
41
+ if sub_folder:
42
+ backup_directory += '/' + sub_folder
43
+ elif schema:
44
+ backup_directory += '/' + schema
45
+ return BackupDb(self.storage,
46
+ backup_directory,
47
+ settings.DATABASES['default'],
48
+ getattr(settings, 'BACKUP_LOCAL_DB_DIR', gettempdir()),
49
+ self.logger,
50
+ schema=schema,
51
+ table=table,
52
+ exclude_tables=getattr(settings, 'BACKUP_EXCLUDE_TABLES', None),
53
+ exclude_table_data=getattr(settings, 'BACKUP_EXCLUDE_TABLE_DATA', None),
54
+ config=self.config)
55
+
56
+ def backup_db_and_folders(self, schema=None, table=None, include_db=True, all_schemas=False,
57
+ include_folders=True, include_s3_folders=True, sub_folder=None):
58
+ changed_files = []
59
+ if include_db and self.config.include_db:
60
+ schemas = [s[0] for s in get_schemas()] if all_schemas else [schema]
61
+ for s in schemas:
62
+ db = self.get_backup_db(s, table, sub_folder)
63
+ db.backup_db_to_storage()
64
+ if not sub_folder and self.config.retention:
65
+ db.prune_old_backups(self.config.retention)
66
+
67
+ if include_folders and self.config.dirs:
68
+ b = BackupLocal(self.storage, self.config.root, self.logger, config=self.config)
69
+ for backup in self.config.dirs:
70
+ b.backup_folder(*backup)
71
+ changed_files += b.changed_files
72
+
73
+ if include_s3_folders and self.config.s3_dirs:
74
+ s3_backup = BackupS3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY,
75
+ self.storage,
76
+ self.config.root,
77
+ self.logger,
78
+ config=self.config)
79
+ for s3 in self.config.s3_dirs:
80
+ s3_backup.backup(settings.AWS_PRIVATE_STORAGE_BUCKET_NAME, *s3)
81
+ changed_files += s3_backup.changed_files
82
+
83
+ if changed_files:
84
+ summary = ', '.join(changed_files[:5]) + ('...' if len(changed_files) > 5 else '')
85
+ self.logger.warning(f'{len(changed_files)} source files changed since being backed up: {summary}')
86
+ if self.config.changed_files == CHANGED_PROTECT:
87
+ # raised after everything else has completed so the db dump and all
88
+ # unchanged files are safely backed up before the run is marked failed
89
+ raise ChangedFilesError(f'{len(changed_files)} source files changed since being backed up '
90
+ f'and were NOT backed up: {summary}')
91
+
92
+ def extend_file_retention(self, workers=8):
93
+ """Ensure everything under the backup root keeps at least the configured
94
+ min_days of object-lock retention. Costs 1-2 API calls per file - schedule
95
+ daily rather than running with every backup."""
96
+ min_days = self.storage.lock.get('min_days')
97
+ if not min_days:
98
+ self.logger.info('No object-lock min_days configured - nothing to extend')
99
+ return
100
+ stats = self.storage.extend_retention(self.storage.ensure_folder(self.config.root), min_days,
101
+ workers=workers)
102
+ if stats is None:
103
+ self.logger.info('This storage backend does not support object-lock retention')
104
+ return
105
+ self.logger.info(f"Object-lock retention: {stats['checked']} files checked, "
106
+ f"{stats['extended']} extended to {min_days} days")
107
+ for error in stats['errors']:
108
+ self.logger.warning(f'Retention not extended: {error}')
109
+ return stats
@@ -0,0 +1,119 @@
1
+ import concurrent.futures
2
+ import logging
3
+ import threading
4
+
5
+ import boto3
6
+ import requests
7
+ from boto3.s3.transfer import TransferConfig
8
+
9
+
10
+ class B2AuthError(Exception):
11
+ pass
12
+
13
+
14
+ def b2_s3_endpoint(key_id, application_key):
15
+ """Backblaze B2 keys work with B2's S3-compatible API; the account's S3 endpoint
16
+ is returned by b2_authorize_account so it does not need to be configured."""
17
+ response = requests.get('https://api.backblazeb2.com/b2api/v2/b2_authorize_account',
18
+ auth=(key_id, application_key), timeout=30)
19
+ if response.status_code != 200:
20
+ raise B2AuthError(response.text)
21
+ return response.json()['s3ApiUrl']
22
+
23
+
24
+ class BackupAzureToS3:
25
+ """
26
+ Incremental, copy-only backup of Azure blob storage to an S3-compatible bucket
27
+ (e.g. Backblaze B2). Nothing is ever deleted from the destination; on B2, version
28
+ retention of overwritten files is controlled by the bucket's lifecycle rules.
29
+
30
+ A file is copied when it is missing from the destination, its size differs, or the
31
+ source blob was modified after the destination copy was uploaded (upload always
32
+ happens after the source write it captured, so destination timestamps only lag a
33
+ source change when a backup is needed).
34
+
35
+ :param storage: a django-storages AzureStorage instance - provides the container
36
+ client for a single paginated listing and open() for streaming
37
+ :param progress: optional callback receiving the stats dict after each copy
38
+ """
39
+
40
+ def __init__(self, storage, access_key_id, secret_key, bucket, endpoint_url=None,
41
+ logger=None, progress=None, workers=8):
42
+ if endpoint_url is None:
43
+ endpoint_url = b2_s3_endpoint(access_key_id, secret_key)
44
+ self.s3 = boto3.client('s3',
45
+ aws_access_key_id=access_key_id,
46
+ aws_secret_access_key=secret_key,
47
+ endpoint_url=endpoint_url,
48
+ # https://s3.<region>.backblazeb2.com
49
+ region_name=endpoint_url.split('.')[1])
50
+ self.storage = storage
51
+ self.bucket = bucket
52
+ self.logger = logger or logging.getLogger(__name__)
53
+ self.progress = progress
54
+ self.workers = workers
55
+ self.transfer_config = TransferConfig(multipart_threshold=64 * 1024 * 1024)
56
+
57
+ def list_source(self, prefix):
58
+ return {b.name: b for b in self.storage.client.list_blobs(name_starts_with=prefix)}
59
+
60
+ def list_destination(self, prefix):
61
+ files = {}
62
+ for page in self.s3.get_paginator('list_objects_v2').paginate(Bucket=self.bucket, Prefix=prefix):
63
+ for s3_object in page.get('Contents', []):
64
+ files[s3_object['Key']] = s3_object
65
+ return files
66
+
67
+ @staticmethod
68
+ def needs_copy(blob, s3_object):
69
+ if s3_object is None or blob.size != s3_object['Size']:
70
+ return True
71
+ return blob.last_modified > s3_object['LastModified']
72
+
73
+ def copy_file(self, blob, dest_key):
74
+ # src_last_modified_millis is the file-info key rclone uses for modtime, so
75
+ # files uploaded here are seen as unchanged by rclone (and vice versa)
76
+ extra = {'Metadata': {'src_last_modified_millis': str(int(blob.last_modified.timestamp() * 1000))}}
77
+ content_type = getattr(blob.content_settings, 'content_type', None)
78
+ if content_type:
79
+ extra['ContentType'] = content_type
80
+ with self.storage.open(blob.name, 'rb') as f:
81
+ self.s3.upload_fileobj(f, self.bucket, dest_key, ExtraArgs=extra, Config=self.transfer_config)
82
+
83
+ def backup(self, prefix, dest_prefix=None):
84
+ """ Copy new/changed files under an Azure prefix to the bucket
85
+ :param prefix: source folder in the Azure container, with trailing /
86
+ :param dest_prefix: key prefix in the bucket, defaults to prefix
87
+ :return: stats dict
88
+ """
89
+ if dest_prefix is None:
90
+ dest_prefix = prefix
91
+ source = self.list_source(prefix)
92
+ destination = self.list_destination(dest_prefix)
93
+ to_copy = [(blob, dest_prefix + name[len(prefix):]) for name, blob in source.items()
94
+ if self.needs_copy(blob, destination.get(dest_prefix + name[len(prefix):]))]
95
+
96
+ stats = {'source_files': len(source), 'to_copy': len(to_copy), 'copied': 0,
97
+ 'copied_bytes': 0, 'errors': []}
98
+ lock = threading.Lock()
99
+
100
+ def copy(item):
101
+ blob, dest_key = item
102
+ for attempt in (1, 2):
103
+ try:
104
+ self.copy_file(blob, dest_key)
105
+ with lock:
106
+ stats['copied'] += 1
107
+ stats['copied_bytes'] += blob.size
108
+ if self.progress:
109
+ self.progress(stats)
110
+ return
111
+ except Exception as e:
112
+ if attempt == 2:
113
+ self.logger.exception(f'failed to copy {blob.name}')
114
+ with lock:
115
+ stats['errors'].append(f'{blob.name}: {e}')
116
+
117
+ with concurrent.futures.ThreadPoolExecutor(max_workers=self.workers) as pool:
118
+ list(pool.map(copy, to_copy))
119
+ return stats
@@ -0,0 +1,211 @@
1
+ import datetime
2
+ import os
3
+ import subprocess
4
+ import urllib.parse
5
+ from tempfile import NamedTemporaryFile, TemporaryFile
6
+
7
+ import requests
8
+
9
+ from .base_backup import BaseBackup
10
+ from .compression import decompress
11
+ from .encryption import decrypt_in_place, encrypt_file
12
+ from .prune_backups import PruneBackups
13
+ from .sql_functions import delete_table
14
+
15
+ DUMP_EXTENSION = 'dump'
16
+
17
+
18
+ def get_ip_address():
19
+ try:
20
+ ip_response = requests.get('https://api.ipify.org/')
21
+ if ip_response.status_code == 200 and len(ip_response.text) < 16:
22
+ ip_address = ip_response.text.replace('.', '_')
23
+ else:
24
+ ip_address = 'fail'
25
+ except (requests.exceptions.Timeout, requests.exceptions.ConnectionError, requests.exceptions.HTTPError):
26
+ ip_address = 'exception'
27
+ return ip_address
28
+
29
+
30
+ class DatabaseUploadError(Exception):
31
+ pass
32
+
33
+
34
+ class DatabaseBackupError(Exception):
35
+ pass
36
+
37
+
38
+ DB_FILE_EXTENSIONS = ('.' + DUMP_EXTENSION, '.bz2', '.gz', '.sql')
39
+
40
+
41
+ class BackupDb(BaseBackup):
42
+
43
+ def __init__(self, storage, backup_dir, database, local_backup_dir, logger, schema=None,
44
+ table=None, exclude_tables=None, exclude_table_data=None, config=None):
45
+ super().__init__(storage, backup_dir, logger, config=config)
46
+ self.postgres_backup = PostgresBackup(database, self.logger, schema, table,
47
+ exclude_tables=exclude_tables,
48
+ exclude_table_data=exclude_table_data,
49
+ encryption_key=self.encryption_key)
50
+ self.local_backup_dir = local_backup_dir
51
+
52
+ def backup_db_to_storage(self):
53
+ metadata = {'ip_address': get_ip_address()}
54
+ if self.postgres_backup.table:
55
+ metadata['schema'] = self.postgres_backup.schema
56
+ metadata['table'] = self.postgres_backup.table
57
+ filename = f'table_{self.postgres_backup.table}'
58
+ elif self.postgres_backup.schema:
59
+ metadata['schema'] = self.postgres_backup.schema
60
+ filename = f'schema_{self.postgres_backup.schema}'
61
+ else:
62
+ filename = 'db'
63
+ filename += f'_{datetime.datetime.today().strftime("%Y_%m_%d_%H_%M")}.{DUMP_EXTENSION}'
64
+ # only the unique name is wanted - backup_db writes to <name>.dump, so the placeholder
65
+ # file itself is closed and removed rather than left open for the life of the process
66
+ backup_stream = NamedTemporaryFile(delete=False)
67
+ backup_stream.close()
68
+ os.remove(backup_stream.name)
69
+ backup_filename = None
70
+ upload_filename = None
71
+ try:
72
+ backup_filename = self.postgres_backup.backup_db('', backup_stream.name)
73
+ if self.encryption_key is not None:
74
+ # encrypt to a second temp file so check_upload can verify the storage
75
+ # backend's hash against the ciphertext it actually received
76
+ upload_filename = backup_filename + '.enc-tmp'
77
+ metadata['md5'] = encrypt_file(backup_filename, upload_filename, self.encryption_key)
78
+ metadata['encrypted'] = '1'
79
+ os.remove(backup_filename)
80
+ else:
81
+ upload_filename = backup_filename
82
+ # stored alongside the file so destinations without a server-side md5
83
+ # (multipart S3, Azure) can still deduplicate and verify
84
+ metadata['md5'] = self.md5sum(backup_filename)
85
+ self.logger.info('Copying backup to storage')
86
+ with open(upload_filename, 'rb') as compressed_file:
87
+ stored_file = self.storage.upload(self.base_backup_dir, filename, compressed_file,
88
+ metadata=metadata,
89
+ lock_days=self.storage.lock_days('db'))
90
+ if not self.check_upload(stored_file, upload_filename):
91
+ raise DatabaseUploadError
92
+ finally:
93
+ for temp_file in (backup_filename, upload_filename):
94
+ if temp_file and os.path.exists(temp_file):
95
+ os.remove(temp_file)
96
+
97
+ def restore_db_from_storage(self, file_id=None, file_name=None):
98
+ if file_id:
99
+ file_info = self.storage.get_file(file_id)
100
+ else:
101
+ file_info = self.storage.find_file(self.base_backup_dir, file_name)
102
+ local_name = self.storage.download(file_info, local_folder=self.local_backup_dir)
103
+ if file_info['metadata'].get('table'):
104
+ delete_table(file_info['metadata']['schema'], file_info['metadata']['table'])
105
+ self.postgres_backup.restore_db(os.path.join(self.local_backup_dir, local_name))
106
+
107
+ def get_db_backup_files(self, deleted=False, metadata_filter=None):
108
+ files = self.storage.list_files(self.base_backup_dir, metadata_filter=metadata_filter,
109
+ deleted=deleted, include_metadata=True)
110
+ return sorted((f for f in files if f['name'].endswith(DB_FILE_EXTENSIONS)),
111
+ key=lambda f: f['created'], reverse=True)
112
+
113
+ def get_latest_db_backup(self):
114
+ files = self.get_db_backup_files()
115
+ if len(files) > 0:
116
+ return files[0]
117
+
118
+ def prune_old_backups(self, recipe):
119
+ backups = self.get_db_backup_files(metadata_filter={'ip_address': get_ip_address()})
120
+ backup_dict = {b['created']: b for b in backups}
121
+ pb = PruneBackups(backup_dict)
122
+ removal = pb.backups_to_remove(recipe)
123
+ for k in removal:
124
+ try:
125
+ self.storage.delete(removal[k]['id'])
126
+ except Exception as e:
127
+ # deletes may be intentionally blocked (object lock, delete-less
128
+ # credentials) - the backup itself has already succeeded
129
+ self.logger.warning(f'Could not delete old backup {removal[k]["name"]}: {e}')
130
+
131
+
132
+ class PostgresBackup:
133
+
134
+ def __init__(self, database, logger, schema=None, table=None, exclude_tables=None, exclude_table_data=None,
135
+ encryption_key=None):
136
+ self.logger = logger
137
+ self.schema = schema
138
+ self.table = table
139
+ self.encryption_key = encryption_key
140
+ self.exclude_tables = exclude_tables or []
141
+ self.exclude_table_data = exclude_table_data or []
142
+ self.connection_string = (f'postgresql://{database["USER"]}:{urllib.parse.quote(database["PASSWORD"])}'
143
+ f'@{database["HOST"]}/{database["NAME"]}')
144
+
145
+ def psql(self, commands):
146
+ return subprocess.call(['psql', '-d', self.connection_string] + commands)
147
+
148
+ def restore_db(self, backup_file):
149
+ decrypt_in_place(backup_file, self.encryption_key)
150
+ if backup_file.endswith('.' + DUMP_EXTENSION):
151
+ return_code = subprocess.call(['pg_restore', '-d', self.connection_string, '--clean', '--if-exists',
152
+ backup_file])
153
+ command = 'pg_restore'
154
+ os.remove(backup_file)
155
+ else:
156
+ decompressed_name = decompress(backup_file)
157
+ return_code = self.psql(['-f', decompressed_name])
158
+ command = 'psql'
159
+ os.remove(decompressed_name)
160
+ if return_code != 0:
161
+ # not fatal - pg_restore exits non-zero for ignorable warnings under --clean --if-exists,
162
+ # but the restore may equally have failed outright, so make it visible
163
+ self.logger.warning(f'{command} exited with code {return_code}. Check the output above to confirm the '
164
+ f'restore completed as expected.')
165
+ return return_code
166
+
167
+ def backup_db(self, backup_local_db_dir, filename):
168
+ self.logger.info('Creating backup file ' + filename)
169
+ if backup_local_db_dir:
170
+ if not os.path.exists(backup_local_db_dir):
171
+ os.makedirs(backup_local_db_dir)
172
+ backup_path = backup_local_db_dir + '/' + filename
173
+ else:
174
+ backup_path = filename
175
+ commands = ['pg_dump', '-Fc', '-d', self.connection_string]
176
+ if self.table:
177
+ self.logger.info(f'Backing up table {self.schema}.{self.table}')
178
+ commands += ['-a', '-t', f'{self.schema}.{self.table}']
179
+ elif self.schema:
180
+ self.logger.info(f'Backing up schema {self.schema}')
181
+ commands += ['-n', self.schema]
182
+ else:
183
+ self.logger.info(f'Backing up database')
184
+ for t in self.exclude_tables:
185
+ commands += [f'--exclude-table={t}']
186
+ for t in self.exclude_table_data:
187
+ commands += [f'--exclude-table-data={t}']
188
+ dump_path = backup_path + '.' + DUMP_EXTENSION
189
+ try:
190
+ # stderr goes to a temp file rather than a pipe so a noisy dump cannot fill the pipe
191
+ # buffer and deadlock while we are still reading stdout
192
+ with TemporaryFile() as error_file:
193
+ with open(dump_path, 'wb') as output:
194
+ dump_process = subprocess.Popen(commands, stdout=subprocess.PIPE, stderr=error_file)
195
+ for chunk in iter(lambda: dump_process.stdout.read(1024 * 1024), b''):
196
+ output.write(chunk)
197
+ dump_process.wait()
198
+ error_file.seek(0)
199
+ errors = error_file.read().decode(errors='replace').strip()
200
+ if dump_process.returncode != 0:
201
+ if errors:
202
+ self.logger.error(errors)
203
+ raise DatabaseBackupError(f'pg_dump failed with exit code {dump_process.returncode}')
204
+ if errors:
205
+ self.logger.warning(errors)
206
+ except BaseException:
207
+ # never leave a partial dump behind for the caller to upload as if it were valid
208
+ if os.path.exists(dump_path):
209
+ os.remove(dump_path)
210
+ raise
211
+ return dump_path
@@ -0,0 +1,66 @@
1
+ import os
2
+
3
+ from .base_backup import BaseBackup, CHANGED_HISTORY, CHANGED_PROTECT
4
+ from .encryption import EncryptingReader, decrypt_in_place
5
+
6
+
7
+ class BackupLocal(BaseBackup):
8
+
9
+ def __init__(self, *args, **kwargs):
10
+ super().__init__(*args, **kwargs)
11
+ self.changed_files = []
12
+
13
+ def backup_folder(self, source_dir, backup_dir):
14
+ self.logger.info(f'Backing up {source_dir} to {backup_dir}')
15
+ mode = self.config.changed_files
16
+ encrypt = self.encryption_key is not None
17
+ lock_days = self.storage.lock_days('file')
18
+ storage_dir = self.storage.ensure_folder(backup_dir, parent=self.base_backup_dir)
19
+ # encrypted stored bytes hash differently from the source, so dedup then needs
20
+ # the plaintext md5 recorded in each file's metadata at upload
21
+ files_by_name = self.get_files_by_name(storage_dir, include_metadata=encrypt)
22
+ for f in os.listdir(source_dir):
23
+ full_filename = os.path.join(source_dir, f)
24
+ if os.path.isfile(full_filename):
25
+ md5 = self.md5sum(full_filename)
26
+ # older Google Drive backups were stored under the full local path,
27
+ # so check that name as well to avoid re-uploading them all
28
+ existing = files_by_name.get(f, []) + files_by_name.get(full_filename, [])
29
+ if md5 in [self.content_hash(e) for e in existing]:
30
+ self.logger.info(' Exists - ' + f)
31
+ continue
32
+ if existing:
33
+ if mode == CHANGED_PROTECT:
34
+ self.changed_files.append(full_filename)
35
+ self.logger.warning(f'NOT backing up {full_filename} - it no longer matches '
36
+ f'its existing backup')
37
+ continue
38
+ if mode == CHANGED_HISTORY:
39
+ self.changed_files.append(full_filename)
40
+ self.logger.warning(f'{full_filename} changed - keeping the previous backup version')
41
+ self.storage.keep_version(existing[0], lock_days=lock_days)
42
+ self.logger.info('Backup - ' + f)
43
+ # the metadata md5 is always the plaintext hash - it is what dedup compares
44
+ with open(full_filename, 'rb') as backup_stream:
45
+ if encrypt:
46
+ stream = EncryptingReader(backup_stream, os.path.getsize(full_filename),
47
+ self.encryption_key, logger=self.logger)
48
+ metadata = {'md5': md5, 'encrypted': '1'}
49
+ else:
50
+ stream = backup_stream
51
+ metadata = {'md5': md5}
52
+ self.storage.upload(storage_dir, f, stream, metadata=metadata,
53
+ lock_days=lock_days)
54
+ elif os.path.isdir(full_filename):
55
+ self.backup_folder(full_filename, backup_dir + '/' + f)
56
+
57
+ # previous name, kept for compatibility
58
+ backup_to_drive = backup_folder
59
+
60
+ def restore_folder(self, folder_name, destination_root):
61
+ folder = self.storage.get_folder(folder_name, parent=self.base_backup_dir)
62
+ for path, stored_file in self.storage.walk(folder):
63
+ local_folder = os.path.join(destination_root, folder_name, path)
64
+ os.makedirs(local_folder, exist_ok=True)
65
+ local_name = self.storage.download(stored_file, local_folder=local_folder)
66
+ decrypt_in_place(os.path.join(local_folder, local_name), self.encryption_key)
@@ -0,0 +1,159 @@
1
+ import io
2
+ import boto3
3
+ import hashlib
4
+ from .base_backup import BaseBackup, CHANGED_HISTORY, CHANGED_PROTECT
5
+ from .encryption import EncryptingReader
6
+
7
+
8
+ class S3File(io.RawIOBase):
9
+ """
10
+ Binary stream to access S3 files. Provides seek and read a variable number of bytes.
11
+ """
12
+
13
+ def __init__(self, s3_object):
14
+ self.s3_object = s3_object
15
+ self.position = 0
16
+ self.md5 = hashlib.md5(b'')
17
+
18
+ def __repr__(self):
19
+ return "<%s s3_object=%r>" % (type(self).__name__, self.s3_object)
20
+
21
+ @property
22
+ def size(self):
23
+ return self.s3_object.content_length
24
+
25
+ def tell(self):
26
+ return self.position
27
+
28
+ def seek(self, offset, whence=io.SEEK_SET):
29
+ if whence == io.SEEK_SET:
30
+ self.position = offset
31
+ elif whence == io.SEEK_CUR:
32
+ self.position += offset
33
+ elif whence == io.SEEK_END:
34
+ self.position = self.size + offset
35
+ else:
36
+ raise ValueError("invalid whence (%r, should be %d, %d, %d)" % (
37
+ whence, io.SEEK_SET, io.SEEK_CUR, io.SEEK_END
38
+ ))
39
+ return self.position
40
+
41
+ def seekable(self):
42
+ return True
43
+
44
+ def read(self, size=-1):
45
+ if self.position >= self.size:
46
+ return b''
47
+ if size == -1:
48
+ range_header = f'bytes={self.position}'
49
+ self.seek(offset=0, whence=io.SEEK_END)
50
+ else:
51
+ new_position = self.position + size
52
+ if new_position >= self.size:
53
+ return self.read()
54
+ range_header = f'bytes={self.position}-{new_position - 1}'
55
+ self.seek(offset=size, whence=io.SEEK_CUR)
56
+ data = self.s3_object.get(Range=range_header)["Body"].read()
57
+ self.md5.update(data)
58
+ return data
59
+
60
+ def readable(self):
61
+ return True
62
+
63
+
64
+ class BackupFolders:
65
+ """
66
+ Keeps a dictionary of destination folder handles along with the files already
67
+ backed up into them (whose metadata holds the source S3 ETag)
68
+ """
69
+
70
+ def __init__(self, backup, base_folder):
71
+ self.base_folder = base_folder
72
+ self.backup = backup
73
+ self.folders = \
74
+ {'/': {'files': backup.get_files_by_name(base_folder, include_metadata=True),
75
+ 'folder': backup.storage.ensure_folder(base_folder, parent=backup.base_backup_dir)}
76
+ }
77
+
78
+ def add_folder(self, folder):
79
+ return {
80
+ 'files': self.backup.get_files_by_name(self.base_folder + '/' + folder, include_metadata=True),
81
+ 'folder': self.backup.storage.ensure_folder(folder, parent=self.folders['/']['folder']),
82
+ }
83
+
84
+ def file_status(self, folder, file, file_hash):
85
+ """'match' - already backed up, 'new' - not in the backup, 'changed' - backed
86
+ up with different contents"""
87
+ if file == '':
88
+ return 'match'
89
+ if folder not in self.folders:
90
+ self.folders[folder] = self.add_folder(folder)
91
+ existing = self.folders[folder]['files'].get(file)
92
+ if not existing:
93
+ return 'new'
94
+ return 'match' if file_hash in [BackupS3.get_etag(f) for f in existing] else 'changed'
95
+
96
+ def existing_file(self, folder, file):
97
+ return self.folders[folder]['files'][file][0]
98
+
99
+ def parent(self, folder):
100
+ return self.folders[folder]['folder']
101
+
102
+
103
+ class BackupS3(BaseBackup):
104
+ """
105
+ Copies files from a folder and sub folders in an S3 bucket to the backup storage.
106
+ Will skip files where the S3 ETag matches the value stored in the file's metadata.
107
+ """
108
+
109
+ def __init__(self, access_key_id, access_key, storage, backup_dir, logger, config=None):
110
+ super().__init__(storage, backup_dir, logger, config=config)
111
+ self.s3 = boto3.resource('s3', aws_access_key_id=access_key_id, aws_secret_access_key=access_key)
112
+ self.changed_files = []
113
+
114
+ @staticmethod
115
+ def get_etag(f):
116
+ metadata = f.get('metadata', {})
117
+ # S3-compatible destinations return metadata keys lower-cased
118
+ return metadata.get('ETag', metadata.get('etag'))
119
+
120
+ def backup(self, bucket_name, prefix, destination):
121
+ """ Backup from a S3 prefix (folder) to the backup storage
122
+ :param bucket_name:
123
+ :param prefix: consider like a folder with no trailing /
124
+ :param destination:
125
+ :return:
126
+ """
127
+
128
+ mode = self.config.changed_files
129
+ lock_days = self.storage.lock_days('file')
130
+ folders = BackupFolders(self, destination)
131
+ bucket = self.s3.Bucket(name=bucket_name)
132
+ for f in bucket.objects.filter(Prefix=prefix):
133
+ filename = f.key.split('/')[-1]
134
+ path = f.key[len(prefix) + 1:-1*(len(filename) + 1)]
135
+ if path == '':
136
+ path = '/'
137
+ status = folders.file_status(path, filename, f.e_tag)
138
+ if status == 'match':
139
+ self.logger.info(f'found {f.key}')
140
+ continue
141
+ if status == 'changed':
142
+ if mode == CHANGED_PROTECT:
143
+ self.changed_files.append(f.key)
144
+ self.logger.warning(f'NOT backing up {f.key} - it no longer matches its existing backup')
145
+ continue
146
+ if mode == CHANGED_HISTORY:
147
+ self.changed_files.append(f.key)
148
+ self.logger.warning(f'{f.key} changed - keeping the previous backup version')
149
+ self.storage.keep_version(folders.existing_file(path, filename), lock_days=lock_days)
150
+ self.logger.info(f'Backing up {f.key}')
151
+ s3_file = S3File(self.s3.Object(bucket_name, f.key))
152
+ # dedup compares the source ETag stored in metadata, so it is unaffected
153
+ # by the stored bytes being encrypted
154
+ metadata = {'ETag': f.e_tag}
155
+ if self.encryption_key is not None:
156
+ s3_file = EncryptingReader(s3_file, s3_file.size, self.encryption_key, logger=self.logger)
157
+ metadata['encrypted'] = '1'
158
+ self.storage.upload(folders.parent(path), filename, s3_file,
159
+ metadata=metadata, lock_days=lock_days)