| 1 |
""" |
| 2 |
Restore database. |
| 3 |
""" |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import io |
| 8 |
import json |
| 9 |
import os |
| 10 |
import sys |
| 11 |
from importlib import import_module |
| 12 |
|
| 13 |
from django.conf import settings |
| 14 |
from django.core.management.base import CommandError |
| 15 |
from django.db import connection |
| 16 |
|
| 17 |
from dbbackup import utils |
| 18 |
from dbbackup.db.base import get_connector |
| 19 |
from dbbackup.management.commands._base import BaseDbBackupCommand, make_option |
| 20 |
from dbbackup.signals import post_restore, pre_restore |
| 21 |
from dbbackup.storage import StorageError, get_storage |
| 22 |
|
| 23 |
|
| 24 |
class Command(BaseDbBackupCommand): |
| 25 |
help = "Restore a database backup from storage, encrypted and/or compressed." |
| 26 |
content_type = "db" |
| 27 |
no_drop = False |
| 28 |
pg_options = "" |
| 29 |
input_database_name = None |
| 30 |
database_name = None |
| 31 |
database = None |
| 32 |
|
| 33 |
option_list = ( |
| 34 |
*BaseDbBackupCommand.option_list, |
| 35 |
make_option("-d", "--database", help="Database to restore"), |
| 36 |
make_option("-i", "--input-filename", help="Specify filename to backup from"), |
| 37 |
make_option("-I", "--input-path", help="Specify path on local filesystem to backup from"), |
| 38 |
make_option( |
| 39 |
"-s", |
| 40 |
"--servername", |
| 41 |
help="If backup file is not specified, filter the existing ones with the given servername", |
| 42 |
), |
| 43 |
make_option("-c", "--decrypt", default=False, action="store_true", help="Decrypt data before restoring"), |
| 44 |
make_option("-p", "--passphrase", help="Passphrase for decrypt file", default=None), |
| 45 |
make_option( |
| 46 |
"-z", "--uncompress", action="store_true", default=False, help="Uncompress gzip data before restoring" |
| 47 |
), |
| 48 |
make_option( |
| 49 |
"-n", |
| 50 |
"--schema", |
| 51 |
action="append", |
| 52 |
default=[], |
| 53 |
help="Specify schema(s) to restore. Can be used multiple times.", |
| 54 |
), |
| 55 |
make_option( |
| 56 |
"-r", |
| 57 |
"--no-drop", |
| 58 |
action="store_true", |
| 59 |
default=False, |
| 60 |
help="Don't clean (drop) the database. This only works with mongodb and postgresql.", |
| 61 |
), |
| 62 |
make_option( |
| 63 |
"--pg-options", |
| 64 |
dest="pg_options", |
| 65 |
default="", |
| 66 |
help="Additional pg_restore options, e.g. '--if-exists --no-owner'. Use quotes.", |
| 67 |
), |
| 68 |
) |
| 69 |
|
| 70 |
def handle(self, *args, **options): |
| 71 |
"""Django command handler.""" |
| 72 |
self.verbosity = int(options.get("verbosity", "1")) |
| 73 |
self.quiet = options.get("quiet") |
| 74 |
self._set_logger_level() |
| 75 |
|
| 76 |
try: |
| 77 |
connection.close() |
| 78 |
self.filename = options.get("input_filename") |
| 79 |
self.path = options.get("input_path") |
| 80 |
self.servername = options.get("servername") |
| 81 |
self.decrypt = options.get("decrypt") |
| 82 |
self.uncompress = options.get("uncompress") |
| 83 |
self.passphrase = options.get("passphrase") |
| 84 |
self.interactive = options.get("interactive") |
| 85 |
self.input_database_name = options.get("database") |
| 86 |
self.database_name, self.database = self._get_database(self.input_database_name) |
| 87 |
self.storage = get_storage() |
| 88 |
self.no_drop = options.get("no_drop") |
| 89 |
self.pg_options = options.get("pg_options", "") |
| 90 |
self.schemas = options.get("schema") |
| 91 |
self._restore_backup() |
| 92 |
except StorageError as err: |
| 93 |
raise CommandError(err) from err |
| 94 |
|
| 95 |
def _get_database(self, database_name: str | None): |
| 96 |
"""Get the database to restore.""" |
| 97 |
if not database_name: |
| 98 |
if len(settings.DATABASES) > 1: |
| 99 |
errmsg = "Because this project contains more than one database, you must specify the --database option." |
| 100 |
raise CommandError(errmsg) |
| 101 |
database_name = next(iter(settings.DATABASES.keys())) |
| 102 |
if database_name not in settings.DATABASES: |
| 103 |
msg = f"Database {database_name} does not exist." |
| 104 |
raise CommandError(msg) |
| 105 |
return database_name, settings.DATABASES[database_name] |
| 106 |
|
| 107 |
def _check_metadata(self, filename): |
| 108 |
""" |
| 109 |
Check if the backup file has metadata and if it matches the current database. |
| 110 |
""" |
| 111 |
metadata_filename = f"{filename}.metadata" |
| 112 |
metadata = None |
| 113 |
|
| 114 |
if self.path: |
| 115 |
# Local file |
| 116 |
# self.path is the full path to the backup file |
| 117 |
metadata_path = f"{self.path}.metadata" |
| 118 |
if os.path.exists(metadata_path): |
| 119 |
with open(metadata_path) as fd: |
| 120 |
metadata = json.load(fd) |
| 121 |
else: |
| 122 |
# Storage file |
| 123 |
try: |
| 124 |
# Check if metadata file exists in storage |
| 125 |
# list_directory returns a list of filenames |
| 126 |
# We can't easily check existence without listing or trying to open |
| 127 |
# But read_file might fail if not exists depending on storage |
| 128 |
# Let's try to read it |
| 129 |
metadata_file = self.storage.read_file(metadata_filename) |
| 130 |
except Exception: |
| 131 |
self.logger.debug("No metadata file found for '%s'", filename) |
| 132 |
return None |
| 133 |
|
| 134 |
# Read and parse metadata |
| 135 |
try: |
| 136 |
metadata = json.load(metadata_file) |
| 137 |
except Exception: |
| 138 |
self.logger.warning( |
| 139 |
"Malformatted metadata file for '%s'! Dbbackup will ignore this metadata.", filename |
| 140 |
) |
| 141 |
return None |
| 142 |
|
| 143 |
if not metadata: |
| 144 |
return None |
| 145 |
|
| 146 |
backup_engine = metadata.get("engine") |
| 147 |
current_engine = settings.DATABASES[self.database_name]["ENGINE"] |
| 148 |
backup_connector = metadata.get("connector") |
| 149 |
|
| 150 |
if backup_engine != current_engine and backup_connector != "dbbackup.db.django.DjangoConnector": |
| 151 |
msg = ( |
| 152 |
f"Backup file '{filename}' was created with database engine '{backup_engine}', " |
| 153 |
f"but you are restoring to a database using '{current_engine}'. " |
| 154 |
"Restoring to a different database engine is not supported." |
| 155 |
) |
| 156 |
raise CommandError(msg) |
| 157 |
|
| 158 |
# Check if we custom metadata validation is configured |
| 159 |
user_metadata_valid = utils.validate_user_metadata(metadata) |
| 160 |
if not user_metadata_valid: |
| 161 |
msg = f"Custom metadata validation failed for backup file '{filename}'." |
| 162 |
raise CommandError(msg) |
| 163 |
|
| 164 |
return metadata |
| 165 |
|
| 166 |
def _restore_backup(self): |
| 167 |
"""Restore the specified database.""" |
| 168 |
input_filename, input_file = self._get_backup_file( |
| 169 |
database=self.input_database_name, servername=self.servername |
| 170 |
) |
| 171 |
|
| 172 |
self.logger.info( |
| 173 |
"Restoring backup for database '%s' and server '%s'", |
| 174 |
self.database_name, |
| 175 |
self.servername, |
| 176 |
) |
| 177 |
|
| 178 |
if self.schemas: |
| 179 |
self.logger.info(f"Restoring schemas: {self.schemas}") # noqa: G004 |
| 180 |
|
| 181 |
self.logger.info(f"Restoring: {input_filename}") # noqa: G004 |
| 182 |
|
| 183 |
metadata = self._check_metadata(input_filename) |
| 184 |
|
| 185 |
# Send pre_restore signal |
| 186 |
pre_restore.send( |
| 187 |
sender=self.__class__, |
| 188 |
database=self.database, |
| 189 |
database_name=self.database_name, |
| 190 |
filename=input_filename, |
| 191 |
servername=self.servername, |
| 192 |
storage=self.storage, |
| 193 |
) |
| 194 |
|
| 195 |
if self.decrypt: |
| 196 |
unencrypted_file, input_filename = utils.unencrypt_file(input_file, input_filename, self.passphrase) |
| 197 |
input_file.close() |
| 198 |
input_file = unencrypted_file |
| 199 |
if self.uncompress: |
| 200 |
uncompressed_file, input_filename = utils.uncompress_file(input_file, input_filename) |
| 201 |
input_file.close() |
| 202 |
input_file = uncompressed_file |
| 203 |
|
| 204 |
# Convert remote storage files to SpooledTemporaryFile for compatibility with subprocess |
| 205 |
# This fixes the issue with FTP and other remote storage backends that don't support fileno() |
| 206 |
if not self.path: # Only for remote storage files, not local files |
| 207 |
try: |
| 208 |
# Test if the file supports fileno() - required by subprocess.Popen |
| 209 |
input_file.fileno() |
| 210 |
except (AttributeError, io.UnsupportedOperation): |
| 211 |
# File doesn't support fileno(), convert to SpooledTemporaryFile |
| 212 |
self.logger.debug( |
| 213 |
"Converting remote storage file to temporary file due to missing fileno() support required by subprocess" |
| 214 |
) |
| 215 |
temp_file = utils.create_spooled_temporary_file(fileobj=input_file) |
| 216 |
input_file.close() |
| 217 |
input_file = temp_file |
| 218 |
|
| 219 |
self.logger.info("Restore tempfile created: %s", utils.handle_size(input_file)) |
| 220 |
if self.interactive: |
| 221 |
self._ask_confirmation() |
| 222 |
|
| 223 |
input_file.seek(0) |
| 224 |
|
| 225 |
# Try to use connector from metadata if available |
| 226 |
self.connector = None |
| 227 |
if metadata and "connector" in metadata: |
| 228 |
connector_path = metadata["connector"] |
| 229 |
try: |
| 230 |
module_name = ".".join(connector_path.split(".")[:-1]) |
| 231 |
class_name = connector_path.split(".")[-1] |
| 232 |
module = import_module(module_name) |
| 233 |
connector_class = getattr(module, class_name) |
| 234 |
self.connector = connector_class(self.database_name) |
| 235 |
self.logger.info("Using connector from metadata: '%s'", connector_path) |
| 236 |
except (ImportError, AttributeError): |
| 237 |
self.logger.warning( |
| 238 |
"Connector '%s' from metadata not found!!! Falling back to the connector in your Django settings.", |
| 239 |
connector_path, |
| 240 |
) |
| 241 |
if self.interactive: |
| 242 |
answer = input("Do you want to continue with the connector defined in your Django settings? [Y/n] ") |
| 243 |
if not answer.lower().startswith("y"): |
| 244 |
self.logger.info("Quitting") |
| 245 |
sys.exit(0) |
| 246 |
|
| 247 |
# Fallback to a connector from Django settings and/or our default connector map. |
| 248 |
if not self.connector: |
| 249 |
self.connector = get_connector(self.database_name) |
| 250 |
|
| 251 |
if self.schemas: |
| 252 |
self.connector.schemas = self.schemas |
| 253 |
self.connector.drop = not self.no_drop |
| 254 |
self.connector.pg_options = self.pg_options |
| 255 |
self.connector.restore_dump(input_file) |
| 256 |
|
| 257 |
# Send post_restore signal |
| 258 |
post_restore.send( |
| 259 |
sender=self.__class__, |
| 260 |
database=self.database, |
| 261 |
database_name=self.database_name, |
| 262 |
filename=input_filename, |
| 263 |
servername=self.servername, |
| 264 |
connector=self.connector, |
| 265 |
storage=self.storage, |
| 266 |
) |