bdbackup 0.6.1__tar.gz → 0.6.2__tar.gz

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.
Files changed (48) hide show
  1. {bdbackup-0.6.1 → bdbackup-0.6.2}/PKG-INFO +51 -2
  2. {bdbackup-0.6.1 → bdbackup-0.6.2}/README.md +50 -1
  3. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/cli.py +26 -3
  4. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/config.py +20 -2
  5. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/validation.py +2 -0
  6. {bdbackup-0.6.1 → bdbackup-0.6.2}/config.toml.example +26 -1
  7. {bdbackup-0.6.1 → bdbackup-0.6.2}/pyproject.toml +1 -1
  8. {bdbackup-0.6.1 → bdbackup-0.6.2}/tests/test_helpers.py +33 -0
  9. {bdbackup-0.6.1 → bdbackup-0.6.2}/tests/test_history.py +56 -0
  10. bdbackup-0.6.2/tests/test_run_selector.py +155 -0
  11. {bdbackup-0.6.1 → bdbackup-0.6.2}/.gitignore +0 -0
  12. {bdbackup-0.6.1 → bdbackup-0.6.2}/LICENSE +0 -0
  13. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/__init__.py +0 -0
  14. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/backends.py +0 -0
  15. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/dboperations.py +0 -0
  16. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/engines.py +0 -0
  17. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/filebackup.py +0 -0
  18. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/history.py +0 -0
  19. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/mysql/__init__.py +0 -0
  20. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/mysql/helpers.py +0 -0
  21. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/mysql/mysqldump.py +0 -0
  22. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/mysql/xtrabackup.py +0 -0
  23. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/recovery.py +0 -0
  24. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/retention.py +0 -0
  25. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/scheduling.py +0 -0
  26. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/templates/__init__.py +0 -0
  27. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/templates/_matching.py +0 -0
  28. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/templates/python_dev.py +0 -0
  29. {bdbackup-0.6.1 → bdbackup-0.6.2}/bdbackup/utils.py +0 -0
  30. {bdbackup-0.6.1 → bdbackup-0.6.2}/scripts/check_release.py +0 -0
  31. {bdbackup-0.6.1 → bdbackup-0.6.2}/scripts/integration_mysql.py +0 -0
  32. {bdbackup-0.6.1 → bdbackup-0.6.2}/scripts/integration_physical.py +0 -0
  33. {bdbackup-0.6.1 → bdbackup-0.6.2}/scripts/smoke_install.py +0 -0
  34. {bdbackup-0.6.1 → bdbackup-0.6.2}/template.txt +0 -0
  35. {bdbackup-0.6.1 → bdbackup-0.6.2}/tests/__init__.py +0 -0
  36. {bdbackup-0.6.1 → bdbackup-0.6.2}/tests/conftest.py +0 -0
  37. {bdbackup-0.6.1 → bdbackup-0.6.2}/tests/test_architecture.py +0 -0
  38. {bdbackup-0.6.1 → bdbackup-0.6.2}/tests/test_cli.py +0 -0
  39. {bdbackup-0.6.1 → bdbackup-0.6.2}/tests/test_correctness.py +0 -0
  40. {bdbackup-0.6.1 → bdbackup-0.6.2}/tests/test_encryption.py +0 -0
  41. {bdbackup-0.6.1 → bdbackup-0.6.2}/tests/test_engines.py +0 -0
  42. {bdbackup-0.6.1 → bdbackup-0.6.2}/tests/test_import.py +0 -0
  43. {bdbackup-0.6.1 → bdbackup-0.6.2}/tests/test_performance.py +0 -0
  44. {bdbackup-0.6.1 → bdbackup-0.6.2}/tests/test_release_fixes.py +0 -0
  45. {bdbackup-0.6.1 → bdbackup-0.6.2}/tests/test_retention.py +0 -0
  46. {bdbackup-0.6.1 → bdbackup-0.6.2}/tests/test_safety_nets.py +0 -0
  47. {bdbackup-0.6.1 → bdbackup-0.6.2}/tests/test_security.py +0 -0
  48. {bdbackup-0.6.1 → bdbackup-0.6.2}/tests/test_templates.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bdbackup
3
- Version: 0.6.1
3
+ Version: 0.6.2
4
4
  Summary: File and MySQL/MariaDB backups with verification, retention, and guided recovery
5
5
  Project-URL: Homepage, https://github.com/ayder/bdbackup
6
6
  Project-URL: Repository, https://github.com/ayder/bdbackup
@@ -193,6 +193,9 @@ TEMPLATE = ExclusionTemplate(
193
193
 
194
194
  ## Database engines
195
195
 
196
+ `schedule` and `restore_root` are job metadata and are not passed to an engine backend.
197
+ Custom engines accepting arbitrary keyword arguments no longer receive `restore_root`.
198
+
196
199
  Database engines are pluggable and live in per-database family packages
197
200
  (`bdbackup/mysql/` today; `bdbackup/postgres/` is planned). Each engine maps a
198
201
  config `type` name to a backend class; adding one never requires editing
@@ -514,7 +517,7 @@ mysqldump job, set `database = "mydatabase"`; for all databases include
514
517
  `--all-databases` in `options`.
515
518
 
516
519
  Except for the optional `[history]` settings, each top-level table is one job;
517
- its keys (except `type` and optional `schedule`) are passed
520
+ its keys (except `type`, `schedule`, and `restore_root`) are passed
518
521
  to the backend constructor, so they use Python-style underscores
519
522
  (`exclude_templates`), not CLI dashes. See [config.toml.example](https://github.com/ayder/bdbackup/blob/main/config.toml.example)
520
523
  for a fully annotated config with every option explained.
@@ -531,6 +534,32 @@ Run every job:
531
534
  bdbackup run --config ~/.config/bdbackup/config.toml --all
532
535
  ```
533
536
 
537
+ For an xtrabackup job, take an incremental using its own `backup_root`, credentials,
538
+ binary, and encryption settings:
539
+
540
+ ```bash
541
+ bdbackup run --config ~/.config/bdbackup/config.toml mysql-prod --incremental
542
+ ```
543
+
544
+ `--full` is the default; an incremental requires a successful full in that job's
545
+ root and chains to the latest successful incremental, if present. `--full` and
546
+ `--incremental` together exit 2. Selecting any non-xtrabackup job with
547
+ `--incremental` also exits 2 before any job runs. `--verify/--no-verify` applies to
548
+ both backup kinds. Validation and cron recommendations ignore the selector.
549
+
550
+ For example, schedule a weekly full on Sunday and incrementals on the other days:
551
+
552
+ ```cron
553
+ 0 2 * * 0 bdbackup --config /opt/dbs/config.toml run mysql-prod
554
+ 0 2 * * 1-6 bdbackup --config /opt/dbs/config.toml run mysql-prod --incremental
555
+ ```
556
+
557
+ Pruning after each full deletes whole dated chains older than `retention_days`.
558
+ Set `retention_days` longer than the interval between fulls to preserve the previous
559
+ full's incrementals. History now records configured physical backups as
560
+ `xtrabackup-full` / `xtrabackup-incremental` (previously `xtrabackup`); update filters
561
+ that use the old type. Existing history rows are unchanged.
562
+
534
563
  ### Validate configuration and permissions
535
564
 
536
565
  Check all configured jobs without creating a backup or running retention:
@@ -617,6 +646,14 @@ are not inspected; review those separately. If crontab cannot be read, suggested
617
646
  entries are still shown but the helper exits with status 1.
618
647
 
619
648
  XtraBackup job entries run full backups, including their built-in pruning.
649
+ The helper recommends fulls only; add an incremental cron entry yourself, for example:
650
+
651
+ ```cron
652
+ 0 2 * * 1-6 bdbackup --config /opt/dbs/config.toml run mysql-prod --incremental
653
+ ```
654
+
655
+ Adjust the recommended full entry to your intended full-backup schedule.
656
+
620
657
  Separate retention jobs remain for flat backup files; `apply = false` stays a dry
621
658
  run in cron too. Validation/cron helpers exit 0 when their checks pass, 1 for failed
622
659
  or incomplete checks, and 2 for invalid command/configuration syntax.
@@ -672,6 +709,18 @@ bdbackup restore --config config.toml
672
709
  bdbackup restore --config config.toml --job files-daily
673
710
  ```
674
711
 
712
+ Each backup job may set `restore_root = "/restore/mysql-prod"` to override
713
+ `[history] restore_root` for its guided-restore suggestions. It must be a nonempty
714
+ path string; `~` expands and relative paths resolve against the config file.
715
+ Job-level `restore_root` requires `[history]` and is not allowed on retention jobs.
716
+ Validation checks that each job's root is writable or can be created.
717
+ Physical jobs usually need a separate root with room for the full and its
718
+ incrementals, staged near the database datadir.
719
+
720
+ The current config's job is matched by the history record's job name. If that job
721
+ has no `restore_root`, or is no longer configured, the history root is used.
722
+ An explicit `--dst` always wins.
723
+
675
724
  Restore lists successful, available artifacts, asks for the backup ID, suggests
676
725
  `<restore_root>/<job>-<id>`, and asks for confirmation. You can edit the suggested
677
726
  path. Repeated restores suggest a numbered alternative; history-based restore
@@ -162,6 +162,9 @@ TEMPLATE = ExclusionTemplate(
162
162
 
163
163
  ## Database engines
164
164
 
165
+ `schedule` and `restore_root` are job metadata and are not passed to an engine backend.
166
+ Custom engines accepting arbitrary keyword arguments no longer receive `restore_root`.
167
+
165
168
  Database engines are pluggable and live in per-database family packages
166
169
  (`bdbackup/mysql/` today; `bdbackup/postgres/` is planned). Each engine maps a
167
170
  config `type` name to a backend class; adding one never requires editing
@@ -483,7 +486,7 @@ mysqldump job, set `database = "mydatabase"`; for all databases include
483
486
  `--all-databases` in `options`.
484
487
 
485
488
  Except for the optional `[history]` settings, each top-level table is one job;
486
- its keys (except `type` and optional `schedule`) are passed
489
+ its keys (except `type`, `schedule`, and `restore_root`) are passed
487
490
  to the backend constructor, so they use Python-style underscores
488
491
  (`exclude_templates`), not CLI dashes. See [config.toml.example](https://github.com/ayder/bdbackup/blob/main/config.toml.example)
489
492
  for a fully annotated config with every option explained.
@@ -500,6 +503,32 @@ Run every job:
500
503
  bdbackup run --config ~/.config/bdbackup/config.toml --all
501
504
  ```
502
505
 
506
+ For an xtrabackup job, take an incremental using its own `backup_root`, credentials,
507
+ binary, and encryption settings:
508
+
509
+ ```bash
510
+ bdbackup run --config ~/.config/bdbackup/config.toml mysql-prod --incremental
511
+ ```
512
+
513
+ `--full` is the default; an incremental requires a successful full in that job's
514
+ root and chains to the latest successful incremental, if present. `--full` and
515
+ `--incremental` together exit 2. Selecting any non-xtrabackup job with
516
+ `--incremental` also exits 2 before any job runs. `--verify/--no-verify` applies to
517
+ both backup kinds. Validation and cron recommendations ignore the selector.
518
+
519
+ For example, schedule a weekly full on Sunday and incrementals on the other days:
520
+
521
+ ```cron
522
+ 0 2 * * 0 bdbackup --config /opt/dbs/config.toml run mysql-prod
523
+ 0 2 * * 1-6 bdbackup --config /opt/dbs/config.toml run mysql-prod --incremental
524
+ ```
525
+
526
+ Pruning after each full deletes whole dated chains older than `retention_days`.
527
+ Set `retention_days` longer than the interval between fulls to preserve the previous
528
+ full's incrementals. History now records configured physical backups as
529
+ `xtrabackup-full` / `xtrabackup-incremental` (previously `xtrabackup`); update filters
530
+ that use the old type. Existing history rows are unchanged.
531
+
503
532
  ### Validate configuration and permissions
504
533
 
505
534
  Check all configured jobs without creating a backup or running retention:
@@ -586,6 +615,14 @@ are not inspected; review those separately. If crontab cannot be read, suggested
586
615
  entries are still shown but the helper exits with status 1.
587
616
 
588
617
  XtraBackup job entries run full backups, including their built-in pruning.
618
+ The helper recommends fulls only; add an incremental cron entry yourself, for example:
619
+
620
+ ```cron
621
+ 0 2 * * 1-6 bdbackup --config /opt/dbs/config.toml run mysql-prod --incremental
622
+ ```
623
+
624
+ Adjust the recommended full entry to your intended full-backup schedule.
625
+
589
626
  Separate retention jobs remain for flat backup files; `apply = false` stays a dry
590
627
  run in cron too. Validation/cron helpers exit 0 when their checks pass, 1 for failed
591
628
  or incomplete checks, and 2 for invalid command/configuration syntax.
@@ -641,6 +678,18 @@ bdbackup restore --config config.toml
641
678
  bdbackup restore --config config.toml --job files-daily
642
679
  ```
643
680
 
681
+ Each backup job may set `restore_root = "/restore/mysql-prod"` to override
682
+ `[history] restore_root` for its guided-restore suggestions. It must be a nonempty
683
+ path string; `~` expands and relative paths resolve against the config file.
684
+ Job-level `restore_root` requires `[history]` and is not allowed on retention jobs.
685
+ Validation checks that each job's root is writable or can be created.
686
+ Physical jobs usually need a separate root with room for the full and its
687
+ incrementals, staged near the database datadir.
688
+
689
+ The current config's job is matched by the history record's job name. If that job
690
+ has no `restore_root`, or is no longer configured, the history root is used.
691
+ An explicit `--dst` always wins.
692
+
644
693
  Restore lists successful, available artifacts, asks for the backup ID, suggests
645
694
  `<restore_root>/<job>-<id>`, and asks for confirmation. You can edit the suggested
646
695
  path. Repeated restores suggest a numbered alternative; history-based restore
@@ -899,7 +899,12 @@ def restore(
899
899
  raise click.UsageError("The selected backup does not belong to --job")
900
900
  if not record.available:
901
901
  raise BackupError("Backup is unsuccessful, missing, or has been replaced/modified")
902
- destination = dst or suggested_destination(record, config.history.restore_root)
902
+ current_job = config.jobs.get(record.job_name)
903
+ restore_root = (
904
+ current_job.restore_root if current_job and current_job.restore_root
905
+ else config.history.restore_root
906
+ )
907
+ destination = dst or suggested_destination(record, restore_root)
903
908
  click.echo(f"Backup: {record.path}")
904
909
  if dst is None and not yes:
905
910
  destination = Path(click.prompt("Restore destination", default=str(destination)))
@@ -957,6 +962,8 @@ def history_cmd(config_path: Path | None, job: str | None, successful: bool) ->
957
962
  )
958
963
  @click.argument("job_name", required=False)
959
964
  @click.option("--all", "run_all", is_flag=True, help="Run every job in the config.")
965
+ @click.option("--full", is_flag=True, help="Take a full backup (the default).")
966
+ @click.option("--incremental", is_flag=True, help="Take an incremental backup of xtrabackup jobs.")
960
967
  @click.option("--validate", "validate_only", is_flag=True,
961
968
  help="Validate selected jobs without running backups or retention.")
962
969
  @click.option("--cron", "cron_only", is_flag=True,
@@ -971,11 +978,15 @@ def run(
971
978
  config_path: Path | None,
972
979
  job_name: str | None,
973
980
  run_all: bool,
981
+ full: bool,
982
+ incremental: bool,
974
983
  verify: bool,
975
984
  validate_only: bool,
976
985
  cron_only: bool,
977
986
  ) -> int:
978
987
  """Run one or more configured backup jobs."""
988
+ if full and incremental:
989
+ raise click.UsageError("Choose --full or --incremental, not both")
979
990
  try:
980
991
  config = _get_config(config_path, required=True)
981
992
  except ConfigError as exc:
@@ -996,6 +1007,12 @@ def run(
996
1007
  click.get_current_context().exit(
997
1008
  _configuration_helpers(config, selected, validate_only, cron_only)
998
1009
  )
1010
+ if incremental:
1011
+ unsupported = [job.name for job in selected if job.type != "xtrabackup"]
1012
+ if unsupported:
1013
+ raise click.UsageError(
1014
+ "--incremental applies only to xtrabackup jobs: " + ", ".join(unsupported)
1015
+ )
999
1016
  logger = logging.getLogger("bdbackup.cli")
1000
1017
  failures = []
1001
1018
  for job in selected:
@@ -1016,15 +1033,21 @@ def run(
1016
1033
  backend = build_backend(job)
1017
1034
  _protect_history(backend, config)
1018
1035
  info.update(backup_restore_info(backend))
1019
- result = backend.backup()
1036
+ result = (
1037
+ backend.incremental_backup()
1038
+ if job.type == "xtrabackup" and incremental else backend.backup()
1039
+ )
1020
1040
  if not result.success:
1021
1041
  raise BackupError("Backend reported an unsuccessful backup")
1022
1042
  if verify:
1023
1043
  backend.verify(result)
1024
1044
  return result
1025
1045
 
1046
+ backup_type = job.type
1047
+ if job.type == "xtrabackup":
1048
+ backup_type = "xtrabackup-incremental" if incremental else "xtrabackup-full"
1026
1049
  result = _tracked_backup(
1027
- config, job.name, job.type, _create, info,
1050
+ config, job.name, backup_type, _create, info,
1028
1051
  encrypted=job.params.get("encrypt") is True,
1029
1052
  )
1030
1053
  click.echo(f"Job {job.name}: {result.path}")
@@ -21,6 +21,7 @@ class Job:
21
21
  type: str
22
22
  params: dict[str, Any]
23
23
  schedule: str | None = None
24
+ restore_root: Path | None = None
24
25
 
25
26
 
26
27
  class ConfigError(Exception):
@@ -77,7 +78,21 @@ class Config:
77
78
  schedule = validate_schedule(schedule)
78
79
  except ValueError as exc:
79
80
  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
+ restore_root = None
82
+ if "restore_root" in section:
83
+ value = section["restore_root"]
84
+ if not isinstance(value, str) or not value.strip():
85
+ raise ConfigError(f"Job {name!r}: restore_root must be a nonempty path string")
86
+ if job_type == "retention":
87
+ raise ConfigError(
88
+ f"Job {name!r}: restore_root is not allowed in retention jobs"
89
+ )
90
+ if self.history is None:
91
+ raise ConfigError(f"Job {name!r}: restore_root requires a [history] section")
92
+ restore_root = (self.path.parent / Path(value).expanduser()).resolve()
93
+ params = {
94
+ k: v for k, v in section.items() if k not in {"type", "schedule", "restore_root"}
95
+ }
81
96
  # Config paths are relative to the config file; file-template entries
82
97
  # and excludes remain relative to the explicitly selected source path.
83
98
  for key in (
@@ -96,7 +111,10 @@ class Config:
96
111
  params[key] = self.path.parent / Path(params[key]).expanduser()
97
112
  except TypeError as exc:
98
113
  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)
114
+ self.jobs[name] = Job(
115
+ name=name, type=job_type, params=params, schedule=schedule,
116
+ restore_root=restore_root,
117
+ )
100
118
 
101
119
  def get(self, name: str) -> Job:
102
120
  if name not in self.jobs:
@@ -320,6 +320,8 @@ def validate_config(config: Config, jobs: list[Job]) -> tuple[list[str], bool]:
320
320
  for job in jobs:
321
321
  report.lines.append(f"\nJob {job.name!r} ({job.type})")
322
322
  try:
323
+ if job.restore_root is not None:
324
+ _directory(report, job.restore_root, "Recovery root", write=True, create=True)
323
325
  if job.type == "retention":
324
326
  _retention(report, job)
325
327
  continue
@@ -35,7 +35,7 @@
35
35
  # Keep the live SQLite database outside paths included in file backups.
36
36
  [history]
37
37
  database = "history.sqlite3"
38
- restore_root = "/restore/bdbackup" # default if omitted: ./restores, beside this config
38
+ restore_root = "/restore/bdbackup" # default: ./restores beside this config; jobs may override it
39
39
 
40
40
  # Configured jobs record automatically; direct commands opt in via:
41
41
  # bdbackup --config config.toml file ...
@@ -126,12 +126,33 @@ jobs = 1
126
126
  # ---------------------------------------------------------------------------
127
127
  [mysql-prod]
128
128
  type = "xtrabackup"
129
+ # Guided recovery staging root for this job; requires [history].
130
+ # restore_root = "/restore/mysql-prod"
129
131
  # schedule = "0 2 * * *" # optional override for --cron
130
132
 
131
133
  # Root directory for this job's backups; dated subdirectories are created
132
134
  # underneath.
133
135
  backup_root = "/backup/mysql/production"
134
136
 
137
+ # MySQL 8.0/8.4: run the following SQL as a MySQL administrator for local
138
+ # XtraBackup connections. Replace the password; skip CREATE USER if it exists.
139
+ # These are SQL examples only; bdbackup does not execute these comments.
140
+ # CREATE USER 'xtrabackup'@'localhost'
141
+ # IDENTIFIED BY 'REPLACE_WITH_A_STRONG_PASSWORD';
142
+ # GRANT BACKUP_ADMIN, PROCESS, RELOAD, LOCK TABLES, REPLICATION CLIENT
143
+ # ON *.* TO 'xtrabackup'@'localhost';
144
+ # GRANT SELECT ON performance_schema.log_status
145
+ # TO 'xtrabackup'@'localhost';
146
+ # GRANT SELECT ON performance_schema.keyring_component_status
147
+ # TO 'xtrabackup'@'localhost';
148
+ # GRANT SELECT ON performance_schema.replication_group_members
149
+ # TO 'xtrabackup'@'localhost';
150
+ # SHOW GRANTS FOR 'xtrabackup'@'localhost';
151
+ # If using --safe-slave-backup to stop/start replication threads, also run:
152
+ # GRANT REPLICATION_SLAVE_ADMIN ON *.* TO 'xtrabackup'@'localhost';
153
+ # MySQL 5.7 and MariaDB require different grants. The operating-system user
154
+ # running the backup must also have access to MySQL's data files.
155
+ # Reference: https://docs.percona.com/percona-xtrabackup/8.4/privileges.html
135
156
  user = "xtrabackup"
136
157
  # password = "secret"
137
158
  binary = "xtrabackup" # or "mariabackup"
@@ -143,6 +164,10 @@ parallel = 2 # copy threads
143
164
  # Optional AES256 backup encryption (Percona XtraBackup only).
144
165
  # TOML booleans are true/false, not yes/no. Enabling encryption requires an
145
166
  # existing, readable key file containing exactly 32 bytes (no trailing newline).
167
+ # Create a readable 32-character key once (do not overwrite a key in use):
168
+ # openssl rand -base64 24 | tr -d '\n' > /etc/mysql/xtrabackup.key
169
+ # chmod 600 /etc/mysql/xtrabackup.key
170
+ # stat -c %s /etc/mysql/xtrabackup.key # must print 32
146
171
  encrypt = false
147
172
  # encrypt_key_file = "/etc/mysql/xtrabackup.key"
148
173
  # Keep the key outside the backup tree and retain it for as long as its backups.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "bdbackup"
7
- version = "0.6.1"
7
+ version = "0.6.2"
8
8
  description = "File and MySQL/MariaDB backups with verification, retention, and guided recovery"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -401,3 +401,36 @@ def test_partial_revokes_never_claim_effective_access(config_path, mysql_client)
401
401
  result = CliRunner().invoke(main, ["--config", str(config_path), "--validate"])
402
402
  assert result.exit_code == 1
403
403
  assert "Partial revokes require manual privilege review" in result.output
404
+
405
+
406
+ def test_selector_does_not_change_validate_or_cron(config_path, mysql_client):
407
+ runner = CliRunner()
408
+ for mode in ("--validate", "--cron"):
409
+ args = ["--config", str(config_path), "run", mode]
410
+ default = runner.invoke(main, args)
411
+ incremental = runner.invoke(main, [*args, "--incremental"])
412
+ assert default.exit_code == incremental.exit_code == 0
413
+ assert default.output == incremental.output
414
+
415
+
416
+ @pytest.mark.parametrize("creatable", [True, False], ids=["creatable", "blocked"])
417
+ def test_validate_reports_job_restore_root(tmp_path, creatable):
418
+ (tmp_path / "source.txt").write_text("source")
419
+ (tmp_path / "paths").write_text("source.txt\n")
420
+ root = tmp_path / "new/rr"
421
+ if not creatable:
422
+ (tmp_path / "blocker").write_text("not a directory")
423
+ root = tmp_path / "blocker/rr"
424
+ config = tmp_path / "config.toml"
425
+ config.write_text(
426
+ '[history]\ndatabase="state/history.db"\n'
427
+ '[files]\ntype="file"\ntemplate_filename="paths"\n'
428
+ 'chdir="."\nbackup_dst="backup.tar"\n'
429
+ f'restore_root="{root}"\n'
430
+ )
431
+ result = CliRunner().invoke(main, ["--config", str(config), "run", "--validate", "files"])
432
+ section = result.output.split("Job 'files' (file)", 1)[1]
433
+ status = "OK" if creatable else "FAIL"
434
+ assert f"[{status}] Recovery root: {root.resolve()}" in section
435
+ assert result.exit_code == (0 if creatable else 1), result.output
436
+ assert not root.exists()
@@ -365,3 +365,59 @@ def test_suggestion_avoids_existing_paths_and_job_path_traversal(tmp_path):
365
365
  first.mkdir(parents=True)
366
366
  second = suggested_destination(record, tmp_path / "restore")
367
367
  assert second != first and second.parent == first.parent
368
+
369
+
370
+ @pytest.mark.parametrize("job_name", ["daily", "mysql-prod"])
371
+ def test_job_restore_root_does_not_reach_backend(config_file, physical_runner, job_name):
372
+ text = config_file.read_text()
373
+ if job_name == "daily":
374
+ text = text.replace('[daily]', '[daily]\nrestore_root="job-recovery"')
375
+ else:
376
+ text += ('[mysql-prod]\ntype="xtrabackup"\nbackup_root="backups"\n'
377
+ 'restore_root="job-recovery"\n')
378
+ config_file.write_text(text)
379
+ with patch("subprocess.run", side_effect=physical_runner):
380
+ result = invoke("run", "--config", config_file, job_name)
381
+ assert result.exit_code == 0, result.output
382
+ if job_name == "daily":
383
+ assert list((config_file.parent / "archives").glob("daily*.tar.gz")) == [
384
+ config_file.parent / "archives/daily.tar.gz"
385
+ ]
386
+ else:
387
+ assert len([p for p in (config_file.parent / "backups").glob("*/Full_*")
388
+ if not p.is_symlink()]) == 1
389
+ assert "restore_root" not in Config(config_file).get(job_name).params
390
+
391
+
392
+ def test_restore_suggests_job_root_then_history_root(config_file):
393
+ config_file.write_text(config_file.read_text() +
394
+ '[other]\ntype="file"\ntemplate_filename="paths"\n'
395
+ 'chdir="source"\nbackup_dst="archives/other"\nformat="tar.gz"\n')
396
+ for job in ("daily", "other"):
397
+ result = invoke("run", "--config", config_file, job)
398
+ assert result.exit_code == 0, result.output
399
+ config_file.write_text(config_file.read_text().replace(
400
+ '[daily]', '[daily]\nrestore_root="job-recovery"'))
401
+ for backup_id, relative in ((1, "job-recovery/daily-1"), (2, "recovery/other-2")):
402
+ result = invoke("restore", "--config", config_file, "--backup-id", backup_id, input="\nn\n")
403
+ assert str(config_file.parent / relative) in result.output
404
+ assert result.exit_code == 1 # user declined recovery
405
+ assert not (config_file.parent / "job-recovery").exists()
406
+ assert not (config_file.parent / "recovery").exists()
407
+
408
+
409
+ @pytest.mark.parametrize("case", ["retention", "no-history", "number", "empty"])
410
+ def test_restore_root_misplaced_or_invalid_is_config_error(config_file, case):
411
+ text = config_file.read_text()
412
+ value = '5' if case == "number" else '""' if case == "empty" else '"r"'
413
+ text = text.replace('[daily]', f'[daily]\nrestore_root={value}')
414
+ if case == "retention":
415
+ text = text.replace('type="file"', 'type="retention"')
416
+ elif case == "no-history":
417
+ text = text[text.index('[daily]'):]
418
+ config_file.write_text(text)
419
+ for flags in (("--validate",), ()):
420
+ result = invoke("run", "--config", config_file, "daily", *flags)
421
+ assert result.exit_code == 2, result.output
422
+ assert "restore_root" in result.output
423
+ assert "daily" in result.output
@@ -0,0 +1,155 @@
1
+ """Configured physical backup selectors preserve each job's settings and history."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from unittest.mock import patch
6
+
7
+ import pytest
8
+ from click.testing import CliRunner
9
+
10
+ from bdbackup.cli import main
11
+ from bdbackup.config import Config
12
+ from bdbackup.history import History
13
+
14
+
15
+ @pytest.fixture
16
+ def xb_config(tmp_path):
17
+ (tmp_path / "source").mkdir()
18
+ (tmp_path / "source/hello").write_text("recover me")
19
+ (tmp_path / "paths").write_text("hello\n")
20
+ config = tmp_path / "config.toml"
21
+ config.write_text(
22
+ '[history]\ndatabase="history.db"\n'
23
+ '[mysql-prod]\ntype="xtrabackup"\nbackup_root="backups"\n'
24
+ 'user="bk_user"\npassword="bk-secret"\nbinary="mariadb-backup"\n'
25
+ '[files]\ntype="file"\ntemplate_filename="paths"\n'
26
+ 'chdir="source"\nbackup_dst="archives/files"\nformat="tar.gz"\n'
27
+ )
28
+ return config
29
+
30
+
31
+ @pytest.fixture
32
+ def recording_runner(physical_runner, monkeypatch):
33
+ commands, defaults = [], []
34
+
35
+ def run(cmd, **kwargs):
36
+ commands.append(list(cmd))
37
+ defaults.append(Path(cmd[1].split("=", 1)[1]).read_text())
38
+ return physical_runner(cmd, **kwargs)
39
+
40
+ monkeypatch.setattr("subprocess.run", run)
41
+ return commands, defaults
42
+
43
+
44
+ def invoke(config, *args):
45
+ return CliRunner().invoke(main, ["--config", str(config), "run", *args])
46
+
47
+
48
+ def records(config):
49
+ return History(Config(config).history).records()
50
+
51
+
52
+ def fulls(root):
53
+ return sorted(p for p in root.glob("*/Full_*") if not p.is_symlink())
54
+
55
+
56
+ def test_run_incremental_chains_in_job_root(xb_config, recording_runner):
57
+ for flags in ((), ("--incremental",), ("--incremental",)):
58
+ result = invoke(xb_config, "mysql-prod", *flags)
59
+ assert result.exit_code == 0, result.output
60
+ root = (xb_config.parent / "backups").resolve()
61
+ chains = list(root.glob("*/Incremental/Full_*"))
62
+ increments = sorted(p for chain in chains for p in chain.iterdir() if p.is_dir())
63
+ assert len(increments) == 2
64
+ assert len(chains) == 1
65
+ assert json.loads((increments[1] / "bdbackup.json").read_text())["parent"] == str(
66
+ increments[0].relative_to(root)
67
+ )
68
+ commands, defaults = recording_runner
69
+ for command, parent in zip(commands[1:], [fulls(root)[0], increments[0]], strict=True):
70
+ assert command[0] == "mariadb-backup"
71
+ assert f"--incremental-basedir={parent}" in command
72
+ assert all('user="bk_user"' in text and 'password="bk-secret"' in text for text in defaults)
73
+ assert all("bk-secret" not in arg for command in commands for arg in command)
74
+
75
+
76
+ def test_run_incremental_uses_job_encryption(xb_config, physical_runner, monkeypatch):
77
+ key = xb_config.parent / "key"
78
+ key.write_bytes(b"0123456789abcdef0123456789abcdef")
79
+ xb_config.write_text(xb_config.read_text().replace(
80
+ 'binary="mariadb-backup"',
81
+ 'binary="xtrabackup"\nencrypt=true\nencrypt_key_file="key"',
82
+ ))
83
+ commands = []
84
+
85
+ def run(cmd, **kwargs):
86
+ commands.append(cmd)
87
+ result = physical_runner(cmd, **kwargs)
88
+ target = Path(next(a.split("=", 1)[1] for a in cmd if a.startswith("--target-dir=")))
89
+ if "--encrypt=AES256" in cmd:
90
+ (target / "data.ibd").rename(target / "data.ibd.xbcrypt")
91
+ return result
92
+
93
+ monkeypatch.setattr("subprocess.run", run)
94
+ for flags in ((), ("--incremental",)):
95
+ result = invoke(xb_config, "mysql-prod", *flags)
96
+ assert result.exit_code == 0, result.output
97
+ assert any(a.startswith("--incremental-basedir=") for a in commands[1]), (
98
+ "incremental-basedir missing from second command"
99
+ )
100
+ assert "--encrypt=AES256" in commands[1]
101
+ assert f"--encrypt-key-file={key}" in commands[1]
102
+ metadata, = (xb_config.parent / "backups").glob("*/Incremental/Full_*/*/bdbackup.json")
103
+ assert json.loads(metadata.read_text())["encrypted"] is True
104
+
105
+
106
+ def test_run_full_flag_and_default_take_full(xb_config, recording_runner):
107
+ for flags in ((), ("--full",)):
108
+ result = invoke(xb_config, "mysql-prod", *flags)
109
+ assert result.exit_code == 0, result.output
110
+ root = xb_config.parent / "backups"
111
+ assert len(fulls(root)) == 2
112
+ assert not list(root.glob("*/Incremental"))
113
+ assert not any(a.startswith("--incremental-basedir") for c in recording_runner[0] for a in c)
114
+
115
+
116
+ @pytest.mark.parametrize("args,message", [
117
+ (("mysql-prod", "--full", "--incremental"), "Choose --full or --incremental, not both"),
118
+ (("files", "--incremental"), "--incremental applies only to xtrabackup jobs: files"),
119
+ (("--all", "--incremental"), "--incremental applies only to xtrabackup jobs: files"),
120
+ ], ids=["both-flags", "file", "all"])
121
+ def test_run_selector_usage_errors(xb_config, args, message):
122
+ with (
123
+ patch("bdbackup.mysql.XtraBackup.full_backup") as full,
124
+ patch("bdbackup.mysql.XtraBackup.incremental_backup") as incremental,
125
+ patch("bdbackup.filebackup.FileBackup.backup") as file,
126
+ ):
127
+ result = invoke(xb_config, *args)
128
+ assert result.exit_code == 2, result.output
129
+ assert message in result.output
130
+ full.assert_not_called()
131
+ incremental.assert_not_called()
132
+ file.assert_not_called()
133
+ assert not Config(xb_config).history.database.exists() or records(xb_config) == []
134
+
135
+
136
+ def test_run_incremental_without_full_fails(xb_config, recording_runner, caplog):
137
+ result = invoke(xb_config, "mysql-prod", "--incremental")
138
+ assert result.exit_code == 1, result.output
139
+ assert "No successful full backup found; run full backup first" in caplog.text
140
+ assert not fulls(xb_config.parent / "backups")
141
+ record, = records(xb_config)
142
+ assert record.status == "failed"
143
+
144
+
145
+ def test_run_records_full_and_incremental_types(xb_config, recording_runner):
146
+ result = invoke(xb_config, "mysql-prod")
147
+ assert result.exit_code == 0, result.output
148
+ record, = records(xb_config)
149
+ assert record.job_name == "mysql-prod"
150
+ assert record.backup_type == "xtrabackup-full"
151
+ result = invoke(xb_config, "mysql-prod", "--incremental")
152
+ assert result.exit_code == 0, result.output
153
+ assert [(r.job_name, r.backup_type) for r in reversed(records(xb_config))] == [
154
+ ("mysql-prod", "xtrabackup-full"), ("mysql-prod", "xtrabackup-incremental"),
155
+ ]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes