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.
@@ -0,0 +1,471 @@
1
+ """Verified physical backups with explicit incremental dependencies."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import logging
8
+ import os
9
+ import re
10
+ import shutil
11
+ import subprocess
12
+ import tempfile
13
+ from contextlib import nullcontext
14
+ from datetime import UTC, datetime, timedelta
15
+ from pathlib import Path
16
+ from uuid import uuid4
17
+
18
+ from bdbackup.backends import BackupError, BackupResult
19
+ from bdbackup.engines import EngineInfo, register_engine
20
+ from bdbackup.mysql.helpers import mysql_cnf_file
21
+ from bdbackup.utils import process_lock, redact_cmd
22
+
23
+
24
+ class XtraBackup:
25
+ """Run XtraBackup/mariabackup and retain full dependency chains."""
26
+
27
+ METADATA = "bdbackup.json"
28
+
29
+ def __init__(
30
+ self,
31
+ backup_root: str | Path,
32
+ user: str = "xtrabackup",
33
+ password: str | None = None,
34
+ binary: str = "xtrabackup",
35
+ compress: str = "",
36
+ compress_threads: int = 4,
37
+ parallel: int = 1,
38
+ throttle: int | None = None,
39
+ retention_days: int = 5,
40
+ encrypt: bool = False,
41
+ encrypt_key_file: str | Path | None = None,
42
+ ):
43
+ self.backup_root = Path(backup_root).expanduser().resolve()
44
+ self.user = user
45
+ self.password = password
46
+ self.binary = binary
47
+ self.compress = compress
48
+ self.is_mariadb = Path(binary).name in {"mariabackup", "mariadb-backup"}
49
+ if not isinstance(encrypt, bool):
50
+ raise ValueError("encrypt must be a boolean (true or false in TOML)")
51
+ self.encrypt = encrypt
52
+ self.encrypt_key_file = (
53
+ Path(encrypt_key_file).expanduser().resolve() if encrypt_key_file else None
54
+ )
55
+ if encrypt:
56
+ self._encryption_key_id()
57
+ if self.is_mariadb and compress not in {"", "quicklz"}:
58
+ raise ValueError("mariabackup supports only quicklz compression; omit for uncompressed")
59
+ self.compress_threads = compress_threads
60
+ self.parallel = parallel
61
+ self.throttle = throttle
62
+ self.retention_days = retention_days
63
+ if retention_days < 1 or parallel < 1 or compress_threads < 1:
64
+ raise ValueError("retention_days, parallel and compress_threads must be >= 1")
65
+ if throttle is not None and throttle < 1:
66
+ raise ValueError("throttle must be >= 1")
67
+ self.logger = logging.getLogger("bdbackup.mysql.xtrabackup")
68
+
69
+ def _encryption_key_id(self) -> str:
70
+ """Validate AES256 key material without putting it in commands or metadata."""
71
+ if self.is_mariadb:
72
+ raise ValueError("Backup encryption requires Percona XtraBackup, not mariabackup")
73
+ if self.encrypt_key_file is None:
74
+ raise ValueError(
75
+ "Encryption requires encrypt_key_file (e.g. /etc/mysql/xtrabackup.key)"
76
+ )
77
+ try:
78
+ if not self.encrypt_key_file.is_file():
79
+ raise OSError("not a regular file")
80
+ with self.encrypt_key_file.open("rb") as key_file:
81
+ key = key_file.read(33)
82
+ except OSError as exc:
83
+ raise BackupError(f"Cannot read encryption key file: {self.encrypt_key_file}") from exc
84
+ if len(key) != 32:
85
+ raise ValueError("AES256 encryption key file must contain exactly 32 bytes")
86
+ return hashlib.sha256(key).hexdigest()
87
+
88
+ @property
89
+ def date_dir(self) -> Path:
90
+ return self.backup_root / self._utc_now().strftime("%Y-%m-%d")
91
+
92
+ @property
93
+ def lock_path(self) -> Path:
94
+ return self.backup_root / ".bdbackup.lock"
95
+
96
+ def _utc_now(self) -> datetime:
97
+ return datetime.now(UTC)
98
+
99
+ def _identity(self) -> str:
100
+ return f"{self._utc_now():%Y%m%dT%H%M%S%f}-{uuid4().hex}"
101
+
102
+ def _latest_full_date_dir(self) -> Path | None:
103
+ if not self.backup_root.exists():
104
+ return None
105
+ candidates = [
106
+ p
107
+ for p in self.backup_root.iterdir()
108
+ if (
109
+ not p.is_symlink()
110
+ and p.is_dir()
111
+ and re.fullmatch(r"\d{4}-\d{2}-\d{2}", p.name)
112
+ and (p / ".full_success").is_file()
113
+ )
114
+ ]
115
+ return max(candidates, default=None)
116
+
117
+ def _latest_full(self) -> Path:
118
+ day = self._latest_full_date_dir()
119
+ if day is None:
120
+ raise BackupError("No successful full backup found; run full backup first")
121
+ full = (day / "Full_Latest").resolve()
122
+ if full.parent != day or not full.name.startswith("Full_") or not self._valid_base(full):
123
+ raise BackupError("Latest full is missing or invalid; run a new full backup")
124
+ return full
125
+
126
+ def _base_cmd(
127
+ self,
128
+ target_dir: Path,
129
+ defaults_file: Path,
130
+ incremental_basedir: Path | None = None,
131
+ ) -> list[str]:
132
+ cmd = [
133
+ self.binary,
134
+ f"--defaults-extra-file={defaults_file}",
135
+ "--backup",
136
+ f"--target-dir={target_dir}",
137
+ ]
138
+ if self.compress:
139
+ cmd.extend(
140
+ [f"--compress={self.compress}", f"--compress-threads={self.compress_threads}"]
141
+ )
142
+ if self.encrypt:
143
+ cmd.extend(["--encrypt=AES256", f"--encrypt-key-file={self.encrypt_key_file}"])
144
+ if self.parallel > 1:
145
+ cmd.append(f"--parallel={self.parallel}")
146
+ if self.throttle:
147
+ cmd.append(f"--throttle={self.throttle}")
148
+ if incremental_basedir:
149
+ cmd.append(f"--incremental-basedir={incremental_basedir}")
150
+ return cmd
151
+
152
+ def _run(self, cmd: list[str]) -> None:
153
+ self.logger.info("Running: %s", " ".join(redact_cmd(cmd, [self.password])))
154
+ # Keep large backup logs out of memory.
155
+ with tempfile.TemporaryFile(mode="w+") as output:
156
+ proc = subprocess.run( # noqa: S603
157
+ cmd,
158
+ stdout=output,
159
+ stderr=subprocess.STDOUT,
160
+ check=False,
161
+ text=True,
162
+ )
163
+ if proc.returncode:
164
+ output.seek(0, os.SEEK_END)
165
+ output.seek(max(0, output.tell() - 65536))
166
+ raise BackupError(f"{self.binary} failed ({proc.returncode}): {output.read()}")
167
+
168
+ @staticmethod
169
+ def _read_to_lsn(checkpoints: Path) -> int | None:
170
+ try:
171
+ values = dict(
172
+ line.split("=", 1) for line in checkpoints.read_text().splitlines() if "=" in line
173
+ )
174
+ return int({key.strip(): value.strip() for key, value in values.items()}["to_lsn"])
175
+ except (OSError, ValueError, KeyError):
176
+ return None
177
+
178
+ @staticmethod
179
+ def _checkpoints(target: Path) -> dict:
180
+ checkpoint = target / "mariadb_backup_checkpoints"
181
+ if not checkpoint.exists():
182
+ checkpoint = target / "xtrabackup_checkpoints"
183
+ try:
184
+ values = dict(
185
+ line.split("=", 1) for line in checkpoint.read_text().splitlines() if "=" in line
186
+ )
187
+ values = {key.strip(): value.strip() for key, value in values.items()}
188
+ start, end = int(values["from_lsn"]), int(values["to_lsn"])
189
+ kind = values["backup_type"]
190
+ if start < 0 or end <= 0 or end < start:
191
+ raise ValueError("invalid LSN range")
192
+ if kind not in {"full-backuped", "incremental", "log-applied", "full-prepared"}:
193
+ raise ValueError("unknown backup type")
194
+ return {"from_lsn": start, "to_lsn": end, "backup_type": kind}
195
+ except (OSError, ValueError, KeyError) as exc:
196
+ raise BackupError(f"Invalid checkpoints in {target}: {exc}") from exc
197
+
198
+ def _valid_base(self, path: Path) -> bool:
199
+ try:
200
+ return self._checkpoints(path)["backup_type"] in {"full-backuped", "incremental"}
201
+ except BackupError:
202
+ return False
203
+
204
+ def _metadata(self, path: Path) -> dict:
205
+ try:
206
+ data = json.loads((path / self.METADATA).read_text())
207
+ checkpoints = self._checkpoints(path)
208
+ if (
209
+ data["schema"] != 1
210
+ or data["from_lsn"] != checkpoints["from_lsn"]
211
+ or data["to_lsn"] != checkpoints["to_lsn"]
212
+ ):
213
+ raise ValueError("metadata/checkpoints disagree")
214
+ if data["kind"] not in {"full", "incremental"}:
215
+ raise ValueError("invalid backup kind")
216
+ return data
217
+ except (OSError, ValueError, KeyError, TypeError) as exc:
218
+ raise BackupError(f"Invalid dependency metadata in {path}: {exc}") from exc
219
+
220
+ def _chain(self, full: Path) -> list[Path]:
221
+ """Resolve the single committed chain belonging to this full, never by wall clock."""
222
+ root = full.parent / "Incremental" / full.name
223
+ if not root.exists():
224
+ return []
225
+ expected_full = str(full.relative_to(self.backup_root))
226
+ children: dict[str, Path] = {}
227
+ count = 0
228
+ for candidate in root.iterdir():
229
+ if candidate.name.endswith(".tmp") or candidate.name.startswith("."):
230
+ continue
231
+ if candidate.is_symlink() or not candidate.is_dir():
232
+ raise BackupError(f"Unexpected incremental entry: {candidate}")
233
+ meta = self._metadata(candidate)
234
+ if meta.get("full") != expected_full or meta["kind"] != "incremental":
235
+ raise BackupError(f"Incremental belongs to a different full: {candidate}")
236
+ parent = meta.get("parent")
237
+ if not isinstance(parent, str) or parent in children:
238
+ raise BackupError(f"Ambiguous incremental parent: {candidate}")
239
+ children[parent] = candidate
240
+ count += 1
241
+ chain = []
242
+ parent = full
243
+ while str(parent.relative_to(self.backup_root)) in children:
244
+ child = children.pop(str(parent.relative_to(self.backup_root)))
245
+ if self._checkpoints(child)["from_lsn"] != self._checkpoints(parent)["to_lsn"]:
246
+ raise BackupError(f"Broken incremental LSN chain: {child}")
247
+ if not self._valid_base(child):
248
+ raise BackupError(f"Incremental has already been prepared: {child}")
249
+ chain.append(child)
250
+ parent = child
251
+ if len(chain) != count:
252
+ raise BackupError("Incremental chain has missing parents or cycles")
253
+ return chain
254
+
255
+ def _create(self, target: Path, full: Path | None = None, parent: Path | None = None):
256
+ key_id = self._encryption_key_id() if self.encrypt else None
257
+ if parent is not None:
258
+ parent_meta = self._metadata(parent)
259
+ if (parent_meta.get("encrypted", False) != self.encrypt
260
+ or parent_meta.get("encryption_key_id") != key_id):
261
+ raise BackupError("Encryption settings/key changed; take a new full backup")
262
+ pending = Path(str(target) + ".tmp")
263
+ pending.mkdir(parents=True, mode=0o700)
264
+ try:
265
+ with mysql_cnf_file(user=self.user, password=self.password) as defaults:
266
+ self._run(self._base_cmd(pending, defaults, parent))
267
+ if self.encrypt and not any(pending.rglob("*.xbcrypt")):
268
+ raise BackupError("Encrypted backup produced no encrypted files")
269
+ self.verify(BackupResult(pending))
270
+ checkpoints = self._checkpoints(pending)
271
+ if parent is not None:
272
+ if (
273
+ checkpoints["backup_type"] != "incremental"
274
+ or checkpoints["from_lsn"] != self._checkpoints(parent)["to_lsn"]
275
+ ):
276
+ raise BackupError("New incremental does not continue its selected parent")
277
+ elif checkpoints["backup_type"] != "full-backuped" or checkpoints["from_lsn"] != 0:
278
+ raise BackupError("Full backup did not produce full-backuped checkpoints")
279
+ metadata = {
280
+ "schema": 1,
281
+ "kind": "incremental" if parent else "full",
282
+ "full": str((full or target).relative_to(self.backup_root)),
283
+ "parent": str(parent.relative_to(self.backup_root)) if parent else None,
284
+ "created": self._utc_now().isoformat(),
285
+ "encrypted": self.encrypt,
286
+ "encryption_key_id": key_id,
287
+ **checkpoints,
288
+ }
289
+ (pending / self.METADATA).write_text(json.dumps(metadata, indent=2) + "\n")
290
+ pending.rename(target)
291
+ finally:
292
+ if pending.exists():
293
+ shutil.rmtree(pending)
294
+ return BackupResult(target, size_bytes=self._size(target), success=True)
295
+
296
+ @staticmethod
297
+ def _size(target: Path) -> int:
298
+ return sum(p.stat().st_size for p in target.rglob("*") if p.is_file())
299
+
300
+ def backup(self, name: str | None = None) -> BackupResult:
301
+ return self.full_backup()
302
+
303
+ def full_backup(self, *, acquire_lock: bool = True) -> BackupResult:
304
+ with process_lock(self.lock_path) if acquire_lock else nullcontext():
305
+ target = self.date_dir / f"Full_{self._identity()}"
306
+ result = self._create(target)
307
+ link = target.parent / "Full_Latest"
308
+ temporary_link = target.parent / f".latest-{uuid4().hex}"
309
+ try:
310
+ temporary_link.symlink_to(target.name, target_is_directory=True)
311
+ os.replace(temporary_link, link)
312
+ finally:
313
+ temporary_link.unlink(missing_ok=True)
314
+ (target.parent / ".full_success").touch()
315
+ self.prune(acquire_lock=False)
316
+ return result
317
+
318
+ def incremental_backup(self, *, acquire_lock: bool = True) -> BackupResult:
319
+ with process_lock(self.lock_path) if acquire_lock else nullcontext():
320
+ full = self._latest_full()
321
+ # Legacy incrementals have no reliable parent identity; never guess their chain.
322
+ if not (full / self.METADATA).exists():
323
+ raise BackupError(
324
+ "Legacy backup has no dependency metadata; take a new full backup"
325
+ )
326
+ self._metadata(full)
327
+ chain = self._chain(full)
328
+ parent = chain[-1] if chain else full
329
+ target = full.parent / "Incremental" / full.name / self._identity()
330
+ return self._create(target, full, parent)
331
+
332
+ def prepare(
333
+ self,
334
+ target: str | Path,
335
+ destination: str | Path,
336
+ ) -> Path:
337
+ """Prepare a separate full recovery copy, following an incremental's parent chain."""
338
+ source = Path(target).expanduser().resolve()
339
+ dest = Path(destination).expanduser().absolute()
340
+ if dest.exists() or dest.is_symlink():
341
+ raise BackupError(f"Recovery destination already exists: {dest}")
342
+ if dest.resolve().is_relative_to(self.backup_root):
343
+ raise BackupError("Recovery destination must be outside the backup root")
344
+ with process_lock(self.lock_path):
345
+ cp = self._checkpoints(source)
346
+ if cp["backup_type"] == "incremental":
347
+ meta = self._metadata(source)
348
+ full = (self.backup_root / meta["full"]).resolve()
349
+ if not full.is_relative_to(self.backup_root):
350
+ raise BackupError("Full backup escapes the backup root")
351
+ chain = self._chain(full)
352
+ if source not in chain:
353
+ raise BackupError("Requested incremental is not in the committed chain")
354
+ sources = [full, *chain[: chain.index(source) + 1]]
355
+ elif cp["backup_type"] == "full-backuped":
356
+ sources = [source]
357
+ else:
358
+ raise BackupError("Source has already been prepared; use an original backup")
359
+ dest.parent.mkdir(parents=True, exist_ok=True)
360
+ with (
361
+ process_lock(dest.with_name(dest.name + ".lock")),
362
+ tempfile.TemporaryDirectory(
363
+ prefix=".bdbackup-prepare-",
364
+ dir=dest.parent,
365
+ ) as workspace,
366
+ mysql_cnf_file(user=self.user, password=self.password) as defaults,
367
+ ):
368
+ if dest.exists():
369
+ raise BackupError(f"Recovery destination already exists: {dest}")
370
+ copies = []
371
+ for index, original in enumerate(sources):
372
+ copy = Path(workspace) / str(index)
373
+ shutil.copytree(original, copy, symlinks=True)
374
+ # Database recovery tools may follow symlinks; reject them in the work copy.
375
+ if any(p.is_symlink() for p in copy.rglob("*")):
376
+ raise BackupError("Physical backup contains unsupported symlinks")
377
+ if any(copy.rglob("*.xbcrypt")):
378
+ key_id = self._encryption_key_id()
379
+ if (copy / self.METADATA).exists():
380
+ expected_key = self._metadata(copy).get("encryption_key_id")
381
+ if expected_key is not None and expected_key != key_id:
382
+ raise BackupError("Encryption key does not match this backup")
383
+ self._run([
384
+ self.binary,
385
+ f"--defaults-extra-file={defaults}",
386
+ "--decrypt=AES256",
387
+ f"--encrypt-key-file={self.encrypt_key_file}",
388
+ "--remove-original",
389
+ f"--target-dir={copy}",
390
+ ])
391
+ if any(copy.rglob("*.xbcrypt")):
392
+ raise BackupError("Decryption left encrypted files in recovery copy")
393
+ if any(p.suffix in {".zst", ".qp", ".lz4"} for p in copy.rglob("*")):
394
+ self._run(
395
+ [
396
+ self.binary,
397
+ f"--defaults-extra-file={defaults}",
398
+ "--decompress",
399
+ f"--target-dir={copy}",
400
+ ]
401
+ )
402
+ copies.append(copy)
403
+ base = copies[0]
404
+ common = [
405
+ self.binary,
406
+ f"--defaults-extra-file={defaults}",
407
+ "--prepare",
408
+ f"--target-dir={base}",
409
+ ]
410
+ self._run(
411
+ [*common, "--apply-log-only"]
412
+ if len(copies) > 1 and not self.is_mariadb
413
+ else common
414
+ )
415
+ for index, incremental in enumerate(copies[1:], 1):
416
+ cmd = [*common, f"--incremental-dir={incremental}"]
417
+ if index < len(copies) - 1 and not self.is_mariadb:
418
+ cmd.append("--apply-log-only")
419
+ self._run(cmd)
420
+ self.verify(BackupResult(base))
421
+ prepared = self._checkpoints(base)
422
+ expected_lsn = self._checkpoints(sources[-1])["to_lsn"]
423
+ if prepared["to_lsn"] != expected_lsn or prepared["backup_type"] not in {
424
+ "full-prepared",
425
+ "log-applied",
426
+ }:
427
+ raise BackupError("Prepared copy does not match the requested recovery point")
428
+ (base / self.METADATA).unlink(missing_ok=True)
429
+ base.rename(dest)
430
+ return dest
431
+
432
+ def verify(self, result: BackupResult | None = None) -> BackupResult:
433
+ target = result.path if result else self._latest_full()
434
+ self._checkpoints(target)
435
+ return BackupResult(target, size_bytes=self._size(target), success=True)
436
+
437
+ def prune(self, *, acquire_lock: bool = True) -> list[Path]:
438
+ """Expire whole daily chains under the same lock as writers, keeping the latest full."""
439
+ if not self.backup_root.exists():
440
+ return []
441
+ with process_lock(self.lock_path) if acquire_lock else nullcontext():
442
+ newest = self._latest_full_date_dir()
443
+ if newest is None:
444
+ raise BackupError("No successful full backup; refusing to prune")
445
+ self._latest_full()
446
+ cutoff = self._utc_now().date() - timedelta(days=self.retention_days - 1)
447
+ removed = []
448
+ for item in self.backup_root.iterdir():
449
+ if item.is_symlink() or not item.is_dir() or item == newest:
450
+ continue
451
+ if not (item / ".full_success").is_file():
452
+ continue
453
+ if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", item.name):
454
+ continue
455
+ try:
456
+ day = datetime.strptime(item.name, "%Y-%m-%d").date()
457
+ except ValueError:
458
+ continue
459
+ if day < cutoff:
460
+ shutil.rmtree(item)
461
+ removed.append(item)
462
+ return removed
463
+
464
+
465
+ ENGINE = EngineInfo(
466
+ name="xtrabackup",
467
+ backend=XtraBackup,
468
+ description="Physical backups via XtraBackup / mariabackup with explicit dependency chains.",
469
+ family="mysql",
470
+ )
471
+ register_engine(ENGINE)
bdbackup/recovery.py ADDED
@@ -0,0 +1,80 @@
1
+ """Restore recorded backups into a new recovery directory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import gzip
6
+ import json
7
+ import re
8
+ import shutil
9
+ from pathlib import Path
10
+
11
+ from bdbackup.backends import BackupError
12
+ from bdbackup.filebackup import FileBackup
13
+ from bdbackup.history import BackupRecord
14
+ from bdbackup.mysql import MySQLBackup, XtraBackup
15
+
16
+
17
+ def backup_restore_info(backend) -> dict[str, str]:
18
+ """Save only recovery routing, never connection credentials or arbitrary options."""
19
+ if isinstance(backend, FileBackup):
20
+ return {"kind": "file"}
21
+ if isinstance(backend, MySQLBackup):
22
+ return {"kind": "mysqldump"}
23
+ if isinstance(backend, XtraBackup):
24
+ info = {"kind": "xtrabackup", "backup_root": str(backend.backup_root),
25
+ "binary": backend.binary}
26
+ if backend.encrypt:
27
+ info.update(encryption="AES256", encrypt_key_file=str(backend.encrypt_key_file))
28
+ return info
29
+ return {}
30
+
31
+
32
+ def suggested_destination(record: BackupRecord, root: Path) -> Path:
33
+ name = re.sub(r"[^a-zA-Z0-9_-]+", "-", record.job_name).strip("-")[:80] or "backup"
34
+ base = root / f"{name}-{record.id}"
35
+ target = base
36
+ number = 1
37
+ while target.exists() or target.is_symlink():
38
+ target = base.with_name(f"{base.name}-{number}")
39
+ number += 1
40
+ return target
41
+
42
+
43
+ def restore_record(
44
+ record: BackupRecord, destination: Path, *, encrypt_key_file: Path | None = None,
45
+ ) -> Path:
46
+ if not record.available:
47
+ raise BackupError("Backup is unsuccessful, missing, or has been replaced/modified")
48
+ source = Path(record.path)
49
+ # Do not resolve the final component: a dangling destination symlink must be rejected.
50
+ destination = destination.expanduser().absolute()
51
+ if destination.exists() or destination.is_symlink():
52
+ raise BackupError(f"Recovery destination must be new: {destination}")
53
+ info = json.loads(record.restore_info)
54
+ kind = info.get("kind")
55
+ if kind == "xtrabackup":
56
+ backend = XtraBackup(
57
+ backup_root=info["backup_root"], binary=info["binary"],
58
+ encrypt=bool(record.encrypted),
59
+ encrypt_key_file=encrypt_key_file or info.get("encrypt_key_file"),
60
+ )
61
+ return backend.prepare(source, destination)
62
+ if kind not in {"file", "mysqldump"}:
63
+ raise BackupError(f"History restore is not supported for engine {record.backup_type!r}")
64
+ destination.mkdir(parents=True, mode=0o700)
65
+ try:
66
+ if kind == "file":
67
+ FileBackup.restore_archive(source, destination)
68
+ else:
69
+ sql = destination / "backup.sql"
70
+ with gzip.open(source, "rb") as archive, sql.open("xb") as output:
71
+ sql.chmod(0o600)
72
+ shutil.copyfileobj(archive, output, 1024 * 1024)
73
+ if not sql.stat().st_size:
74
+ raise BackupError("Dump contains no SQL")
75
+ if not record.available:
76
+ raise BackupError("Backup changed during restoration")
77
+ except BaseException:
78
+ shutil.rmtree(destination)
79
+ raise
80
+ return destination