| 1 |
""" |
| 2 |
Utils for handle files. |
| 3 |
""" |
| 4 |
|
| 5 |
import contextlib |
| 6 |
import logging |
| 7 |
from datetime import datetime, timezone |
| 8 |
|
| 9 |
from django.core.exceptions import ImproperlyConfigured |
| 10 |
|
| 11 |
from dbbackup import settings, utils |
| 12 |
|
| 13 |
|
| 14 |
def get_storage(path=None, options=None): |
| 15 |
""" |
| 16 |
Get the specified storage configured with options. |
| 17 |
|
| 18 |
:param path: Path in Python dot style to module containing the storage |
| 19 |
class. If empty settings.STORAGES["dbbackup"] will be used. |
| 20 |
:type path: ``str`` |
| 21 |
|
| 22 |
:param options: Parameters for configure the storage, if empty |
| 23 |
settings.STORAGES["dbbackup"]["OPTIONS"] will be used. |
| 24 |
:type options: ``dict`` |
| 25 |
|
| 26 |
:return: Storage configured |
| 27 |
:rtype: :class:`.Storage` |
| 28 |
""" |
| 29 |
path = path or settings.STORAGE |
| 30 |
options = options or settings.STORAGE_OPTIONS |
| 31 |
if not path: |
| 32 |
msg = 'You must specify a storage class using settings.STORAGES["dbbackup"] settings.' |
| 33 |
raise ImproperlyConfigured(msg) |
| 34 |
return Storage(path, **options) |
| 35 |
|
| 36 |
|
| 37 |
class StorageError(Exception): |
| 38 |
pass |
| 39 |
|
| 40 |
|
| 41 |
class Storage: |
| 42 |
""" |
| 43 |
This object make high-level storage operations for upload/download or |
| 44 |
list and filter files. It uses a Django storage object for low-level |
| 45 |
operations. |
| 46 |
""" |
| 47 |
|
| 48 |
@property |
| 49 |
def logger(self): |
| 50 |
if not hasattr(self, "_logger"): |
| 51 |
self._logger = logging.getLogger("dbbackup.storage") |
| 52 |
return self._logger |
| 53 |
|
| 54 |
def __init__(self, storage_path=None, **options): |
| 55 |
""" |
| 56 |
Initialize a Django Storage instance with given options. |
| 57 |
|
| 58 |
:param storage_path: Path to a Django Storage class with dot style |
| 59 |
If ``None``, ``settings.STORAGES["dbbackup"]`` will |
| 60 |
be used. |
| 61 |
:type storage_path: str |
| 62 |
""" |
| 63 |
self._storage_path = storage_path or settings.STORAGE |
| 64 |
options = options.copy() |
| 65 |
options.update(settings.STORAGE_OPTIONS) |
| 66 |
options = {key.lower(): value for key, value in options.items()} |
| 67 |
self.storageCls = get_storage_class(self._storage_path) |
| 68 |
self.storage = self.storageCls(**options) |
| 69 |
self.name = self.storageCls.__name__ |
| 70 |
|
| 71 |
def __str__(self): |
| 72 |
return f"dbbackup-{self.storage.__str__()}" |
| 73 |
|
| 74 |
def delete_file(self, filepath): |
| 75 |
self.logger.debug("Deleting file %s", filepath) |
| 76 |
self.storage.delete(name=filepath) |
| 77 |
|
| 78 |
def list_directory(self, path=""): |
| 79 |
return [self._normalize_listed_name(name) for name in self.storage.listdir(path)[1]] |
| 80 |
|
| 81 |
def write_file(self, filehandle, filename): |
| 82 |
self.logger.debug("Writing file %s", filename) |
| 83 |
self.storage.save(name=filename, content=filehandle) |
| 84 |
|
| 85 |
def read_file(self, filepath): |
| 86 |
self.logger.debug("Reading file %s", filepath) |
| 87 |
file_ = self.storage.open(name=filepath, mode="rb") |
| 88 |
if not getattr(file_, "name", None): |
| 89 |
file_.name = filepath |
| 90 |
return file_ |
| 91 |
|
| 92 |
def list_backups( |
| 93 |
self, |
| 94 |
encrypted=None, |
| 95 |
compressed=None, |
| 96 |
content_type=None, |
| 97 |
database=None, |
| 98 |
servername=None, |
| 99 |
): |
| 100 |
""" |
| 101 |
List stored files except given filter. If filter is None, it won't be |
| 102 |
used. ``content_type`` must be ``'db'`` for database backups or |
| 103 |
``'media'`` for media backups. |
| 104 |
|
| 105 |
:param encrypted: Filter by encrypted or not |
| 106 |
:type encrypted: ``bool`` or ``None`` |
| 107 |
|
| 108 |
:param compressed: Filter by compressed or not |
| 109 |
:type compressed: ``bool`` or ``None`` |
| 110 |
|
| 111 |
:param content_type: Filter by media or database backup, must be |
| 112 |
``'db'`` or ``'media'`` |
| 113 |
|
| 114 |
:type content_type: ``str`` or ``None`` |
| 115 |
|
| 116 |
:param database: Filter by source database's name |
| 117 |
:type: ``str`` or ``None`` |
| 118 |
|
| 119 |
:param servername: Filter by source server's name |
| 120 |
:type: ``str`` or ``None`` |
| 121 |
|
| 122 |
:returns: List of files |
| 123 |
:rtype: ``list`` of ``str`` |
| 124 |
""" |
| 125 |
if content_type not in ("db", "media", None): |
| 126 |
msg = f"Bad content_type {content_type}, must be 'db', 'media', or None" |
| 127 |
raise TypeError(msg) |
| 128 |
# TODO: Make better filter for include only backups |
| 129 |
files = [f for f in self.list_directory() if utils.filename_to_datestring(f)] |
| 130 |
# Exclude metadata files |
| 131 |
files = [f for f in files if not f.endswith(".metadata")] |
| 132 |
if encrypted is not None: |
| 133 |
files = [f for f in files if (".gpg" in f) == encrypted] |
| 134 |
if compressed is not None: |
| 135 |
files = [f for f in files if (".gz" in f) == compressed] |
| 136 |
if content_type == "media": |
| 137 |
files = [f for f in files if ".tar" in f] |
| 138 |
elif content_type == "db": |
| 139 |
files = [f for f in files if ".tar" not in f] |
| 140 |
if database: |
| 141 |
files = [f for f in files if database in f] |
| 142 |
if servername: |
| 143 |
files = [f for f in files if servername in f] |
| 144 |
return files |
| 145 |
|
| 146 |
def get_latest_backup( |
| 147 |
self, |
| 148 |
encrypted=None, |
| 149 |
compressed=None, |
| 150 |
content_type=None, |
| 151 |
database=None, |
| 152 |
servername=None, |
| 153 |
): |
| 154 |
""" |
| 155 |
Return the latest backup file name. |
| 156 |
|
| 157 |
:param encrypted: Filter by encrypted or not |
| 158 |
:type encrypted: ``bool`` or ``None`` |
| 159 |
|
| 160 |
:param compressed: Filter by compressed or not |
| 161 |
:type compressed: ``bool`` or ``None`` |
| 162 |
|
| 163 |
:param content_type: Filter by media or database backup, must be |
| 164 |
``'db'`` or ``'media'`` |
| 165 |
|
| 166 |
:type content_type: ``str`` or ``None`` |
| 167 |
|
| 168 |
:param database: Filter by source database's name |
| 169 |
:type: ``str`` or ``None`` |
| 170 |
|
| 171 |
:param servername: Filter by source server's name |
| 172 |
:type: ``str`` or ``None`` |
| 173 |
|
| 174 |
:returns: Most recent file |
| 175 |
:rtype: ``str`` |
| 176 |
|
| 177 |
:raises: FileNotFound: If no backup file is found |
| 178 |
""" |
| 179 |
files = self.list_backups( |
| 180 |
encrypted=encrypted, |
| 181 |
compressed=compressed, |
| 182 |
content_type=content_type, |
| 183 |
database=database, |
| 184 |
servername=servername, |
| 185 |
) |
| 186 |
if not files: |
| 187 |
msg = "There's no backup file available." |
| 188 |
raise StorageError(msg) |
| 189 |
return max(files, key=self._filename_to_date_or_min) |
| 190 |
|
| 191 |
def get_older_backup( |
| 192 |
self, |
| 193 |
encrypted=None, |
| 194 |
compressed=None, |
| 195 |
content_type=None, |
| 196 |
database=None, |
| 197 |
servername=None, |
| 198 |
): |
| 199 |
""" |
| 200 |
Return the older backup's file name. |
| 201 |
|
| 202 |
:param encrypted: Filter by encrypted or not |
| 203 |
:type encrypted: ``bool`` or ``None`` |
| 204 |
|
| 205 |
:param compressed: Filter by compressed or not |
| 206 |
:type compressed: ``bool`` or ``None`` |
| 207 |
|
| 208 |
:param content_type: Filter by media or database backup, must be |
| 209 |
``'db'`` or ``'media'`` |
| 210 |
|
| 211 |
:type content_type: ``str`` or ``None`` |
| 212 |
|
| 213 |
:param database: Filter by source database's name |
| 214 |
:type: ``str`` or ``None`` |
| 215 |
|
| 216 |
:param servername: Filter by source server's name |
| 217 |
:type: ``str`` or ``None`` |
| 218 |
|
| 219 |
:returns: Older file |
| 220 |
:rtype: ``str`` |
| 221 |
|
| 222 |
:raises: FileNotFound: If no backup file is found |
| 223 |
""" |
| 224 |
files = self.list_backups( |
| 225 |
encrypted=encrypted, |
| 226 |
compressed=compressed, |
| 227 |
content_type=content_type, |
| 228 |
database=database, |
| 229 |
servername=servername, |
| 230 |
) |
| 231 |
if not files: |
| 232 |
msg = "There's no backup file available." |
| 233 |
raise StorageError(msg) |
| 234 |
return min(files, key=self._filename_to_date_or_min) |
| 235 |
|
| 236 |
def clean_old_backups( |
| 237 |
self, |
| 238 |
encrypted=None, |
| 239 |
compressed=None, |
| 240 |
content_type=None, |
| 241 |
database=None, |
| 242 |
servername=None, |
| 243 |
keep_number=None, |
| 244 |
): |
| 245 |
""" |
| 246 |
Delete olders backups and hold the number defined. |
| 247 |
|
| 248 |
:param encrypted: Filter by encrypted or not |
| 249 |
:type encrypted: ``bool`` or ``None`` |
| 250 |
|
| 251 |
:param compressed: Filter by compressed or not |
| 252 |
:type compressed: ``bool`` or ``None`` |
| 253 |
|
| 254 |
:param content_type: Filter by media or database backup, must be |
| 255 |
``'db'`` or ``'media'`` |
| 256 |
|
| 257 |
:type content_type: ``str`` or ``None`` |
| 258 |
|
| 259 |
:param database: Filter by source database's name |
| 260 |
:type: ``str`` or ``None`` |
| 261 |
|
| 262 |
:param servername: Filter by source server's name |
| 263 |
:type: ``str`` or ``None`` |
| 264 |
|
| 265 |
:param keep_number: Number of files to keep, other will be deleted |
| 266 |
:type keep_number: ``int`` or ``None`` |
| 267 |
""" |
| 268 |
if keep_number is None: |
| 269 |
keep_number = settings.CLEANUP_KEEP if content_type == "db" else settings.CLEANUP_KEEP_MEDIA |
| 270 |
keep_filter = settings.CLEANUP_KEEP_FILTER |
| 271 |
files = self.list_backups( |
| 272 |
encrypted=encrypted, |
| 273 |
compressed=compressed, |
| 274 |
content_type=content_type, |
| 275 |
database=database, |
| 276 |
servername=servername, |
| 277 |
) |
| 278 |
files = sorted(files, key=self._filename_to_date_or_min, reverse=True) |
| 279 |
files_to_delete = [fi for i, fi in enumerate(files) if i >= keep_number] |
| 280 |
for filename in files_to_delete: |
| 281 |
if keep_filter(filename): |
| 282 |
continue |
| 283 |
self.delete_file(filename) |
| 284 |
|
| 285 |
metadata_filename = f"{filename}.metadata" |
| 286 |
if self.storage.exists(metadata_filename): |
| 287 |
self.delete_file(metadata_filename) |
| 288 |
|
| 289 |
@staticmethod |
| 290 |
def _filename_to_date_or_min(filename: str) -> datetime: |
| 291 |
file_date = utils.filename_to_date(filename) |
| 292 |
if file_date is None: |
| 293 |
return datetime.min.replace(tzinfo=timezone.utc) |
| 294 |
if file_date.tzinfo is None: |
| 295 |
return file_date.replace(tzinfo=timezone.utc) |
| 296 |
return file_date |
| 297 |
|
| 298 |
def _normalize_listed_name(self, name: str) -> str: |
| 299 |
location = getattr(self.storage, "location", "") or "" |
| 300 |
if not location: |
| 301 |
return name |
| 302 |
|
| 303 |
normalized_location = location.replace("\\", "/").strip("/") |
| 304 |
normalized_name = name.replace("\\", "/") |
| 305 |
prefix = f"{normalized_location}/" |
| 306 |
if normalized_location and normalized_name.startswith(prefix): |
| 307 |
return normalized_name[len(prefix) :] |
| 308 |
return name |
| 309 |
|
| 310 |
|
| 311 |
def get_storage_class(path=None): |
| 312 |
""" |
| 313 |
Return the configured storage class. |
| 314 |
|
| 315 |
:param path: Path in Python dot style to module containing the storage |
| 316 |
class. If empty, the default storage class will be used. |
| 317 |
:type path: str or None |
| 318 |
|
| 319 |
:returns: Storage class |
| 320 |
:rtype: :class:`django.core.files.storage.Storage` |
| 321 |
""" |
| 322 |
from django.utils.module_loading import import_string |
| 323 |
|
| 324 |
if path: |
| 325 |
# this is a workaround to keep compatibility with Django >= 5.1 (django.core.files.storage.get_storage_class is removed) |
| 326 |
return import_string(path) |
| 327 |
|
| 328 |
with contextlib.suppress(Exception): |
| 329 |
from django.core.files.storage import DefaultStorage |
| 330 |
|
| 331 |
return DefaultStorage |
| 332 |
|
| 333 |
from django.core.files.storage import get_storage_class |
| 334 |
|
| 335 |
return get_storage_class() |