local_backup.py 12 KB

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