Add native MQTT monitoring with Home Assistant Discovery
Objective and user benefit
Add an optional native MQTT integration to Borg Backup UI so users can display backup health in Home Assistant dashboards and build their own automations. Use Home Assistant MQTT Discovery to create devices/entities without requiring a custom Home Assistant integration.
This issue captures the maintainer discussion and is an implementation specification, not an instruction to publish a stable release. Initial scope is monitoring only. Remote control is a separate future phase.
Existing issue search
Searched open and closed issues for MQTT, Home Assistant, homeassistant and Mosquitto. No dedicated integration issue was found. #269 mentions optional Apprise MQTT dependencies, but covers notification-provider packaging rather than persistent MQTT state, discovery and availability. #82 mentions Home Assistant in Docker shutdown configuration; it is not an MQTT integration task.
Phase 1: agreed product scope
- [ ] Publish plugin availability and selected backup-job states to an existing external MQTT broker.
- [ ] Support automatic Home Assistant MQTT Discovery, with a plugin/server device and associated job devices/entities.
- [ ] Provide German and English settings, validation, connection diagnostics and documentation.
- [ ] Keep the feature disabled by default and use
borg-backup-uias the default configurable topic prefix. Do not useborgbackupas the product default. - [ ] Support multiple Unraid servers on the same broker without topic or entity collisions.
- [ ] Do not accept backup, restore, deletion or configuration commands over MQTT in phase 1.
Settings and diagnostics
Provide an MQTT section under Settings > Integrations, integrated into the existing settings architecture:
- Enabled toggle; broker hostname/address and port.
- Username and write-only password using existing secret storage/access conventions.
- Plain MQTT or TLS with certificate and hostname verification; optional private CA certificate.
- Configurable topic prefix, with
borg-backup-uias the default. - Home Assistant Discovery toggle and advanced discovery prefix (default
homeassistant). - Backup-job selection, defaulting to all eligible backup jobs; define how newly created jobs join an all-jobs selection.
- Connection test and an explicit Home Assistant resynchronization action.
- Connection state, last successful publication, and bounded, sanitized error diagnostics.
Validate settings before applying them. Changing the broker, credentials or prefix must safely reconfigure the worker and account for the previous discovery namespace. Integration management must follow the existing admin authorization and request protections.
TLS here protects the plugin-to-broker connection. It does not require HTTPS on the Borg Backup UI web interface or a server certificate for that interface. Do not add an insecure certificate-verification bypass as the default.
Initial entity inventory
Publish available structured values with explicit units and timestamp semantics:
| Scope | Values |
|---|---|
| Plugin/server | Availability, plugin version, number of running backup jobs |
| Job activity | Running/idle, current meaningful execution step |
| Last completed run | Result, completion time, duration |
| Backup health | Last successful backup timestamp, backup overdue |
| Schedule | Enabled state, next scheduled run when available |
| Data sizes | Original bytes, compressed bytes, newly stored/deduplicated bytes where available |
| Restore verification | Result/status, last test, validity deadline and overdue state where available |
Keep current activity separate from the last completed outcome. A running job must not erase its last successful backup evidence. Preserve warning, failed, cancelled, skipped and never-run distinctions where supported by the existing model. Use unknown/unavailable for missing values; do not invent zero sizes, success, timestamps or percentage progress.
Database archive readback verification is not proof of importing a dump into a test database. Preserve this distinction in MQTT names and values as well as in the existing UI. Detailed local dump disk-usage sensors are not required for phase 1; avoid adding recursive disk scans merely to publish MQTT updates.
Topic and identity contract
Suggested topic structure:
borg-backup-ui/<instance-id>/availability
borg-backup-ui/<instance-id>/status
borg-backup-ui/<instance-id>/jobs/<job-id>/state
- Use a persistent installation identity and existing stable job identities, not display names or IP addresses, for topics and HA unique IDs.
- Show readable server/job names in HA. Renaming a job must update display metadata without creating duplicate entities.
- Document payload fields, stable machine-readable status values, units, UTC/offset-aware timestamps and schema versioning. Localized UI labels must not change machine-readable states.
- Include a publication/update timestamp so stale data is diagnosable.
- Publish only an explicit allowlist of telemetry fields. Do not publish credentials, repository secrets, complete logs, source-path lists or raw internal status objects.
- Review installation identity behavior for configuration restore/cloning so separate servers do not silently share an MQTT client ID.
Runtime implementation
Fit the existing standalone Python/Unraid architecture; no framework, database or service-layout migration is required.
Starting points to inspect during implementation:
borg_backup_ui.py: existing service lifecycle and background loops.runtime/lib/status.pyandapi/status_api.py: persisted job outcomes and status data.api/jobs_api.py: stable job identity, configuration and restore-verification enrichment.api/restore_tests_api.pyand existing schedule/overdue calculations.runtime/lib/notification_events.py: structured events, useful for publication triggers where appropriate.
Use an independent MQTT publisher/worker. Notifications alone are insufficient: MQTT must also recover the current state on startup/reconnect and must not depend on enabled email/Unraid/Apprise notifications. Reuse existing business calculations; avoid a competing scheduler or definitions of backup success/overdue.
Evaluate paho-mqtt as the client. Pin and bundle the selected compatible version and dependencies with hashes, license notices and package tests. Verify the supported Unraid Python/runtime baseline. Do not install packages with pip at runtime on the user's server. Check whether the added dependency changes Apprise provider availability and document/test any resulting effect.
- Publish promptly on relevant state changes where practical, plus a configurable/bounded reconciliation interval (suggested starting point: 30 seconds).
- Read existing local state; do not invoke Borg scans, mount storage, rewrite user configuration or make self-HTTP calls just to collect telemetry.
- Keep broker network I/O out of backup execution and HTTP request critical paths.
- Use timeouts, bounded queues, coalescing of superseded state, and reconnect backoff. Broker failures must neither fail nor significantly delay backups or grow memory/disk usage indefinitely.
- Integrate worker startup, configuration reload and shutdown with the existing service lifecycle and maintenance/migration gates.
Discovery, retention and recovery
- Use stable HA discovery IDs and appropriate device/entity metadata, units and device classes.
- Use retained discovery and latest-state messages, with a documented QoS policy; QoS 1 is a reasonable starting point. State processing must tolerate duplicate delivery.
- Provide an availability topic with Last Will and explicit graceful offline/online transitions. Publish online only when the worker has initialized its state.
- On broker reconnect, publish a fresh snapshot instead of replaying obsolete intermediate states.
- Handle Home Assistant's birth/status message (normally
homeassistant/status) by resending discovery and current state, with bounded staggering if needed. - Remove owned retained discovery/state for deleted or deselected jobs so ghost entities do not accumulate. Track pending cleanup across temporary broker outages.
- Define and document discovery removal when disabling the integration or changing broker/topic prefix. Scope all cleanup to topics owned by this installation; never use broad wildcard deletion.
- Repeated synchronization, restart or rename must be idempotent and must not duplicate entities.
- Persistent state must not make disconnected or stale plugin data appear indefinitely healthy. Test plugin and broker restarts, including retained online state and abrupt plugin termination.
Test setup on Unraid
The maintainer can use two Docker containers on Unraid:
- Home Assistant Container.
- Eclipse Mosquitto as a separate broker, with persistent configuration/data and authenticated access.
- A Borg Backup UI test-channel package containing this integration.
Home Assistant Container does not include app/add-on management, so Mosquitto runs separately. Configure the HA MQTT integration and the plugin with the same reachable broker. HTTPS on the plugin web UI is not required. Test plain MQTT on an isolated/trusted local test network and verified TLS, including a private CA, before calling TLS support complete.
Use safe test jobs and fixture failures. Include the realistic case where an Appdata job stops Home Assistant and/or Mosquitto: backups must finish independently, and discovery/current state must recover after the containers restart.
Acceptance and validation
- [ ] Settings save/load, validation, write-only secrets, authorization and DE/EN UI work with MQTT disabled and enabled.
- [ ] Discovery produces the intended server/job entities; values and timestamps match the plugin for idle, running, success, warning, failure, cancellation, skipped and never-run states.
- [ ] Backup overdue and restore-test validity use existing semantics; archive readback is not presented as a database restore test.
- [ ] Renaming preserves entity identity; deleting/deselecting jobs cleans up owned entities; repeated sync creates no duplicates.
- [ ] Multiple plugin instances on one broker remain isolated.
- [ ] Plugin restart, abrupt termination, broker restart, HA restart, incorrect credentials and TLS trust/hostname failures are handled predictably without leaking secrets.
- [ ] Broker outages do not alter backup results or block backup/HTTP execution; resource use and retries remain bounded.
- [ ] Configuration changes and offline cleanup do not publish under a stale identity or delete unrelated retained messages.
- [ ] Test with a real local Mosquitto broker as well as unit/contract and bilingual browser tests. Keep network-dependent tests deterministic and isolated.
- [ ] Test the packaged Unraid runtime, dependency/license contents and restart/reinstall behavior.
- [ ] Update German/English manuals with container setup, example dashboard/automation use, troubleshooting, topic contract, data freshness and discovery cleanup.
- [ ] Add a user-visible release-note fragment referencing this issue.
- [ ] Follow the repository workflow: focused local tests, code PR, authoritative GitHub CI, published and verified test-channel candidate, then manual Unraid/HA verification. Stable promotion requires separate explicit maintainer test/release approval and a separate release PR.
Phase 2: optional future control, not phase-1 acceptance
A separately scoped follow-up could add explicitly enabled commands to start selected backup jobs or restore tests from Home Assistant.
Before implementation, define per-job opt-in, broker topic permissions, command IDs/expiry and acknowledgements, duplicate/replay handling, and rejection of retained or stale commands. Route accepted commands through existing job validation, locks and execution paths. Do not bypass those safeguards or create a second job runner.
Destructive operations such as restore execution, deletion/prune or configuration changes are not implicitly included. Phase 2 requires a separate implementation decision and issue.
Effort estimate and boundaries
The discussion estimated approximately 5-8 developer-days for a reliable monitoring-only first version, including settings/TLS, discovery/state publication, recovery/lifecycle handling, tests, DE/EN documentation and a test candidate. This is a rough planning estimate, not a delivery commitment. Phase-2 remote control is excluded.
No broker installation, Home Assistant deployment, code implementation or stable release is performed by creating this issue.
References
- Home Assistant MQTT and Discovery: https://www.home-assistant.io/integrations/mqtt/
- Home Assistant Container: https://www.home-assistant.io/installation/linux/#install-home-assistant-container
- Eclipse Paho Python client: https://eclipse.dev/paho/files/paho.mqtt.python/html/client.html
- Official Mosquitto Docker image: https://github.com/eclipse-mosquitto/mosquitto/blob/master/docker/generic/README.md
- Mosquitto authentication: https://mosquitto.org/documentation/authentication-methods/