jobs.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. import json
  2. import subprocess
  3. import threading
  4. from datetime import datetime
  5. from flask import (
  6. Blueprint,
  7. current_app,
  8. flash,
  9. redirect,
  10. render_template,
  11. request,
  12. url_for,
  13. )
  14. from db import db, Job, Run, Destination
  15. from helpers import read_archive_info, get_ynh_apps
  16. bp = Blueprint("jobs", __name__)
  17. # --- Dashboard local ----------------------------------------------------------
  18. @bp.route("/")
  19. def index():
  20. from db import RemoteInstance
  21. jobs = Job.query.order_by(Job.name).all()
  22. last_runs = {
  23. j.id: Run.query.filter_by(job_id=j.id).order_by(Run.started_at.desc()).first()
  24. for j in jobs
  25. }
  26. instances = RemoteInstance.query.order_by(RemoteInstance.name).all()
  27. return render_template("dashboard_local.html", jobs=jobs, last_runs=last_runs,
  28. instances=instances)
  29. # --- CRUD Jobs ----------------------------------------------------------------
  30. def _used_app_ids(exclude_job_id=None):
  31. """Retourne les app_id déjà couverts par un job ynh_app existant."""
  32. q = Job.query.filter_by(type="ynh_app")
  33. if exclude_job_id:
  34. q = q.filter(Job.id != exclude_job_id)
  35. return {json.loads(j.config_json).get("app_id") for j in q.all() if j.config_json}
  36. @bp.route("/jobs/new", methods=["GET", "POST"])
  37. def job_new():
  38. if request.method == "POST":
  39. return _save_job(None)
  40. return render_template("job_form.html", job=None,
  41. ynh_apps=get_ynh_apps(exclude_app_ids=_used_app_ids()),
  42. destinations=Destination.query.filter_by(enabled=True).all())
  43. @bp.route("/jobs/<int:job_id>/edit", methods=["GET", "POST"])
  44. def job_edit(job_id):
  45. job = db.get_or_404(Job, job_id)
  46. if request.method == "POST":
  47. return _save_job(job)
  48. return render_template("job_form.html", job=job,
  49. ynh_apps=get_ynh_apps(exclude_app_ids=_used_app_ids(exclude_job_id=job_id)),
  50. destinations=Destination.query.filter_by(enabled=True).all())
  51. @bp.route("/jobs/<int:job_id>/delete", methods=["POST"])
  52. def job_delete(job_id):
  53. job = db.get_or_404(Job, job_id)
  54. from scheduler import remove_job
  55. remove_job(job.id)
  56. db.session.delete(job)
  57. db.session.commit()
  58. flash(f"Job « {job.name} » supprimé.", "success")
  59. return redirect(url_for("jobs.index"))
  60. @bp.route("/jobs/<int:job_id>/run", methods=["POST"])
  61. def job_run_now(job_id):
  62. job = db.get_or_404(Job, job_id)
  63. from scheduler import _execute_job
  64. app = current_app._get_current_object()
  65. threading.Thread(target=_execute_job, args=(job.id,), daemon=True).start()
  66. flash(f"Job « {job.name} » lancé manuellement.", "success")
  67. return redirect(url_for("jobs.index"))
  68. @bp.route("/jobs/bulk", methods=["POST"])
  69. def jobs_bulk():
  70. action = request.form.get("action")
  71. job_ids = [int(jid) for jid in request.form.getlist("job_ids") if jid.isdigit()]
  72. if not job_ids:
  73. return redirect(url_for("jobs.index"))
  74. from scheduler import schedule_job, remove_job, _execute_job
  75. if action == "run":
  76. for jid in job_ids:
  77. job = db.session.get(Job, jid)
  78. if job:
  79. threading.Thread(target=_execute_job, args=(jid,), daemon=True).start()
  80. flash(f"{len(job_ids)} job(s) lancé(s) en arrière-plan.", "info")
  81. elif action == "enable":
  82. for jid in job_ids:
  83. job = db.session.get(Job, jid)
  84. if job:
  85. job.enabled = True
  86. job.updated_at = datetime.utcnow()
  87. schedule_job(job)
  88. db.session.commit()
  89. flash(f"{len(job_ids)} job(s) activé(s).", "success")
  90. elif action == "disable":
  91. for jid in job_ids:
  92. job = db.session.get(Job, jid)
  93. if job:
  94. job.enabled = False
  95. job.updated_at = datetime.utcnow()
  96. remove_job(jid)
  97. db.session.commit()
  98. flash(f"{len(job_ids)} job(s) désactivé(s).", "info")
  99. elif action == "delete":
  100. names = []
  101. for jid in job_ids:
  102. job = db.session.get(Job, jid)
  103. if job:
  104. names.append(job.name)
  105. remove_job(jid)
  106. db.session.delete(job)
  107. db.session.commit()
  108. flash(f"{len(names)} job(s) supprimé(s).", "success")
  109. return redirect(url_for("jobs.index"))
  110. @bp.route("/jobs/<int:job_id>/toggle", methods=["POST"])
  111. def job_toggle(job_id):
  112. job = db.get_or_404(Job, job_id)
  113. from scheduler import schedule_job, remove_job
  114. job.enabled = not job.enabled
  115. job.updated_at = datetime.utcnow()
  116. db.session.commit()
  117. if job.enabled:
  118. schedule_job(job)
  119. flash(f"Job « {job.name} » activé.", "success")
  120. else:
  121. remove_job(job.id)
  122. flash(f"Job « {job.name} » désactivé.", "info")
  123. return redirect(url_for("jobs.index"))
  124. @bp.route("/jobs/<int:job_id>/history")
  125. def job_history(job_id):
  126. job = db.get_or_404(Job, job_id)
  127. runs = Run.query.filter_by(job_id=job_id).order_by(Run.started_at.desc()).limit(100).all()
  128. return render_template("job_history.html", job=job, runs=runs)
  129. # --- Navigateur d'archives ----------------------------------------------------
  130. @bp.route("/archives")
  131. def archives():
  132. from jobs.utils import batch_list_archives
  133. from db import _size_human, RemoteInstance
  134. backup_dir = current_app.config["YUNOHOST_BACKUP_DIR"]
  135. # UN seul appel sudo find pour toutes les tailles + mtimes
  136. file_stats = batch_list_archives(backup_dir)
  137. sorted_names = sorted(file_stats, key=lambda n: file_stats[n]["mtime"], reverse=True)
  138. # Pré-charger runs et jobs en une passe DB (pas de subprocess)
  139. runs_by_archive = {}
  140. for run in Run.query.order_by(Run.started_at.desc()).all():
  141. if run.archive_name and run.archive_name not in runs_by_archive:
  142. runs_by_archive[run.archive_name] = run
  143. jobs_by_id = {j.id: j for j in Job.query.all()}
  144. items = []
  145. for name in sorted_names:
  146. size_bytes = file_stats[name]["size_bytes"] or None
  147. run = runs_by_archive.get(name)
  148. job = jobs_by_id.get(run.job_id) if run else None
  149. items.append({
  150. "name": name,
  151. "type": job.type if job else "",
  152. "job_name": job.name if job else "—",
  153. "job_id": job.id if job else None,
  154. "last_status": run.status if run else None,
  155. "run_at": run.started_at if run else None,
  156. "size_bytes": size_bytes,
  157. "size_human": _size_human(size_bytes) if size_bytes else "—",
  158. })
  159. instances = RemoteInstance.query.order_by(RemoteInstance.name).all()
  160. return render_template("archives.html", items=items, instances=instances)
  161. @bp.route("/archives/<path:archive_name>/download")
  162. def archive_download(archive_name):
  163. import os, subprocess
  164. from flask import Response, stream_with_context
  165. backup_dir = current_app.config["YUNOHOST_BACKUP_DIR"]
  166. archive_path = os.path.join(backup_dir, archive_name + ".tar")
  167. tmp_path = f"/tmp/backupmanager_webdl_{archive_name}.tar"
  168. try:
  169. r = subprocess.run(["sudo", "rsync", archive_path, tmp_path],
  170. capture_output=True, text=True, timeout=3600)
  171. if r.returncode != 0:
  172. flash(f"Téléchargement impossible : {r.stderr.strip()}", "error")
  173. return redirect(url_for("jobs.archives"))
  174. def _stream():
  175. try:
  176. with open(tmp_path, "rb") as f:
  177. while True:
  178. chunk = f.read(1024 * 1024)
  179. if not chunk:
  180. break
  181. yield chunk
  182. finally:
  183. subprocess.run(["sudo", "rm", "-f", tmp_path], capture_output=True)
  184. return Response(
  185. stream_with_context(_stream()),
  186. mimetype="application/octet-stream",
  187. headers={"Content-Disposition": f'attachment; filename="{archive_name}.tar"'},
  188. )
  189. except Exception as exc:
  190. subprocess.run(["sudo", "rm", "-f", tmp_path], capture_output=True)
  191. flash(f"Erreur : {exc}", "error")
  192. return redirect(url_for("jobs.archives"))
  193. @bp.route("/archives/<path:archive_name>/delete", methods=["POST"])
  194. def archive_delete(archive_name):
  195. import os, subprocess
  196. backup_dir = current_app.config["YUNOHOST_BACKUP_DIR"]
  197. tar_path = os.path.join(backup_dir, archive_name + ".tar")
  198. info_path = os.path.join(backup_dir, archive_name + ".info.json")
  199. subprocess.run(["sudo", "rm", "-f", tar_path, info_path], capture_output=True)
  200. flash(f"Archive « {archive_name} » supprimée.", "success")
  201. return redirect(url_for("jobs.archives"))
  202. # --- Restauration -------------------------------------------------------------
  203. @bp.route("/archives/<path:archive_name>/restore", methods=["GET", "POST"])
  204. def archive_restore(archive_name):
  205. backup_dir = current_app.config["YUNOHOST_BACKUP_DIR"]
  206. info = read_archive_info(archive_name, backup_dir)
  207. if request.method == "GET":
  208. return render_template("restore_confirm.html", archive_name=archive_name, info=info)
  209. _start_restore(archive_name)
  210. flash(f"Restauration de « {archive_name} » démarrée en arrière-plan.", "success")
  211. return redirect(url_for("jobs.index"))
  212. def _start_restore(archive_name):
  213. """Crée un Run de restauration et lance le thread. Retourne (restore_run_id, archive_type)."""
  214. backup_dir = current_app.config["YUNOHOST_BACKUP_DIR"]
  215. info = read_archive_info(archive_name, backup_dir)
  216. archive_type = info.get("type", "")
  217. original_run = Run.query.filter_by(archive_name=archive_name).first()
  218. restore_run_id = None
  219. if original_run:
  220. restore_run = Run(
  221. job_id=original_run.job_id,
  222. started_at=datetime.utcnow(),
  223. status="running",
  224. archive_name=archive_name,
  225. log_text="[RESTAURATION en cours…]",
  226. )
  227. db.session.add(restore_run)
  228. db.session.commit()
  229. restore_run_id = restore_run.id
  230. app = current_app._get_current_object()
  231. threading.Thread(
  232. target=_do_restore_job,
  233. args=(app, archive_name, archive_type, restore_run_id),
  234. daemon=True,
  235. ).start()
  236. return restore_run_id, archive_type
  237. def _do_restore_job(app, archive_name, archive_type, restore_run_id):
  238. with app.app_context():
  239. run = db.session.get(Run, restore_run_id) if restore_run_id else None
  240. try:
  241. backup_dir = app.config["YUNOHOST_BACKUP_DIR"]
  242. if archive_type == "custom_dir":
  243. from jobs.custom_dir import restore_custom_dir
  244. log = restore_custom_dir(archive_name, backup_dir)
  245. elif archive_type in ("mysql", "postgresql"):
  246. from jobs.db_dump import restore_db_dump
  247. log = restore_db_dump(archive_name, backup_dir)
  248. elif archive_type == "ynh_app":
  249. result = subprocess.run(
  250. ["sudo", "yunohost", "backup", "restore", archive_name,
  251. "--apps", "--force"],
  252. capture_output=True, text=True, timeout=3600,
  253. )
  254. log = (result.stdout + result.stderr).strip()
  255. if result.returncode != 0:
  256. raise RuntimeError(f"yunohost backup restore a échoué :\n{log}")
  257. elif archive_type == "ynh_system":
  258. result = subprocess.run(
  259. ["sudo", "yunohost", "backup", "restore", archive_name,
  260. "--system", "--force"],
  261. capture_output=True, text=True, timeout=3600,
  262. )
  263. log = (result.stdout + result.stderr).strip()
  264. if result.returncode != 0:
  265. raise RuntimeError(f"yunohost backup restore a échoué :\n{log}")
  266. else:
  267. raise NotImplementedError(
  268. f"Restauration non supportée pour le type '{archive_type}'."
  269. )
  270. if run:
  271. run.status = "success"
  272. run.finished_at = datetime.utcnow()
  273. run.log_text = f"[RESTAURATION]\n{log or 'OK'}"
  274. db.session.commit()
  275. except Exception as exc:
  276. app.logger.error(f"Restauration {archive_name} échouée : {exc}")
  277. if run:
  278. run.status = "error"
  279. run.finished_at = datetime.utcnow()
  280. run.log_text = f"[RESTAURATION]\n{exc}"
  281. db.session.commit()
  282. # --- Helper save job ----------------------------------------------------------
  283. def _save_job(job):
  284. f = request.form
  285. job_type = f.get("type", "")
  286. name = f.get("name", "").strip()
  287. if not name:
  288. flash("Le nom est requis.", "error")
  289. return render_template("job_form.html", job=job, ynh_apps=get_ynh_apps(exclude_app_ids=_used_app_ids(exclude_job_id=job.id if job else None)),
  290. destinations=Destination.query.filter_by(enabled=True).all())
  291. cfg = {}
  292. if job_type == "ynh_app":
  293. cfg = {"app_id": f.get("app_id", ""), "core_only": f.get("core_only") == "1"}
  294. elif job_type == "ynh_system":
  295. cfg = {}
  296. elif job_type in ("mysql", "postgresql"):
  297. dbname = f.get("db_database", "").strip()
  298. if not dbname:
  299. flash("Le nom de la base de données est requis.", "error")
  300. return render_template("job_form.html", job=job, ynh_apps=get_ynh_apps(exclude_app_ids=_used_app_ids(exclude_job_id=job.id if job else None)),
  301. destinations=Destination.query.filter_by(enabled=True).all())
  302. cfg = {"database": dbname}
  303. elif job_type == "custom_dir":
  304. source_path = f.get("source_path", "").strip().rstrip("/")
  305. if not source_path or not source_path.startswith("/"):
  306. flash("Le chemin source doit être un chemin absolu (ex: /opt/monapp).", "error")
  307. return render_template("job_form.html", job=job, ynh_apps=get_ynh_apps(exclude_app_ids=_used_app_ids(exclude_job_id=job.id if job else None)),
  308. destinations=Destination.query.filter_by(enabled=True).all())
  309. excludes = [e.strip() for e in f.get("excludes", "").splitlines() if e.strip()]
  310. restore_cfg = {}
  311. user_name = f.get("restore_user_name", "").strip()
  312. if user_name:
  313. restore_cfg["system_user"] = {
  314. "name": user_name,
  315. "home": f.get("restore_user_home", source_path).strip() or source_path,
  316. "shell": f.get("restore_user_shell", "/bin/false").strip() or "/bin/false",
  317. }
  318. service_name = f.get("restore_service_name", "").strip()
  319. if service_name:
  320. restore_cfg["systemd_service"] = {
  321. "name": service_name,
  322. "service_file": f.get("restore_service_file", "").strip(),
  323. }
  324. owner = f.get("restore_perm_owner", "").strip()
  325. mode = f.get("restore_perm_mode", "").strip()
  326. if owner or mode:
  327. restore_cfg["permissions"] = {}
  328. if owner:
  329. restore_cfg["permissions"]["owner"] = owner
  330. if mode:
  331. restore_cfg["permissions"]["mode"] = mode
  332. post_cmds = [c.strip() for c in f.get("restore_post_cmds", "").splitlines() if c.strip()]
  333. if post_cmds:
  334. restore_cfg["post_restore_commands"] = post_cmds
  335. cfg = {"source_path": source_path, "excludes": excludes, "restore": restore_cfg}
  336. if job is None:
  337. job = Job()
  338. db.session.add(job)
  339. from scheduler import schedule_job, remove_job
  340. dest_id = f.get("destination_id", "").strip()
  341. job.name = name
  342. job.type = job_type
  343. job.config_json = json.dumps(cfg)
  344. cron_raw = (f.get("cron_expr") or "").strip()
  345. job.cron_expr = cron_raw # "" = manuel (NOT NULL compatible avec le schéma existant)
  346. job.retention_mode = f.get("retention_mode", "count")
  347. job.retention_value = int(f.get("retention_value", 7))
  348. job.enabled = f.get("enabled") == "1"
  349. job.core_only = cfg.get("core_only", False)
  350. job.destination_id = int(dest_id) if dest_id else None
  351. job.updated_at = datetime.utcnow()
  352. db.session.commit()
  353. if job.enabled:
  354. schedule_job(job)
  355. else:
  356. remove_job(job.id)
  357. flash(f"Job « {job.name} » enregistré.", "success")
  358. return redirect(url_for("jobs.index"))