ynh_backup.py 6.3 KB

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