Debian Codegraph @

dbbackup/utils.py

raw
1 """
2 Utility functions for dbbackup.
3 """
4
5 from __future__ import annotations
6
7 import copy
8 import gzip
9 import json
10 import logging
11 import os
12 import re
13 import sys
14 import tempfile
15 import traceback
16 from datetime import datetime
17 from functools import wraps
18 from getpass import getpass
19 from importlib import import_module
20 from shutil import copyfileobj
21
22 from django.core.mail import EmailMultiAlternatives
23 from django.db import connection
24 from django.http import HttpRequest
25 from django.utils import timezone
26
27 from dbbackup import settings
28
29 FAKE_HTTP_REQUEST = HttpRequest()
30 FAKE_HTTP_REQUEST.META["SERVER_NAME"] = ""
31 FAKE_HTTP_REQUEST.META["SERVER_PORT"] = ""
32 FAKE_HTTP_REQUEST.META["HTTP_HOST"] = settings.HOSTNAME
33 FAKE_HTTP_REQUEST.path = "/DJANGO-DBBACKUP-EXCEPTION"
34
35 BYTES = (
36 ("PiB", 1125899906842624.0),
37 ("TiB", 1099511627776.0),
38 ("GiB", 1073741824.0),
39 ("MiB", 1048576.0),
40 ("KiB", 1024.0),
41 ("B", 1.0),
42 )
43
44 REG_FILENAME_CLEAN = re.compile(r"-+")
45
46
47 class EncryptionError(Exception):
48 pass
49
50
51 class DecryptionError(Exception):
52 pass
53
54
55 def bytes_to_str(byte_val, decimals=1):
56 """
57 Convert bytes to a human readable string.
58
59 :param byteVal: Value to convert in bytes
60 :type byteVal: int or float
61
62 :param decimal: Number of decimal to display
63 :type decimal: int
64
65 :returns: Number of byte with the best unit of measure
66 :rtype: str
67 """
68 for unit, byte in BYTES:
69 if byte_val >= byte:
70 if decimals == 0:
71 return f"{int(round(byte_val / byte, 0))} {unit}"
72 return f"{round(byte_val / byte, decimals)} {unit}"
73 return f"{byte_val} B"
74
75
76 def handle_size(filehandle):
77 """
78 Get file's size to a human readable string.
79
80 :param filehandle: File to handle
81 :type filehandle: file
82
83 :returns: File's size with the best unit of measure
84 :rtype: str
85 """
86 if hasattr(filehandle, "size"):
87 return bytes_to_str(filehandle.size)
88
89 filehandle.seek(0, 2)
90 return bytes_to_str(filehandle.tell())
91
92
93 def mail_admins(subject, message, fail_silently=False, connection=None, html_message=None):
94 """Sends a message to the admins, as defined by the DBBACKUP_ADMINS setting."""
95 if not settings.ADMINS:
96 return
97 mail = EmailMultiAlternatives(
98 f"{settings.EMAIL_SUBJECT_PREFIX}{subject}",
99 message,
100 settings.SERVER_EMAIL,
101 [a[1] for a in settings.ADMINS],
102 connection=connection,
103 )
104
105 if html_message:
106 mail.attach_alternative(html_message, "text/html")
107 mail.send(fail_silently=fail_silently)
108
109
110 def email_uncaught_exception(func):
111 """
112 Function decorator for send email with uncaught exceptions to admins.
113 Email is sent to ``settings.DBBACKUP_FAILURE_RECIPIENTS``
114 (``settings.ADMINS`` if not defined). The message contains a traceback
115 of error.
116 """
117
118 @wraps(func)
119 def wrapper(*args, **kwargs):
120 try:
121 func(*args, **kwargs)
122 except Exception:
123 logger = logging.getLogger("dbbackup")
124 exc_type, exc_value, tb = sys.exc_info()
125 tb_str = "".join(traceback.format_tb(tb))
126 msg = f"{getattr(exc_type, '__name__', str(exc_type) or 'Exception')}: {exc_value}\n{tb_str}"
127 logger.exception(msg)
128 raise
129 finally:
130 connection.close()
131
132 return wrapper
133
134
135 def create_spooled_temporary_file(filepath=None, fileobj=None):
136 """
137 Create a spooled temporary file. if ``filepath`` or ``fileobj`` is
138 defined its content will be copied into temporary file.
139
140 :param filepath: Path of input file
141 :type filepath: str
142
143 :param fileobj: Input file object
144 :type fileobj: file
145
146 :returns: Spooled temporary file
147 :rtype: :class:`tempfile.SpooledTemporaryFile`
148 """
149 spooled_file = tempfile.SpooledTemporaryFile(max_size=settings.TMP_FILE_MAX_SIZE, dir=settings.TMP_DIR)
150 if filepath:
151 fileobj = open(filepath, "r+b")
152 if fileobj is not None:
153 fileobj.seek(0)
154 copyfileobj(fileobj, spooled_file, settings.TMP_FILE_READ_SIZE)
155 return spooled_file
156
157
158 def _gpg_encrypt_file(inputfile, filepath, recipients, always_trust):
159 import gnupg
160
161 g = gnupg.GPG()
162 return g.encrypt_file(
163 inputfile,
164 output=filepath,
165 recipients=recipients,
166 always_trust=always_trust,
167 )
168
169
170 def encrypt_file(inputfile, filename): # sourcery skip: extract-method
171 """
172 Encrypt input file using GPG and remove .gpg extension to its name.
173
174 :param inputfile: File to encrypt
175 :type inputfile: ``file`` like object
176
177 :param filename: File's name
178 :type filename: ``str``
179
180 :returns: Tuple with file and new file's name
181 :rtype: :class:`tempfile.SpooledTemporaryFile`, ``str``
182 """
183 tempdir = tempfile.mkdtemp(dir=settings.TMP_DIR)
184 try:
185 filename = f"{filename}.gpg"
186 filepath = os.path.join(tempdir, filename)
187 if "b" not in inputfile.mode:
188 msg = "Input file must be opened in binary mode."
189 raise ValueError(msg)
190 try:
191 inputfile.seek(0)
192 always_trust = bool(settings.GPG_ALWAYS_TRUST)
193 result = _gpg_encrypt_file(inputfile, filepath, settings.GPG_RECIPIENT, always_trust)
194 inputfile.close()
195 if not result:
196 msg = f"Encryption failed; status: {result.status}"
197 raise EncryptionError(msg)
198 return create_spooled_temporary_file(filepath), filename
199 finally:
200 if os.path.exists(filepath):
201 os.remove(filepath)
202 finally:
203 os.rmdir(tempdir)
204
205
206 def unencrypt_file(inputfile, filename, passphrase=None):
207 """
208 Unencrypt input file using GPG and remove .gpg extension to its name.
209
210 :param inputfile: File to encrypt
211 :type inputfile: ``file`` like object
212
213 :param filename: File's name
214 :type filename: ``str``
215
216 :param passphrase: Passphrase of GPG key, if equivalent to False, it will
217 be asked to user. If user answer an empty pass, no
218 passphrase will be used.
219 :type passphrase: ``str`` or ``None``
220
221 :returns: Tuple with file and new file's name
222 :rtype: :class:`tempfile.SpooledTemporaryFile`, ``str``
223 """
224 import gnupg
225
226 def get_passphrase(passphrase=passphrase):
227 return passphrase or getpass("Input Passphrase: ") or None
228
229 temp_dir = tempfile.mkdtemp(dir=settings.TMP_DIR)
230 try:
231 new_basename = os.path.basename(filename).replace(".gpg", "")
232 temp_filename = os.path.join(temp_dir, new_basename)
233 try:
234 inputfile.seek(0)
235 g = gnupg.GPG()
236 result = g.decrypt_file(
237 fileobj_or_path=inputfile,
238 passphrase=get_passphrase(),
239 output=temp_filename,
240 )
241 if not result:
242 msg = f"Decryption failed; status: {result.status}"
243 raise DecryptionError(msg)
244 outputfile = create_spooled_temporary_file(temp_filename)
245 finally:
246 if os.path.exists(temp_filename):
247 os.remove(temp_filename)
248 finally:
249 os.rmdir(temp_dir)
250 return outputfile, new_basename
251
252
253 def compress_file(inputfile, filename):
254 """
255 Compress input file using gzip and change its name.
256
257 :param inputfile: File to compress
258 :type inputfile: ``file`` like object
259
260 :param filename: File's name
261 :type filename: ``str``
262
263 :returns: Tuple with compressed file and new file's name
264 :rtype: :class:`tempfile.SpooledTemporaryFile`, ``str``
265 """
266 outputfile = create_spooled_temporary_file()
267 new_filename = f"{filename}.gz"
268 zipfile = gzip.GzipFile(filename=filename, fileobj=outputfile, mode="wb")
269 try:
270 inputfile.seek(0)
271 copyfileobj(inputfile, zipfile, settings.TMP_FILE_READ_SIZE)
272 finally:
273 zipfile.close()
274 return outputfile, new_filename
275
276
277 def uncompress_file(inputfile, filename):
278 """
279 Uncompress this file using gzip and change its name.
280
281 :param inputfile: File to compress
282 :type inputfile: ``file`` like object
283
284 :param filename: File's name
285 :type filename: ``str``
286
287 :returns: Tuple with file and new file's name
288 :rtype: :class:`tempfile.SpooledTemporaryFile`, ``str``
289 """
290 zipfile = gzip.GzipFile(fileobj=inputfile, mode="rb")
291 try:
292 inputfile.seek(0)
293 outputfile = create_spooled_temporary_file(fileobj=zipfile)
294 finally:
295 zipfile.close()
296 new_basename = os.path.basename(filename).replace(".gz", "")
297 return outputfile, new_basename
298
299
300 def timestamp(value):
301 """
302 Return the timestamp of a datetime.datetime object.
303
304 :param value: a datetime object
305 :type value: datetime.datetime
306
307 :return: the timestamp
308 :rtype: str
309 """
310 value = value if timezone.is_naive(value) else timezone.localtime(value)
311 return value.strftime(settings.DATE_FORMAT)
312
313
314 def filename_details(filepath):
315 # TODO: What was this function made for ?
316 return ""
317
318
319 PATTERN_MATCHNG = (
320 ("%a", r"[A-Z][a-z]+"),
321 ("%A", r"[A-Z][a-z]+"),
322 ("%w", r"\d"),
323 ("%d", r"\d{2}"),
324 ("%b", r"[A-Z][a-z]+"),
325 ("%B", r"[A-Z][a-z]+"),
326 ("%m", r"\d{2}"),
327 ("%y", r"\d{2}"),
328 ("%Y", r"\d{4}"),
329 ("%H", r"\d{2}"),
330 ("%I", r"\d{2}"),
331 # ('%p', r'(?AM|PM|am|pm)'),
332 ("%M", r"\d{2}"),
333 ("%S", r"\d{2}"),
334 ("%f", r"\d{6}"),
335 # ('%z', r'\+\d{4}'),
336 # ('%Z', r'(?|UTC|EST|CST)'),
337 ("%j", r"\d{3}"),
338 ("%U", r"\d{2}"),
339 ("%W", r"\d{2}"),
340 # ('%c', r'[A-Z][a-z]+ [A-Z][a-z]{2} \d{2} \d{2}:\d{2}:\d{2} \d{4}'),
341 # ('%x', r'd{2}/d{2}/d{4}'),
342 # ('%X', r'd{2}:d{2}:d{2}'),
343 # ('%%', r'%'),
344 )
345
346
347 def datefmt_to_regex(datefmt):
348 """
349 Convert a strftime format string to a regex.
350
351 :param datefmt: strftime format string
352 :type datefmt: ``str``
353
354 :returns: Equivalent regex
355 :rtype: ``re.compite``
356 """
357 new_string = datefmt
358 for pat, reg in PATTERN_MATCHNG:
359 new_string = new_string.replace(pat, reg)
360 return re.compile(f"({new_string})")
361
362
363 def filename_to_datestring(filename, datefmt=None):
364 """
365 Return the date part of a file name.
366
367 :param datefmt: strftime format string, ``settings.DATE_FORMAT`` is used
368 if is ``None``
369 :type datefmt: ``str`` or ``None``
370
371 :returns: Date part or nothing if not found
372 :rtype: ``str`` or ``NoneType``
373 """
374 datefmt = datefmt or settings.DATE_FORMAT
375 regex = datefmt_to_regex(datefmt)
376 search = regex.search(filename)
377 return search.groups()[0] if search else None
378
379
380 def filename_to_date(filename, datefmt=None):
381 """
382 Return a datetime from a file name.
383
384 :param datefmt: strftime format string, ``settings.DATE_FORMAT`` is used
385 if is ``None``
386 :type datefmt: ``str`` or ``NoneType``
387
388 :returns: Date guessed or nothing if no date found
389 :rtype: ``datetime.datetime`` or ``NoneType``
390 """
391 datefmt = datefmt or settings.DATE_FORMAT
392 datestring = filename_to_datestring(filename, datefmt)
393 return None if datestring is None else datetime.strptime(datestring, datefmt)
394
395
396 def filename_generate(extension, database_name="", servername=None, content_type="db", wildcard=None):
397 """
398 Create a new backup filename.
399
400 :param extension: Extension of backup file
401 :type extension: ``str``
402
403 :param database_name: If it is database backup specify its name
404 :type database_name: ``str``
405
406 :param servername: Specify server name or by default ``settings.DBBACKUP_HOSTNAME``
407 :type servername: ``str``
408
409 :param content_type: Content type to backup, ``'media'`` or ``'db'``
410 :type content_type: ``str``
411
412 :param wildcard: Replace datetime with this wilecard regex
413 :type content_type: ``str``
414
415 :returns: Computed file name
416 :rtype: ``str`
417 """
418 if content_type == "db":
419 if "/" in database_name:
420 database_name = os.path.basename(database_name)
421 if "." in database_name:
422 database_name = database_name.split(".")[0]
423 template = settings.FILENAME_TEMPLATE
424 elif content_type == "media":
425 template = settings.MEDIA_FILENAME_TEMPLATE
426 else:
427 template = settings.FILENAME_TEMPLATE
428
429 params = {
430 "servername": servername or settings.HOSTNAME,
431 "datetime": wildcard or datetime.now().strftime(settings.DATE_FORMAT),
432 "databasename": database_name,
433 "extension": extension,
434 "content_type": content_type,
435 }
436 if callable(template):
437 filename = template(**params)
438 else:
439 filename = template.format(**params)
440 filename = REG_FILENAME_CLEAN.sub("-", filename)
441 filename = filename.removeprefix("-")
442 return filename
443
444
445 def _get_function_from_path(func_or_path):
446 """
447 Load a callable from a dotted path or return the callable itself.
448
449 :param func_or_path: Dotted path to callable or callable itself
450 :type func_or_path: str | callable
451
452 :returns: Callable object
453 :rtype: callable
454 """
455 if callable(func_or_path):
456 return func_or_path
457
458 path = func_or_path
459 module_path, func_name = path.rsplit(".", 1)
460 try:
461 module = import_module(module_path)
462 except ImportError as e:
463 msg = f"Could not import module '{module_path}': {e}"
464 raise ImportError(msg) from e
465 func = getattr(module, func_name)
466 if not callable(func):
467 msg = f"The object at '{path}' is not callable."
468 raise TypeError(msg)
469 return func
470
471
472 def get_user_metadata(metadata: dict | None = None) -> dict:
473 """
474 Get user generated metadata from the user's custom metadata setter.
475
476 :returns: Custom metadata dictionary
477 :rtype: dict
478 """
479 user_metadata = {}
480 setter_setting = settings.BACKUP_METADATA_SETTER
481 if setter_setting:
482 setter_function = _get_function_from_path(setter_setting)
483 try:
484 # We pass a copy to avoid side effects
485 user_metadata = setter_function(copy.deepcopy(metadata))
486 except Exception:
487 logger = logging.getLogger("dbbackup")
488 logger.exception("Error loading custom metadata: %s")
489
490 if user_metadata is None:
491 user_metadata = {}
492
493 if not isinstance(user_metadata, dict):
494 msg = "DBBACKUP_BACKUP_METADATA_SETTER must return a dictionary."
495 raise ValueError(msg)
496
497 # Validate that we can serialize the provided data
498 try:
499 json.dumps(user_metadata)
500 except Exception as e:
501 msg = f"Custom metadata is not JSON serializable: {e}"
502 raise ValueError(msg) from e
503 return user_metadata
504
505
506 def validate_user_metadata(metadata) -> bool | None:
507 """
508 Validate custom metadata using a callable defined in `settings.py`.
509 Raise a CommandError to provide custom feedback if validation fails.
510
511 :param metadata: Metadata dictionary to validate
512 :type metadata: dict
513
514 :returns: True if validation passes (or None), False otherwise
515 :rtype: Optional[bool]
516 """
517 validator_setting = settings.RESTORE_METADATA_VALIDATOR
518 if validator_setting:
519 validator_function = _get_function_from_path(validator_setting)
520 try:
521 # We pass a copy to avoid side effects
522 user_metadata = validator_function(copy.deepcopy(metadata))
523 except Exception as e:
524 msg = f"Error during custom metadata validation: {e}"
525 raise ValueError(msg) from e
526 if user_metadata is None:
527 return None
528 if not isinstance(user_metadata, bool):
529 msg = "DBBACKUP_RESTORE_METADATA_VALIDATOR must return a boolean or None."
530 raise TypeError(msg)
531 return user_metadata
532 return True