ynh_backup.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import json
  2. import os
  3. import subprocess
  4. from datetime import datetime
  5. from db import db, Job, Run
  6. BACKUP_DIR = None # initialisé depuis app.config
  7. def execute_job(job_id):
  8. """Point d'entrée appelé par APScheduler (dans app_context Flask)."""
  9. from flask import current_app
  10. backup_dir = current_app.config["YUNOHOST_BACKUP_DIR"]
  11. instance = current_app.config["INSTANCE_NAME"]
  12. job = db.session.get(Job, job_id)
  13. if not job or not job.enabled:
  14. return
  15. run = Run(job_id=job_id, started_at=datetime.utcnow(), status="running")
  16. db.session.add(run)
  17. db.session.commit()
  18. try:
  19. if job.type == "ynh_app":
  20. archive_name, log = _run_ynh_app(job, instance, backup_dir)
  21. elif job.type == "ynh_system":
  22. archive_name, log = _run_ynh_system(job, instance, backup_dir)
  23. elif job.type in ("mysql", "postgresql"):
  24. from jobs.db_dump import run_db_dump
  25. archive_name, log = run_db_dump(job, instance, backup_dir)
  26. elif job.type == "custom_dir":
  27. from jobs.custom_dir import backup_custom_dir
  28. archive_name, log = backup_custom_dir(job, instance, backup_dir)
  29. else:
  30. raise ValueError(f"Type de job non géré : {job.type}")
  31. archive_path = os.path.join(backup_dir, archive_name + ".tar")
  32. from jobs.utils import sudo_getsize
  33. size_bytes = sudo_getsize(archive_path) or None
  34. run.status = "success"
  35. run.archive_name = archive_name
  36. run.size_bytes = size_bytes
  37. run.log_text = log
  38. from retention import apply_retention
  39. deleted = apply_retention(job, archive_name, backup_dir)
  40. if deleted:
  41. run.log_text += f"\n\nRétention : {len(deleted)} archive(s) supprimée(s) : {', '.join(deleted)}"
  42. # Transfert automatique vers la destination configurée
  43. if job.destination_id:
  44. from db import Destination
  45. from flask import current_app
  46. dest = db.session.get(Destination, job.destination_id)
  47. if dest and dest.enabled:
  48. data_dir = current_app.config["DATA_DIR"]
  49. try:
  50. from jobs.transfer import transfer_archive
  51. transfer_log = transfer_archive(archive_name, dest, backup_dir, data_dir)
  52. run.log_text += f"\n\nTransfert → {dest.remote_str} :\n{transfer_log}"
  53. except Exception as transfer_exc:
  54. run.log_text += f"\n\n⚠ Transfert échoué vers {dest.remote_str} :\n{transfer_exc}"
  55. except Exception as exc:
  56. run.status = "error"
  57. run.log_text = str(exc)
  58. finally:
  59. run.finished_at = datetime.utcnow()
  60. db.session.commit()
  61. try:
  62. from notifications import send_job_notification
  63. send_job_notification(run, job)
  64. except Exception:
  65. pass
  66. def _archive_name(instance, label):
  67. date_str = datetime.utcnow().strftime("%Y%m%d")
  68. return f"{instance}_{label}_{date_str}"
  69. def _run_ynh_app(job, instance, backup_dir):
  70. cfg = json.loads(job.config_json or "{}")
  71. app_id = cfg.get("app_id", "")
  72. core_only = cfg.get("core_only", job.core_only)
  73. archive = _archive_name(instance, app_id)
  74. _abort_if_exists(archive, backup_dir)
  75. cmd = ["sudo", "yunohost", "backup", "create", "--apps", app_id, "--name", archive]
  76. if core_only:
  77. cmd = ["sudo", "env", "BACKUP_CORE_ONLY=1"] + cmd[1:]
  78. result = subprocess.run(cmd, capture_output=True, text=True, timeout=3600)
  79. log = (result.stdout + result.stderr).strip()
  80. if result.returncode != 0:
  81. raise RuntimeError(f"yunohost backup create a échoué (code {result.returncode}) :\n{log}")
  82. return archive, log
  83. def _run_ynh_system(job, instance, backup_dir):
  84. archive = _archive_name(instance, "system")
  85. _abort_if_exists(archive, backup_dir)
  86. cmd = ["sudo", "yunohost", "backup", "create", "--system", "--name", archive]
  87. result = subprocess.run(cmd, capture_output=True, text=True, timeout=3600)
  88. log = (result.stdout + result.stderr).strip()
  89. if result.returncode != 0:
  90. raise RuntimeError(f"yunohost backup create a échoué (code {result.returncode}) :\n{log}")
  91. return archive, log
  92. def _abort_if_exists(archive_name, backup_dir):
  93. from jobs.utils import sudo_exists
  94. path = os.path.join(backup_dir, archive_name + ".tar")
  95. if sudo_exists(path):
  96. raise RuntimeError(
  97. f"L'archive {archive_name}.tar existe déjà. "
  98. "Supprimez-la manuellement ou attendez le prochain cycle."
  99. )