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/__init__.py +15 -0
- bdbackup/backends.py +56 -0
- bdbackup/cli.py +1045 -0
- bdbackup/config.py +114 -0
- bdbackup/dboperations.py +88 -0
- bdbackup/engines.py +167 -0
- bdbackup/filebackup.py +305 -0
- bdbackup/history.py +180 -0
- bdbackup/mysql/__init__.py +26 -0
- bdbackup/mysql/helpers.py +50 -0
- bdbackup/mysql/mysqldump.py +161 -0
- bdbackup/mysql/xtrabackup.py +471 -0
- bdbackup/recovery.py +80 -0
- bdbackup/retention.py +636 -0
- bdbackup/scheduling.py +196 -0
- bdbackup/templates/__init__.py +163 -0
- bdbackup/templates/_matching.py +159 -0
- bdbackup/templates/python_dev.py +54 -0
- bdbackup/utils.py +58 -0
- bdbackup/validation.py +400 -0
- bdbackup-0.6.1.dist-info/METADATA +752 -0
- bdbackup-0.6.1.dist-info/RECORD +25 -0
- bdbackup-0.6.1.dist-info/WHEEL +4 -0
- bdbackup-0.6.1.dist-info/entry_points.txt +2 -0
- bdbackup-0.6.1.dist-info/licenses/LICENSE +21 -0
bdbackup/config.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Configuration-driven job definitions for bdbackup."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import tomllib
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from bdbackup.engines import EngineError, get_engine, list_engines
|
|
11
|
+
from bdbackup.filebackup import FileBackup
|
|
12
|
+
from bdbackup.history import HistorySettings
|
|
13
|
+
from bdbackup.scheduling import validate_schedule
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class Job:
|
|
18
|
+
"""A single named backup job parsed from config."""
|
|
19
|
+
|
|
20
|
+
name: str
|
|
21
|
+
type: str
|
|
22
|
+
params: dict[str, Any]
|
|
23
|
+
schedule: str | None = None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ConfigError(Exception):
|
|
27
|
+
"""Raised when a configuration file is invalid."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def supported_types() -> set[str]:
|
|
31
|
+
"""Return all valid job types: builtins plus every registered engine name."""
|
|
32
|
+
return {"file", "retention"} | set(list_engines())
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Config:
|
|
36
|
+
"""Load and validate a TOML job configuration file."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, path: str | Path):
|
|
39
|
+
self.path = Path(path).expanduser().resolve()
|
|
40
|
+
self.jobs: dict[str, Job] = {}
|
|
41
|
+
self.history: HistorySettings | None = None
|
|
42
|
+
self._load()
|
|
43
|
+
|
|
44
|
+
def _load(self) -> None:
|
|
45
|
+
if not self.path.exists():
|
|
46
|
+
raise ConfigError(f"Config file not found: {self.path}")
|
|
47
|
+
try:
|
|
48
|
+
with self.path.open("rb") as f:
|
|
49
|
+
data = tomllib.load(f)
|
|
50
|
+
except (OSError, tomllib.TOMLDecodeError) as exc:
|
|
51
|
+
raise ConfigError(f"Cannot read config {self.path}: {exc}") from exc
|
|
52
|
+
|
|
53
|
+
if "history" in data:
|
|
54
|
+
section = data.pop("history")
|
|
55
|
+
if not isinstance(section, dict) or set(section) - {"database", "restore_root"}:
|
|
56
|
+
raise ConfigError("[history] accepts only database and restore_root")
|
|
57
|
+
paths = {}
|
|
58
|
+
for key, default in (("database", None), ("restore_root", "restores")):
|
|
59
|
+
value = section.get(key, default)
|
|
60
|
+
if not isinstance(value, str) or not value.strip() or value == ":memory:":
|
|
61
|
+
raise ConfigError(f"[history] {key} must be a nonempty filesystem path")
|
|
62
|
+
paths[key] = (self.path.parent / Path(value).expanduser()).resolve()
|
|
63
|
+
self.history = HistorySettings(**paths)
|
|
64
|
+
|
|
65
|
+
for name, section in data.items():
|
|
66
|
+
if not isinstance(section, dict):
|
|
67
|
+
raise ConfigError(f"Job {name!r} must be a table")
|
|
68
|
+
job_type = section.get("type")
|
|
69
|
+
if job_type not in supported_types():
|
|
70
|
+
raise ConfigError(
|
|
71
|
+
f"Job {name!r} has unsupported type {job_type!r}; "
|
|
72
|
+
f"expected one of {sorted(supported_types())}"
|
|
73
|
+
)
|
|
74
|
+
schedule = section.get("schedule")
|
|
75
|
+
if "schedule" in section:
|
|
76
|
+
try:
|
|
77
|
+
schedule = validate_schedule(schedule)
|
|
78
|
+
except ValueError as exc:
|
|
79
|
+
raise ConfigError(f"Job {name!r}: {exc}") from exc
|
|
80
|
+
params = {k: v for k, v in section.items() if k not in {"type", "schedule"}}
|
|
81
|
+
# Config paths are relative to the config file; file-template entries
|
|
82
|
+
# and excludes remain relative to the explicitly selected source path.
|
|
83
|
+
for key in (
|
|
84
|
+
"template_filename",
|
|
85
|
+
"backup_dst",
|
|
86
|
+
"chdir",
|
|
87
|
+
"out_dir",
|
|
88
|
+
"backup_root",
|
|
89
|
+
"encrypt_key_file",
|
|
90
|
+
"full_dir",
|
|
91
|
+
"incr_dir",
|
|
92
|
+
"log_dir",
|
|
93
|
+
):
|
|
94
|
+
if key in params:
|
|
95
|
+
try:
|
|
96
|
+
params[key] = self.path.parent / Path(params[key]).expanduser()
|
|
97
|
+
except TypeError as exc:
|
|
98
|
+
raise ConfigError(f"Job {name!r}: {key} must be a path string") from exc
|
|
99
|
+
self.jobs[name] = Job(name=name, type=job_type, params=params, schedule=schedule)
|
|
100
|
+
|
|
101
|
+
def get(self, name: str) -> Job:
|
|
102
|
+
if name not in self.jobs:
|
|
103
|
+
raise ConfigError(f"Job {name!r} not found in {self.path}")
|
|
104
|
+
return self.jobs[name]
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def build_backend(job: Job):
|
|
108
|
+
"""Instantiate the appropriate backend for a parsed job via the engine registry."""
|
|
109
|
+
if job.type == "file":
|
|
110
|
+
return FileBackup(**job.params)
|
|
111
|
+
try:
|
|
112
|
+
return get_engine(job.type).backend(**job.params)
|
|
113
|
+
except EngineError as exc:
|
|
114
|
+
raise ConfigError(str(exc)) from exc
|
bdbackup/dboperations.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Lightweight MySQL operations for tracking backup metadata."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class MySQLOps:
|
|
10
|
+
"""Manage backup metadata in a MySQL database.
|
|
11
|
+
|
|
12
|
+
Requires PyMySQL to be installed (``pip install bdbackup[mysql]``).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
host: str = "localhost",
|
|
18
|
+
user: str = "root",
|
|
19
|
+
password: str = "",
|
|
20
|
+
database: str = "backup_information",
|
|
21
|
+
):
|
|
22
|
+
self.host = host
|
|
23
|
+
self.user = user
|
|
24
|
+
self.password = password
|
|
25
|
+
self.database = database
|
|
26
|
+
self.db: Any | None = None
|
|
27
|
+
self.cursor: Any | None = None
|
|
28
|
+
self.dblist: list[str] = []
|
|
29
|
+
self.logger = logging.getLogger("bdbackup.db")
|
|
30
|
+
self._connect()
|
|
31
|
+
|
|
32
|
+
def _connect(self) -> None:
|
|
33
|
+
try:
|
|
34
|
+
import pymysql
|
|
35
|
+
|
|
36
|
+
self.db = pymysql.connect(
|
|
37
|
+
host=self.host,
|
|
38
|
+
user=self.user,
|
|
39
|
+
password=self.password,
|
|
40
|
+
database=self.database,
|
|
41
|
+
)
|
|
42
|
+
self.cursor = self.db.cursor()
|
|
43
|
+
self.logger.info("Connected to MySQL metadata database")
|
|
44
|
+
except ImportError:
|
|
45
|
+
self.logger.error(
|
|
46
|
+
"PyMySQL is required for metadata tracking. "
|
|
47
|
+
"Install it with: pip install bdbackup[mysql]"
|
|
48
|
+
)
|
|
49
|
+
raise
|
|
50
|
+
except Exception as exc:
|
|
51
|
+
self.logger.error("Unable to connect to MySQL: %s", exc)
|
|
52
|
+
raise
|
|
53
|
+
|
|
54
|
+
def get_dblist(self) -> list[str]:
|
|
55
|
+
"""Return the list of active databases from tbl_backup."""
|
|
56
|
+
sql = "SELECT `ID`, `DATABASE`, `LAST_BACKUP_TIMESTAMP` FROM tbl_backup WHERE `STATUS` = 1"
|
|
57
|
+
try:
|
|
58
|
+
self.cursor.execute(sql)
|
|
59
|
+
rows = self.cursor.fetchall()
|
|
60
|
+
self.dblist = [row[1] for row in rows]
|
|
61
|
+
for row in rows:
|
|
62
|
+
self.logger.info("ID=%s, DB=%s, TIME=%s", row[0], row[1], row[2])
|
|
63
|
+
except Exception as exc:
|
|
64
|
+
self.logger.error("Unable to fetch database list: %s", exc)
|
|
65
|
+
raise
|
|
66
|
+
return self.dblist
|
|
67
|
+
|
|
68
|
+
def update_db(self, dbname: str) -> None:
|
|
69
|
+
"""Update the last backup timestamp for a database."""
|
|
70
|
+
sql = "UPDATE tbl_backup SET `LAST_BACKUP_TIMESTAMP` = NOW() WHERE `DATABASE` = %s"
|
|
71
|
+
try:
|
|
72
|
+
self.cursor.execute(sql, (dbname,))
|
|
73
|
+
self.db.commit()
|
|
74
|
+
self.logger.info("Updated backup timestamp for %s", dbname)
|
|
75
|
+
except Exception as exc:
|
|
76
|
+
self.db.rollback()
|
|
77
|
+
self.logger.error("Unable to update %s: %s", dbname, exc)
|
|
78
|
+
raise
|
|
79
|
+
|
|
80
|
+
def close(self) -> None:
|
|
81
|
+
"""Close the database connection."""
|
|
82
|
+
if self.db:
|
|
83
|
+
self.db.close()
|
|
84
|
+
self.db = None
|
|
85
|
+
self.cursor = None
|
|
86
|
+
|
|
87
|
+
def __del__(self) -> None:
|
|
88
|
+
self.close()
|
bdbackup/engines.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Registry of backup engines, pluggable per database family.
|
|
2
|
+
|
|
3
|
+
An engine maps a config ``type`` name (e.g. ``mysqldump``, ``xtrabackup``,
|
|
4
|
+
``xtrabackup80``, ``mysql-shell``) to a backend class implementing the
|
|
5
|
+
:class:`~bdbackup.backends.BackupBackend` protocol. Engines are discovered
|
|
6
|
+
from two locations and merged by name:
|
|
7
|
+
|
|
8
|
+
1. Built-in engines shipped inside family packages (see FAMILIES below),
|
|
9
|
+
so they work with ``uv tool install``. Each family package self-discovers
|
|
10
|
+
its engine modules.
|
|
11
|
+
2. User engines: any ``*.py`` file in ``<config dir>/engines/`` where the
|
|
12
|
+
config dir resolves via :func:`bdbackup.utils.config_dir`
|
|
13
|
+
(``$BDBACKUP_CONFIG_DIR`` -> ``$XDG_CONFIG_HOME/bdbackup`` ->
|
|
14
|
+
``~/.config/bdbackup``).
|
|
15
|
+
|
|
16
|
+
An engine module self-registers by defining either::
|
|
17
|
+
|
|
18
|
+
ENGINE = EngineInfo(name="my-engine", backend=MyEngine, description="...")
|
|
19
|
+
|
|
20
|
+
or::
|
|
21
|
+
|
|
22
|
+
def register() -> EngineInfo: ...
|
|
23
|
+
|
|
24
|
+
Adding an engine (built-in or user) never requires editing existing code:
|
|
25
|
+
drop in a new module and it is picked up on the next run. A whole new
|
|
26
|
+
database family (e.g. postgres) requires adding its package import path to
|
|
27
|
+
FAMILIES below — the single deliberate modification point.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import importlib
|
|
33
|
+
import importlib.util
|
|
34
|
+
import logging
|
|
35
|
+
import pkgutil
|
|
36
|
+
from collections.abc import Iterable
|
|
37
|
+
from dataclasses import dataclass
|
|
38
|
+
|
|
39
|
+
from bdbackup.utils import config_dir
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
"EngineError",
|
|
43
|
+
"EngineInfo",
|
|
44
|
+
"get_engine",
|
|
45
|
+
"list_engines",
|
|
46
|
+
"register_engine",
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
logger = logging.getLogger("bdbackup.engines")
|
|
50
|
+
|
|
51
|
+
# Import paths of family packages that self-discover their engine modules.
|
|
52
|
+
# To add a database family (e.g. postgres): create bdbackup/postgres/ and
|
|
53
|
+
# append "bdbackup.postgres" here — nothing else needs to change.
|
|
54
|
+
FAMILIES: tuple[str, ...] = (
|
|
55
|
+
"bdbackup.mysql",
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True)
|
|
60
|
+
class EngineInfo:
|
|
61
|
+
"""A named backup engine bound to a backend class."""
|
|
62
|
+
|
|
63
|
+
name: str
|
|
64
|
+
backend: type
|
|
65
|
+
description: str = ""
|
|
66
|
+
family: str = "mysql"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class EngineError(Exception):
|
|
70
|
+
"""Raised when an engine cannot be found or loaded."""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
_REGISTRY: dict[str, EngineInfo] = {}
|
|
74
|
+
_LOADED = False
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def register_engine(engine: EngineInfo) -> None:
|
|
78
|
+
"""Register *engine*, replacing any existing engine with the same name."""
|
|
79
|
+
_REGISTRY[engine.name] = engine
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _collect(module) -> None:
|
|
83
|
+
"""Register whatever an engine module exposes (ENGINE or register())."""
|
|
84
|
+
engine = getattr(module, "ENGINE", None)
|
|
85
|
+
if isinstance(engine, EngineInfo):
|
|
86
|
+
register_engine(engine)
|
|
87
|
+
hook = getattr(module, "register", None)
|
|
88
|
+
if callable(hook):
|
|
89
|
+
produced = hook()
|
|
90
|
+
if isinstance(produced, EngineInfo):
|
|
91
|
+
register_engine(produced)
|
|
92
|
+
elif isinstance(produced, Iterable):
|
|
93
|
+
for item in produced:
|
|
94
|
+
if isinstance(item, EngineInfo):
|
|
95
|
+
register_engine(item)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _load_builtin() -> None:
|
|
99
|
+
"""Import every engine module shipped inside each family package."""
|
|
100
|
+
for family in FAMILIES:
|
|
101
|
+
pkg = importlib.import_module(family)
|
|
102
|
+
for info in pkgutil.iter_modules(pkg.__path__):
|
|
103
|
+
if info.name.startswith("_"):
|
|
104
|
+
continue
|
|
105
|
+
try:
|
|
106
|
+
module = importlib.import_module(f"{family}.{info.name}")
|
|
107
|
+
_collect(module)
|
|
108
|
+
except Exception as exc: # pragma: no cover - defensive
|
|
109
|
+
logger.warning(
|
|
110
|
+
"Failed to load built-in engine %r.%r: %s", family, info.name, exc
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _load_user() -> None:
|
|
115
|
+
"""Import user engine modules from <config dir>/engines/*.py."""
|
|
116
|
+
user_dir = config_dir() / "engines"
|
|
117
|
+
if not user_dir.is_dir():
|
|
118
|
+
return
|
|
119
|
+
for file in sorted(user_dir.glob("*.py")):
|
|
120
|
+
if file.name.startswith("_"):
|
|
121
|
+
continue
|
|
122
|
+
try:
|
|
123
|
+
spec = importlib.util.spec_from_file_location(
|
|
124
|
+
f"bdbackup_user_engine_{file.stem}", file
|
|
125
|
+
)
|
|
126
|
+
if spec is None or spec.loader is None: # pragma: no cover - defensive
|
|
127
|
+
continue
|
|
128
|
+
module = importlib.util.module_from_spec(spec)
|
|
129
|
+
spec.loader.exec_module(module)
|
|
130
|
+
_collect(module)
|
|
131
|
+
except Exception as exc:
|
|
132
|
+
logger.warning("Failed to load user engine %s: %s", file, exc)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _ensure_loaded() -> None:
|
|
136
|
+
global _LOADED
|
|
137
|
+
if _LOADED:
|
|
138
|
+
return
|
|
139
|
+
_load_builtin()
|
|
140
|
+
_load_user()
|
|
141
|
+
_LOADED = True
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def list_engines() -> dict[str, EngineInfo]:
|
|
145
|
+
"""Return all registered engines, keyed by name."""
|
|
146
|
+
_ensure_loaded()
|
|
147
|
+
return dict(_REGISTRY)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def get_engine(name: str) -> EngineInfo:
|
|
151
|
+
"""Return the engine called *name* or raise :class:`EngineError`."""
|
|
152
|
+
_ensure_loaded()
|
|
153
|
+
try:
|
|
154
|
+
return _REGISTRY[name]
|
|
155
|
+
except KeyError:
|
|
156
|
+
available = ", ".join(sorted(_REGISTRY)) or "<none>"
|
|
157
|
+
raise EngineError(
|
|
158
|
+
f"Unknown engine {name!r}. Available: {available}. "
|
|
159
|
+
f"User engines are loaded from {config_dir() / 'engines'}/*.py"
|
|
160
|
+
) from None
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _reset_for_tests() -> None:
|
|
164
|
+
"""Clear the registry and loaded flag (test isolation only)."""
|
|
165
|
+
global _LOADED
|
|
166
|
+
_REGISTRY.clear()
|
|
167
|
+
_LOADED = False
|
bdbackup/filebackup.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
"""Template-driven, atomically published tar archive backups."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import fnmatch
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import stat
|
|
9
|
+
import sys
|
|
10
|
+
import tarfile
|
|
11
|
+
import tempfile
|
|
12
|
+
from collections.abc import Iterable
|
|
13
|
+
from pathlib import Path, PurePosixPath
|
|
14
|
+
|
|
15
|
+
from bdbackup.backends import BackupError, BackupResult
|
|
16
|
+
from bdbackup.templates import build_matcher, resolve_patterns
|
|
17
|
+
from bdbackup.utils import process_lock
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class FileBackup:
|
|
21
|
+
"""Create a verified archive without replacing a good backup on failure."""
|
|
22
|
+
|
|
23
|
+
FORMATS = {
|
|
24
|
+
"tar": ("w", ".tar", "r"),
|
|
25
|
+
"tar.gz": ("w:gz", ".tar.gz", "r:gz"),
|
|
26
|
+
"tar.zst": ("w:zst", ".tar.zst", "r:zst"),
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
backup_dst: str | Path,
|
|
32
|
+
template_filename: str | Path | None = None,
|
|
33
|
+
chdir: str | Path | None = None,
|
|
34
|
+
format: str = "tar",
|
|
35
|
+
exclude: Iterable[str] | None = None,
|
|
36
|
+
exclude_pattern: Iterable[str] | None = None,
|
|
37
|
+
exclude_templates: Iterable[str] | None = None,
|
|
38
|
+
follow_symlinks: bool = False,
|
|
39
|
+
):
|
|
40
|
+
self.chdir = Path(chdir).expanduser().absolute() if chdir else None
|
|
41
|
+
self.template_filename = Path(template_filename).expanduser() if template_filename else None
|
|
42
|
+
self.backup_paths: list[Path] = []
|
|
43
|
+
self.backup_dst = Path(backup_dst).expanduser().absolute()
|
|
44
|
+
self.format = format
|
|
45
|
+
self.follow_symlinks = follow_symlinks
|
|
46
|
+
base = self.chdir or Path.cwd()
|
|
47
|
+
self.exclude = {(base / Path(e).expanduser()).resolve() for e in (exclude or [])}
|
|
48
|
+
self.exclude_patterns = list(exclude_pattern or [])
|
|
49
|
+
self.exclude_templates = list(exclude_templates or [])
|
|
50
|
+
self._template_matcher = (
|
|
51
|
+
build_matcher(resolve_patterns(self.exclude_templates))
|
|
52
|
+
if self.exclude_templates
|
|
53
|
+
else None
|
|
54
|
+
)
|
|
55
|
+
self.tar: tarfile.TarFile | None = None
|
|
56
|
+
self._pending: Path | None = None
|
|
57
|
+
self._lock = None
|
|
58
|
+
self._expected: list[str] = []
|
|
59
|
+
self.logger = logging.getLogger("bdbackup.file")
|
|
60
|
+
if format not in self.FORMATS:
|
|
61
|
+
raise ValueError(f"Unsupported format {format!r}; choose from {set(self.FORMATS)}")
|
|
62
|
+
if format == "tar.zst" and sys.version_info < (3, 14):
|
|
63
|
+
raise ValueError("tar.zst requires Python 3.14 or newer; use tar or tar.gz")
|
|
64
|
+
self.tar_opt, self.tar_ext, self.tar_read_opt = self.FORMATS[format]
|
|
65
|
+
self.tar_filename = Path(str(self.backup_dst) + self.tar_ext)
|
|
66
|
+
self.lock_filename = Path(str(self.tar_filename) + ".lock")
|
|
67
|
+
if self.backup_dst.is_dir():
|
|
68
|
+
raise IsADirectoryError(f"backup_dst must be a file path: {self.backup_dst}")
|
|
69
|
+
if self.template_filename:
|
|
70
|
+
self.load_template(self.template_filename)
|
|
71
|
+
|
|
72
|
+
def load_template(self, template: str | Path) -> list[Path]:
|
|
73
|
+
template = Path(template).expanduser()
|
|
74
|
+
self.backup_paths = [
|
|
75
|
+
Path(line.strip()).expanduser()
|
|
76
|
+
for line in template.read_text(encoding="utf-8").splitlines()
|
|
77
|
+
if line.strip() and not line.strip().startswith("#")
|
|
78
|
+
]
|
|
79
|
+
return self.backup_paths
|
|
80
|
+
|
|
81
|
+
def open_archive(self) -> tarfile.TarFile:
|
|
82
|
+
"""Open a private staging archive under the destination's process lock."""
|
|
83
|
+
if self.tar is not None:
|
|
84
|
+
return self.tar
|
|
85
|
+
lock = process_lock(self.lock_filename)
|
|
86
|
+
lock.__enter__()
|
|
87
|
+
self._lock = lock
|
|
88
|
+
try:
|
|
89
|
+
fd, name = tempfile.mkstemp(
|
|
90
|
+
prefix=f".{self.tar_filename.name}.",
|
|
91
|
+
suffix=".tmp",
|
|
92
|
+
dir=self.tar_filename.parent,
|
|
93
|
+
)
|
|
94
|
+
os.close(fd)
|
|
95
|
+
self._pending = Path(name)
|
|
96
|
+
self._expected = []
|
|
97
|
+
self.tar = tarfile.open(
|
|
98
|
+
self._pending,
|
|
99
|
+
self.tar_opt,
|
|
100
|
+
dereference=self.follow_symlinks,
|
|
101
|
+
)
|
|
102
|
+
return self.tar
|
|
103
|
+
except BaseException:
|
|
104
|
+
self.close_archive(publish=False)
|
|
105
|
+
raise
|
|
106
|
+
|
|
107
|
+
def close_archive(self, *, publish: bool = True) -> None:
|
|
108
|
+
"""Close, verify and publish; on any error discard only staging output."""
|
|
109
|
+
try:
|
|
110
|
+
if self.tar is not None:
|
|
111
|
+
self.tar.close()
|
|
112
|
+
self.tar = None
|
|
113
|
+
if self._pending is not None and publish:
|
|
114
|
+
self.verify(BackupResult(self._pending))
|
|
115
|
+
with tarfile.open(self._pending, "r:*") as archive:
|
|
116
|
+
if self._expected and archive.getnames() != self._expected:
|
|
117
|
+
raise BackupError("Archive members do not match the selected inputs")
|
|
118
|
+
with self._pending.open("rb") as stream:
|
|
119
|
+
os.fsync(stream.fileno())
|
|
120
|
+
os.replace(self._pending, self.tar_filename)
|
|
121
|
+
finally:
|
|
122
|
+
self.tar = None
|
|
123
|
+
try:
|
|
124
|
+
if self._pending is not None:
|
|
125
|
+
self._pending.unlink(missing_ok=True)
|
|
126
|
+
finally:
|
|
127
|
+
self._pending = None
|
|
128
|
+
if self._lock is not None:
|
|
129
|
+
self._lock.__exit__(None, None, None)
|
|
130
|
+
self._lock = None
|
|
131
|
+
|
|
132
|
+
def _match_roots(self) -> list[Path]:
|
|
133
|
+
if self.chdir:
|
|
134
|
+
return [self.chdir]
|
|
135
|
+
return [self._resolve_path(p) for p in self.backup_paths]
|
|
136
|
+
|
|
137
|
+
def _hard_excluded(self, path: Path) -> bool:
|
|
138
|
+
if path in {self.tar_filename, self.lock_filename, self._pending}:
|
|
139
|
+
return True
|
|
140
|
+
resolved = path.resolve()
|
|
141
|
+
internal = {self.tar_filename.resolve(), self.lock_filename.resolve()}
|
|
142
|
+
if self._pending is not None:
|
|
143
|
+
internal.add(self._pending.resolve())
|
|
144
|
+
if resolved in internal:
|
|
145
|
+
return True
|
|
146
|
+
if any(resolved.is_relative_to(e) for e in self.exclude):
|
|
147
|
+
return True
|
|
148
|
+
roots = self._match_roots()
|
|
149
|
+
candidates = [path]
|
|
150
|
+
for parent in path.parents:
|
|
151
|
+
if any(parent == root or parent.is_relative_to(root) for root in roots):
|
|
152
|
+
candidates.append(parent)
|
|
153
|
+
return any(
|
|
154
|
+
fnmatch.fnmatch(str(candidate), pattern) or fnmatch.fnmatch(candidate.name, pattern)
|
|
155
|
+
for candidate in candidates
|
|
156
|
+
for pattern in self.exclude_patterns
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
def _is_excluded(self, path: Path, is_dir: bool | None = None) -> bool:
|
|
160
|
+
if self._hard_excluded(path):
|
|
161
|
+
return True
|
|
162
|
+
return bool(
|
|
163
|
+
self._template_matcher
|
|
164
|
+
and self._template_matcher.matches(
|
|
165
|
+
path,
|
|
166
|
+
path.is_dir() if is_dir is None else is_dir,
|
|
167
|
+
self._match_roots(),
|
|
168
|
+
)
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
def _resolve_path(self, raw_path: Path) -> Path:
|
|
172
|
+
return Path(os.path.abspath((self.chdir or Path.cwd()) / raw_path))
|
|
173
|
+
|
|
174
|
+
@staticmethod
|
|
175
|
+
def _make_arcname(path: Path, base: Path | None) -> str:
|
|
176
|
+
# Keep the lexical name: resolving symlinks changes names and creates collisions.
|
|
177
|
+
if base is not None:
|
|
178
|
+
try:
|
|
179
|
+
return path.relative_to(base).as_posix()
|
|
180
|
+
except ValueError:
|
|
181
|
+
pass
|
|
182
|
+
return path.as_posix().lstrip("/")
|
|
183
|
+
|
|
184
|
+
def _walk(self) -> Iterable[tuple[Path, str]]:
|
|
185
|
+
emitted: set[str] = set()
|
|
186
|
+
|
|
187
|
+
def visit(path: Path, ancestors: frozenset[tuple[int, int]], base: Path | None):
|
|
188
|
+
if self._hard_excluded(path):
|
|
189
|
+
return
|
|
190
|
+
info = path.stat() if self.follow_symlinks else path.lstat()
|
|
191
|
+
is_dir = stat.S_ISDIR(info.st_mode)
|
|
192
|
+
if not (is_dir or stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode)):
|
|
193
|
+
raise BackupError(f"Unsupported special input file: {path}")
|
|
194
|
+
excluded = self._is_excluded(path, is_dir)
|
|
195
|
+
arcname = self._make_arcname(path, base)
|
|
196
|
+
if not excluded and arcname not in emitted:
|
|
197
|
+
emitted.add(arcname)
|
|
198
|
+
yield path, arcname
|
|
199
|
+
if not is_dir:
|
|
200
|
+
return
|
|
201
|
+
if excluded and not (self._template_matcher and self._template_matcher.has_negations):
|
|
202
|
+
return
|
|
203
|
+
inode = (info.st_dev, info.st_ino)
|
|
204
|
+
if inode in ancestors:
|
|
205
|
+
raise BackupError(f"Symlink directory cycle: {path}")
|
|
206
|
+
with os.scandir(path) as entries:
|
|
207
|
+
children = sorted(entry.name for entry in entries)
|
|
208
|
+
for name in children:
|
|
209
|
+
yield from visit(path / name, ancestors | {inode}, base)
|
|
210
|
+
|
|
211
|
+
for raw_path in self.backup_paths:
|
|
212
|
+
base = self.chdir or (None if raw_path.is_absolute() else Path.cwd())
|
|
213
|
+
yield from visit(self._resolve_path(raw_path), frozenset(), base)
|
|
214
|
+
|
|
215
|
+
def backup(self, *, debug: bool = False, dry_run: bool = False) -> BackupResult:
|
|
216
|
+
if not self.backup_paths:
|
|
217
|
+
self.close_archive(publish=False)
|
|
218
|
+
raise BackupError("No backup paths selected; the template is empty")
|
|
219
|
+
total_size = count = 0
|
|
220
|
+
try:
|
|
221
|
+
if not dry_run:
|
|
222
|
+
self.open_archive()
|
|
223
|
+
for path, arcname in self._walk():
|
|
224
|
+
if debug or dry_run:
|
|
225
|
+
self.logger.info("Would back up: %s -> %s", path, arcname)
|
|
226
|
+
before = path.stat() if self.follow_symlinks else path.lstat()
|
|
227
|
+
if not dry_run:
|
|
228
|
+
self.tar.add(path, arcname=arcname, recursive=False)
|
|
229
|
+
after = path.stat() if self.follow_symlinks else path.lstat()
|
|
230
|
+
if stat.S_ISREG(before.st_mode) and (
|
|
231
|
+
before.st_size,
|
|
232
|
+
before.st_mtime_ns,
|
|
233
|
+
before.st_ino,
|
|
234
|
+
) != (after.st_size, after.st_mtime_ns, after.st_ino):
|
|
235
|
+
raise BackupError(f"Input changed during backup: {path}")
|
|
236
|
+
self._expected.append(arcname)
|
|
237
|
+
count += 1
|
|
238
|
+
total_size += before.st_size if stat.S_ISREG(before.st_mode) else 0
|
|
239
|
+
if not count:
|
|
240
|
+
raise BackupError("No archive members selected after exclusions")
|
|
241
|
+
if not dry_run:
|
|
242
|
+
self.close_archive()
|
|
243
|
+
except BaseException:
|
|
244
|
+
self.close_archive(publish=False)
|
|
245
|
+
raise
|
|
246
|
+
return BackupResult(
|
|
247
|
+
self.tar_filename,
|
|
248
|
+
size_bytes=total_size if dry_run else self.tar_filename.stat().st_size,
|
|
249
|
+
success=True,
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
def verify(self, result: BackupResult | None = None) -> BackupResult:
|
|
253
|
+
archive = result.path if result else self.tar_filename
|
|
254
|
+
try:
|
|
255
|
+
with tarfile.open(archive, "r:*") as tar:
|
|
256
|
+
count = 0
|
|
257
|
+
for member in tar:
|
|
258
|
+
count += 1
|
|
259
|
+
if member.isfile():
|
|
260
|
+
with tar.extractfile(member) as stream:
|
|
261
|
+
while stream.read(1024 * 1024):
|
|
262
|
+
pass
|
|
263
|
+
if not count:
|
|
264
|
+
raise BackupError(f"Archive {archive} contains no members")
|
|
265
|
+
# Consume the compressed trailer too, so gzip/zstd corruption is surfaced.
|
|
266
|
+
while tar.fileobj.read(1024 * 1024):
|
|
267
|
+
pass
|
|
268
|
+
except (tarfile.TarError, OSError, EOFError) as exc:
|
|
269
|
+
raise BackupError(f"Archive verification failed for {archive}: {exc}") from exc
|
|
270
|
+
return BackupResult(archive, size_bytes=archive.stat().st_size, success=True)
|
|
271
|
+
|
|
272
|
+
def prune(self) -> list[Path]:
|
|
273
|
+
return []
|
|
274
|
+
|
|
275
|
+
@staticmethod
|
|
276
|
+
def _restore_filter(member: tarfile.TarInfo, destination: str) -> tarfile.TarInfo:
|
|
277
|
+
if PurePosixPath(member.name).is_absolute() or ".." in PurePosixPath(member.name).parts:
|
|
278
|
+
raise BackupError(f"Unsafe archive member path: {member.name}")
|
|
279
|
+
filtered = tarfile.data_filter(member, destination)
|
|
280
|
+
# Preserve ordinary directory permissions; discard special permission bits.
|
|
281
|
+
if filtered.isdir():
|
|
282
|
+
filtered.mode = member.mode & 0o777
|
|
283
|
+
return filtered
|
|
284
|
+
|
|
285
|
+
@classmethod
|
|
286
|
+
def restore_archive(cls, archive: str | Path, extract_dir: str | Path) -> Path:
|
|
287
|
+
"""Restore safe files, directories and contained links on every supported Python."""
|
|
288
|
+
dest = Path(extract_dir).expanduser()
|
|
289
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
290
|
+
try:
|
|
291
|
+
with tarfile.open(Path(archive).expanduser(), "r:*") as tar:
|
|
292
|
+
# extractall restores directory metadata after its children.
|
|
293
|
+
tar.extractall(dest, filter=cls._restore_filter) # noqa: S202
|
|
294
|
+
except (tarfile.TarError, OSError, EOFError) as exc:
|
|
295
|
+
raise BackupError(f"Restore failed: {exc}") from exc
|
|
296
|
+
return dest
|
|
297
|
+
|
|
298
|
+
def restore(self, extract_dir: str | Path, archive: str | Path | None = None) -> Path:
|
|
299
|
+
return self.restore_archive(archive or self.tar_filename, extract_dir)
|
|
300
|
+
|
|
301
|
+
def __enter__(self) -> FileBackup:
|
|
302
|
+
return self
|
|
303
|
+
|
|
304
|
+
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
|
|
305
|
+
self.close_archive(publish=exc_type is None)
|