bdbackup 0.6.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
bdbackup/history.py ADDED
@@ -0,0 +1,180 @@
1
+ """Persistent backup run history. Connections are short-lived and process-safe."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import sqlite3
8
+ from collections.abc import Callable, Iterator
9
+ from contextlib import contextmanager
10
+ from dataclasses import dataclass
11
+ from datetime import UTC, datetime
12
+ from pathlib import Path
13
+
14
+ from bdbackup.backends import BackupError, BackupResult
15
+
16
+
17
+ class HistoryError(BackupError):
18
+ """History could not be read or written reliably."""
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class HistorySettings:
23
+ database: Path
24
+ restore_root: Path
25
+
26
+
27
+ def artifact_identity(path: Path) -> str:
28
+ """Detect removed/replaced artifacts, including archives with reused names."""
29
+ stat = path.stat()
30
+ values = [stat.st_dev, stat.st_ino]
31
+ if path.is_file():
32
+ values.extend([stat.st_size, stat.st_mtime_ns])
33
+ return json.dumps(values)
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class BackupRecord:
38
+ id: int
39
+ job_name: str
40
+ backup_type: str
41
+ started_at: str
42
+ completed_at: str | None
43
+ status: str
44
+ path: str | None
45
+ size_bytes: int | None
46
+ identity: str | None
47
+ restore_info: str
48
+ error: str | None
49
+ encrypted: bool = False
50
+
51
+ @property
52
+ def available(self) -> bool:
53
+ if self.status != "success" or not self.path:
54
+ return False
55
+ try:
56
+ return artifact_identity(Path(self.path)) == self.identity
57
+ except OSError:
58
+ return False
59
+
60
+
61
+ class History:
62
+ """Record attempts before work starts; mark success only after verification."""
63
+
64
+ def __init__(self, settings: HistorySettings):
65
+ self.settings = settings
66
+
67
+ @contextmanager
68
+ def _connect(self, *, create: bool = False) -> Iterator[sqlite3.Connection]:
69
+ path = self.settings.database
70
+ connection = None
71
+ try:
72
+ if create:
73
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
74
+ try:
75
+ fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
76
+ except FileExistsError:
77
+ pass
78
+ else:
79
+ os.close(fd)
80
+ elif not path.exists():
81
+ raise HistoryError(f"History database does not exist: {path}")
82
+ mode = "rw" if create else "ro"
83
+ connection = sqlite3.connect(f"{path.as_uri()}?mode={mode}", uri=True, timeout=30)
84
+ connection.row_factory = sqlite3.Row
85
+ with connection:
86
+ if create:
87
+ connection.execute("BEGIN IMMEDIATE")
88
+ schema = connection.execute("PRAGMA user_version").fetchone()[0]
89
+ if schema not in (0, 1, 2) or (not create and schema == 0):
90
+ raise HistoryError(f"Unsupported history schema version: {schema}")
91
+ if create and schema == 0:
92
+ connection.execute(
93
+ """CREATE TABLE backup_runs (
94
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
95
+ job_name TEXT NOT NULL,
96
+ backup_type TEXT NOT NULL,
97
+ started_at TEXT NOT NULL,
98
+ completed_at TEXT,
99
+ status TEXT NOT NULL CHECK(status IN ('running', 'success', 'failed')),
100
+ path TEXT,
101
+ size_bytes INTEGER,
102
+ identity TEXT,
103
+ restore_info TEXT NOT NULL,
104
+ error TEXT
105
+ )"""
106
+ )
107
+ connection.execute(
108
+ "CREATE INDEX backup_runs_job ON backup_runs(job_name, id DESC)"
109
+ )
110
+ connection.execute("PRAGMA user_version = 1")
111
+ if create and schema in (0, 1):
112
+ connection.execute(
113
+ "ALTER TABLE backup_runs ADD COLUMN encrypted INTEGER NOT NULL "
114
+ "DEFAULT 0 CHECK(encrypted IN (0, 1))"
115
+ )
116
+ connection.execute("PRAGMA user_version = 2")
117
+ yield connection
118
+ except (OSError, sqlite3.Error) as exc:
119
+ raise HistoryError(f"Cannot access history database {path}: {exc}") from exc
120
+ finally:
121
+ if connection is not None:
122
+ connection.close()
123
+
124
+ def run(
125
+ self,
126
+ job_name: str,
127
+ backup_type: str,
128
+ action: Callable[[], BackupResult],
129
+ restore_info: dict[str, str] | None = None,
130
+ *,
131
+ encrypted: bool = False,
132
+ ) -> BackupResult:
133
+ with self._connect(create=True) as db:
134
+ cursor = db.execute(
135
+ """INSERT INTO backup_runs
136
+ (job_name, backup_type, started_at, status, restore_info, encrypted)
137
+ VALUES (?, ?, ?, 'running', ?, ?)""",
138
+ (job_name, backup_type, datetime.now(UTC).isoformat(),
139
+ json.dumps(restore_info or {}), int(encrypted)),
140
+ )
141
+ run_id = cursor.lastrowid
142
+ try:
143
+ result = action()
144
+ if not result.success:
145
+ raise BackupError("Backend reported an unsuccessful backup")
146
+ path = result.path.resolve(strict=True)
147
+ identity = artifact_identity(path)
148
+ except BaseException as exc:
149
+ # Store the exception class only: external diagnostics may contain credentials.
150
+ with self._connect(create=True) as db:
151
+ db.execute(
152
+ "UPDATE backup_runs SET status='failed', completed_at=?, error=? WHERE id=?",
153
+ (datetime.now(UTC).isoformat(), type(exc).__name__, run_id),
154
+ )
155
+ raise
156
+ with self._connect(create=True) as db:
157
+ db.execute(
158
+ """UPDATE backup_runs SET status='success', completed_at=?, path=?,
159
+ size_bytes=?, identity=?, restore_info=? WHERE id=?""",
160
+ (datetime.now(UTC).isoformat(), str(path), result.size_bytes, identity,
161
+ json.dumps(restore_info or {}), run_id),
162
+ )
163
+ return result
164
+
165
+ def records(self, *, job: str | None = None, successful: bool = False) -> list[BackupRecord]:
166
+ with self._connect() as db:
167
+ rows = db.execute(
168
+ """SELECT * FROM backup_runs
169
+ WHERE (? IS NULL OR job_name=?) AND (?=0 OR status='success')
170
+ ORDER BY id DESC""",
171
+ (job, job, int(successful)),
172
+ ).fetchall()
173
+ return [BackupRecord(**dict(row)) for row in rows]
174
+
175
+ def get(self, run_id: int) -> BackupRecord:
176
+ with self._connect() as db:
177
+ row = db.execute("SELECT * FROM backup_runs WHERE id=?", (run_id,)).fetchone()
178
+ if row is None:
179
+ raise HistoryError(f"Backup ID {run_id} was not found")
180
+ return BackupRecord(**dict(row))
@@ -0,0 +1,26 @@
1
+ """MySQL/MariaDB backup engine family.
2
+
3
+ Importing this package imports every engine module inside it
4
+ (``mysqldump.py``, ``xtrabackup.py``, and any future variant dropped in
5
+ such as ``xtrabackup_80.py`` or ``mysql_shell.py``). Importing an engine
6
+ module runs its ``register_engine()`` call, populating the central registry
7
+ in :mod:`bdbackup.engines` — no wiring changes are ever needed to add an
8
+ engine here. MySQL-specific helpers live in :mod:`bdbackup.mysql.helpers`.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import importlib
14
+ import pkgutil
15
+
16
+ __all__ = ["MySQLBackup", "XtraBackup"]
17
+
18
+ # Import every engine module so its ENGINE registration runs (drives
19
+ # bdbackup.engines discovery too, which imports this package).
20
+ for _info in pkgutil.iter_modules(__path__):
21
+ if _info.name.startswith("_"):
22
+ continue
23
+ importlib.import_module(f"{__name__}.{_info.name}")
24
+
25
+ from bdbackup.mysql.mysqldump import MySQLBackup # noqa: E402
26
+ from bdbackup.mysql.xtrabackup import XtraBackup # noqa: E402
@@ -0,0 +1,50 @@
1
+ """MySQL/MariaDB-specific helpers shared by the mysql family's engines."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import stat
7
+ import tempfile
8
+ from contextlib import contextmanager
9
+ from pathlib import Path
10
+
11
+
12
+ def _quote_option(value: str) -> str:
13
+ """Serialize a MySQL option value without comments or escape interpretation."""
14
+ if any(ord(char) < 32 or ord(char) == 127 for char in value):
15
+ raise ValueError("MySQL credentials must not contain control characters")
16
+ return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
17
+
18
+
19
+ @contextmanager
20
+ def mysql_cnf_file(
21
+ *,
22
+ user: str,
23
+ password: str | None = None,
24
+ host: str | None = None,
25
+ port: int | None = None,
26
+ ):
27
+ """Create a temporary mysql client options file with safe permissions.
28
+
29
+ Yields the Path to the file. The file is deleted when the context exits.
30
+ Using a defaults-extra-file keeps credentials out of argv and process lists.
31
+ """
32
+ fd, raw_path = tempfile.mkstemp(prefix="bdbackup-cnf-", suffix=".cnf")
33
+ path = Path(raw_path)
34
+ try:
35
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
36
+ f.write("[client]\n")
37
+ f.write(f"user={_quote_option(user)}\n")
38
+ if password is not None:
39
+ f.write(f"password={_quote_option(password)}\n")
40
+ if host:
41
+ f.write(f"host={_quote_option(host)}\n")
42
+ if port is not None:
43
+ f.write(f"port={port}\n")
44
+ os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
45
+ yield path
46
+ finally:
47
+ try:
48
+ path.unlink()
49
+ except FileNotFoundError:
50
+ pass
@@ -0,0 +1,161 @@
1
+ """Logical MySQL backup engine using mysqldump."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import gzip
6
+ import logging
7
+ import os
8
+ import shutil
9
+ import subprocess
10
+ import tempfile
11
+ from collections.abc import Iterable
12
+ from pathlib import Path
13
+ from urllib.parse import quote
14
+ from uuid import uuid4
15
+
16
+ from bdbackup.backends import BackupError, BackupResult
17
+ from bdbackup.engines import EngineInfo, register_engine
18
+ from bdbackup.mysql.helpers import mysql_cnf_file
19
+ from bdbackup.utils import redact_cmd, today_stamp
20
+
21
+
22
+ class MySQLBackup:
23
+ """Create compressed logical MySQL backups with mysqldump."""
24
+
25
+ DEFAULT_OPTIONS = (
26
+ "--single-transaction",
27
+ "--databases",
28
+ "--routines",
29
+ "--events",
30
+ "--triggers",
31
+ )
32
+
33
+ def __init__(
34
+ self,
35
+ out_dir: str | Path = ".",
36
+ user: str = "root",
37
+ password: str | None = None,
38
+ host: str = "localhost",
39
+ port: int = 3306,
40
+ options: Iterable[str] | None = None,
41
+ jobs: int = 1,
42
+ database: str | None = None,
43
+ ):
44
+ self.out_dir = Path(out_dir).expanduser().absolute()
45
+ self.user = user
46
+ self.password = password
47
+ self.host = host
48
+ self.port = port
49
+ self.database = database
50
+ if jobs < 1:
51
+ raise ValueError("jobs must be >= 1")
52
+ self.jobs = jobs
53
+ self.options = list(dict.fromkeys([*self.DEFAULT_OPTIONS, *(options or [])]))
54
+ if "--all-databases" in self.options:
55
+ self.options.remove("--databases")
56
+ self.logger = logging.getLogger("bdbackup.mysql.mysqldump")
57
+
58
+ def _build_cmd(self, database: str | None, defaults_file: Path) -> list[str]:
59
+ cmd = [
60
+ "mysqldump",
61
+ f"--defaults-extra-file={defaults_file}",
62
+ *self.options,
63
+ ]
64
+ if database:
65
+ cmd.append(database)
66
+ return cmd
67
+
68
+ def backup(self, database: str | None = None) -> BackupResult:
69
+ """Stream only SQL to a private gzip file, then verify and publish it."""
70
+ database = database if database is not None else self.database
71
+ if database is not None and (
72
+ not database or database.startswith("-") or "\x00" in database
73
+ ):
74
+ raise BackupError("Invalid database name")
75
+ if not database and "--all-databases" not in self.options:
76
+ raise BackupError("Specify a database or include --all-databases")
77
+ self.out_dir.mkdir(parents=True, exist_ok=True)
78
+ label = quote(database or "all-databases", safe="")
79
+ out_filename = self.out_dir / f"{label}-{today_stamp()}-{uuid4().hex}.sql.gz"
80
+ fd, raw = tempfile.mkstemp(prefix=".bdbackup-dump-", suffix=".tmp", dir=self.out_dir)
81
+ os.close(fd)
82
+ pending = Path(raw)
83
+ try:
84
+ with (
85
+ mysql_cnf_file(
86
+ user=self.user,
87
+ password=self.password,
88
+ host=self.host,
89
+ port=self.port,
90
+ ) as defaults_file,
91
+ tempfile.TemporaryFile() as errors,
92
+ ):
93
+ cmd = self._build_cmd(database, defaults_file)
94
+ self.logger.info("Running: %s", " ".join(redact_cmd(cmd, [self.password])))
95
+ with subprocess.Popen( # noqa: S603
96
+ cmd,
97
+ stdout=subprocess.PIPE,
98
+ stderr=errors,
99
+ ) as proc:
100
+ try:
101
+ if proc.stdout is None:
102
+ raise BackupError("mysqldump stdout was unexpectedly None")
103
+ with gzip.open(pending, "wb") as gz:
104
+ shutil.copyfileobj(proc.stdout, gz, 1024 * 1024)
105
+ proc.wait()
106
+ except BaseException:
107
+ proc.kill()
108
+ proc.wait()
109
+ raise
110
+ errors.seek(max(0, errors.tell() - 65536))
111
+ diagnostic = errors.read().decode("utf-8", errors="replace")
112
+ if proc.returncode:
113
+ raise BackupError(f"mysqldump failed ({proc.returncode}): {diagnostic}")
114
+ if diagnostic:
115
+ self.logger.warning("mysqldump: %s", diagnostic.rstrip())
116
+ self.verify(BackupResult(pending))
117
+ with pending.open("rb") as stream:
118
+ os.fsync(stream.fileno())
119
+ # A unique name and exclusive hard-link publication never replace an older dump.
120
+ os.link(pending, out_filename)
121
+ finally:
122
+ pending.unlink(missing_ok=True)
123
+ return BackupResult(out_filename, size_bytes=out_filename.stat().st_size, success=True)
124
+
125
+ def verify(self, result: BackupResult | None = None) -> BackupResult:
126
+ """Read the entire gzip stream, including its checksum, and reject empty SQL."""
127
+ if result is None:
128
+ raise BackupError("A dump result is required for verification")
129
+ dump = result.path
130
+ try:
131
+ with gzip.open(dump, "rb") as gz:
132
+ if not gz.read(1):
133
+ raise BackupError(f"Dump contains no SQL: {dump}")
134
+ while gz.read(1024 * 1024):
135
+ pass
136
+ except (OSError, EOFError) as exc:
137
+ raise BackupError(f"Dump verification failed for {dump}: {exc}") from exc
138
+ return BackupResult(dump, size_bytes=dump.stat().st_size, success=True)
139
+
140
+ def backup_all(self, databases: Iterable[str]) -> list[BackupResult]:
141
+ """Dump multiple databases, optionally in parallel."""
142
+ dbs = list(databases)
143
+ if self.jobs == 1:
144
+ return [self.backup(db) for db in dbs]
145
+ from concurrent.futures import ThreadPoolExecutor
146
+
147
+ with ThreadPoolExecutor(max_workers=self.jobs) as pool:
148
+ return list(pool.map(self.backup, dbs))
149
+
150
+ def prune(self) -> list[Path]:
151
+ """mysqldump has no built-in retention policy; return an empty list."""
152
+ return []
153
+
154
+
155
+ ENGINE = EngineInfo(
156
+ name="mysqldump",
157
+ backend=MySQLBackup,
158
+ description="Logical backups via mysqldump (gzip-compressed SQL).",
159
+ family="mysql",
160
+ )
161
+ register_engine(ENGINE)