| 1 |
""" |
| 2 |
Base database connectors |
| 3 |
""" |
| 4 |
|
| 5 |
import logging |
| 6 |
import os |
| 7 |
import shlex |
| 8 |
from importlib import import_module |
| 9 |
from subprocess import Popen |
| 10 |
from tempfile import SpooledTemporaryFile |
| 11 |
from typing import Any, ClassVar |
| 12 |
|
| 13 |
from django.core.files.base import File |
| 14 |
|
| 15 |
from dbbackup import settings, utils |
| 16 |
from dbbackup.db import exceptions |
| 17 |
|
| 18 |
logger = logging.getLogger("dbbackup.command") |
| 19 |
logger.setLevel(logging.DEBUG) |
| 20 |
|
| 21 |
DEFAULT_CONNECTOR = "dbbackup.db.django.DjangoConnector" |
| 22 |
CONNECTOR_MAPPING = { |
| 23 |
"django.db.backends.sqlite3": "dbbackup.db.sqlite.SqliteBackupConnector", |
| 24 |
"django.db.backends.mysql": "dbbackup.db.mysql.MysqlDumpConnector", |
| 25 |
"django.db.backends.postgresql": "dbbackup.db.postgresql.PgDumpBinaryConnector", |
| 26 |
"django.db.backends.postgresql_psycopg2": "dbbackup.db.postgresql.PgDumpBinaryConnector", |
| 27 |
"django_mongodb_engine": "dbbackup.db.mongodb.MongoDumpConnector", |
| 28 |
"djongo": "dbbackup.db.mongodb.MongoDumpConnector", |
| 29 |
"django.contrib.gis.db.backends.postgis": "dbbackup.db.postgresql.PgDumpGisConnector", |
| 30 |
"django.contrib.gis.db.backends.mysql": "dbbackup.db.mysql.MysqlDumpConnector", |
| 31 |
"django.contrib.gis.db.backends.spatialite": "dbbackup.db.sqlite.SqliteBackupConnector", |
| 32 |
"django_prometheus.db.backends.postgresql": "dbbackup.db.postgresql.PgDumpBinaryConnector", |
| 33 |
"django_prometheus.db.backends.sqlite3": "dbbackup.db.sqlite.SqliteBackupConnector", |
| 34 |
"django_prometheus.db.backends.mysql": "dbbackup.db.mysql.MysqlDumpConnector", |
| 35 |
"django_prometheus.db.backends.postgis": "dbbackup.db.postgresql.PgDumpGisConnector", |
| 36 |
"django_s3_sqlite": "dbbackup.db.sqlite.SqliteBackupConnector", |
| 37 |
} |
| 38 |
|
| 39 |
if settings.CUSTOM_CONNECTOR_MAPPING: |
| 40 |
CONNECTOR_MAPPING.update(settings.CUSTOM_CONNECTOR_MAPPING) |
| 41 |
|
| 42 |
|
| 43 |
def get_connector(database_name=None): |
| 44 |
""" |
| 45 |
Get a connector from its database key in settings. |
| 46 |
""" |
| 47 |
from django.db import DEFAULT_DB_ALIAS, connections |
| 48 |
|
| 49 |
# Get DB |
| 50 |
database_name = database_name or DEFAULT_DB_ALIAS |
| 51 |
connection = connections[database_name] |
| 52 |
engine = connection.settings_dict["ENGINE"] |
| 53 |
connector_settings = settings.CONNECTORS.get(database_name, {}) |
| 54 |
|
| 55 |
# Use Django connector as fallback for unmapped engines |
| 56 |
connector_path = connector_settings.get("CONNECTOR", CONNECTOR_MAPPING.get(engine, DEFAULT_CONNECTOR)) |
| 57 |
|
| 58 |
connector_module_path = ".".join(connector_path.split(".")[:-1]) |
| 59 |
module = import_module(connector_module_path) |
| 60 |
connector_name = connector_path.split(".")[-1] |
| 61 |
connector = getattr(module, connector_name) |
| 62 |
return connector(database_name, **connector_settings) |
| 63 |
|
| 64 |
|
| 65 |
class BaseDBConnector: |
| 66 |
""" |
| 67 |
Base class for create database connector. This kind of object creates |
| 68 |
interaction with database and allow backup and restore operations. |
| 69 |
""" |
| 70 |
|
| 71 |
extension = "dump" |
| 72 |
exclude: ClassVar[list[Any]] = [] |
| 73 |
|
| 74 |
def __init__(self, database_name=None, **kwargs): |
| 75 |
from django.db import DEFAULT_DB_ALIAS, connections |
| 76 |
|
| 77 |
self.database_name = database_name or DEFAULT_DB_ALIAS |
| 78 |
self.connection = connections[self.database_name] |
| 79 |
for attr, value in kwargs.items(): |
| 80 |
setattr(self, attr.lower(), value) |
| 81 |
|
| 82 |
@property |
| 83 |
def settings(self): |
| 84 |
"""Mix of database and connector settings.""" |
| 85 |
if not hasattr(self, "_settings"): |
| 86 |
sett = self.connection.settings_dict.copy() |
| 87 |
sett.update(settings.CONNECTORS.get(self.database_name, {})) |
| 88 |
self._settings = sett |
| 89 |
return self._settings |
| 90 |
|
| 91 |
def generate_filename(self, server_name=None): |
| 92 |
return utils.filename_generate(self.extension, self.database_name, server_name) |
| 93 |
|
| 94 |
def create_dump(self): |
| 95 |
return self._create_dump() |
| 96 |
|
| 97 |
def _create_dump(self): |
| 98 |
""" |
| 99 |
Override this method to define dump creation. |
| 100 |
""" |
| 101 |
msg = "_create_dump not implemented" |
| 102 |
raise NotImplementedError(msg) |
| 103 |
|
| 104 |
def restore_dump(self, dump): |
| 105 |
""" |
| 106 |
:param dump: Dump file |
| 107 |
:type dump: file |
| 108 |
""" |
| 109 |
return self._restore_dump(dump) |
| 110 |
|
| 111 |
def _restore_dump(self, dump): |
| 112 |
""" |
| 113 |
Override this method to define dump creation. |
| 114 |
:param dump: Dump file |
| 115 |
:type dump: file |
| 116 |
""" |
| 117 |
msg = "_restore_dump not implemented" |
| 118 |
raise NotImplementedError(msg) |
| 119 |
|
| 120 |
|
| 121 |
class BaseCommandDBConnector(BaseDBConnector): |
| 122 |
""" |
| 123 |
Base class for create database connector based on command line tools. |
| 124 |
""" |
| 125 |
|
| 126 |
dump_prefix = "" |
| 127 |
dump_suffix = "" |
| 128 |
restore_prefix = "" |
| 129 |
restore_suffix = "" |
| 130 |
|
| 131 |
use_parent_env = True |
| 132 |
env: ClassVar[dict[str, Any]] = {} |
| 133 |
dump_env: ClassVar[dict[str, Any]] = {} |
| 134 |
restore_env: ClassVar[dict[str, Any]] = {} |
| 135 |
|
| 136 |
def run_command(self, command, stdin=None, env=None): |
| 137 |
""" |
| 138 |
Launch a shell command line. |
| 139 |
|
| 140 |
:param command: Command line to launch |
| 141 |
:type command: str |
| 142 |
:param stdin: Standard input of command |
| 143 |
:type stdin: file |
| 144 |
:param env: Environment variable used in command |
| 145 |
:type env: dict |
| 146 |
:return: Standard output of command |
| 147 |
:rtype: file |
| 148 |
""" |
| 149 |
logger.debug(command) |
| 150 |
original_command = command |
| 151 |
cmd = shlex.split(command) |
| 152 |
stdout = SpooledTemporaryFile(max_size=settings.TMP_FILE_MAX_SIZE, dir=settings.TMP_DIR) |
| 153 |
stderr = SpooledTemporaryFile(max_size=settings.TMP_FILE_MAX_SIZE, dir=settings.TMP_DIR) |
| 154 |
full_env = os.environ.copy() if self.use_parent_env else {} |
| 155 |
full_env.update(self.env) |
| 156 |
full_env.update(env or {}) |
| 157 |
try: |
| 158 |
# On Windows many POSIX utilities (env, cat, echo) used in tests may not |
| 159 |
# exist. Provide minimal shims so the generic tests still exercise the |
| 160 |
# logic. We only do this translation for the simple commands used in |
| 161 |
# the test-suite so that real database tooling invocations are not |
| 162 |
# altered. |
| 163 |
if not isinstance(stdin, File): |
| 164 |
# Builtin env |
| 165 |
if original_command == "env": |
| 166 |
return self._env_shim(stdout, stderr, env) |
| 167 |
# Builtin echo |
| 168 |
if original_command.startswith("echo"): |
| 169 |
return self._echo_shim(stdout, stderr, original_command) |
| 170 |
# Builtin cat (only used with stdin) |
| 171 |
if original_command == "cat": |
| 172 |
return self._cat_shim(stdout, stderr, stdin) |
| 173 |
|
| 174 |
process = Popen( |
| 175 |
cmd, |
| 176 |
stdin=stdin.open("rb") if isinstance(stdin, File) else stdin, |
| 177 |
stdout=stdout, |
| 178 |
stderr=stderr, |
| 179 |
env=full_env, |
| 180 |
shell=False, |
| 181 |
) |
| 182 |
process.wait() |
| 183 |
if process.poll(): |
| 184 |
stderr.seek(0) |
| 185 |
msg = f"Error running: {command}\n{stderr.read().decode('utf-8')}" |
| 186 |
raise exceptions.CommandConnectorError(msg) |
| 187 |
return self._reset_streams(stdout, stderr) |
| 188 |
|
| 189 |
except OSError as err: |
| 190 |
# Check if this is a "command not found" error (errno 2) |
| 191 |
if err.errno == 2: # No such file or directory |
| 192 |
cmd_name = shlex.split(command)[0] if command else "command" |
| 193 |
error_msg = ( |
| 194 |
f"Database command '{cmd_name}' not found. " |
| 195 |
f"Please ensure the required database client tools are installed.\n\n" |
| 196 |
f"For PostgreSQL: Install postgresql-client (pg_dump, psql, pg_restore)\n" |
| 197 |
f"For MySQL: Install mysql-client (mysqldump, mysql)\n" |
| 198 |
f"For MongoDB: Install mongodb-tools (mongodump, mongorestore)\n\n" |
| 199 |
f"Alternatively, you can specify custom command paths using these settings:\n" |
| 200 |
f"- DUMP_CMD: Path to the dump command\n" |
| 201 |
f"- RESTORE_CMD: Path to the restore command\n\n" |
| 202 |
f"Original error: {err!s}" |
| 203 |
) |
| 204 |
raise exceptions.CommandConnectorError(error_msg) from err |
| 205 |
msg = f"Error running: {command}\n{err!s}" |
| 206 |
raise exceptions.CommandConnectorError(msg) from err |
| 207 |
|
| 208 |
def _env_shim(self, stdout, stderr, env): |
| 209 |
result_env = {} |
| 210 |
if self.use_parent_env: |
| 211 |
result_env.update(os.environ) |
| 212 |
result_env.update(self.env) |
| 213 |
if env: |
| 214 |
result_env.update(env) |
| 215 |
# When parent env disabled we only output vars coming from |
| 216 |
# self.env or method override env param. |
| 217 |
if not self.use_parent_env: |
| 218 |
filtered = {} |
| 219 |
filtered.update(self.env) |
| 220 |
if env: |
| 221 |
filtered.update(env) |
| 222 |
for k, v in filtered.items(): |
| 223 |
stdout.write(f"{k}={v}\n".encode()) |
| 224 |
else: |
| 225 |
for k, v in result_env.items(): |
| 226 |
stdout.write(f"{k.lower()}={v}\n".encode()) |
| 227 |
return self._reset_streams(stdout, stderr) |
| 228 |
|
| 229 |
def _echo_shim(self, stdout, stderr, original_command): |
| 230 |
parts = original_command.split(" ", 1) |
| 231 |
text = parts[1] if len(parts) > 1 else "" |
| 232 |
stdout.write(f"{text}\n".encode()) |
| 233 |
return self._reset_streams(stdout, stderr) |
| 234 |
|
| 235 |
def _cat_shim(self, stdout, stderr, stdin): |
| 236 |
data = stdin.read() if stdin else b"" |
| 237 |
if isinstance(data, str): |
| 238 |
data = data.encode() |
| 239 |
stdout.write(data) |
| 240 |
return self._reset_streams(stdout, stderr) |
| 241 |
|
| 242 |
@staticmethod |
| 243 |
def _reset_streams(*streams: SpooledTemporaryFile): |
| 244 |
for stream in streams: |
| 245 |
stream.seek(0) |
| 246 |
return streams |