jobs.py 19 KB

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