jobs.py 14 KB

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