| 1 |
""" |
| 2 |
Abstract Command. |
| 3 |
""" |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import logging |
| 8 |
import sys |
| 9 |
from shutil import copyfileobj |
| 10 |
from typing import TYPE_CHECKING |
| 11 |
|
| 12 |
from django.core.management.base import BaseCommand, CommandError |
| 13 |
|
| 14 |
from dbbackup.storage import StorageError |
| 15 |
|
| 16 |
if TYPE_CHECKING: |
| 17 |
from dbbackup.storage import Storage |
| 18 |
|
| 19 |
USELESS_ARGS = ("callback", "callback_args", "callback_kwargs", "metavar") |
| 20 |
TYPES = { |
| 21 |
"string": str, |
| 22 |
"int": int, |
| 23 |
"long": int, |
| 24 |
"float": float, |
| 25 |
"complex": complex, |
| 26 |
"choice": list, |
| 27 |
} |
| 28 |
LOGGING_VERBOSITY = { |
| 29 |
0: logging.WARNING, |
| 30 |
1: logging.INFO, |
| 31 |
2: logging.DEBUG, |
| 32 |
3: logging.DEBUG, |
| 33 |
} |
| 34 |
|
| 35 |
|
| 36 |
def make_option(*args, **kwargs): |
| 37 |
return args, kwargs |
| 38 |
|
| 39 |
|
| 40 |
class BaseDbBackupCommand(BaseCommand): |
| 41 |
""" |
| 42 |
Base command class used for create all dbbackup command. |
| 43 |
""" |
| 44 |
|
| 45 |
base_option_list = ( |
| 46 |
make_option( |
| 47 |
"--noinput", |
| 48 |
action="store_false", |
| 49 |
dest="interactive", |
| 50 |
default=True, |
| 51 |
help="Tells Django to NOT prompt the user for input of any kind.", |
| 52 |
), |
| 53 |
make_option( |
| 54 |
"-q", |
| 55 |
"--quiet", |
| 56 |
action="store_true", |
| 57 |
default=False, |
| 58 |
help="Tells Django to NOT output other text than errors.", |
| 59 |
), |
| 60 |
) |
| 61 |
option_list = () |
| 62 |
|
| 63 |
verbosity = 1 |
| 64 |
quiet = False |
| 65 |
logger = logging.getLogger("dbbackup.command") |
| 66 |
storage: Storage |
| 67 |
path: str | None = None |
| 68 |
filename: str | None = None |
| 69 |
decrypt = False |
| 70 |
uncompress = False |
| 71 |
encrypt = False |
| 72 |
compress = False |
| 73 |
content_type = "" |
| 74 |
|
| 75 |
def __init__(self, *args, **kwargs): |
| 76 |
self.option_list = self.base_option_list + self.option_list |
| 77 |
super().__init__(*args, **kwargs) |
| 78 |
|
| 79 |
def add_arguments(self, parser): |
| 80 |
for args, kwargs in self.option_list: |
| 81 |
kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_") and k not in USELESS_ARGS} |
| 82 |
parser.add_argument(*args, **kwargs) |
| 83 |
|
| 84 |
def _set_logger_level(self): |
| 85 |
level = 60 if self.quiet else LOGGING_VERBOSITY[int(self.verbosity)] |
| 86 |
self.logger.setLevel(level) |
| 87 |
|
| 88 |
# Find or create a StreamHandler for console output so that |
| 89 |
# --verbosity works regardless of the user's Django LOGGING |
| 90 |
# configuration. Only add one handler to avoid duplicates. |
| 91 |
for handler in self.logger.handlers: |
| 92 |
if isinstance(handler, logging.StreamHandler): |
| 93 |
handler.setLevel(level) |
| 94 |
break |
| 95 |
else: |
| 96 |
handler = logging.StreamHandler(sys.stderr) |
| 97 |
handler.setLevel(level) |
| 98 |
handler.setFormatter(logging.Formatter("%(levelname)s %(message)s")) |
| 99 |
self.logger.addHandler(handler) |
| 100 |
|
| 101 |
def _ask_confirmation(self): |
| 102 |
answer = input("Are you sure you want to continue? [Y/n] ") |
| 103 |
if answer.lower().startswith("n"): |
| 104 |
self.logger.info("Quitting") |
| 105 |
sys.exit(0) |
| 106 |
|
| 107 |
def read_from_storage(self, path): |
| 108 |
return self.storage.read_file(path) |
| 109 |
|
| 110 |
def write_to_storage(self, file, path): |
| 111 |
self.logger.info("Writing file to %s", path) |
| 112 |
self.storage.write_file(file, path) |
| 113 |
|
| 114 |
def read_local_file(self, path): |
| 115 |
"""Open file in read mode on local filesystem.""" |
| 116 |
return open(path, "rb") |
| 117 |
|
| 118 |
def write_local_file(self, outputfile, path): |
| 119 |
"""Write file to the desired path.""" |
| 120 |
self.logger.info("Writing file to %s", path) |
| 121 |
outputfile.seek(0) |
| 122 |
with open(path, "wb") as fd: |
| 123 |
copyfileobj(outputfile, fd) |
| 124 |
|
| 125 |
def _get_backup_file(self, database=None, servername=None): |
| 126 |
if self.path: |
| 127 |
input_filename = self.path |
| 128 |
input_file = self.read_local_file(self.path) |
| 129 |
else: |
| 130 |
if self.filename: |
| 131 |
input_filename = self.filename |
| 132 |
# Fetch the latest backup if filepath not specified |
| 133 |
else: |
| 134 |
self.logger.info("Finding latest backup") |
| 135 |
try: |
| 136 |
input_filename = self.storage.get_latest_backup( |
| 137 |
encrypted=self.decrypt, |
| 138 |
compressed=self.uncompress, |
| 139 |
content_type=self.content_type, |
| 140 |
database=database, |
| 141 |
servername=servername, |
| 142 |
) |
| 143 |
except StorageError as err: |
| 144 |
raise CommandError(err.args[0]) from err |
| 145 |
input_file = self.read_from_storage(input_filename) |
| 146 |
return input_filename, input_file |
| 147 |
|
| 148 |
def _cleanup_old_backups(self, database=None, servername=None): |
| 149 |
""" |
| 150 |
Cleanup old backups, keeping the number of backups specified by |
| 151 |
DBBACKUP_CLEANUP_KEEP. |
| 152 |
""" |
| 153 |
self.storage.clean_old_backups( |
| 154 |
encrypted=self.encrypt, |
| 155 |
compressed=self.compress, |
| 156 |
content_type=self.content_type, |
| 157 |
database=database, |
| 158 |
servername=servername, |
| 159 |
) |