app.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. import json
  2. import logging
  3. import os
  4. import subprocess
  5. from datetime import datetime
  6. from flask import (
  7. Flask,
  8. flash,
  9. jsonify,
  10. redirect,
  11. render_template,
  12. request,
  13. url_for,
  14. )
  15. from werkzeug.middleware.proxy_fix import ProxyFix
  16. # --- Configuration -----------------------------------------------------------
  17. _config_path = os.environ.get(
  18. "BACKUPMANAGER_CONFIG",
  19. os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.py"),
  20. )
  21. app = Flask(__name__)
  22. app.config.from_pyfile(_config_path)
  23. app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + app.config["DB_PATH"]
  24. app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
  25. # Proxy headers Nginx → Flask (sous-chemin + HTTPS)
  26. app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1)
  27. # Filtre Jinja2 pour désérialiser du JSON dans les templates
  28. app.jinja_env.filters["fromjson"] = json.loads
  29. # Logging
  30. os.makedirs(os.path.dirname(app.config["LOG_PATH"]), exist_ok=True)
  31. logging.basicConfig(
  32. filename=app.config["LOG_PATH"],
  33. level=logging.INFO,
  34. format="%(asctime)s %(levelname)s %(message)s",
  35. )
  36. # --- Extensions --------------------------------------------------------------
  37. from db import db, Job, Run
  38. db.init_app(app)
  39. from scheduler import init_scheduler, schedule_job, remove_job
  40. # --- Démarrage ---------------------------------------------------------------
  41. with app.app_context():
  42. db.create_all()
  43. init_scheduler(app)
  44. for _job in Job.query.filter_by(enabled=True).all():
  45. schedule_job(_job)
  46. # --- Auth API ----------------------------------------------------------------
  47. @app.before_request
  48. def _check_api_auth():
  49. if not request.path.startswith("/api/"):
  50. return
  51. if request.path == "/api/v1/health":
  52. return
  53. token = request.headers.get("X-BackupManager-Key", "")
  54. if token != app.config["API_TOKEN"]:
  55. return jsonify({"error": "Unauthorized"}), 401
  56. # --- Context processors ------------------------------------------------------
  57. @app.context_processor
  58. def _inject_globals():
  59. return {
  60. "instance_name": app.config.get("INSTANCE_NAME", ""),
  61. "now": datetime.utcnow(),
  62. }
  63. # --- Helpers -----------------------------------------------------------------
  64. def _read_archive_info(archive_name):
  65. backup_dir = app.config["YUNOHOST_BACKUP_DIR"]
  66. archive_path = os.path.join(backup_dir, archive_name + ".tar")
  67. try:
  68. import tarfile as _tarfile
  69. with _tarfile.open(archive_path) as tar:
  70. member = tar.extractfile("backup_info.json")
  71. if member:
  72. return json.loads(member.read())
  73. except Exception:
  74. pass
  75. return {}
  76. def _get_ynh_apps():
  77. try:
  78. result = subprocess.run(
  79. ["sudo", "yunohost", "app", "list", "--output-as", "json"],
  80. capture_output=True,
  81. text=True,
  82. timeout=15,
  83. )
  84. if result.returncode == 0:
  85. return json.loads(result.stdout).get("apps", [])
  86. except Exception:
  87. pass
  88. return []
  89. # --- Routes dashboard --------------------------------------------------------
  90. @app.route("/")
  91. def index():
  92. jobs = Job.query.order_by(Job.name).all()
  93. last_runs = {
  94. j.id: Run.query.filter_by(job_id=j.id).order_by(Run.started_at.desc()).first()
  95. for j in jobs
  96. }
  97. return render_template("dashboard_local.html", jobs=jobs, last_runs=last_runs)
  98. @app.route("/jobs/new", methods=["GET", "POST"])
  99. def job_new():
  100. if request.method == "POST":
  101. return _save_job(None)
  102. return render_template("job_form.html", job=None, ynh_apps=_get_ynh_apps())
  103. @app.route("/jobs/<int:job_id>/edit", methods=["GET", "POST"])
  104. def job_edit(job_id):
  105. job = db.get_or_404(Job, job_id)
  106. if request.method == "POST":
  107. return _save_job(job)
  108. return render_template("job_form.html", job=job, ynh_apps=_get_ynh_apps())
  109. @app.route("/jobs/<int:job_id>/delete", methods=["POST"])
  110. def job_delete(job_id):
  111. job = db.get_or_404(Job, job_id)
  112. remove_job(job.id)
  113. db.session.delete(job)
  114. db.session.commit()
  115. flash(f"Job « {job.name} » supprimé.", "success")
  116. return redirect(url_for("index"))
  117. @app.route("/jobs/<int:job_id>/run", methods=["POST"])
  118. def job_run_now(job_id):
  119. job = db.get_or_404(Job, job_id)
  120. from scheduler import _execute_job
  121. import threading
  122. t = threading.Thread(target=_execute_job, args=(job.id,), daemon=True)
  123. t.start()
  124. flash(f"Job « {job.name} » lancé manuellement.", "success")
  125. return redirect(url_for("index"))
  126. @app.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. @app.route("/archives/<path:archive_name>/restore", methods=["GET", "POST"])
  132. def archive_restore(archive_name):
  133. info = _read_archive_info(archive_name)
  134. archive_type = info.get("type", "")
  135. if request.method == "GET":
  136. return render_template("restore_confirm.html", archive_name=archive_name, info=info)
  137. def _do_restore():
  138. with app.app_context():
  139. try:
  140. backup_dir = app.config["YUNOHOST_BACKUP_DIR"]
  141. if archive_type == "custom_dir":
  142. from jobs.custom_dir import restore_custom_dir
  143. restore_custom_dir(archive_name, backup_dir)
  144. else:
  145. raise NotImplementedError(
  146. f"Restauration non supportée pour le type '{archive_type}'."
  147. )
  148. except Exception as exc:
  149. app.logger.error(f"Restauration {archive_name} échouée : {exc}")
  150. import threading
  151. threading.Thread(target=_do_restore, daemon=True).start()
  152. flash(f"Restauration de « {archive_name} » démarrée en arrière-plan.", "success")
  153. return redirect(url_for("index"))
  154. @app.route("/jobs/<int:job_id>/toggle", methods=["POST"])
  155. def job_toggle(job_id):
  156. job = db.get_or_404(Job, job_id)
  157. job.enabled = not job.enabled
  158. job.updated_at = datetime.utcnow()
  159. db.session.commit()
  160. if job.enabled:
  161. schedule_job(job)
  162. flash(f"Job « {job.name} » activé.", "success")
  163. else:
  164. remove_job(job.id)
  165. flash(f"Job « {job.name} » désactivé.", "info")
  166. return redirect(url_for("index"))
  167. def _save_job(job):
  168. f = request.form
  169. job_type = f.get("type", "")
  170. name = f.get("name", "").strip()
  171. if not name:
  172. flash("Le nom est requis.", "error")
  173. return render_template("job_form.html", job=job, ynh_apps=_get_ynh_apps())
  174. cfg = {}
  175. if job_type == "ynh_app":
  176. cfg = {"app_id": f.get("app_id", ""), "core_only": f.get("core_only") == "1"}
  177. elif job_type == "ynh_system":
  178. cfg = {}
  179. elif job_type in ("mysql", "postgresql"):
  180. dbname = f.get("db_database", "").strip()
  181. if not dbname:
  182. flash("Le nom de la base de données est requis.", "error")
  183. return render_template("job_form.html", job=job, ynh_apps=_get_ynh_apps())
  184. cfg = {"database": dbname}
  185. elif job_type == "custom_dir":
  186. source_path = f.get("source_path", "").strip().rstrip("/")
  187. if not source_path or not source_path.startswith("/"):
  188. flash("Le chemin source doit être un chemin absolu (ex: /opt/monapp).", "error")
  189. return render_template("job_form.html", job=job, ynh_apps=_get_ynh_apps())
  190. excludes = [e.strip() for e in f.get("excludes", "").splitlines() if e.strip()]
  191. restore_cfg = {}
  192. user_name = f.get("restore_user_name", "").strip()
  193. if user_name:
  194. restore_cfg["system_user"] = {
  195. "name": user_name,
  196. "home": f.get("restore_user_home", source_path).strip() or source_path,
  197. "shell": f.get("restore_user_shell", "/bin/false").strip() or "/bin/false",
  198. }
  199. service_name = f.get("restore_service_name", "").strip()
  200. if service_name:
  201. restore_cfg["systemd_service"] = {
  202. "name": service_name,
  203. "service_file": f.get("restore_service_file", "").strip(),
  204. }
  205. owner = f.get("restore_perm_owner", "").strip()
  206. mode = f.get("restore_perm_mode", "").strip()
  207. if owner or mode:
  208. restore_cfg["permissions"] = {}
  209. if owner:
  210. restore_cfg["permissions"]["owner"] = owner
  211. if mode:
  212. restore_cfg["permissions"]["mode"] = mode
  213. post_cmds = [c.strip() for c in f.get("restore_post_cmds", "").splitlines() if c.strip()]
  214. if post_cmds:
  215. restore_cfg["post_restore_commands"] = post_cmds
  216. cfg = {"source_path": source_path, "excludes": excludes, "restore": restore_cfg}
  217. if job is None:
  218. job = Job()
  219. db.session.add(job)
  220. job.name = name
  221. job.type = job_type
  222. job.config_json = json.dumps(cfg)
  223. job.cron_expr = f.get("cron_expr", "0 3 * * *").strip()
  224. job.retention_mode = f.get("retention_mode", "count")
  225. job.retention_value = int(f.get("retention_value", 7))
  226. job.enabled = f.get("enabled") == "1"
  227. job.core_only = cfg.get("core_only", False)
  228. job.updated_at = datetime.utcnow()
  229. db.session.commit()
  230. if job.enabled:
  231. schedule_job(job)
  232. else:
  233. remove_job(job.id)
  234. flash(f"Job « {job.name} » enregistré.", "success")
  235. return redirect(url_for("index"))
  236. # --- API v1 ------------------------------------------------------------------
  237. @app.route("/api/v1/health")
  238. def api_health():
  239. return jsonify({"status": "ok", "instance": app.config.get("INSTANCE_NAME")})
  240. @app.route("/api/v1/jobs")
  241. def api_jobs():
  242. jobs = Job.query.all()
  243. return jsonify([
  244. {
  245. "id": j.id,
  246. "name": j.name,
  247. "type": j.type,
  248. "cron_expr": j.cron_expr,
  249. "enabled": j.enabled,
  250. "retention_mode": j.retention_mode,
  251. "retention_value": j.retention_value,
  252. }
  253. for j in jobs
  254. ])
  255. @app.route("/api/v1/jobs/<int:job_id>/runs")
  256. def api_job_runs(job_id):
  257. runs = Run.query.filter_by(job_id=job_id).order_by(Run.started_at.desc()).limit(50).all()
  258. return jsonify([
  259. {
  260. "id": r.id,
  261. "started_at": r.started_at.isoformat() if r.started_at else None,
  262. "finished_at": r.finished_at.isoformat() if r.finished_at else None,
  263. "status": r.status,
  264. "archive_name": r.archive_name,
  265. "size_bytes": r.size_bytes,
  266. }
  267. for r in runs
  268. ])
  269. @app.route("/api/v1/jobs/<int:job_id>/run", methods=["POST"])
  270. def api_job_run(job_id):
  271. job = db.get_or_404(Job, job_id)
  272. from scheduler import _execute_job
  273. import threading
  274. threading.Thread(target=_execute_job, args=(job.id,), daemon=True).start()
  275. return jsonify({"status": "triggered", "job_id": job_id})
  276. @app.route("/api/v1/archives")
  277. def api_archives():
  278. backup_dir = app.config["YUNOHOST_BACKUP_DIR"]
  279. archives = []
  280. try:
  281. for fname in sorted(os.listdir(backup_dir)):
  282. if fname.endswith(".tar"):
  283. path = os.path.join(backup_dir, fname)
  284. archives.append({
  285. "name": fname[:-4],
  286. "size_bytes": os.path.getsize(path),
  287. "modified_at": datetime.utcfromtimestamp(os.path.getmtime(path)).isoformat(),
  288. })
  289. except OSError:
  290. pass
  291. return jsonify(archives)
  292. @app.route("/api/v1/archives/<name>", methods=["DELETE"])
  293. def api_archive_delete(name):
  294. backup_dir = app.config["YUNOHOST_BACKUP_DIR"]
  295. for ext in (".tar", ".info.json"):
  296. path = os.path.join(backup_dir, name + ext)
  297. if os.path.exists(path):
  298. os.remove(path)
  299. return jsonify({"status": "deleted", "name": name})