borg-backup-ui icon indicating copy to clipboard operation
borg-backup-ui copied to clipboard

Add integrated MariaDB and PostgreSQL Docker backups with bundled managed scripts

Open borg-codex-bot opened this issue 1 month ago • 0 comments

Problem and user impact

Users currently need to import and edit the MariaDB/PostgreSQL Pre-hook examples from #557, provision credentials, and manually include the dump directory in a backup job. Those repository examples are not installed by the plugin. A completed export can therefore be missed by Borg, and script configuration is difficult to maintain.

Add permanent database backup settings and job integration for MariaDB and PostgreSQL running in local Docker containers. The plugin invokes the database's own dump tool, stages the output privately, and includes completed dumps in the current Borg archive. This is a logical database backup feature, not a full server or point-in-time recovery solution.

User-approved requirements:

  • Start with MariaDB and PostgreSQL in Docker.
  • Ship the required scripts with the plugin; no manual download/import is required for the integrated feature.
  • Clearly identify bundled scripts as maintained by Borg Backup UI. Direct edits may be overwritten by a plugin update.
  • Keep user configuration and credentials separate from managed scripts and preserve them during updates.

1. Scope and UI

Add Settings > Database backups using the existing settings and profile patterns, translated into German and English.

Each reusable profile has:

  • Immutable ID, display name, engine (mariadb or postgresql), enabled state.
  • Explicit local container selection, optional execution user, loopback connection port, and an explicit nonempty database list. Do not automatically add newly discovered databases to backup scope.
  • MariaDB: path to a protected client option file inside the container.
  • PostgreSQL: database user and path to a protected pgpass file inside the container.
  • Local staging mount and private staging directory, configurable free-space threshold, and bounded timeout (suggested default: 1800 seconds per database).
  • Explicit local retention policy: retain completed dumps by default, or opt in to removal of this run's managed dump files after verified archiving. Show space usage and provide explicit cleanup for retained/orphaned runs.
  • PostgreSQL option to include global roles/tablespaces, off by default with the omitted scope clearly displayed.

Provide Check connection (bounded read-only checks) and Create test dump (explicit operation that writes a private dump, reports location/size/status, and does not claim Borg protection). Long-running test dumps must expose status and cancellation without blocking the HTTP handler.

Jobs select one or more database profile IDs. Show the selected databases and restore scope in the wizard summary. Allow database-only jobs as well as jobs with existing file sources; source validation must require at least one valid file source or enabled database profile. All selected profiles are required in v1: no silently optional/ignored dump failures.

2. Bundled scripts and update ownership

Deliver maintained, parameterized executables for both engines within the existing plugin runtime layout, for example source files runtime/scripts/database-dump-mariadb.sh and runtime/scripts/database-dump-postgresql.sh. Verify their installed paths through the existing package builder. These are installed plugin assets, not automatically generated entries in the administrator's script inventory.

The first comment block after the shebang must include this notice in English and German:

Managed by Borg Backup UI.
This script is shipped and maintained by the plugin.
Local changes may be overwritten by the next plugin update.
Configure database backups in Settings > Database backups.
For custom behavior, create a separate user-managed copy.

Verwaltet durch Borg Backup UI.
Dieses Skript wird mit dem Plugin ausgeliefert und gepflegt.
Lokale Aenderungen koennen beim naechsten Plugin-Update ueberschrieben werden.
Datenbank-Sicherungen unter Einstellungen > Datenbank-Sicherungen konfigurieren.
Fuer eigene Anpassungen eine separate benutzerverwaltete Kopie erstellen.

Also document the invocation contract, parameters, exit codes, side effects, and script/protocol version. Display the ownership/update notice in the UI wherever managed scripts are presented. If their source is exposed in the UI, make that view read-only.

Plugin updates replace bundled assets but preserve profiles, credential references, existing custom scripts, and job assignments. Do not place user settings/passwords into bundled code. Never overwrite job-scripts.json to install or refresh these helpers.

Custom adaptations remain separately managed Pre hooks. Document that such copies do not receive plugin script updates and do not automatically inherit integrated dump inclusion/reporting. Prevent accidental double execution by explaining that the same export should not be configured both as a custom hook and as an integrated profile.

3. Persistence and architecture

Use the existing Python API, inventory locking/atomic persistence, job metadata, runner, resource locks, and workflow/reporting. No new service, scheduler, framework, or plugin layout is needed.

Proposed persistence: versioned config/database-profiles.json under the configured data root and an additive database_profile_ids field in job metadata. Jobs without the field behave exactly as before. Snapshot resolved profile settings at run start so edits do not alter an active run. Missing/disabled referenced profiles fail validation; block deletion of profiles referenced by any job, including disabled jobs.

For v1, credentials are administrator-provisioned protected files inside the container. The UI stores references only; it does not copy passwords out of Docker environment variables or edit container configuration. Setup guidance must explain that referenced files are not part of the plugin configuration backup. Preserve profile definitions/references through existing configuration backup/restore and report missing container credentials after restore.

Keep the runtime adapter/helper contract small: validated inputs, streamed dump output, sanitized structured result, and explicit cancellation/termination acknowledgement. Keep orchestration in the existing runner instead of building a second scheduler into shell scripts.

Relevant code to extend:

  • api/wizard_runner.py: orchestration and ResourceLockSet.
  • runtime/lib/job_workflow.py: measured database backup step.
  • api/job_control.py: cancellation/status.
  • api/inventory_store.py and api/apprise_profiles_api.py: existing persistence patterns.
  • api/job_scripts.py: existing custom hooks remain independent.
  • plugin/build.sh: delivery of the bundled helpers and package validation.

4. Execution order and concurrency

For jobs with database profiles:

  1. Resolve/snapshot configuration and acquire existing job/repository resource locks. Also acquire the existing docker-control resource even if this job does not stop containers, preventing another plugin job from stopping a database during export. Use the same coordination for connection checks and test dumps. Keep existing lock conflict behavior.
  2. Execute the existing Pre hook, perform existing mounts/prerequisite checks, and validate staging storage and database/container readiness.
  3. Execute a visible database_backup phase before existing Docker/VM stop actions. Process profiles/databases sequentially in v1. Resolve the chosen container to its ID and use that identity throughout the operation; a replacement or stop during export must fail the run.
  4. Continue existing Docker/VM stop policies, borg create, service recovery, maintenance, Post hook, and final reporting. Existing stop selections are not silently changed.
  5. Apply configured cleanup only to owned files whose successful archiving has been verified; preserve completed output on failures/warnings by default.

Pre-hook failures prevent dumps. Dump failure, missing tools, inaccessible database, timeout, empty/truncated output, missing mount, or insufficient space prevent borg create. Never reuse an older dump as the current run's result.

A live database dump does not promise a common recovery point with application files or other databases. In v1, application quiescing remains an explicit existing Pre/Post-hook responsibility; no new dependency orchestrator is included. Explain that stopping the application only after the dump is insufficient for that guarantee. MariaDB profiles reject selected nontransactional base tables in the online transactional mode, and documentation requires no concurrent schema changes.

5. Database tool contracts

MariaDB:

  • Require the container's mariadb-dump and appropriate client tooling; do not silently substitute MySQL binaries or install packages.
  • Export each explicitly selected database using transactional streaming options, including routines, events and triggers. Validate required privileges; do not silently drop objects after a permission error.
  • Produce SQL with database creation/selection information. Global database users/grants are excluded in v1 and must be identified as a separate restore prerequisite. Exclude system schemas from normal selection.

PostgreSQL:

  • Require the container's pg_dump and corresponding client/restore tools; use custom format, with internal compression disabled so Borg controls compression.
  • Include the selected database's schema and data; report required extensions and compatible restore tooling.
  • If global objects are selected, add a separate pg_dumpall --globals-only --no-role-passwords SQL artifact. Do not include role password hashes. Explain that credentials must be reprovisioned and tablespace paths may need adapting on restore.
  • Different database dumps and the global-object export are not a cluster-wide atomic snapshot.

Record actual server/client versions and check supported compatibility; images without required tools fail with an actionable message. Define and document a tested version/image matrix during implementation.

6. Staging and archive integrity

Use an explicitly selected persistent local pool/disk, never the Unraid boot stick or implicit RAM storage. Verify the expected mount is present so an absent pool cannot redirect a large dump onto the root filesystem. Require private directories/files (0700/0600), safe ownership, and symlink/path traversal protection.

Create an owned per-run directory and write partial files. Publish completed files atomically only after the exporter exits successfully and checks pass. Stream to disk rather than buffering complete dumps in memory. Free-space thresholds are guards, not size guarantees; handle ENOSPC during writing.

Automatically add only this run's completed artifacts and a manifest to the effective Borg sources. Show the exact archive location in the result. Do not recursively include historical runs or partial files through broad source paths. Detect conflicts with exclusions, marker-based exclusions and filesystem boundary settings; never silently archive without the required dumps. Confirm that expected artifacts are present in the created archive before reporting database archiving as complete.

Manifest fields: format version, job/run/profile IDs, engine, selected database names, container identity, server/client/helper versions, timestamps, sizes, checksums, included/omitted scope, and restoration guidance. Exclude credentials and raw client diagnostics.

Borg warnings remain warnings. Do not remove local output merely because borg create returned a warning or produced an archive name. Prune does not manage local dumps. Cleanup must be ownership-scoped, policy-authorized, and incapable of deleting existing user files or another run's data.

7. Cancellation, diagnostics, and recovery

Stopping the host-side docker exec process alone does not prove the in-container exporter stopped. Implement and test an owned in-container process lifecycle, bounded termination, and exit verification. Never kill unrelated database/server processes or stop an entire container to cancel a dump.

On an unconfirmed termination, report an unresolved operation and block conflicting retries until reconciled; do not release protection as if cleanup succeeded. Restart recovery must identify incomplete runs and reconcile live/stale exports before retrying. Retained completed dumps and orphaned partial runs must be visible for explicit cleanup.

Use structured, localized error codes and sanitized diagnostics, never raw secrets/client output or dump contents in logs/support bundles. Do not pass passwords in command arguments. Validate names/paths and use argument arrays or safely separated parameters without user-controlled shell interpolation. Avoid unrelated inherited database connection settings changing the intended target.

Reports distinguish dump completed, archived, and restore tested. Show per-database duration, size and outcome; a successful connection or readable dump header is not a restore test.

8. Restore and boundaries

Provide German/English instructions for extracting the archived artifacts and importing them into a separate database/container using matching MariaDB tools or pg_restore/psql. Explain roles, grants, extensions, tablespaces, credentials and application-file consistency. No automatic restore into production in v1.

Out of scope: MySQL, SQLite, remote databases/SSH, automatic container installation/reconfiguration, physical backups, replication/PITR/binlog/WAL management, arbitrary custom dump commands, automatic discovery of future databases, and a new application maintenance orchestrator.

9. Acceptance criteria and validation

  • [ ] Settings profiles, job selection, validation, reports and documentation work in German and English.
  • [ ] Both managed scripts are included in the built plugin with executable permissions and the bilingual ownership/update notice; a fresh install needs no manual script import.
  • [ ] An upgrade replaces managed scripts while preserving profiles, credential references, custom scripts and job assignments. No database export runs during install/update.
  • [ ] A database-only job and a mixed file/database job create archives containing exactly the current completed exports and manifest.
  • [ ] Existing jobs, hooks, scheduling, resource locks, recovery and notifications retain their behavior when the feature is not configured.
  • [ ] Unit/integration tests cover validation, inventory conflicts, secret redaction, profile snapshots, exporter failures, permission failures, missing tools/mounts, disk full, exclusions, warnings, cancellation, restart recovery and concurrent jobs/test dumps.
  • [ ] Process-lifecycle tests prove no exporter is left running after confirmed cancellation and unresolved exporters cannot be silently retried.
  • [ ] Tests verify failed exports never fall back to old dumps, partial/historical outputs cannot leak into archives through broad sources, and cleanup cannot affect unrelated data.
  • [ ] Real Docker tests for both engines create data and database objects, run a job, extract from Borg, restore into isolated containers, and verify data/objects. Test MariaDB routines/events/triggers/views and PostgreSQL ownership/global-object options, including documented omissions.
  • [ ] Manual Unraid fresh-install and upgrade tests cover package delivery, settings pages, credential-file setup, backup, cancellation, archive extraction and restore. Container images and database versions are recorded.
  • [ ] New interfaces/scripts use Python docstrings or shell function comments for inputs, outputs, errors and side effects.

10. Implementation and release plan

Implement under this issue on a fresh issue-specific branch from current origin/main. Suggested order: persistence/settings and packaged helpers; runner/staging/locking; wizard/status/reporting; restore documentation and integration tests. This issue does not authorize a larger architecture change.

User-visible feature: add release-notes/pending/<issue-number>.md before final preflight and update technical history as appropriate. Run focused checks, commit/push the final implementation, run ./plugin/mr-preflight.sh once for that final commit, create the code PR without stable artifacts, then create and verify a test-channel candidate with ./plugin/deploy-test.sh <version>. Stable promotion requires explicit maintainer test approval and a separate release PR.

This issue is a concrete implementation concept only; no implementation or release is part of its creation.

References

Maintainer-requested usability revision

The maintainer requested these changes after testing PR #592:

  • Store credentials in plugin-managed files under the Borg Backup UI secrets directory, entered through the UI. No manually provisioned container credential file or bind mount is required for new profiles. Existing references remain usable for data preservation.
  • List available databases using the configured database account and offer explicit checkbox selection. Discovery must never automatically extend a saved backup scope.
  • Match the established Settings card layout, theme colors, controls and responsive behavior.
  • Show bundled database helpers under Scripts as read-only managed assets, separate from custom job hooks.

Credentials must travel only over Docker stdin into an owned temporary in-container file and be removed after confirmed termination, including recovery. Keep passwords out of arguments, logs, responses and ordinary configuration exports; include managed files in the explicit encrypted Secrets backup. Changing credentials must not mutate a running job's credential snapshot. The revised implementation gets a new final-commit preflight and verified test-channel candidate; stable remains subject to explicit maintainer approval.

borg-codex-bot avatar Oct 24 '26 06:10 borg-codex-bot