local_backup.py 12 KB

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