local_backup.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. """Scheduled local backup service.
  2. Creates ZIP snapshots of the full Bambuddy data (database + data directories)
  3. on a configurable schedule with retention management.
  4. """
  5. import asyncio
  6. import logging
  7. from datetime import datetime, timedelta, timezone
  8. from pathlib import Path
  9. from sqlalchemy import select
  10. from backend.app.core.config import settings as app_settings
  11. from backend.app.core.database import async_session
  12. from backend.app.models.settings import Settings
  13. # The TZ-env resolution used to live here. It moved to utils/local_time when the
  14. # smart-plug energy history (#2539) needed the same local day boundary. Re-exported
  15. # under the old private name so existing importers keep working.
  16. from backend.app.utils.local_time import local_zone as _local_zone
  17. logger = logging.getLogger(__name__)
  18. SCHEDULE_INTERVALS = {
  19. "hourly": 3600,
  20. "daily": 86400,
  21. "weekly": 604800,
  22. }
  23. def _default_backup_dir() -> Path:
  24. return app_settings.base_dir / "backups"
  25. class LocalBackupService:
  26. """Manages scheduled local backup snapshots with retention."""
  27. def __init__(self):
  28. self._scheduler_task: asyncio.Task | None = None
  29. self._check_interval = 60
  30. self._running: bool = False
  31. self._last_backup_at: str | None = None
  32. self._last_status: str | None = None
  33. self._last_message: str | None = None
  34. self._next_run: datetime | None = None
  35. async def start_scheduler(self):
  36. """Start the background scheduler loop."""
  37. if self._scheduler_task is not None:
  38. return
  39. logger.info("Starting local backup scheduler")
  40. # Seed next_run from settings so the first check has a target
  41. await self._seed_next_run()
  42. self._scheduler_task = asyncio.create_task(self._scheduler_loop())
  43. def stop_scheduler(self):
  44. """Stop the scheduler."""
  45. if self._scheduler_task:
  46. self._scheduler_task.cancel()
  47. self._scheduler_task = None
  48. logger.info("Stopped local backup scheduler")
  49. async def _scheduler_loop(self):
  50. """Main scheduler loop — checks for due backups every minute."""
  51. while True:
  52. try:
  53. await asyncio.sleep(self._check_interval)
  54. await self._check_scheduled_backup()
  55. except asyncio.CancelledError:
  56. break
  57. except Exception as e:
  58. logger.error("Error in local backup scheduler: %s", e)
  59. await asyncio.sleep(60)
  60. async def _seed_next_run(self):
  61. """Load settings and calculate initial next_run."""
  62. try:
  63. settings = await self._load_settings()
  64. if settings.get("enabled"):
  65. self._next_run = self._calculate_next_run(
  66. settings.get("schedule", "daily"),
  67. settings.get("time", "03:00"),
  68. )
  69. except Exception as e:
  70. logger.debug("Could not seed local backup next_run: %s", e)
  71. async def _load_settings(self) -> dict:
  72. """Read local backup settings from the DB."""
  73. async with async_session() as db:
  74. keys = [
  75. "local_backup_enabled",
  76. "local_backup_schedule",
  77. "local_backup_time",
  78. "local_backup_retention",
  79. "local_backup_path",
  80. ]
  81. result = await db.execute(select(Settings).where(Settings.key.in_(keys)))
  82. rows = {r.key: r.value for r in result.scalars().all()}
  83. return {
  84. "enabled": rows.get("local_backup_enabled", "false").lower() == "true",
  85. "schedule": rows.get("local_backup_schedule", "daily"),
  86. "time": rows.get("local_backup_time", "03:00"),
  87. "retention": int(rows.get("local_backup_retention", "5")),
  88. "path": rows.get("local_backup_path", ""),
  89. }
  90. async def _check_scheduled_backup(self):
  91. """Check if a scheduled backup is due and run it."""
  92. settings = await self._load_settings()
  93. if not settings["enabled"]:
  94. self._next_run = None
  95. return
  96. now = datetime.now(timezone.utc)
  97. # If no next_run set, schedule one
  98. if self._next_run is None:
  99. self._next_run = self._calculate_next_run(settings["schedule"], settings["time"])
  100. return
  101. if self._next_run <= now:
  102. logger.info("Running scheduled local backup")
  103. await self.run_backup(settings)
  104. self._next_run = self._calculate_next_run(settings["schedule"], settings["time"])
  105. def _calculate_next_run(self, schedule_type: str, time_str: str = "03:00") -> datetime:
  106. """Calculate the next scheduled run time.
  107. For hourly: next full hour (timezone-agnostic).
  108. For daily/weekly: next occurrence of the configured HH:MM, interpreted
  109. in the container's local timezone (TZ env var, UTC fallback). Returns
  110. a UTC-aware datetime for storage / comparison against ``now``.
  111. """
  112. now_utc = datetime.now(timezone.utc)
  113. if schedule_type == "hourly":
  114. # Next full hour
  115. next_run = now_utc.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)
  116. return next_run
  117. # Parse HH:MM time
  118. try:
  119. parts = time_str.strip().split(":")
  120. hour = int(parts[0])
  121. minute = int(parts[1]) if len(parts) > 1 else 0
  122. except (ValueError, IndexError):
  123. hour, minute = 3, 0
  124. local_tz = _local_zone()
  125. now_local = now_utc.astimezone(local_tz)
  126. # Next occurrence of HH:MM local time, today or tomorrow.
  127. # ``fold=0`` resolves the ambiguous wall-clock window at DST fall-back
  128. # to the earlier instance (consistent with cron's behaviour). On the
  129. # spring-forward gap the synthesized local time will normalise to the
  130. # next valid instant when converted to UTC.
  131. next_local = now_local.replace(hour=hour, minute=minute, second=0, microsecond=0, fold=0)
  132. if next_local <= now_local:
  133. next_local += timedelta(days=1)
  134. if schedule_type == "weekly":
  135. next_local += timedelta(weeks=1)
  136. return next_local.astimezone(timezone.utc)
  137. def _resolve_backup_dir(self, path_setting: str) -> Path:
  138. """Resolve the backup output directory from settings."""
  139. if path_setting.strip():
  140. return Path(path_setting.strip())
  141. return _default_backup_dir()
  142. async def run_backup(self, settings: dict | None = None) -> dict:
  143. """Run a backup now. Returns {success, message, filename}."""
  144. if self._running:
  145. return {"success": False, "message": "Backup already in progress"}
  146. self._running = True
  147. try:
  148. if settings is None:
  149. settings = await self._load_settings()
  150. backup_dir = self._resolve_backup_dir(settings["path"])
  151. backup_dir.mkdir(parents=True, exist_ok=True)
  152. from backend.app.api.routes.settings import create_backup_zip
  153. zip_path, filename = await create_backup_zip(output_path=backup_dir)
  154. # Prune old backups
  155. retention = max(1, settings["retention"])
  156. self._prune_backups(backup_dir, retention)
  157. self._last_backup_at = datetime.now(timezone.utc).isoformat()
  158. self._last_status = "success"
  159. self._last_message = filename
  160. logger.info("Local backup created: %s", zip_path)
  161. return {"success": True, "message": "Backup created", "filename": filename}
  162. except Exception as e:
  163. self._last_backup_at = datetime.now(timezone.utc).isoformat()
  164. self._last_status = "failed"
  165. self._last_message = str(e)
  166. logger.error("Local backup failed: %s", e, exc_info=True)
  167. return {"success": False, "message": f"Backup failed: {e}"}
  168. finally:
  169. self._running = False
  170. def _prune_backups(self, backup_dir: Path, retention: int):
  171. """Delete oldest backups exceeding the retention count."""
  172. backups = sorted(
  173. backup_dir.glob("bambuddy-backup-*.zip"),
  174. key=lambda p: p.stat().st_mtime,
  175. reverse=True,
  176. )
  177. for old_backup in backups[retention:]:
  178. try:
  179. old_backup.unlink()
  180. logger.info("Pruned old backup: %s", old_backup.name)
  181. except OSError as e:
  182. logger.warning("Could not delete old backup %s: %s", old_backup.name, e)
  183. def get_status(self) -> dict:
  184. """Return current scheduler status."""
  185. return {
  186. "is_running": self._running,
  187. "last_backup_at": self._last_backup_at,
  188. "last_status": self._last_status,
  189. "last_message": self._last_message,
  190. "next_run": self._next_run.isoformat() if self._next_run else None,
  191. }
  192. def resolve_backup_file(self, path_setting: str, filename: str) -> Path | None:
  193. """Resolve a backup filename to a full path, with safety checks."""
  194. if "/" in filename or "\\" in filename or ".." in filename:
  195. return None
  196. if not filename.startswith("bambuddy-backup-") or not filename.endswith(".zip"):
  197. return None
  198. backup_dir = self._resolve_backup_dir(path_setting)
  199. target = (
  200. backup_dir / filename
  201. ) # SEC-PATH-OK: filename rejected above on /, \\, .., plus startswith "bambuddy-backup-" + endswith ".zip" gate
  202. if not target.exists():
  203. return None
  204. return target
  205. def list_backups(self, path_setting: str) -> list[dict]:
  206. """List backup ZIP files in the backup directory."""
  207. backup_dir = self._resolve_backup_dir(path_setting)
  208. if not backup_dir.exists():
  209. return []
  210. backups = []
  211. for f in sorted(backup_dir.glob("bambuddy-backup-*.zip"), key=lambda p: p.stat().st_mtime, reverse=True):
  212. stat = f.stat()
  213. backups.append(
  214. {
  215. "filename": f.name,
  216. "size": stat.st_size,
  217. "created_at": datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc).isoformat(),
  218. }
  219. )
  220. return backups
  221. def delete_backup(self, path_setting: str, filename: str) -> dict:
  222. """Delete a specific backup file. Returns {success, message}."""
  223. # Path traversal protection
  224. if "/" in filename or "\\" in filename or ".." in filename:
  225. return {"success": False, "message": "Invalid filename"}
  226. backup_dir = self._resolve_backup_dir(path_setting)
  227. target = (
  228. backup_dir / filename
  229. ) # SEC-PATH-OK: filename rejected above on /, \\, .., plus startswith "bambuddy-backup-" + endswith ".zip" gate below
  230. if not target.exists():
  231. return {"success": False, "message": "Backup not found"}
  232. if not target.name.startswith("bambuddy-backup-") or not target.name.endswith(".zip"):
  233. return {"success": False, "message": "Invalid backup file"}
  234. try:
  235. target.unlink()
  236. return {"success": True, "message": "Backup deleted"}
  237. except OSError as e:
  238. return {"success": False, "message": f"Could not delete: {e}"}
  239. local_backup_service = LocalBackupService()