backup_service.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. """
  2. Backup service for SquidStats databases.
  3. Currently implemented:
  4. - SQLite
  5. Planned (not yet implemented):
  6. - MySQL / MariaDB
  7. - PostgreSQL
  8. """
  9. import os
  10. import re
  11. import shutil
  12. import sqlite3
  13. import subprocess
  14. from datetime import datetime
  15. from pathlib import Path
  16. from urllib.parse import urlparse
  17. from flask_babel import gettext as _
  18. from loguru import logger
  19. from config import Config
  20. from database.database import get_session
  21. from database.models.models import BackupConfig
  22. # Constants
  23. _MAX_RETENTION = 3
  24. _DEFAULT_BACKUP_DIR = "/opt/SquidStats/backups"
  25. FREQUENCY_CHOICES = {
  26. "daily_weekly": "Diaria — máx. 3 por semana",
  27. "daily_monthly": "Diaria — máx. 3 por mes",
  28. }
  29. _BACKUP_FILENAME_RE = re.compile(
  30. r"^squidstats_backup_[A-Za-z0-9_]+_[0-9]{8}_[0-9]{6}\.(sqlite3|sql)$"
  31. )
  32. # Config helpers
  33. def _default_config() -> dict:
  34. return {
  35. "db_type": "sqlite",
  36. "frequency": "daily_weekly",
  37. "backup_dir": _DEFAULT_BACKUP_DIR,
  38. "enabled": False,
  39. }
  40. def load_config() -> dict:
  41. """Read backup configuration from the database. Returns defaults if no row exists."""
  42. session = get_session()
  43. try:
  44. row = session.query(BackupConfig).first()
  45. if row is None:
  46. return _default_config()
  47. return {
  48. "db_type": row.db_type,
  49. "frequency": row.frequency,
  50. "backup_dir": row.backup_dir,
  51. "enabled": bool(row.enabled),
  52. }
  53. except Exception as e:
  54. logger.warning(f"Could not read backup config from DB, using defaults: {e}")
  55. return _default_config()
  56. finally:
  57. session.close()
  58. def save_config(cfg: dict) -> None:
  59. """Upsert backup configuration into the database (single-row table)."""
  60. allowed_keys = {"db_type", "frequency", "backup_dir", "enabled"}
  61. safe = {k: v for k, v in cfg.items() if k in allowed_keys}
  62. session = get_session()
  63. try:
  64. row = session.query(BackupConfig).first()
  65. if row is None:
  66. row = BackupConfig(
  67. db_type=safe.get("db_type", "sqlite"),
  68. frequency=safe.get("frequency", "daily_weekly"),
  69. backup_dir=safe.get("backup_dir", _DEFAULT_BACKUP_DIR),
  70. enabled=int(bool(safe.get("enabled", False))),
  71. created_at=datetime.now(),
  72. )
  73. session.add(row)
  74. else:
  75. if "db_type" in safe:
  76. row.db_type = safe["db_type"]
  77. if "frequency" in safe:
  78. row.frequency = safe["frequency"]
  79. if "backup_dir" in safe:
  80. row.backup_dir = safe["backup_dir"]
  81. if "enabled" in safe:
  82. row.enabled = int(bool(safe["enabled"]))
  83. row.updated_at = datetime.now()
  84. session.commit()
  85. except Exception as e:
  86. session.rollback()
  87. logger.exception(f"Error saving backup config: {e}")
  88. raise
  89. finally:
  90. session.close()
  91. # Backup directory helpers
  92. def _backup_dir(cfg: dict) -> Path:
  93. p = Path(cfg.get("backup_dir", _DEFAULT_BACKUP_DIR))
  94. try:
  95. p.mkdir(parents=True, exist_ok=True)
  96. except OSError as e:
  97. message = (
  98. f"No se puede acceder al directorio de salvas '{p}': {e}. "
  99. "Verifique que el directorio exista y que SquidStats tenga permisos."
  100. )
  101. logger.error(message)
  102. raise OSError(message) from e
  103. return p
  104. def _list_backup_files(backup_dir: Path) -> list[Path]:
  105. """Return backup files sorted newest-first."""
  106. files = [
  107. *backup_dir.glob("squidstats_backup_*.sqlite3"),
  108. *backup_dir.glob("squidstats_backup_*.sql"),
  109. ]
  110. return sorted(files, key=lambda f: f.stat().st_mtime, reverse=True)
  111. def _normalize_backup_filename(filename: str) -> Path | None:
  112. """Validate and normalize a backup filename from untrusted input."""
  113. if not filename:
  114. return None
  115. candidate = Path(filename)
  116. if candidate.name != filename:
  117. return None
  118. if candidate.is_absolute():
  119. return None
  120. if ".." in filename:
  121. return None
  122. if not _BACKUP_FILENAME_RE.fullmatch(filename):
  123. return None
  124. return Path(candidate.name)
  125. def _get_safe_backup_path(backup_dir: Path, filename: str) -> Path | None:
  126. """Return a safe backup path inside the configured backup directory."""
  127. normalized = _normalize_backup_filename(filename)
  128. if normalized is None:
  129. return None
  130. safe_root = os.path.realpath(backup_dir)
  131. fullpath = os.path.realpath(os.path.join(backup_dir, str(normalized)))
  132. if not fullpath.startswith(safe_root + os.sep) and fullpath != safe_root:
  133. return None
  134. return Path(fullpath)
  135. def _human_size(size_bytes: int) -> str:
  136. for unit in ("B", "KB", "MB", "GB"):
  137. if size_bytes < 1024:
  138. return f"{size_bytes:.1f} {unit}"
  139. size_bytes /= 1024
  140. return f"{size_bytes:.1f} TB"
  141. def list_backups(cfg: dict | None = None) -> list[dict]:
  142. """Return a list of backup metadata dicts, newest first."""
  143. if cfg is None:
  144. cfg = load_config()
  145. try:
  146. bdir = _backup_dir(cfg)
  147. except Exception as e:
  148. logger.error(f"No se puede acceder al directorio de salvas: {e}")
  149. return []
  150. try:
  151. result = []
  152. for f in _list_backup_files(bdir):
  153. stat = f.stat()
  154. created = datetime.fromtimestamp(stat.st_mtime)
  155. btype = "auto" if "_auto_" in f.name else "manual"
  156. result.append(
  157. {
  158. "filename": f.name,
  159. "created_at": created.strftime("%Y-%m-%d %H:%M"),
  160. "size_bytes": stat.st_size,
  161. "size_human": _human_size(stat.st_size),
  162. "type": btype,
  163. }
  164. )
  165. return result
  166. except Exception as e:
  167. logger.exception(f"Error listando salvas: {e}")
  168. return []
  169. # Retention enforcement
  170. def _enforce_retention(backup_dir: Path) -> None:
  171. """Delete oldest backups beyond _MAX_RETENTION."""
  172. files = _list_backup_files(backup_dir)
  173. for f in files[_MAX_RETENTION:]:
  174. try:
  175. f.unlink()
  176. logger.info(f"Backup retention: removed old backup {f.name}")
  177. except Exception as e:
  178. logger.warning(f"Could not remove old backup {f.name}: {e}")
  179. # Period quota check
  180. def _count_backups_in_period(backup_dir: Path, frequency: str) -> int:
  181. """Count how many auto-backups exist within the current period window."""
  182. now = datetime.now()
  183. count = 0
  184. for f in _list_backup_files(backup_dir):
  185. if "_auto_" not in f.name:
  186. continue
  187. mtime = datetime.fromtimestamp(f.stat().st_mtime)
  188. if frequency == "daily_weekly":
  189. if (
  190. mtime.isocalendar()[1] == now.isocalendar()[1]
  191. and mtime.year == now.year
  192. ):
  193. count += 1
  194. else: # daily_monthly
  195. if mtime.month == now.month and mtime.year == now.year:
  196. count += 1
  197. return count
  198. # SQLite backup
  199. def _sqlite_backup(backup_dir: Path, tag: str) -> Path:
  200. """Perform an online SQLite backup using sqlite3.Connection.backup()."""
  201. db_url = Config.DATABASE_URL
  202. parsed = urlparse(db_url)
  203. db_path = parsed.path
  204. # sqlite:///relative/path.db -> path is '/relative/path.db' but it should be project-relative
  205. if db_path.startswith("/") and not Path(db_path).exists():
  206. project_root = Path(os.path.dirname(os.path.abspath(__file__))).parent.parent
  207. rel_path = db_path.lstrip("/")
  208. alt_path = project_root / rel_path
  209. if alt_path.exists():
  210. db_path = str(alt_path)
  211. if not db_path or db_path == "/":
  212. db_path = db_url.replace("sqlite:///", "")
  213. db_path = Path(db_path)
  214. if not db_path.is_absolute():
  215. project_root = Path(os.path.dirname(os.path.abspath(__file__))).parent.parent
  216. db_path = project_root / db_path
  217. if not db_path.exists():
  218. # try fallback for sqlite:///filename.db
  219. try_path = (
  220. Path(os.path.dirname(os.path.abspath(__file__))).parent.parent
  221. / db_path.name
  222. )
  223. if try_path.exists():
  224. db_path = try_path
  225. else:
  226. raise FileNotFoundError(f"SQLite database not found: {db_path}")
  227. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  228. dest = backup_dir / f"squidstats_backup_{tag}_{timestamp}.sqlite3"
  229. src_conn = sqlite3.connect(str(db_path))
  230. dst_conn = sqlite3.connect(str(dest))
  231. try:
  232. src_conn.backup(dst_conn)
  233. finally:
  234. dst_conn.close()
  235. src_conn.close()
  236. logger.info(
  237. f"SQLite backup created: {dest.name} ({_human_size(dest.stat().st_size)})"
  238. )
  239. return dest
  240. # MySQL / MariaDB backup
  241. def _mysql_backup(backup_dir: Path, tag: str) -> Path:
  242. """Backup using mysqldump. Requires mysqldump to be installed."""
  243. db_url = Config.DATABASE_URL
  244. parsed = urlparse(db_url)
  245. host = parsed.hostname or "localhost"
  246. port = str(parsed.port or 3306)
  247. user = parsed.username or "root"
  248. password = parsed.password or ""
  249. dbname = parsed.path.lstrip("/")
  250. if not dbname:
  251. raise ValueError("No database name found in DATABASE_URL")
  252. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  253. dest = backup_dir / f"squidstats_backup_{tag}_{timestamp}.sql"
  254. cmd = [
  255. shutil.which("mysqldump") or "mysqldump",
  256. f"--host={host}",
  257. f"--port={port}",
  258. f"--user={user}",
  259. "--single-transaction",
  260. "--routines",
  261. "--triggers",
  262. dbname,
  263. ]
  264. env = os.environ.copy()
  265. if password:
  266. env["MYSQL_PWD"] = password
  267. with open(dest, "w") as f:
  268. result = subprocess.run(cmd, stdout=f, stderr=subprocess.PIPE, env=env) # noqa: S603
  269. if result.returncode != 0:
  270. dest.unlink(missing_ok=True)
  271. raise RuntimeError(
  272. f"mysqldump failed (exit {result.returncode}): {result.stderr.decode().strip()}"
  273. )
  274. logger.info(
  275. f"MySQL backup created: {dest.name} ({_human_size(dest.stat().st_size)})"
  276. )
  277. return dest
  278. # PostgreSQL backup
  279. def _postgresql_backup(backup_dir: Path, tag: str) -> Path:
  280. """Backup using pg_dump. Requires pg_dump to be installed."""
  281. db_url = Config.DATABASE_URL
  282. parsed = urlparse(db_url)
  283. host = parsed.hostname or "localhost"
  284. port = str(parsed.port or 5432)
  285. user = parsed.username or "postgres"
  286. password = parsed.password or ""
  287. dbname = parsed.path.lstrip("/")
  288. if not dbname:
  289. raise ValueError("No database name found in DATABASE_URL")
  290. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  291. dest = backup_dir / f"squidstats_backup_{tag}_{timestamp}.sql"
  292. cmd = [
  293. shutil.which("pg_dump") or "pg_dump",
  294. f"--host={host}",
  295. f"--port={port}",
  296. f"--username={user}",
  297. "--no-password",
  298. "--format=plain",
  299. dbname,
  300. ]
  301. env = os.environ.copy()
  302. env["PGPASSWORD"] = password
  303. with open(dest, "w") as f:
  304. result = subprocess.run(cmd, stdout=f, stderr=subprocess.PIPE, env=env) # noqa: S603
  305. if result.returncode != 0:
  306. dest.unlink(missing_ok=True)
  307. raise RuntimeError(
  308. f"pg_dump failed (exit {result.returncode}): {result.stderr.decode().strip()}"
  309. )
  310. logger.info(
  311. f"PostgreSQL backup created: {dest.name} ({_human_size(dest.stat().st_size)})"
  312. )
  313. return dest
  314. # Public API
  315. def run_backup(is_auto: bool = False) -> dict:
  316. """Execute a database backup according to the current configuration.
  317. Returns a dict with keys: status ('success'|'error'|'skipped'), message,
  318. and filename on success.
  319. """
  320. cfg = load_config()
  321. db_type = cfg.get("db_type", "sqlite").lower()
  322. frequency = cfg.get("frequency", "daily_weekly")
  323. try:
  324. bdir = _backup_dir(cfg)
  325. except OSError:
  326. return {
  327. "status": "error",
  328. "message": _("Error al acceder al directorio de salvas"),
  329. }
  330. tag = "auto" if is_auto else "manual"
  331. if is_auto:
  332. current_in_period = _count_backups_in_period(bdir, frequency)
  333. if current_in_period >= _MAX_RETENTION:
  334. msg = (
  335. f"Quota reached: {current_in_period}/{_MAX_RETENTION} backups "
  336. f"already exist in the current period ({frequency})."
  337. )
  338. logger.info(msg)
  339. return {"status": "skipped", "message": msg}
  340. try:
  341. if db_type == "sqlite":
  342. dest = _sqlite_backup(bdir, tag)
  343. elif db_type in ("mysql", "mariadb"):
  344. dest = _mysql_backup(bdir, tag)
  345. elif db_type == "postgresql":
  346. dest = _postgresql_backup(bdir, tag)
  347. else:
  348. return {"status": "error", "message": f"Motor de BD desconocido: {db_type}"}
  349. except NotImplementedError:
  350. return {
  351. "status": "error",
  352. "message": _("Funcionalidad de salva no implementada"),
  353. }
  354. except Exception:
  355. logger.exception("Backup failed")
  356. return {"status": "error", "message": _("Error al crear la salva")}
  357. _enforce_retention(bdir)
  358. return {
  359. "status": "success",
  360. "message": f"Salva creada correctamente: {dest.name}",
  361. "filename": dest.name,
  362. }
  363. def delete_backup(filename: str) -> dict:
  364. """Delete a specific backup file by name."""
  365. cfg = load_config()
  366. try:
  367. bdir = _backup_dir(cfg)
  368. except OSError:
  369. return {
  370. "status": "error",
  371. "message": _("Error al acceder al directorio de salvas"),
  372. }
  373. target = _get_safe_backup_path(bdir, filename)
  374. if target is None:
  375. return {"status": "error", "message": _("Nombre de archivo inválido")}
  376. if not target.exists():
  377. return {"status": "error", "message": _("La salva no existe")}
  378. target.unlink()
  379. logger.info(f"Backup deleted: {target.name}")
  380. return {"status": "success", "message": f"Salva eliminada: {target.name}"}
  381. def get_backup_file_path(filename: str) -> Path | None:
  382. """Return the absolute Path for a backup file, or None if invalid/missing."""
  383. cfg = load_config()
  384. try:
  385. bdir = _backup_dir(cfg)
  386. except OSError:
  387. return None
  388. target = _get_safe_backup_path(bdir, filename)
  389. if target is None or not target.exists():
  390. return None
  391. return target