| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- import json
- import os
- import subprocess
- from datetime import datetime
- from db import db, Job, Run
- BACKUP_DIR = None # initialisé depuis app.config
- def execute_job(job_id):
- """Point d'entrée appelé par APScheduler (dans app_context Flask)."""
- from flask import current_app
- backup_dir = current_app.config["YUNOHOST_BACKUP_DIR"]
- instance = current_app.config["INSTANCE_NAME"]
- job = db.session.get(Job, job_id)
- if not job or not job.enabled:
- return
- run = Run(job_id=job_id, started_at=datetime.utcnow(), status="running")
- db.session.add(run)
- db.session.commit()
- try:
- if job.type == "ynh_app":
- archive_name, log = _run_ynh_app(job, instance, backup_dir)
- elif job.type == "ynh_system":
- archive_name, log = _run_ynh_system(job, instance, backup_dir)
- elif job.type in ("mysql", "postgresql"):
- from jobs.db_dump import run_db_dump
- archive_name, log = run_db_dump(job, instance, backup_dir)
- else:
- raise ValueError(f"Type de job non géré : {job.type}")
- archive_path = os.path.join(backup_dir, archive_name + ".tar")
- size_bytes = os.path.getsize(archive_path) if os.path.exists(archive_path) else None
- run.status = "success"
- run.archive_name = archive_name
- run.size_bytes = size_bytes
- run.log_text = log
- from retention import apply_retention
- deleted = apply_retention(job, archive_name, backup_dir)
- if deleted:
- run.log_text += f"\n\nRétention : {len(deleted)} archive(s) supprimée(s) : {', '.join(deleted)}"
- except Exception as exc:
- run.status = "error"
- run.log_text = str(exc)
- finally:
- run.finished_at = datetime.utcnow()
- db.session.commit()
- def _archive_name(instance, label):
- date_str = datetime.utcnow().strftime("%Y%m%d")
- return f"{instance}_{label}_{date_str}"
- def _run_ynh_app(job, instance, backup_dir):
- cfg = json.loads(job.config_json or "{}")
- app_id = cfg.get("app_id", "")
- core_only = cfg.get("core_only", job.core_only)
- archive = _archive_name(instance, app_id)
- _abort_if_exists(archive, backup_dir)
- cmd = ["sudo", "yunohost", "backup", "create", "--apps", app_id, "--name", archive]
- if core_only:
- cmd = ["sudo", "env", "BACKUP_CORE_ONLY=1"] + cmd[1:]
- result = subprocess.run(cmd, capture_output=True, text=True, timeout=3600)
- log = (result.stdout + result.stderr).strip()
- if result.returncode != 0:
- raise RuntimeError(f"yunohost backup create a échoué (code {result.returncode}) :\n{log}")
- return archive, log
- def _run_ynh_system(job, instance, backup_dir):
- archive = _archive_name(instance, "system")
- _abort_if_exists(archive, backup_dir)
- cmd = ["sudo", "yunohost", "backup", "create", "--system", "--name", archive]
- result = subprocess.run(cmd, capture_output=True, text=True, timeout=3600)
- log = (result.stdout + result.stderr).strip()
- if result.returncode != 0:
- raise RuntimeError(f"yunohost backup create a échoué (code {result.returncode}) :\n{log}")
- return archive, log
- def _abort_if_exists(archive_name, backup_dir):
- path = os.path.join(backup_dir, archive_name + ".tar")
- if os.path.exists(path):
- raise RuntimeError(
- f"L'archive {archive_name}.tar existe déjà. "
- "Supprimez-la manuellement ou attendez le prochain cycle."
- )
|