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,752 @@
1
+ Metadata-Version: 2.5
2
+ Name: bdbackup
3
+ Version: 0.6.1
4
+ Summary: File and MySQL/MariaDB backups with verification, retention, and guided recovery
5
+ Project-URL: Homepage, https://github.com/ayder/bdbackup
6
+ Project-URL: Repository, https://github.com/ayder/bdbackup
7
+ Project-URL: Issues, https://github.com/ayder/bdbackup/issues
8
+ Author-email: Sinan Alyuruk <sinan@dbsmedya.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: backup,mariabackup,mysql,tar,xtrabackup
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: System Administrators
14
+ Classifier: Operating System :: POSIX
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: System :: Archiving :: Backup
20
+ Requires-Python: >=3.12
21
+ Requires-Dist: click>=8.0
22
+ Provides-Extra: dev
23
+ Requires-Dist: build; extra == 'dev'
24
+ Requires-Dist: pytest-cov; extra == 'dev'
25
+ Requires-Dist: pytest>=7.0; extra == 'dev'
26
+ Requires-Dist: ruff; extra == 'dev'
27
+ Requires-Dist: twine; extra == 'dev'
28
+ Provides-Extra: mysql
29
+ Requires-Dist: pymysql>=1.0; extra == 'mysql'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # bdbackup
33
+
34
+ **Backups by design.**
35
+
36
+ `bdbackup` is a Python library and command-line tool for file and MySQL/MariaDB
37
+ backups with verification, retention, and guided recovery. Define repeatable jobs,
38
+ track their outcomes, and prepare recovery copies with explicit safeguards at
39
+ each step.
40
+
41
+ Choose the backup method that fits your data:
42
+
43
+ - **file** backups from a plain-text template file into a tar archive
44
+ - **mysqldump** logical backups (gzip-compressed)
45
+ - **xtrabackup / mariabackup** physical full and incremental backups
46
+
47
+ Built for day-to-day system administration: TOML configuration, credential files,
48
+ verification before publication, process locking, atomic publication, and optional
49
+ SQLite history keep backup operations explicit and inspectable.
50
+
51
+ ## Support and safety
52
+
53
+ Python 3.12+ on POSIX systems (Linux/macOS); Windows is not supported.
54
+ `tar` and `tar.gz` work on every supported Python; `tar.zst` requires Python 3.14
55
+ with Zstandard support. Database binaries are separate system dependencies.
56
+
57
+ Every built-in backend verifies staging output before publishing it. A missing
58
+ or unreadable file fails the backup and preserves the previous archive. A process
59
+ lock prevents concurrent writers to the same file destination or physical root.
60
+ `--no-verify` skips only the additional verification pass after publication.
61
+ Verification checks archive readability or physical checkpoints; it does not
62
+ replace testing a restore. File backups are not filesystem snapshots: quiesce
63
+ applications or back up snapshots when files can change during a run.
64
+
65
+ Safe relative symlinks, hardlinks, empty directories and ordinary directory
66
+ permissions/timestamps round-trip. Restore rejects escaping paths/links and
67
+ special files on all supported Python versions. Ownership and privileged
68
+ permission bits are intentionally not restored. Use a destination that is not
69
+ being modified by another process during extraction.
70
+
71
+ ## Installation
72
+
73
+ Install the current code from the original GitHub repository:
74
+
75
+ ```bash
76
+ pip install "git+https://github.com/ayder/bdbackup.git"
77
+ ```
78
+
79
+ For versions published to PyPI:
80
+
81
+ ```bash
82
+ pip install bdbackup
83
+ ```
84
+
85
+ With optional MySQL metadata support:
86
+
87
+ ```bash
88
+ pip install "bdbackup[mysql]"
89
+ ```
90
+
91
+ For development:
92
+
93
+ ```bash
94
+ git clone https://github.com/ayder/bdbackup.git
95
+ cd bdbackup
96
+ pip install -e ".[dev]"
97
+ ```
98
+
99
+ ## Global options
100
+
101
+ Place the global option before the command: `bdbackup --logging DEBUG file ...`.
102
+ Levels: `DEBUG`, `INFO`, `WARNING`, `ERROR`.
103
+ The CLI uses these exit codes:
104
+
105
+ | Code | Meaning |
106
+ |------|---------|
107
+ | 0 | Success |
108
+ | 1 | Backup/verify failure, or configuration helper checks failed/incomplete |
109
+ | 2 | Usage error |
110
+ | 3 | Lock held, or retention refused an unsafe/incomplete scan |
111
+
112
+ ## File backup
113
+
114
+ Create a template file listing paths (one per line, `#` for comments,
115
+ whitespace allowed):
116
+
117
+ ```text
118
+ # backup-template.txt
119
+ Documents
120
+ Videos
121
+ data/projects
122
+ ```
123
+
124
+ Run the backup:
125
+
126
+ ```bash
127
+ bdbackup file --template backup-template.txt -d /backup/files/daily
128
+ ```
129
+
130
+ Gzip-compress:
131
+
132
+ ```bash
133
+ bdbackup file --template backup-template.txt -d /backup/files/daily --format tar.gz
134
+ ```
135
+
136
+ Options:
137
+
138
+ | Flag | Description |
139
+ |------|-------------|
140
+ | `--template` | Template file listing paths to archive |
141
+ | `-d, --dst` | Destination archive path (without extension) |
142
+ | `-c, --chdir` | Source path: resolve template paths and relative excludes against it |
143
+ | `-f, --format` | Archive format: `tar`, `tar.gz`, `tar.zst` (Python 3.14+) |
144
+ | `-x, --exclude` | Exact resolved path to exclude (repeatable) |
145
+ | `--exclude-pattern` | Glob pattern to exclude (repeatable) |
146
+ | `--exclude-template` | Named exclusion template, e.g. `python-dev` (repeatable, comma-separated allowed) |
147
+ | `--follow-symlinks` | Follow symbolic links when archiving |
148
+ | `--dry-run` | List what would be archived without writing anything |
149
+ | `--verify / --no-verify` | Verify the archive after creation (default: on) |
150
+ | `--logging` | Log level: `DEBUG`, `INFO`, `WARNING`, `ERROR` |
151
+
152
+ Restore a file archive:
153
+
154
+ ```bash
155
+ bdbackup restore /backup/files/daily.tar -d /restore/here
156
+ ```
157
+
158
+ ### Exclusion templates
159
+
160
+ `--exclude-template` applies a named bundle of gitignore-style exclusion
161
+ patterns so you don't have to repeat common artifact rules:
162
+
163
+ ```bash
164
+ bdbackup file --template backup-template.txt -d /backup/files/daily \
165
+ --exclude-template python-dev
166
+ ```
167
+
168
+ The built-in `python-dev` template skips `__pycache__/`, `*.pyc`, `.venv/`,
169
+ `venv/`, `uv.lock`, `Pipfile.lock`, `poetry.lock`, `*.egg-info/`, `build/`,
170
+ `dist/`, and common tool caches (`.mypy_cache/`, `.pytest_cache/`,
171
+ `.ruff_cache/`, `.tox/`, ...). Templates are repeatable and comma-separated
172
+ values work too; they combine with `-x/--exclude` and `--exclude-pattern`.
173
+
174
+ Patterns use gitignore-style syntax: `*.pyc` matches at any depth, a trailing
175
+ `/` matches directories only, patterns containing a `/` (e.g.
176
+ `tests/containers/*img`) match relative to the backup root, a leading `/`
177
+ anchors to the root, and `!` negates a previous pattern.
178
+
179
+ Custom templates are plain Python files in `~/.config/bdbackup/templates/`
180
+ (honours `$XDG_CONFIG_HOME` and `$BDBACKUP_CONFIG_DIR`) that self-register —
181
+ no existing code needs to change to add one:
182
+
183
+ ```python
184
+ # ~/.config/bdbackup/templates/go_dev.py
185
+ from bdbackup.templates import ExclusionTemplate
186
+
187
+ TEMPLATE = ExclusionTemplate(
188
+ name="go-dev",
189
+ patterns=("vendor/", "vendor/**", "*.test", "go.work"),
190
+ description="Go development artifacts",
191
+ )
192
+ ```
193
+
194
+ ## Database engines
195
+
196
+ Database engines are pluggable and live in per-database family packages
197
+ (`bdbackup/mysql/` today; `bdbackup/postgres/` is planned). Each engine maps a
198
+ config `type` name to a backend class; adding one never requires editing
199
+ existing wiring code:
200
+
201
+ | Engine | Config `type` | Backend | Notes |
202
+ |--------|---------------|---------|-------|
203
+ | `mysqldump` | `mysqldump` | `bdbackup.mysql.MySQLBackup` | Logical, gzip-compressed SQL dumps |
204
+ | `xtrabackup` | `xtrabackup` | `bdbackup.mysql.XtraBackup` | Percona XtraBackup / MariaDB mariabackup |
205
+
206
+ To add an engine, drop a self-registering module into either
207
+ `bdbackup/mysql/` (shipped with the package) or
208
+ `~/.config/bdbackup/engines/` (user-level, no package changes) — a versioned
209
+ xtrabackup variant or a mysql-shell `util.dump()` engine both follow the same
210
+ recipe:
211
+
212
+ ```python
213
+ # ~/.config/bdbackup/engines/mysql_shell.py
214
+ from bdbackup.engines import EngineInfo
215
+
216
+ class MySQLShellDump:
217
+ def __init__(self, out_dir: str = ".", **params): ...
218
+ def backup(self, name=None): ... # BackupBackend protocol
219
+ def verify(self, result=None): ...
220
+ def prune(self): ...
221
+
222
+ ENGINE = EngineInfo(
223
+ name="mysql-shell", # usable as type = "mysql-shell" in config
224
+ backend=MySQLShellDump,
225
+ description="MySQL Shell util.dump() backups",
226
+ family="mysql",
227
+ )
228
+ ```
229
+
230
+ A config `type` is validated against the live registry, so the new engine is
231
+ immediately usable from `config.toml`. MySQL-specific helpers shared by the
232
+ family (e.g. `mysql_cnf_file` for credential-safe defaults files) live in
233
+ `bdbackup/mysql/helpers.py`. A new database family means creating
234
+ `bdbackup/postgres/` and appending `"bdbackup.postgres"` to
235
+ `bdbackup.engines.FAMILIES` — the single deliberate modification point.
236
+
237
+ ## mysqldump
238
+
239
+ Dump a single database:
240
+
241
+ ```bash
242
+ bdbackup mysqldump --database mydatabase -o /backup/mysql/dumps -u root -p
243
+ ```
244
+
245
+ Dump all databases:
246
+
247
+ ```bash
248
+ bdbackup mysqldump --full -o /backup/mysql/dumps -u root -p
249
+ ```
250
+
251
+ Parallel dumps of multiple databases:
252
+
253
+ ```bash
254
+ bdbackup mysqldump --database db1,db2,db3 -o /backup/mysql/dumps -u root -p --jobs 4
255
+ ```
256
+
257
+ Options:
258
+
259
+ | Flag | Description |
260
+ |------|-------------|
261
+ | `--database` | Database name(s), comma-separated (ignored when `--full`) |
262
+ | `-o, --out-dir` | Directory for the dump file |
263
+ | `-u, --user` | MySQL user |
264
+ | `-p, --password` | MySQL password; omit value to be prompted securely |
265
+ | `-h, --host` | MySQL host |
266
+ | `-P, --port` | MySQL port |
267
+ | `--options` | Comma-separated mysqldump options |
268
+ | `--full` | Add `--all-databases` and dump everything |
269
+ | `-j, --jobs` | Parallel dumps when multiple databases are specified |
270
+ | `--verify / --no-verify` | Verify the dump after creation (default: on) |
271
+
272
+ Use a bare `-p` to enter a password securely. Passing `-p PASSWORD` puts it in
273
+ bdbackup's own process arguments and potentially shell history. Child database
274
+ processes receive only a temporary credentials-file path; its contents are
275
+ quoted, its permissions are `0600`, and it is removed after the run.
276
+
277
+ Mysqldump retains `--single-transaction`, `--routines`, `--events` and `--triggers`
278
+ by default. `--options` adds options; explicit `--skip-*` flags can override
279
+ applicable defaults. `--full` retains these defaults and adds `--all-databases`.
280
+ Single-transaction consistency applies to transactional tables; quiesce writes
281
+ to nontransactional tables and avoid schema changes during a dump.
282
+
283
+ ## xtrabackup
284
+
285
+ Full backup:
286
+
287
+ ```bash
288
+ bdbackup xtrabackup full --database production -r /backup/mysql -u xtrabackup -p
289
+ ```
290
+
291
+ Incremental backup (chains to the latest successful full):
292
+
293
+ ```bash
294
+ bdbackup xtrabackup incremental --database production -r /backup/mysql -u xtrabackup -p
295
+ ```
296
+
297
+ Prune old backups by retention days:
298
+
299
+ ```bash
300
+ bdbackup xtrabackup prune --database production -r /backup/mysql --retention 7
301
+ ```
302
+
303
+ Prepare a full backup or an incremental recovery point into a new directory:
304
+
305
+ ```bash
306
+ bdbackup xtrabackup prepare /backup/mysql/production/2026-09-10/Full_ID \
307
+ -r /backup/mysql/production -d /restore/production -u xtrabackup -p
308
+ ```
309
+
310
+ Use the exact path printed by the backup command in place of `Full_ID`. Passing
311
+ an incremental path prepares its full and every prerequisite incremental up to
312
+ that point. Preparation copies sources to private working directories,
313
+ decompresses compressed copies, applies the increments in dependency order, and
314
+ publishes the recovery directory only on success. The destination must be new
315
+ and outside the backup root. Original backups remain available for new
316
+ incrementals and repeated recovery attempts.
317
+
318
+ Use XtraBackup matching your MySQL/Percona server series (8.0 with 8.0, 8.4 with
319
+ 8.4); use `mariabackup` or `mariadb-backup` matching your MariaDB installation.
320
+ MariaDB preparation omits XtraBackup's `--apply-log-only` option. Compression is
321
+ **off by default**. For a compatible recent XtraBackup, select `--compress zstd`;
322
+ MariaDB's deprecated built-in compression accepts only `quicklz` and requires
323
+ `qpress` for decompression. Compatibility must be established with an actual
324
+ recovery test for the exact server and backup binary versions in use.
325
+
326
+ New physical backups record parent/full identities and LSNs in `bdbackup.json`.
327
+ Incrementals live under `DATE/Incremental/FULL_ID/UNIQUE_ID`, and cannot attach to
328
+ another full taken on the same day. Older backups without this metadata require
329
+ a new full before taking further incrementals; full backups can still be
330
+ prepared as recovery copies. Retention removes complete dated chains, preserves
331
+ the newest successful full's date, and refuses to prune without a valid full.
332
+
333
+ Options:
334
+
335
+ | Flag | Description |
336
+ |------|-------------|
337
+ | `mode` | `full`, `incremental`, `prune`, or `prepare` |
338
+ | `--database` | Database name (used for directory naming) |
339
+ | `-r, --root` | Backup root directory |
340
+ | `-u, --user` | MySQL user |
341
+ | `-p, --password` | MySQL password; omit value to be prompted securely |
342
+ | `-b, --binary` | `xtrabackup` or `mariabackup` |
343
+ | `--compress` | Compression algorithm (default: uncompressed) |
344
+ | `--compress-threads` | Compression threads (default: 4) |
345
+ | `--encrypt / --no-encrypt` | AES256 backup encryption (default: off; Percona only) |
346
+ | `--encrypt-key-file` | Required 32-byte key file when encrypting; also used by `prepare` |
347
+ | `--parallel` | Number of copy threads (default: 1) |
348
+ | `--throttle` | Limit I/O to this many IOPS |
349
+ | `--retention` | Days of backups to keep (default: 5) |
350
+ | `--verify / --no-verify` | Verify the backup after creation (default: on) |
351
+
352
+ A process lock prevents two backup runs from corrupting the same backup root.
353
+ Failed backups are written to a temporary directory first and cleaned up on
354
+ error, so a partial backup can never be mistaken for a complete one.
355
+
356
+ ### Encrypted physical backups
357
+
358
+ Percona XtraBackup jobs can optionally encrypt full and incremental backups with
359
+ AES256. In the existing job's TOML section, add:
360
+
361
+ ```toml
362
+ encrypt = true
363
+ encrypt_key_file = "/etc/mysql/xtrabackup.key"
364
+ ```
365
+
366
+ TOML uses `true`/`false`, not `yes`/`no`. The key file must already exist, be
367
+ readable by the backup account, and contain exactly 32 bytes. To create a new
368
+ key once (this command refuses to overwrite an existing key):
369
+
370
+ ```bash
371
+ sudo python3 - <<'PY'
372
+ import os
373
+ from pathlib import Path
374
+
375
+ key_path = Path("/etc/mysql/xtrabackup.key")
376
+ fd = os.open(key_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
377
+ with os.fdopen(fd, "wb") as key_file:
378
+ key_file.write(os.urandom(32))
379
+ PY
380
+ ```
381
+
382
+ Keep this key outside the backup tree and store a separate secure copy: losing
383
+ it makes its encrypted backups unrecoverable. Take a new full backup when changing
384
+ keys or encryption settings; incrementals must use their parent's settings and
385
+ key. Encryption is not supported by the mariabackup backend.
386
+
387
+ Run the configured job normally, or use the direct command:
388
+
389
+ ```bash
390
+ bdbackup run --config /opt/dbs/config.toml mysql-prod
391
+ bdbackup --config /opt/dbs/config.toml xtrabackup full \
392
+ --database production --root /backup/mysql \
393
+ --encrypt --encrypt-key-file /etc/mysql/xtrabackup.key -u mysql -p
394
+ ```
395
+
396
+ History records `encrypted = 1` in SQLite's `backup_runs` table for encrypted
397
+ attempts (`0` otherwise), including failed attempts. The `status` column indicates
398
+ whether an attempt succeeded. History also stores the algorithm and key-file
399
+ path for recovery, never the key itself. Existing history databases upgrade
400
+ automatically on the next backup; old entries remain unencrypted.
401
+
402
+ History restore uses the recorded key path. If the key has moved, provide its
403
+ new location:
404
+
405
+ ```bash
406
+ bdbackup restore --config /opt/dbs/config.toml --backup-id 12 \
407
+ --dst /restore/mysql-prod-12 --encrypt-key-file /secure/saved-xtrabackup.key --yes
408
+ ```
409
+
410
+ Recovery decrypts each full/incremental work copy, then decompresses and prepares
411
+ it. Original backups remain encrypted; the recovery directory contains plaintext.
412
+ For manual `xtrabackup prepare`, supply `--encrypt-key-file` as well.
413
+ See [Percona's encryption documentation](https://docs.percona.com/percona-xtrabackup/8.4/encrypt-backups.html).
414
+
415
+ ## Retention policy (GFS)
416
+
417
+ The `bdbackup retention` command applies a grandfather-father-son policy to
418
+ a backup tree: keep **every** backup for the last N days, then **one per ISO
419
+ week** for N weeks, then **one per calendar month** for N months. Tiers are
420
+ sequential and never overlap, so the retained set is deterministic and easy to
421
+ reason about.
422
+
423
+ ```bash
424
+ # Dry run (default) -- lists what would be deleted, changes nothing
425
+ bdbackup retention --full-dir /backup/mysql/production \
426
+ --incr-dir /backup/mysql/production/incr \
427
+ --log-dir /backup/mysql/production/log \
428
+ --daily 7 --weekly 4 --monthly 6 \
429
+ --incr-days 7 --log-days 30 \
430
+ --min-keep-fulls 2 --pick first
431
+
432
+ # Actually delete
433
+ bdbackup retention ... --apply
434
+ ```
435
+
436
+ | Tier | Flag | Meaning |
437
+ |------|------|---------|
438
+ | Daily | `--daily N` | Keep every backup of the last N calendar days |
439
+ | Weekly | `--weekly N` | Then one backup per ISO week, for N weeks |
440
+ | Monthly | `--monthly N` | Then one backup per calendar month, for N months |
441
+ | Incrementals | `--incr-days N` | Keep incrementals for N days, never past their full |
442
+ | Logs | `--log-days N` | Keep log files for N days |
443
+ | Safety | `--min-keep-fulls N` | Never leave fewer than N newest fulls |
444
+ | Pick | `--pick first/last` | Which backup survives in a weekly/monthly bucket |
445
+
446
+ **Chain safety:** this flat-file policy expects one chronological backup
447
+ stream: each new full starts a chain, and subsequent increments continue that
448
+ chain until the next full. A retained incremental pins its full and every
449
+ preceding incremental in that chain, including prerequisites older than the age
450
+ window. A missing full makes an incremental an orphan. If a full/incremental
451
+ scan skips a file (for example while it is being written), expiration is deferred
452
+ because its dependencies are uncertain. Keep all files for a stream together;
453
+ arbitrary overlapping chains or missing intermediate backups require explicit
454
+ external metadata and are not supported by this filename-based policy.
455
+
456
+ This command handles flat backup files such as `full_*.mbi`, not the dated
457
+ XtraBackup directory tree. Use `bdbackup xtrabackup prune` for physical backups.
458
+
459
+ Only `--full-dir` is required. `--incr-dir` and `--log-dir` are optional.
460
+ `--full-glob`, `--incr-glob`, and `--log-glob` default to `full_*.mbi`,
461
+ `incr_*.mbi`, and `*.log`.
462
+
463
+ ## Config-driven jobs
464
+
465
+ For scheduled or multi-job usage, define a TOML config file. Convention:
466
+ keep all bdbackup settings under `~/.config/bdbackup/` (honours
467
+ `$XDG_CONFIG_HOME` / `$BDBACKUP_CONFIG_DIR`) — `config.toml`, the
468
+ `files.template` path lists, `templates/*.py` exclusion presets, and
469
+ `engines/*.py` database engines.
470
+
471
+ ```toml
472
+ # ~/.config/bdbackup/config.toml
473
+ [files-daily]
474
+ type = "file"
475
+ template_filename = "~/.config/bdbackup/files.template"
476
+ backup_dst = "/backup/files/daily"
477
+ chdir = "/srv/www" # source path: template/exclude entries resolve against it
478
+ format = "tar.gz" # tar.zst requires Python 3.14+
479
+ exclude_pattern = ["*.log", "node_modules"]
480
+ exclude_templates = ["python-dev"]
481
+
482
+ [mysql-prod]
483
+ type = "xtrabackup"
484
+ backup_root = "/backup/mysql/production"
485
+ user = "xtrabackup"
486
+ retention_days = 7
487
+ parallel = 2
488
+
489
+ [mysqldump-all]
490
+ type = "mysqldump"
491
+ out_dir = "/backup/mysql/dumps"
492
+ user = "backup"
493
+ options = ["--single-transaction", "--all-databases"]
494
+
495
+ [mysql-prod-retention]
496
+ type = "retention"
497
+ full_dir = "/backup/flat/full"
498
+ incr_dir = "/backup/flat/incr"
499
+ log_dir = "/backup/flat/log"
500
+ daily = 7
501
+ weekly = 4
502
+ monthly = 6
503
+ incr_days = 7
504
+ log_days = 30
505
+ min_keep_fulls = 2
506
+ pick = "first"
507
+ apply = false # set true once the dry-run output looks right
508
+ ```
509
+
510
+ Configuration paths expand `~`; relative config paths resolve against the
511
+ config file's directory. Template entries and `exclude` entries resolve against
512
+ `chdir` (or the process working directory if omitted). For a single-database
513
+ mysqldump job, set `database = "mydatabase"`; for all databases include
514
+ `--all-databases` in `options`.
515
+
516
+ Except for the optional `[history]` settings, each top-level table is one job;
517
+ its keys (except `type` and optional `schedule`) are passed
518
+ to the backend constructor, so they use Python-style underscores
519
+ (`exclude_templates`), not CLI dashes. See [config.toml.example](https://github.com/ayder/bdbackup/blob/main/config.toml.example)
520
+ for a fully annotated config with every option explained.
521
+
522
+ Run one job:
523
+
524
+ ```bash
525
+ bdbackup run --config ~/.config/bdbackup/config.toml mysql-prod
526
+ ```
527
+
528
+ Run every job:
529
+
530
+ ```bash
531
+ bdbackup run --config ~/.config/bdbackup/config.toml --all
532
+ ```
533
+
534
+ ### Validate configuration and permissions
535
+
536
+ Check all configured jobs without creating a backup or running retention:
537
+
538
+ ```bash
539
+ bdbackup --config /opt/dbs/config.toml --validate
540
+ # Or validate only one job:
541
+ bdbackup run --config /opt/dbs/config.toml mysql-prod --validate
542
+ ```
543
+
544
+ Run validation as the OS account that will run your cron jobs. It checks backend
545
+ settings, required executables, destination access, SQLite/recovery directories,
546
+ file-template sources, and encryption key requirements. Missing directories are
547
+ reported with `mkdir -p` guidance and the required OS-user permissions. A missing
548
+ directory that the backend can create under a writable parent is reported as
549
+ creatable; validation does not create it.
550
+
551
+ For MySQL jobs, the installed `mysql`/`mariadb` client authenticates using the job's
552
+ credentials and reads `CURRENT_USER()`, server version, datadir and `SHOW GRANTS`.
553
+ Passwords are passed through a temporary mode-0600 options file, removed afterward.
554
+ No `CREATE USER` or `GRANT` is executed. Missing privileges produce SQL for an
555
+ administrator, for example:
556
+
557
+ ```sql
558
+ GRANT RELOAD, BACKUP_ADMIN, REPLICATION CLIENT, PROCESS, LOCK TABLES
559
+ ON *.* TO 'xtrabackup_user'@'localhost';
560
+ GRANT SELECT ON `performance_schema`.`log_status`
561
+ TO 'xtrabackup_user'@'localhost';
562
+ ```
563
+
564
+ The helper also checks the performance-schema tables used by current Percona
565
+ XtraBackup and prints `CREATE TABLESPACE` separately as an optional privilege for
566
+ importing individual tables. MariaDB Backup gets its own privilege recommendations.
567
+ See [Percona privileges](https://docs.percona.com/percona-xtrabackup/8.4/privileges.html)
568
+ and [MariaDB Backup privileges](https://mariadb.com/docs/server/server-usage/backup-and-restore/mariadb-backup/mariadb-backup-overview).
569
+
570
+ Checks cover direct grants; role-derived privileges and partial revokes may need
571
+ manual review. Physical datadir checks cover root-directory access, not every data
572
+ file or external tablespace. Custom mysqldump options, routine visibility, GTID
573
+ settings and exact server/binary version compatibility still need review.
574
+ An unreachable database or missing client is a failed/incomplete check, not a pass.
575
+ Retention validation checks settings and directory permissions without scanning
576
+ for deletions, even when `apply = true`. Helpers do not add SQLite history rows.
577
+
578
+ ### Recommend cron entries
579
+
580
+ Inspect the invoking OS account's `crontab -l` and print suggested entries:
581
+
582
+ ```bash
583
+ bdbackup --config /opt/dbs/config.toml --cron
584
+ bdbackup run --config /opt/dbs/config.toml mysql-prod --cron
585
+ # Both helpers can be used together:
586
+ bdbackup --config /opt/dbs/config.toml --validate --cron
587
+ ```
588
+
589
+ Nothing is installed or edited. Defaults are daily backups starting at 02:00 and
590
+ retention starting at 04:00, staggered by 15 minutes within each group. Override
591
+ the time inside any job's existing TOML section:
592
+
593
+ ```toml
594
+ [mysql-prod]
595
+ type = "xtrabackup"
596
+ backup_root = "/backup/mysql/production"
597
+ schedule = "30 1 * * *"
598
+
599
+ [mysql-prod-retention]
600
+ type = "retention"
601
+ full_dir = "/backup/flat/full"
602
+ schedule = "0 5 * * 0"
603
+ apply = false
604
+ ```
605
+
606
+ `schedule` accepts five numeric cron fields with wildcards, lists, ranges and
607
+ steps. It is job metadata, never passed to the backup backend. The recommendations
608
+ use absolute executable/config paths, quote shell arguments, preserve the current
609
+ working directory and suggest the current PATH for cron. Times use the cron
610
+ daemon's timezone. Allow enough time for backups before retention; separate cron
611
+ entries do not establish a dependency.
612
+
613
+ Matching active `bdbackup run` entries for the same config/job (or `--all`) are
614
+ reported without suggesting duplicates. Commented entries and other configs do
615
+ not count. Shell wrappers such as `flock`, scripts, and system-wide cron files
616
+ are not inspected; review those separately. If crontab cannot be read, suggested
617
+ entries are still shown but the helper exits with status 1.
618
+
619
+ XtraBackup job entries run full backups, including their built-in pruning.
620
+ Separate retention jobs remain for flat backup files; `apply = false` stays a dry
621
+ run in cron too. Validation/cron helpers exit 0 when their checks pass, 1 for failed
622
+ or incomplete checks, and 2 for invalid command/configuration syntax.
623
+
624
+ ## Backup history and guided restore
625
+
626
+ Enable SQLite history in your TOML configuration. No extra Python dependency
627
+ or database server is required:
628
+
629
+ ```toml
630
+ [history]
631
+ database = "state/history.sqlite3"
632
+ restore_root = "/restore/bdbackup"
633
+ ```
634
+
635
+ Both paths expand `~`; relative paths resolve against the configuration file.
636
+ `restore_root` defaults to `restores` beside that file. Omitting `[history]`
637
+ disables history. File jobs automatically exclude this live database and its
638
+ SQLite journal files; keep it outside backup inputs when possible. New history
639
+ databases are created with permissions `0600`.
640
+
641
+ `run --config` records every selected backup attempt. For direct commands,
642
+ place `--config` before the command:
643
+
644
+ ```bash
645
+ bdbackup run --config config.toml files-daily
646
+ bdbackup --config config.toml mysqldump --database app,analytics --jobs 2
647
+ bdbackup history --config config.toml
648
+ bdbackup history --config config.toml --job files-daily --successful
649
+ ```
650
+
651
+ Each record contains an ID, job name, backup type, UTC start/completion times,
652
+ status (`running`, `success`, or `failed`), and the successful artifact's absolute
653
+ path and size. Direct file commands use the destination name as the job name;
654
+ direct database commands use the database name. Parallel dumps get one record
655
+ per database, including when another dump fails. Physical full and incremental
656
+ commands record their respective types and the root/binary needed for preparation.
657
+ Credentials and raw error messages are not stored; failed rows contain only the
658
+ exception class. Retention, restore operations, and file dry runs are not backup
659
+ attempts and do not create rows. Direct Python backend calls are not automatically
660
+ recorded; applications can wrap them with `History.run`.
661
+
662
+ History is written before work starts, and success only after the backup and its
663
+ requested verification finish. If history cannot be written, the command fails;
664
+ an artifact already created is preserved. A forcibly killed process may leave a
665
+ `running` row, which is never offered for restore. Existing backups are not
666
+ imported automatically.
667
+
668
+ Select a successful backup interactively:
669
+
670
+ ```bash
671
+ bdbackup restore --config config.toml
672
+ bdbackup restore --config config.toml --job files-daily
673
+ ```
674
+
675
+ Restore lists successful, available artifacts, asks for the backup ID, suggests
676
+ `<restore_root>/<job>-<id>`, and asks for confirmation. You can edit the suggested
677
+ path. Repeated restores suggest a numbered alternative; history-based restore
678
+ requires a new directory even when `--dst` is supplied. For automation, specify
679
+ the exact backup ID and use `--yes`:
680
+
681
+ ```bash
682
+ bdbackup restore --config config.toml --backup-id 12 --dst /restore/job-12 --yes
683
+ ```
684
+
685
+ - File archives are extracted into the selected directory with the existing
686
+ safe extraction filters.
687
+ - MySQL dumps are decompressed and checked into `<destination>/backup.sql`.
688
+ Importing SQL into a running server is a separate administrator action.
689
+ - XtraBackup/MariaDB backups produce a prepared recovery directory, including
690
+ prerequisite increments. The destination must be outside the backup root.
691
+ Server ownership, copy-back, and startup remain administrator actions.
692
+ - Custom engines are recorded, but require their own restore support unless
693
+ they inherit a supported backend.
694
+
695
+ Deleted artifacts remain in history as unavailable. File identity, size, and
696
+ modification time detect replaced archives, so older rows for a reused filename
697
+ are not offered as older recovery points. These checks are not cryptographic
698
+ integrity checks; restoration still validates the actual archive or physical
699
+ dependency chain. History stores references to artifacts and does not preserve
700
+ an archive that a later backup replaces.
701
+
702
+ ## Development
703
+
704
+ Run tests and linting:
705
+
706
+ ```bash
707
+ pytest
708
+ ruff check bdbackup tests scripts
709
+ ```
710
+
711
+ Optional database integration tests use disposable, network-isolated Docker
712
+ containers with synthetic data. They remove only the containers and volumes
713
+ created for that run. Pull the matching images before running:
714
+
715
+ ```bash
716
+ python scripts/integration_mysql.py # mysql:8.4
717
+ python scripts/integration_physical.py percona # percona-server/xtrabackup:8.4
718
+ python scripts/integration_physical.py percona-encrypted # AES256 + zstd recovery
719
+ python scripts/integration_physical.py mariadb # mariadb:11.4
720
+ ```
721
+
722
+ Physical recovery returns a prepared data directory; copying it into a server's
723
+ data directory, assigning ownership to the server user, and starting that server
724
+ are separate administrator actions. Use the same database version and
725
+ filesystem case-sensitivity as the source.
726
+
727
+ `pyproject.toml` (`project.version`) is the sole version source. The package's
728
+ `__version__` and CLI read installed distribution metadata generated from it.
729
+ After changing the version, run `uv lock` to refresh the generated lockfile and
730
+ reinstall with `pip install -e '.[dev]'` to refresh local metadata. Source
731
+ development requires this editable installation.
732
+
733
+ Build and validate a release:
734
+
735
+ ```bash
736
+ python -m build
737
+ twine check dist/*
738
+ python scripts/smoke_install.py dist
739
+ ```
740
+
741
+ Commit the validated changes and create an annotated tag named
742
+ `v<project.version>`. The publishing workflow accepts only that matching tag. It
743
+ runs the reusable CI workflow on that commit (tests on Python 3.12–3.14, lint,
744
+ real MySQL/Percona/MariaDB recovery tests, source/wheel build, Twine, and an
745
+ installed-wheel recovery smoke test), then
746
+ uploads those exact artifacts. Configure the PyPI trusted publisher for
747
+ `ayder/bdbackup`, `publish.yml`, environment `pypi` before releasing. Account
748
+ configuration and actual database recovery evidence are release prerequisites.
749
+
750
+ ## License
751
+
752
+ MIT License. See [LICENSE](https://github.com/ayder/bdbackup/blob/main/LICENSE).