ynh_backup.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. import json
  2. import os
  3. import subprocess
  4. from datetime import datetime
  5. from db import db, Job, Run, Destination, RemoteInstance, _size_human
  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. # Checkpoint 1 : archive créée — persister immédiatement
  35. run.archive_name = archive_name
  36. run.size_bytes = size_bytes
  37. run.log_text = f"[archive] {archive_name} créée ({_size_human(size_bytes)})\n\n{log}"
  38. db.session.commit()
  39. from retention import apply_retention
  40. deleted, failed = apply_retention(job, archive_name, backup_dir)
  41. if deleted:
  42. run.log_text += f"\n\nRétention locale : {len(deleted)} archive(s) supprimée(s) : {', '.join(deleted)}"
  43. if failed:
  44. run.log_text += f"\n⚠ Rétention locale : échec de suppression pour : {', '.join(failed)}"
  45. if deleted or failed:
  46. db.session.commit()
  47. # Checkpoint 2 : transfert vers chaque destination
  48. transfer_errors = 0
  49. for jd in job.job_destinations:
  50. obj = jd.resolved
  51. if obj is None:
  52. continue
  53. if jd.dest_type == "ssh":
  54. if not obj.enabled:
  55. continue
  56. data_dir = current_app.config["DATA_DIR"]
  57. run.log_text += f"\n\nTransfert → {obj.remote_str} : démarré…"
  58. db.session.commit()
  59. try:
  60. from jobs.transfer import transfer_archive
  61. transfer_log = transfer_archive(archive_name, obj, backup_dir, data_dir)
  62. run.log_text += f"\n{transfer_log}"
  63. try:
  64. from retention import apply_ssh_retention
  65. ssh_deleted = apply_ssh_retention(job, obj, data_dir)
  66. if ssh_deleted:
  67. run.log_text += f"\nRétention distante SSH : {len(ssh_deleted)} archive(s) supprimée(s) : {', '.join(ssh_deleted)}"
  68. except Exception as ret_exc:
  69. run.log_text += f"\n⚠ Rétention distante SSH échouée : {ret_exc}"
  70. except Exception as transfer_exc:
  71. run.log_text += f"\n⚠ Transfert échoué : {transfer_exc}"
  72. transfer_errors += 1
  73. db.session.commit()
  74. elif jd.dest_type == "instance":
  75. run.log_text += f"\n\nTransfert HTTP → {obj.name} ({obj.url}) : démarré…"
  76. db.session.commit()
  77. try:
  78. from jobs.transfer import push_archive_to_instance
  79. transfer_log = push_archive_to_instance(archive_name, obj, backup_dir, job=job)
  80. run.log_text += f"\n{transfer_log}"
  81. except Exception as transfer_exc:
  82. run.log_text += f"\n⚠ Transfert HTTP échoué : {transfer_exc}"
  83. transfer_errors += 1
  84. db.session.commit()
  85. run.status = "warning" if transfer_errors else "success"
  86. except Exception as exc:
  87. run.status = "error"
  88. if run.log_text:
  89. run.log_text += f"\n\nErreur fatale : {exc}"
  90. else:
  91. run.log_text = str(exc)
  92. finally:
  93. run.finished_at = datetime.utcnow()
  94. db.session.commit()
  95. try:
  96. from notifications import send_job_notification
  97. send_job_notification(run, job)
  98. except Exception:
  99. pass
  100. def _archive_name(instance, label, backup_dir):
  101. from jobs.utils import unique_archive_name
  102. date_str = datetime.utcnow().strftime("%Y%m%d")
  103. return unique_archive_name(f"{instance}_{label}_{date_str}", backup_dir)
  104. def _run_ynh_app(job, instance, backup_dir):
  105. cfg = json.loads(job.config_json or "{}")
  106. app_id = cfg.get("app_id", "")
  107. core_only = cfg.get("core_only", job.core_only)
  108. archive = _archive_name(instance, app_id, backup_dir)
  109. cmd = ["sudo", "yunohost", "backup", "create", "--apps", app_id, "--name", archive]
  110. run_env = None
  111. if core_only:
  112. # sudo env ... n'est pas autorisé dans sudoers ; on passe la variable
  113. # via l'environnement du processus sudo et env_keep dans sudoers.
  114. run_env = {**os.environ, "BACKUP_CORE_ONLY": "1"}
  115. result = subprocess.run(cmd, capture_output=True, text=True, timeout=3600, env=run_env)
  116. log = (result.stdout + result.stderr).strip()
  117. if result.returncode != 0:
  118. raise RuntimeError(f"yunohost backup create a échoué (code {result.returncode}) :\n{log}")
  119. return archive, log
  120. def _run_ynh_system(job, instance, backup_dir):
  121. cfg = json.loads(job.config_json or "{}")
  122. hooks = cfg.get("hooks", [])
  123. archive = _archive_name(instance, "system", backup_dir)
  124. cmd = ["sudo", "yunohost", "backup", "create", "--system"] + hooks + ["--name", archive]
  125. result = subprocess.run(cmd, capture_output=True, text=True, timeout=3600)
  126. log = (result.stdout + result.stderr).strip()
  127. if result.returncode != 0:
  128. raise RuntimeError(f"yunohost backup create a échoué (code {result.returncode}) :\n{log}")
  129. return archive, log