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/cli.py
ADDED
|
@@ -0,0 +1,1045 @@
|
|
|
1
|
+
"""Command-line interface for bdbackup."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import click
|
|
12
|
+
|
|
13
|
+
from bdbackup import __version__, retention
|
|
14
|
+
from bdbackup.backends import BackupError, BackupResult, setup_logging
|
|
15
|
+
from bdbackup.config import Config, ConfigError, build_backend
|
|
16
|
+
from bdbackup.filebackup import FileBackup
|
|
17
|
+
from bdbackup.history import History
|
|
18
|
+
from bdbackup.mysql import MySQLBackup, XtraBackup
|
|
19
|
+
from bdbackup.recovery import backup_restore_info, restore_record, suggested_destination
|
|
20
|
+
from bdbackup.scheduling import recommend_cron
|
|
21
|
+
from bdbackup.templates import TemplateError
|
|
22
|
+
from bdbackup.validation import validate_config
|
|
23
|
+
|
|
24
|
+
# Exit-code contract: 0 ok, 1 backup/verify failure, 2 usage, 3 locked.
|
|
25
|
+
EXIT_OK = 0
|
|
26
|
+
EXIT_BACKUP_FAILED = 1
|
|
27
|
+
EXIT_USAGE = 2
|
|
28
|
+
EXIT_LOCKED = 3
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@click.group(name="bdbackup", invoke_without_command=True, no_args_is_help=True)
|
|
32
|
+
@click.version_option(version=__version__, prog_name="bdbackup")
|
|
33
|
+
@click.option(
|
|
34
|
+
"--config", "config_path", type=click.Path(exists=True, dir_okay=False, path_type=Path),
|
|
35
|
+
help="TOML configuration; enables configured history for direct backup commands.",
|
|
36
|
+
)
|
|
37
|
+
@click.option(
|
|
38
|
+
"--logging",
|
|
39
|
+
"log_level",
|
|
40
|
+
default="INFO",
|
|
41
|
+
type=click.Choice(["DEBUG", "INFO", "WARNING", "ERROR"], case_sensitive=False),
|
|
42
|
+
help="Log level: DEBUG, INFO, WARNING, ERROR.",
|
|
43
|
+
)
|
|
44
|
+
@click.pass_context
|
|
45
|
+
@click.option("--validate", "validate_only", is_flag=True,
|
|
46
|
+
help="Check configured settings, filesystem access and MySQL grants; do not back up.")
|
|
47
|
+
@click.option("--cron", "cron_only", is_flag=True,
|
|
48
|
+
help="Read crontab -l and recommend entries for configured jobs; do not install.")
|
|
49
|
+
def main(
|
|
50
|
+
ctx: click.Context, log_level: str, config_path: Path | None,
|
|
51
|
+
validate_only: bool, cron_only: bool,
|
|
52
|
+
) -> None:
|
|
53
|
+
"""Backups by design.
|
|
54
|
+
|
|
55
|
+
File and MySQL/MariaDB backups with verification, retention, and guided recovery.
|
|
56
|
+
"""
|
|
57
|
+
setup_logging(getattr(logging, log_level.upper(), logging.INFO))
|
|
58
|
+
ctx.ensure_object(dict)
|
|
59
|
+
ctx.obj["log_level"] = log_level
|
|
60
|
+
try:
|
|
61
|
+
ctx.obj["config"] = Config(config_path) if config_path else None
|
|
62
|
+
except ConfigError as exc:
|
|
63
|
+
raise click.UsageError(str(exc)) from exc
|
|
64
|
+
if validate_only or cron_only:
|
|
65
|
+
if ctx.invoked_subcommand:
|
|
66
|
+
raise click.UsageError("Use global --validate/--cron without a subcommand, "
|
|
67
|
+
"or put these options after run")
|
|
68
|
+
config = _get_config(required=True)
|
|
69
|
+
ctx.exit(_configuration_helpers(config, list(config.jobs.values()),
|
|
70
|
+
validate_only, cron_only))
|
|
71
|
+
if ctx.invoked_subcommand is None:
|
|
72
|
+
click.echo(ctx.get_help())
|
|
73
|
+
ctx.exit(EXIT_USAGE)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _configuration_helpers(config, jobs, validate_only, cron_only) -> int:
|
|
77
|
+
ok = True
|
|
78
|
+
if not jobs:
|
|
79
|
+
raise click.UsageError("No configured jobs selected")
|
|
80
|
+
for enabled, helper in ((validate_only, validate_config), (cron_only, recommend_cron)):
|
|
81
|
+
if enabled:
|
|
82
|
+
lines, success = helper(config, jobs)
|
|
83
|
+
click.echo("\n".join(lines))
|
|
84
|
+
ok = ok and success
|
|
85
|
+
return EXIT_OK if ok else EXIT_BACKUP_FAILED
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _get_config(path: Path | None = None, *, required: bool = False) -> Config | None:
|
|
89
|
+
config = Config(path) if path else click.get_current_context().obj.get("config")
|
|
90
|
+
if required and config is None:
|
|
91
|
+
raise click.UsageError("Provide --config with a TOML configuration file")
|
|
92
|
+
return config
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _tracked_backup(config, name, backup_type, action, restore_info=None, *, encrypted=False):
|
|
96
|
+
if config and config.history:
|
|
97
|
+
return History(config.history).run(
|
|
98
|
+
name, backup_type, action, restore_info, encrypted=encrypted,
|
|
99
|
+
)
|
|
100
|
+
return action()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _protect_history(backend, config):
|
|
104
|
+
if config and config.history and isinstance(backend, FileBackup):
|
|
105
|
+
database = config.history.database
|
|
106
|
+
excluded = {Path(str(database) + suffix) for suffix in ("", "-journal", "-wal", "-shm")}
|
|
107
|
+
if backend.tar_filename.resolve() in excluded:
|
|
108
|
+
raise BackupError("Archive destination conflicts with the history database")
|
|
109
|
+
backend.exclude.update(excluded)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _handle_errors(func, *args, **kwargs) -> int:
|
|
113
|
+
"""Wrap a command body in the exit-code contract."""
|
|
114
|
+
try:
|
|
115
|
+
func(*args, **kwargs)
|
|
116
|
+
except (click.ClickException, click.Abort):
|
|
117
|
+
raise
|
|
118
|
+
except BlockingIOError as exc:
|
|
119
|
+
logging.getLogger("bdbackup.cli").error("Another backup is already running: %s", exc)
|
|
120
|
+
click.get_current_context().exit(EXIT_LOCKED)
|
|
121
|
+
except (ConfigError, TemplateError, ValueError, TypeError) as exc:
|
|
122
|
+
raise click.UsageError(str(exc)) from exc
|
|
123
|
+
except BackupError as exc:
|
|
124
|
+
logging.getLogger("bdbackup.cli").error("Backup/verify failed: %s", exc)
|
|
125
|
+
click.get_current_context().exit(EXIT_BACKUP_FAILED)
|
|
126
|
+
except subprocess.CalledProcessError as exc:
|
|
127
|
+
logging.getLogger("bdbackup.cli").error("External command failed: %s", exc)
|
|
128
|
+
click.get_current_context().exit(EXIT_BACKUP_FAILED)
|
|
129
|
+
except Exception as exc: # pragma: no cover - safety net
|
|
130
|
+
logging.getLogger("bdbackup.cli").exception("Unexpected error: %s", exc)
|
|
131
|
+
click.get_current_context().exit(EXIT_BACKUP_FAILED)
|
|
132
|
+
return EXIT_OK
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@main.command()
|
|
136
|
+
@click.option(
|
|
137
|
+
"--template",
|
|
138
|
+
required=True,
|
|
139
|
+
type=click.Path(exists=True, dir_okay=False, path_type=Path),
|
|
140
|
+
help="Template file listing paths to archive.",
|
|
141
|
+
)
|
|
142
|
+
@click.option(
|
|
143
|
+
"-d",
|
|
144
|
+
"--dst",
|
|
145
|
+
required=True,
|
|
146
|
+
type=click.Path(path_type=Path),
|
|
147
|
+
help="Destination archive path (without extension).",
|
|
148
|
+
)
|
|
149
|
+
@click.option(
|
|
150
|
+
"-c",
|
|
151
|
+
"--chdir",
|
|
152
|
+
type=click.Path(exists=True, file_okay=False, path_type=Path),
|
|
153
|
+
help="Resolve template paths against this directory.",
|
|
154
|
+
)
|
|
155
|
+
@click.option("-z", "--compress/--no-compress", default=False, help="Gzip-compress the archive.")
|
|
156
|
+
@click.option(
|
|
157
|
+
"-f",
|
|
158
|
+
"--format",
|
|
159
|
+
"archive_format",
|
|
160
|
+
default="tar",
|
|
161
|
+
show_default=True,
|
|
162
|
+
type=click.Choice(["tar", "tar.gz", "tar.zst"], case_sensitive=False),
|
|
163
|
+
help="Archive format.",
|
|
164
|
+
)
|
|
165
|
+
@click.option("-x", "--exclude", multiple=True, help="Path/pattern to exclude; can be repeated.")
|
|
166
|
+
@click.option(
|
|
167
|
+
"--exclude-pattern",
|
|
168
|
+
multiple=True,
|
|
169
|
+
help="Glob pattern to exclude; can be repeated.",
|
|
170
|
+
)
|
|
171
|
+
@click.option(
|
|
172
|
+
"--exclude-template",
|
|
173
|
+
"exclude_templates",
|
|
174
|
+
multiple=True,
|
|
175
|
+
metavar="NAME",
|
|
176
|
+
help=(
|
|
177
|
+
"Named exclusion template (e.g. python-dev); can be repeated or "
|
|
178
|
+
"comma-separated. User templates live in ~/.config/bdbackup/templates/."
|
|
179
|
+
),
|
|
180
|
+
)
|
|
181
|
+
@click.option(
|
|
182
|
+
"--follow-symlinks/--no-follow-symlinks",
|
|
183
|
+
default=False,
|
|
184
|
+
show_default=True,
|
|
185
|
+
help="Follow symbolic links when archiving directories.",
|
|
186
|
+
)
|
|
187
|
+
@click.option(
|
|
188
|
+
"--dry-run",
|
|
189
|
+
is_flag=True,
|
|
190
|
+
help="List what would be archived without writing anything.",
|
|
191
|
+
)
|
|
192
|
+
@click.option(
|
|
193
|
+
"--verify/--no-verify",
|
|
194
|
+
default=True,
|
|
195
|
+
show_default=True,
|
|
196
|
+
help="Verify the archive after creation.",
|
|
197
|
+
)
|
|
198
|
+
def file(
|
|
199
|
+
template: Path,
|
|
200
|
+
dst: Path,
|
|
201
|
+
chdir: Path | None,
|
|
202
|
+
compress: bool,
|
|
203
|
+
archive_format: str,
|
|
204
|
+
exclude: tuple[str, ...],
|
|
205
|
+
exclude_pattern: tuple[str, ...],
|
|
206
|
+
exclude_templates: tuple[str, ...],
|
|
207
|
+
follow_symlinks: bool,
|
|
208
|
+
dry_run: bool,
|
|
209
|
+
verify: bool,
|
|
210
|
+
) -> int:
|
|
211
|
+
"""Create a tar archive from a template file listing paths."""
|
|
212
|
+
log_level = click.get_current_context().obj.get("log_level", "INFO")
|
|
213
|
+
debug = log_level == "DEBUG"
|
|
214
|
+
template_names = [
|
|
215
|
+
n.strip() for group in exclude_templates for n in group.split(",") if n.strip()
|
|
216
|
+
]
|
|
217
|
+
config = _get_config()
|
|
218
|
+
|
|
219
|
+
def _create() -> BackupResult:
|
|
220
|
+
try:
|
|
221
|
+
fb = FileBackup(
|
|
222
|
+
backup_dst=dst,
|
|
223
|
+
template_filename=template,
|
|
224
|
+
chdir=chdir,
|
|
225
|
+
format="tar.gz" if compress else archive_format,
|
|
226
|
+
exclude=exclude,
|
|
227
|
+
exclude_pattern=exclude_pattern,
|
|
228
|
+
exclude_templates=template_names,
|
|
229
|
+
follow_symlinks=follow_symlinks,
|
|
230
|
+
)
|
|
231
|
+
except TemplateError as exc:
|
|
232
|
+
raise click.UsageError(str(exc)) from exc
|
|
233
|
+
_protect_history(fb, config)
|
|
234
|
+
try:
|
|
235
|
+
result = fb.backup(debug=debug, dry_run=dry_run)
|
|
236
|
+
if verify and not dry_run:
|
|
237
|
+
fb.verify(result)
|
|
238
|
+
finally:
|
|
239
|
+
fb.close_archive()
|
|
240
|
+
if dry_run:
|
|
241
|
+
click.echo(f"Dry run; would create: {fb.tar_filename}")
|
|
242
|
+
else:
|
|
243
|
+
click.echo(f"Archive created: {fb.tar_filename}")
|
|
244
|
+
return result
|
|
245
|
+
|
|
246
|
+
return _handle_errors(
|
|
247
|
+
lambda: _tracked_backup(
|
|
248
|
+
None if dry_run else config, dst.name, "file", _create, {"kind": "file"},
|
|
249
|
+
)
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
@main.command()
|
|
254
|
+
@click.option("--database", required=False, help="Database name to dump (ignored when --full).")
|
|
255
|
+
@click.option(
|
|
256
|
+
"-o",
|
|
257
|
+
"--out-dir",
|
|
258
|
+
default=".",
|
|
259
|
+
show_default=True,
|
|
260
|
+
type=click.Path(file_okay=False, path_type=Path),
|
|
261
|
+
help="Directory for the dump file.",
|
|
262
|
+
)
|
|
263
|
+
@click.option("-u", "--user", default="root", show_default=True, help="MySQL user.")
|
|
264
|
+
@click.option(
|
|
265
|
+
"-p",
|
|
266
|
+
"--password",
|
|
267
|
+
default=None,
|
|
268
|
+
prompt="MySQL password",
|
|
269
|
+
prompt_required=False,
|
|
270
|
+
hide_input=True,
|
|
271
|
+
is_flag=False,
|
|
272
|
+
help="MySQL password. If given without a value, you are prompted securely.",
|
|
273
|
+
)
|
|
274
|
+
@click.option("-h", "--host", default="localhost", show_default=True, help="MySQL host.")
|
|
275
|
+
@click.option("-P", "--port", default=3306, show_default=True, type=int, help="MySQL port.")
|
|
276
|
+
@click.option(
|
|
277
|
+
"--options",
|
|
278
|
+
default="",
|
|
279
|
+
show_default=True,
|
|
280
|
+
help="Additional comma-separated mysqldump options (safe defaults are retained).",
|
|
281
|
+
)
|
|
282
|
+
@click.option("--full/--no-full", default=False, help="Add --all-databases and dump everything.")
|
|
283
|
+
@click.option(
|
|
284
|
+
"-j",
|
|
285
|
+
"--jobs",
|
|
286
|
+
default=1,
|
|
287
|
+
show_default=True,
|
|
288
|
+
type=click.IntRange(min=1),
|
|
289
|
+
help="Parallel dumps when multiple databases are specified.",
|
|
290
|
+
)
|
|
291
|
+
@click.option(
|
|
292
|
+
"--verify/--no-verify",
|
|
293
|
+
default=True,
|
|
294
|
+
show_default=True,
|
|
295
|
+
help="Verify the dump after creation.",
|
|
296
|
+
)
|
|
297
|
+
def mysqldump(
|
|
298
|
+
database: str | None,
|
|
299
|
+
out_dir: Path,
|
|
300
|
+
user: str,
|
|
301
|
+
password: str | None,
|
|
302
|
+
host: str,
|
|
303
|
+
port: int,
|
|
304
|
+
options: str,
|
|
305
|
+
full: bool,
|
|
306
|
+
jobs: int,
|
|
307
|
+
verify: bool,
|
|
308
|
+
) -> int:
|
|
309
|
+
"""Dump a MySQL database with mysqldump."""
|
|
310
|
+
if not full and not database:
|
|
311
|
+
raise click.UsageError("--database is required unless --full is used.")
|
|
312
|
+
opts = [option.strip() for option in options.split(",") if option.strip()]
|
|
313
|
+
if full:
|
|
314
|
+
opts.append("--all-databases")
|
|
315
|
+
databases = [db.strip() for db in (database or "").split(",") if db.strip()]
|
|
316
|
+
if not full and not databases:
|
|
317
|
+
raise click.UsageError("Provide at least one database name")
|
|
318
|
+
config = _get_config()
|
|
319
|
+
|
|
320
|
+
def _backend():
|
|
321
|
+
return MySQLBackup(
|
|
322
|
+
out_dir=out_dir,
|
|
323
|
+
user=user,
|
|
324
|
+
password=password,
|
|
325
|
+
host=host,
|
|
326
|
+
port=port,
|
|
327
|
+
options=opts,
|
|
328
|
+
jobs=jobs,
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
def _run() -> None:
|
|
332
|
+
if config and config.history:
|
|
333
|
+
# Each worker owns its history transactions, so partial batch failures
|
|
334
|
+
# cannot hide the successful dumps from the other workers.
|
|
335
|
+
def _one(db):
|
|
336
|
+
def _create():
|
|
337
|
+
mb = _backend()
|
|
338
|
+
result = mb.backup(db)
|
|
339
|
+
if verify:
|
|
340
|
+
mb.verify(result)
|
|
341
|
+
return result
|
|
342
|
+
|
|
343
|
+
return _tracked_backup(
|
|
344
|
+
config, db or "all-databases", "mysqldump", _create, {"kind": "mysqldump"},
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
failures = []
|
|
348
|
+
with ThreadPoolExecutor(max_workers=jobs) as pool:
|
|
349
|
+
futures = [pool.submit(_one, db) for db in ([None] if full else databases)]
|
|
350
|
+
for future in as_completed(futures):
|
|
351
|
+
try:
|
|
352
|
+
click.echo(f"Dump written to: {future.result().path}")
|
|
353
|
+
except Exception as exc:
|
|
354
|
+
failures.append(exc)
|
|
355
|
+
if failures:
|
|
356
|
+
raise failures[0]
|
|
357
|
+
return
|
|
358
|
+
mb = _backend()
|
|
359
|
+
results = [mb.backup(None)] if full else mb.backup_all(databases)
|
|
360
|
+
for result in results:
|
|
361
|
+
if verify:
|
|
362
|
+
mb.verify(result)
|
|
363
|
+
click.echo(f"Dump written to: {result.path}")
|
|
364
|
+
|
|
365
|
+
return _handle_errors(_run)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
@main.group(invoke_without_command=False)
|
|
369
|
+
def xtrabackup() -> None:
|
|
370
|
+
"""Run or manage xtrabackup/mariabackup physical backups."""
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
@xtrabackup.command(name="full")
|
|
374
|
+
@click.option("--database", required=True, help="Database name (used for directory naming).")
|
|
375
|
+
@click.option(
|
|
376
|
+
"-r",
|
|
377
|
+
"--root",
|
|
378
|
+
"backup_root",
|
|
379
|
+
required=True,
|
|
380
|
+
type=click.Path(file_okay=False, path_type=Path),
|
|
381
|
+
help="Backup root directory.",
|
|
382
|
+
)
|
|
383
|
+
@click.option("-u", "--user", default="xtrabackup", show_default=True, help="MySQL user.")
|
|
384
|
+
@click.option(
|
|
385
|
+
"-p",
|
|
386
|
+
"--password",
|
|
387
|
+
default=None,
|
|
388
|
+
prompt="MySQL password",
|
|
389
|
+
prompt_required=False,
|
|
390
|
+
hide_input=True,
|
|
391
|
+
is_flag=False,
|
|
392
|
+
help="MySQL password. If given without a value, you are prompted securely.",
|
|
393
|
+
)
|
|
394
|
+
@click.option(
|
|
395
|
+
"-b",
|
|
396
|
+
"--binary",
|
|
397
|
+
default="xtrabackup",
|
|
398
|
+
show_default=True,
|
|
399
|
+
help="Backup binary (xtrabackup or mariabackup).",
|
|
400
|
+
)
|
|
401
|
+
@click.option("--encrypt/--no-encrypt", default=False,
|
|
402
|
+
help="Encrypt with AES256; requires a key file.")
|
|
403
|
+
@click.option("--encrypt-key-file", type=click.Path(dir_okay=False, path_type=Path),
|
|
404
|
+
help="32-byte AES256 key file (e.g. /etc/mysql/xtrabackup.key).")
|
|
405
|
+
@click.option("--compress", default="", help="Compression algorithm; default: uncompressed.")
|
|
406
|
+
@click.option(
|
|
407
|
+
"--compress-threads",
|
|
408
|
+
default=4,
|
|
409
|
+
show_default=True,
|
|
410
|
+
type=click.IntRange(min=1),
|
|
411
|
+
help="Number of compression threads.",
|
|
412
|
+
)
|
|
413
|
+
@click.option(
|
|
414
|
+
"--parallel",
|
|
415
|
+
default=1,
|
|
416
|
+
show_default=True,
|
|
417
|
+
type=click.IntRange(min=1),
|
|
418
|
+
help="Number of copy threads.",
|
|
419
|
+
)
|
|
420
|
+
@click.option(
|
|
421
|
+
"--throttle",
|
|
422
|
+
default=None,
|
|
423
|
+
type=click.IntRange(min=1),
|
|
424
|
+
help="Limit I/O to this many IOPS.",
|
|
425
|
+
)
|
|
426
|
+
@click.option(
|
|
427
|
+
"--retention",
|
|
428
|
+
default=5,
|
|
429
|
+
show_default=True,
|
|
430
|
+
type=click.IntRange(min=1),
|
|
431
|
+
help="Retention in days.",
|
|
432
|
+
)
|
|
433
|
+
@click.option(
|
|
434
|
+
"--verify/--no-verify",
|
|
435
|
+
default=True,
|
|
436
|
+
show_default=True,
|
|
437
|
+
help="Verify the backup after creation.",
|
|
438
|
+
)
|
|
439
|
+
def xtrabackup_full(
|
|
440
|
+
database: str,
|
|
441
|
+
backup_root: Path,
|
|
442
|
+
user: str,
|
|
443
|
+
password: str | None,
|
|
444
|
+
binary: str,
|
|
445
|
+
encrypt: bool,
|
|
446
|
+
encrypt_key_file: Path | None,
|
|
447
|
+
compress: str,
|
|
448
|
+
compress_threads: int,
|
|
449
|
+
parallel: int,
|
|
450
|
+
throttle: int | None,
|
|
451
|
+
retention: int,
|
|
452
|
+
verify: bool,
|
|
453
|
+
) -> int:
|
|
454
|
+
"""Run a full physical backup."""
|
|
455
|
+
config = _get_config()
|
|
456
|
+
info = {"kind": "xtrabackup", "backup_root": str((backup_root / database).resolve()),
|
|
457
|
+
"binary": binary}
|
|
458
|
+
|
|
459
|
+
def _create() -> BackupResult:
|
|
460
|
+
xb = XtraBackup(
|
|
461
|
+
backup_root=backup_root / database,
|
|
462
|
+
user=user,
|
|
463
|
+
password=password,
|
|
464
|
+
binary=binary,
|
|
465
|
+
encrypt=encrypt,
|
|
466
|
+
encrypt_key_file=encrypt_key_file,
|
|
467
|
+
compress=compress,
|
|
468
|
+
compress_threads=compress_threads,
|
|
469
|
+
parallel=parallel,
|
|
470
|
+
throttle=throttle,
|
|
471
|
+
retention_days=retention,
|
|
472
|
+
)
|
|
473
|
+
info.update(backup_restore_info(xb))
|
|
474
|
+
result = xb.full_backup()
|
|
475
|
+
if verify:
|
|
476
|
+
xb.verify(result)
|
|
477
|
+
click.echo(f"Backup written to: {result.path}")
|
|
478
|
+
return result
|
|
479
|
+
|
|
480
|
+
return _handle_errors(
|
|
481
|
+
lambda: _tracked_backup(
|
|
482
|
+
config, database, "xtrabackup-full", _create, info, encrypted=encrypt,
|
|
483
|
+
)
|
|
484
|
+
)
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
@xtrabackup.command(name="incremental")
|
|
488
|
+
@click.option("--database", required=True, help="Database name (used for directory naming).")
|
|
489
|
+
@click.option(
|
|
490
|
+
"-r",
|
|
491
|
+
"--root",
|
|
492
|
+
"backup_root",
|
|
493
|
+
required=True,
|
|
494
|
+
type=click.Path(file_okay=False, path_type=Path),
|
|
495
|
+
help="Backup root directory.",
|
|
496
|
+
)
|
|
497
|
+
@click.option("-u", "--user", default="xtrabackup", show_default=True, help="MySQL user.")
|
|
498
|
+
@click.option(
|
|
499
|
+
"-p",
|
|
500
|
+
"--password",
|
|
501
|
+
default=None,
|
|
502
|
+
prompt="MySQL password",
|
|
503
|
+
prompt_required=False,
|
|
504
|
+
hide_input=True,
|
|
505
|
+
is_flag=False,
|
|
506
|
+
help="MySQL password. If given without a value, you are prompted securely.",
|
|
507
|
+
)
|
|
508
|
+
@click.option(
|
|
509
|
+
"-b",
|
|
510
|
+
"--binary",
|
|
511
|
+
default="xtrabackup",
|
|
512
|
+
show_default=True,
|
|
513
|
+
help="Backup binary (xtrabackup or mariabackup).",
|
|
514
|
+
)
|
|
515
|
+
@click.option("--encrypt/--no-encrypt", default=False,
|
|
516
|
+
help="Encrypt with AES256; requires a key file.")
|
|
517
|
+
@click.option("--encrypt-key-file", type=click.Path(dir_okay=False, path_type=Path),
|
|
518
|
+
help="32-byte AES256 key file (e.g. /etc/mysql/xtrabackup.key).")
|
|
519
|
+
@click.option("--compress", default="", help="Compression algorithm; default: uncompressed.")
|
|
520
|
+
@click.option(
|
|
521
|
+
"--compress-threads",
|
|
522
|
+
default=4,
|
|
523
|
+
show_default=True,
|
|
524
|
+
type=click.IntRange(min=1),
|
|
525
|
+
help="Number of compression threads.",
|
|
526
|
+
)
|
|
527
|
+
@click.option(
|
|
528
|
+
"--parallel",
|
|
529
|
+
default=1,
|
|
530
|
+
show_default=True,
|
|
531
|
+
type=click.IntRange(min=1),
|
|
532
|
+
help="Number of copy threads.",
|
|
533
|
+
)
|
|
534
|
+
@click.option(
|
|
535
|
+
"--throttle",
|
|
536
|
+
default=None,
|
|
537
|
+
type=click.IntRange(min=1),
|
|
538
|
+
help="Limit I/O to this many IOPS.",
|
|
539
|
+
)
|
|
540
|
+
@click.option(
|
|
541
|
+
"--verify/--no-verify",
|
|
542
|
+
default=True,
|
|
543
|
+
show_default=True,
|
|
544
|
+
help="Verify the backup after creation.",
|
|
545
|
+
)
|
|
546
|
+
def xtrabackup_incremental(
|
|
547
|
+
database: str,
|
|
548
|
+
backup_root: Path,
|
|
549
|
+
user: str,
|
|
550
|
+
password: str | None,
|
|
551
|
+
binary: str,
|
|
552
|
+
encrypt: bool,
|
|
553
|
+
encrypt_key_file: Path | None,
|
|
554
|
+
compress: str,
|
|
555
|
+
compress_threads: int,
|
|
556
|
+
parallel: int,
|
|
557
|
+
throttle: int | None,
|
|
558
|
+
verify: bool,
|
|
559
|
+
) -> int:
|
|
560
|
+
"""Run an incremental physical backup based on the latest full."""
|
|
561
|
+
config = _get_config()
|
|
562
|
+
info = {"kind": "xtrabackup", "backup_root": str((backup_root / database).resolve()),
|
|
563
|
+
"binary": binary}
|
|
564
|
+
|
|
565
|
+
def _create() -> BackupResult:
|
|
566
|
+
xb = XtraBackup(
|
|
567
|
+
backup_root=backup_root / database,
|
|
568
|
+
user=user,
|
|
569
|
+
password=password,
|
|
570
|
+
binary=binary,
|
|
571
|
+
encrypt=encrypt,
|
|
572
|
+
encrypt_key_file=encrypt_key_file,
|
|
573
|
+
compress=compress,
|
|
574
|
+
compress_threads=compress_threads,
|
|
575
|
+
parallel=parallel,
|
|
576
|
+
throttle=throttle,
|
|
577
|
+
)
|
|
578
|
+
info.update(backup_restore_info(xb))
|
|
579
|
+
result = xb.incremental_backup()
|
|
580
|
+
if verify:
|
|
581
|
+
xb.verify(result)
|
|
582
|
+
click.echo(f"Backup written to: {result.path}")
|
|
583
|
+
return result
|
|
584
|
+
|
|
585
|
+
return _handle_errors(
|
|
586
|
+
lambda: _tracked_backup(
|
|
587
|
+
config, database, "xtrabackup-incremental", _create, info, encrypted=encrypt,
|
|
588
|
+
)
|
|
589
|
+
)
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
@xtrabackup.command(name="prune")
|
|
593
|
+
@click.option("--database", required=True, help="Database name (used for directory naming).")
|
|
594
|
+
@click.option(
|
|
595
|
+
"-r",
|
|
596
|
+
"--root",
|
|
597
|
+
"backup_root",
|
|
598
|
+
required=True,
|
|
599
|
+
type=click.Path(file_okay=False, path_type=Path),
|
|
600
|
+
help="Backup root directory.",
|
|
601
|
+
)
|
|
602
|
+
@click.option(
|
|
603
|
+
"--retention",
|
|
604
|
+
default=5,
|
|
605
|
+
show_default=True,
|
|
606
|
+
type=click.IntRange(min=1),
|
|
607
|
+
help="Retention in days.",
|
|
608
|
+
)
|
|
609
|
+
def xtrabackup_prune(
|
|
610
|
+
database: str,
|
|
611
|
+
backup_root: Path,
|
|
612
|
+
retention: int,
|
|
613
|
+
) -> int:
|
|
614
|
+
"""Remove backup directories older than retention days."""
|
|
615
|
+
xb = XtraBackup(
|
|
616
|
+
backup_root=backup_root / database,
|
|
617
|
+
retention_days=retention,
|
|
618
|
+
)
|
|
619
|
+
return _handle_errors(lambda: click.echo(f"Pruned {len(xb.prune())} backup directories"))
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
@xtrabackup.command(name="prepare")
|
|
623
|
+
@click.argument("target", type=click.Path(exists=True, file_okay=False, path_type=Path))
|
|
624
|
+
@click.option(
|
|
625
|
+
"-r",
|
|
626
|
+
"--root",
|
|
627
|
+
"backup_root",
|
|
628
|
+
required=True,
|
|
629
|
+
type=click.Path(exists=True, file_okay=False, path_type=Path),
|
|
630
|
+
help="The database's backup root (containing dated directories).",
|
|
631
|
+
)
|
|
632
|
+
@click.option(
|
|
633
|
+
"-d",
|
|
634
|
+
"--dst",
|
|
635
|
+
"destination",
|
|
636
|
+
required=True,
|
|
637
|
+
type=click.Path(path_type=Path),
|
|
638
|
+
help="New recovery directory outside the backup root.",
|
|
639
|
+
)
|
|
640
|
+
@click.option("-u", "--user", default="xtrabackup", show_default=True, help="MySQL user.")
|
|
641
|
+
@click.option(
|
|
642
|
+
"-p",
|
|
643
|
+
"--password",
|
|
644
|
+
default=None,
|
|
645
|
+
prompt="MySQL password",
|
|
646
|
+
prompt_required=False,
|
|
647
|
+
hide_input=True,
|
|
648
|
+
is_flag=False,
|
|
649
|
+
help="MySQL password. If given without a value, you are prompted securely.",
|
|
650
|
+
)
|
|
651
|
+
@click.option(
|
|
652
|
+
"-b",
|
|
653
|
+
"--binary",
|
|
654
|
+
default="xtrabackup",
|
|
655
|
+
show_default=True,
|
|
656
|
+
help="Backup binary (xtrabackup or mariabackup).",
|
|
657
|
+
)
|
|
658
|
+
@click.option("--encrypt-key-file", type=click.Path(dir_okay=False, path_type=Path),
|
|
659
|
+
help="32-byte AES256 key file for encrypted backups.")
|
|
660
|
+
def xtrabackup_prepare(
|
|
661
|
+
target: Path,
|
|
662
|
+
backup_root: Path,
|
|
663
|
+
destination: Path,
|
|
664
|
+
user: str,
|
|
665
|
+
password: str | None,
|
|
666
|
+
binary: str,
|
|
667
|
+
encrypt_key_file: Path | None,
|
|
668
|
+
) -> int:
|
|
669
|
+
"""Run --prepare on a backup directory to make it restorable."""
|
|
670
|
+
xb = XtraBackup(
|
|
671
|
+
backup_root=backup_root,
|
|
672
|
+
user=user,
|
|
673
|
+
password=password,
|
|
674
|
+
binary=binary,
|
|
675
|
+
encrypt_key_file=encrypt_key_file,
|
|
676
|
+
)
|
|
677
|
+
return _handle_errors(lambda: click.echo(f"Prepared: {xb.prepare(target, destination)}"))
|
|
678
|
+
|
|
679
|
+
|
|
680
|
+
@main.command()
|
|
681
|
+
@click.option(
|
|
682
|
+
"--full-dir",
|
|
683
|
+
required=True,
|
|
684
|
+
type=click.Path(file_okay=False, path_type=Path),
|
|
685
|
+
help="Directory containing full backups.",
|
|
686
|
+
)
|
|
687
|
+
@click.option(
|
|
688
|
+
"--incr-dir",
|
|
689
|
+
default=None,
|
|
690
|
+
type=click.Path(file_okay=False, path_type=Path),
|
|
691
|
+
help="Directory containing incremental backups (optional).",
|
|
692
|
+
)
|
|
693
|
+
@click.option(
|
|
694
|
+
"--log-dir",
|
|
695
|
+
default=None,
|
|
696
|
+
type=click.Path(file_okay=False, path_type=Path),
|
|
697
|
+
help="Directory containing backup logs to expire by age (optional).",
|
|
698
|
+
)
|
|
699
|
+
@click.option(
|
|
700
|
+
"--full-glob",
|
|
701
|
+
default=retention.DEFAULTS["full_glob"],
|
|
702
|
+
show_default=True,
|
|
703
|
+
help="Glob matching full backup files.",
|
|
704
|
+
)
|
|
705
|
+
@click.option(
|
|
706
|
+
"--incr-glob",
|
|
707
|
+
default=retention.DEFAULTS["incr_glob"],
|
|
708
|
+
show_default=True,
|
|
709
|
+
help="Glob matching incremental backup files.",
|
|
710
|
+
)
|
|
711
|
+
@click.option(
|
|
712
|
+
"--log-glob",
|
|
713
|
+
default=retention.DEFAULTS["log_glob"],
|
|
714
|
+
show_default=True,
|
|
715
|
+
help="Glob matching log files.",
|
|
716
|
+
)
|
|
717
|
+
@click.option(
|
|
718
|
+
"--daily",
|
|
719
|
+
default=retention.DEFAULTS["daily"],
|
|
720
|
+
show_default=True,
|
|
721
|
+
type=int,
|
|
722
|
+
help="Keep EVERY backup of the last N calendar days.",
|
|
723
|
+
)
|
|
724
|
+
@click.option(
|
|
725
|
+
"--weekly",
|
|
726
|
+
default=retention.DEFAULTS["weekly"],
|
|
727
|
+
show_default=True,
|
|
728
|
+
type=int,
|
|
729
|
+
help="Then one backup per ISO week, for N weeks.",
|
|
730
|
+
)
|
|
731
|
+
@click.option(
|
|
732
|
+
"--monthly",
|
|
733
|
+
default=retention.DEFAULTS["monthly"],
|
|
734
|
+
show_default=True,
|
|
735
|
+
type=int,
|
|
736
|
+
help="Then one backup per calendar month, for N months.",
|
|
737
|
+
)
|
|
738
|
+
@click.option(
|
|
739
|
+
"--incr-days",
|
|
740
|
+
default=retention.DEFAULTS["incr_days"],
|
|
741
|
+
show_default=True,
|
|
742
|
+
type=int,
|
|
743
|
+
help="Keep incrementals for N days, never past their full.",
|
|
744
|
+
)
|
|
745
|
+
@click.option(
|
|
746
|
+
"--log-days",
|
|
747
|
+
default=retention.DEFAULTS["log_days"],
|
|
748
|
+
show_default=True,
|
|
749
|
+
type=int,
|
|
750
|
+
help="Keep logs for N days.",
|
|
751
|
+
)
|
|
752
|
+
@click.option(
|
|
753
|
+
"--pick",
|
|
754
|
+
"pick_mode",
|
|
755
|
+
default=retention.DEFAULTS["pick"],
|
|
756
|
+
show_default=True,
|
|
757
|
+
type=click.Choice(["first", "last"]),
|
|
758
|
+
help="Which backup survives inside a week/month bucket.",
|
|
759
|
+
)
|
|
760
|
+
@click.option(
|
|
761
|
+
"--min-keep-fulls",
|
|
762
|
+
default=retention.DEFAULTS["min_keep_fulls"],
|
|
763
|
+
show_default=True,
|
|
764
|
+
type=int,
|
|
765
|
+
help="Safety floor: never leave fewer than N fulls on disk.",
|
|
766
|
+
)
|
|
767
|
+
@click.option(
|
|
768
|
+
"--now", default=None, metavar="YYYY-MM-DD", help="Pretend it is this date (for testing)."
|
|
769
|
+
)
|
|
770
|
+
@click.option("--apply", is_flag=True, help="Actually delete; default is a dry run.")
|
|
771
|
+
@click.option("-q", "--quiet", is_flag=True, help="Only print the summary line.")
|
|
772
|
+
def retention_cmd(
|
|
773
|
+
full_dir: Path,
|
|
774
|
+
incr_dir: Path | None,
|
|
775
|
+
log_dir: Path | None,
|
|
776
|
+
full_glob: str,
|
|
777
|
+
incr_glob: str,
|
|
778
|
+
log_glob: str,
|
|
779
|
+
daily: int,
|
|
780
|
+
weekly: int,
|
|
781
|
+
monthly: int,
|
|
782
|
+
incr_days: int,
|
|
783
|
+
log_days: int,
|
|
784
|
+
pick_mode: str,
|
|
785
|
+
min_keep_fulls: int,
|
|
786
|
+
now: str | None,
|
|
787
|
+
apply: bool,
|
|
788
|
+
quiet: bool,
|
|
789
|
+
) -> int:
|
|
790
|
+
"""Apply a GFS (daily/weekly/monthly) retention policy to a backup tree.
|
|
791
|
+
|
|
792
|
+
Default is a DRY RUN: nothing is deleted until --apply is passed.
|
|
793
|
+
Incremental backups are chain-safe: they never outlive their parent full,
|
|
794
|
+
and a full that still anchors a live incremental is kept.
|
|
795
|
+
"""
|
|
796
|
+
import datetime as _dt
|
|
797
|
+
|
|
798
|
+
now_dt = None
|
|
799
|
+
if now:
|
|
800
|
+
try:
|
|
801
|
+
now_dt = _dt.datetime.strptime(now, "%Y-%m-%d").replace(hour=23, minute=59, second=59)
|
|
802
|
+
except ValueError:
|
|
803
|
+
raise click.UsageError("--now must be YYYY-MM-DD") from None
|
|
804
|
+
|
|
805
|
+
log_level = click.get_current_context().obj.get("log_level", "INFO")
|
|
806
|
+
rc = retention.run_job(
|
|
807
|
+
full_dir=full_dir,
|
|
808
|
+
incr_dir=incr_dir,
|
|
809
|
+
log_dir=log_dir,
|
|
810
|
+
full_glob=full_glob,
|
|
811
|
+
incr_glob=incr_glob,
|
|
812
|
+
log_glob=log_glob,
|
|
813
|
+
daily=daily,
|
|
814
|
+
weekly=weekly,
|
|
815
|
+
monthly=monthly,
|
|
816
|
+
incr_days=incr_days,
|
|
817
|
+
log_days=log_days,
|
|
818
|
+
pick_mode=pick_mode,
|
|
819
|
+
min_keep_fulls=min_keep_fulls,
|
|
820
|
+
now=now_dt,
|
|
821
|
+
apply_changes=apply,
|
|
822
|
+
verbose=(log_level == "DEBUG"),
|
|
823
|
+
quiet=quiet,
|
|
824
|
+
)
|
|
825
|
+
if rc:
|
|
826
|
+
click.get_current_context().exit(rc)
|
|
827
|
+
return rc
|
|
828
|
+
|
|
829
|
+
|
|
830
|
+
@main.command()
|
|
831
|
+
@click.argument("archive", required=False,
|
|
832
|
+
type=click.Path(exists=True, dir_okay=False, path_type=Path))
|
|
833
|
+
@click.option("--config", "config_path",
|
|
834
|
+
type=click.Path(exists=True, dir_okay=False, path_type=Path))
|
|
835
|
+
@click.option("--backup-id", type=click.IntRange(min=1), help="Successful backup ID from history.")
|
|
836
|
+
@click.option("--job", help="Limit history choices to this job.")
|
|
837
|
+
@click.option("-y", "--yes", is_flag=True, help="Confirm restore of an explicit --backup-id.")
|
|
838
|
+
@click.option(
|
|
839
|
+
"-d",
|
|
840
|
+
"--dst",
|
|
841
|
+
type=click.Path(file_okay=False, path_type=Path),
|
|
842
|
+
help="Recovery directory; history mode suggests a new path when omitted.",
|
|
843
|
+
)
|
|
844
|
+
@click.option(
|
|
845
|
+
"-c",
|
|
846
|
+
"--chdir",
|
|
847
|
+
type=click.Path(exists=True, file_okay=False, path_type=Path),
|
|
848
|
+
help="Resolve template paths against this directory.",
|
|
849
|
+
)
|
|
850
|
+
@click.option("--encrypt-key-file", type=click.Path(dir_okay=False, path_type=Path),
|
|
851
|
+
help="Override the encryption key file recorded in physical backup history.")
|
|
852
|
+
def restore(
|
|
853
|
+
archive: Path | None,
|
|
854
|
+
dst: Path | None,
|
|
855
|
+
chdir: Path | None,
|
|
856
|
+
config_path: Path | None,
|
|
857
|
+
backup_id: int | None,
|
|
858
|
+
encrypt_key_file: Path | None,
|
|
859
|
+
job: str | None,
|
|
860
|
+
yes: bool,
|
|
861
|
+
) -> int:
|
|
862
|
+
"""Restore an archive, or select a successful backup from configured history."""
|
|
863
|
+
def _run():
|
|
864
|
+
if archive is not None:
|
|
865
|
+
if encrypt_key_file is not None:
|
|
866
|
+
raise click.UsageError("--encrypt-key-file requires physical backup history")
|
|
867
|
+
if backup_id is not None or job is not None:
|
|
868
|
+
raise click.UsageError("ARCHIVE cannot be combined with --backup-id or --job")
|
|
869
|
+
if dst is None:
|
|
870
|
+
raise click.UsageError("Provide --dst when restoring an explicit ARCHIVE")
|
|
871
|
+
FileBackup.restore_archive(archive, dst)
|
|
872
|
+
click.echo(f"Restored to: {dst}")
|
|
873
|
+
return
|
|
874
|
+
config = _get_config(config_path, required=True)
|
|
875
|
+
if not config.history:
|
|
876
|
+
raise click.UsageError("Configure [history] database in the TOML file first")
|
|
877
|
+
history = History(config.history)
|
|
878
|
+
if backup_id is None:
|
|
879
|
+
if yes:
|
|
880
|
+
raise click.UsageError("--yes requires an explicit --backup-id")
|
|
881
|
+
records = [r for r in history.records(job=job, successful=True) if r.available]
|
|
882
|
+
if not records:
|
|
883
|
+
raise BackupError("No successful, available backups found")
|
|
884
|
+
click.echo("Successful backups (newest first):")
|
|
885
|
+
for record in records:
|
|
886
|
+
click.echo(
|
|
887
|
+
f"{record.id}: {record.job_name} | {record.backup_type} | "
|
|
888
|
+
f"{record.started_at} | "
|
|
889
|
+
f"{'encrypted' if record.encrypted else 'unencrypted'} | {record.path}"
|
|
890
|
+
)
|
|
891
|
+
selected_id = click.prompt("Backup ID", type=int, default=records[0].id)
|
|
892
|
+
choices = {r.id: r for r in records}
|
|
893
|
+
if selected_id not in choices:
|
|
894
|
+
raise click.UsageError("Choose a backup ID from the displayed list")
|
|
895
|
+
record = choices[selected_id]
|
|
896
|
+
else:
|
|
897
|
+
record = history.get(backup_id)
|
|
898
|
+
if job is not None and record.job_name != job:
|
|
899
|
+
raise click.UsageError("The selected backup does not belong to --job")
|
|
900
|
+
if not record.available:
|
|
901
|
+
raise BackupError("Backup is unsuccessful, missing, or has been replaced/modified")
|
|
902
|
+
destination = dst or suggested_destination(record, config.history.restore_root)
|
|
903
|
+
click.echo(f"Backup: {record.path}")
|
|
904
|
+
if dst is None and not yes:
|
|
905
|
+
destination = Path(click.prompt("Restore destination", default=str(destination)))
|
|
906
|
+
click.echo(f"Recovery destination: {destination}")
|
|
907
|
+
if not yes:
|
|
908
|
+
click.confirm("Restore this backup?", abort=True)
|
|
909
|
+
if encrypt_key_file is not None:
|
|
910
|
+
if not record.backup_type.startswith("xtrabackup"):
|
|
911
|
+
raise click.UsageError("--encrypt-key-file requires a physical backup")
|
|
912
|
+
restored = restore_record(record, destination, encrypt_key_file=encrypt_key_file)
|
|
913
|
+
else:
|
|
914
|
+
restored = restore_record(record, destination)
|
|
915
|
+
if record.backup_type == "mysqldump":
|
|
916
|
+
click.echo(f"SQL recovered to: {restored / 'backup.sql'} (not imported into a server)")
|
|
917
|
+
elif record.backup_type.startswith("xtrabackup"):
|
|
918
|
+
click.echo(f"Prepared recovery directory: {restored}")
|
|
919
|
+
else:
|
|
920
|
+
click.echo(f"Restored to: {restored}")
|
|
921
|
+
|
|
922
|
+
return _handle_errors(_run)
|
|
923
|
+
|
|
924
|
+
|
|
925
|
+
@main.command(name="history")
|
|
926
|
+
@click.option("--config", "config_path",
|
|
927
|
+
type=click.Path(exists=True, dir_okay=False, path_type=Path))
|
|
928
|
+
@click.option("--job", help="Show only this job.")
|
|
929
|
+
@click.option("--successful", is_flag=True, help="Show only successful runs.")
|
|
930
|
+
def history_cmd(config_path: Path | None, job: str | None, successful: bool) -> int:
|
|
931
|
+
"""List recorded backup attempts and whether their artifacts are still available."""
|
|
932
|
+
def _run():
|
|
933
|
+
config = _get_config(config_path, required=True)
|
|
934
|
+
if not config.history:
|
|
935
|
+
raise click.UsageError("Configure [history] database in the TOML file first")
|
|
936
|
+
records = History(config.history).records(job=job, successful=successful)
|
|
937
|
+
if not records:
|
|
938
|
+
click.echo("No backup history found.")
|
|
939
|
+
for record in records:
|
|
940
|
+
available = "available" if record.available else "unavailable"
|
|
941
|
+
click.echo(
|
|
942
|
+
f"{record.id}: {record.job_name} | {record.backup_type} | {record.started_at} | "
|
|
943
|
+
f"{record.status} | {available} | "
|
|
944
|
+
f"{'encrypted' if record.encrypted else 'unencrypted'} | {record.path or '-'}"
|
|
945
|
+
)
|
|
946
|
+
|
|
947
|
+
return _handle_errors(_run)
|
|
948
|
+
|
|
949
|
+
|
|
950
|
+
@main.command(name="run")
|
|
951
|
+
@click.option(
|
|
952
|
+
"-c",
|
|
953
|
+
"--config",
|
|
954
|
+
"config_path",
|
|
955
|
+
type=click.Path(exists=True, dir_okay=False, path_type=Path),
|
|
956
|
+
help="TOML configuration file with job definitions.",
|
|
957
|
+
)
|
|
958
|
+
@click.argument("job_name", required=False)
|
|
959
|
+
@click.option("--all", "run_all", is_flag=True, help="Run every job in the config.")
|
|
960
|
+
@click.option("--validate", "validate_only", is_flag=True,
|
|
961
|
+
help="Validate selected jobs without running backups or retention.")
|
|
962
|
+
@click.option("--cron", "cron_only", is_flag=True,
|
|
963
|
+
help="Recommend cron entries for selected jobs without installing them.")
|
|
964
|
+
@click.option(
|
|
965
|
+
"--verify/--no-verify",
|
|
966
|
+
default=True,
|
|
967
|
+
show_default=True,
|
|
968
|
+
help="Verify backups after creation.",
|
|
969
|
+
)
|
|
970
|
+
def run(
|
|
971
|
+
config_path: Path | None,
|
|
972
|
+
job_name: str | None,
|
|
973
|
+
run_all: bool,
|
|
974
|
+
verify: bool,
|
|
975
|
+
validate_only: bool,
|
|
976
|
+
cron_only: bool,
|
|
977
|
+
) -> int:
|
|
978
|
+
"""Run one or more configured backup jobs."""
|
|
979
|
+
try:
|
|
980
|
+
config = _get_config(config_path, required=True)
|
|
981
|
+
except ConfigError as exc:
|
|
982
|
+
raise click.UsageError(str(exc)) from exc
|
|
983
|
+
|
|
984
|
+
if run_all and job_name:
|
|
985
|
+
raise click.UsageError("Choose JOB_NAME or --all, not both")
|
|
986
|
+
select_all = run_all or ((validate_only or cron_only) and job_name is None)
|
|
987
|
+
names = list(config.jobs.keys()) if select_all else [job_name]
|
|
988
|
+
if not names or any(n is None for n in names):
|
|
989
|
+
raise click.UsageError("Provide a JOB_NAME or use --all.")
|
|
990
|
+
|
|
991
|
+
try:
|
|
992
|
+
selected = [config.get(name) for name in names]
|
|
993
|
+
except ConfigError as exc:
|
|
994
|
+
raise click.UsageError(str(exc)) from exc
|
|
995
|
+
if validate_only or cron_only:
|
|
996
|
+
click.get_current_context().exit(
|
|
997
|
+
_configuration_helpers(config, selected, validate_only, cron_only)
|
|
998
|
+
)
|
|
999
|
+
logger = logging.getLogger("bdbackup.cli")
|
|
1000
|
+
failures = []
|
|
1001
|
+
for job in selected:
|
|
1002
|
+
logger.info("Running job %r (%s)", job.name, job.type)
|
|
1003
|
+
try:
|
|
1004
|
+
if job.type == "retention":
|
|
1005
|
+
params = dict(job.params)
|
|
1006
|
+
if "apply" in params:
|
|
1007
|
+
params["apply_changes"] = params.pop("apply")
|
|
1008
|
+
if "pick" in params:
|
|
1009
|
+
params["pick_mode"] = params.pop("pick")
|
|
1010
|
+
if retention.run_job(**params):
|
|
1011
|
+
failures.append(EXIT_BACKUP_FAILED)
|
|
1012
|
+
continue
|
|
1013
|
+
info = {}
|
|
1014
|
+
|
|
1015
|
+
def _create(job=job, info=info):
|
|
1016
|
+
backend = build_backend(job)
|
|
1017
|
+
_protect_history(backend, config)
|
|
1018
|
+
info.update(backup_restore_info(backend))
|
|
1019
|
+
result = backend.backup()
|
|
1020
|
+
if not result.success:
|
|
1021
|
+
raise BackupError("Backend reported an unsuccessful backup")
|
|
1022
|
+
if verify:
|
|
1023
|
+
backend.verify(result)
|
|
1024
|
+
return result
|
|
1025
|
+
|
|
1026
|
+
result = _tracked_backup(
|
|
1027
|
+
config, job.name, job.type, _create, info,
|
|
1028
|
+
encrypted=job.params.get("encrypt") is True,
|
|
1029
|
+
)
|
|
1030
|
+
click.echo(f"Job {job.name}: {result.path}")
|
|
1031
|
+
except BlockingIOError as exc:
|
|
1032
|
+
logger.error("Job %r locked: %s", job.name, exc)
|
|
1033
|
+
failures.append(EXIT_LOCKED)
|
|
1034
|
+
except Exception as exc:
|
|
1035
|
+
logger.error("Job %r failed: %s", job.name, exc)
|
|
1036
|
+
failures.append(EXIT_BACKUP_FAILED)
|
|
1037
|
+
if failures:
|
|
1038
|
+
click.get_current_context().exit(
|
|
1039
|
+
EXIT_BACKUP_FAILED if EXIT_BACKUP_FAILED in failures else EXIT_LOCKED,
|
|
1040
|
+
)
|
|
1041
|
+
return EXIT_OK
|
|
1042
|
+
|
|
1043
|
+
|
|
1044
|
+
if __name__ == "__main__":
|
|
1045
|
+
sys.exit(main())
|