app.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. elif archive_type in ("mysql", "postgresql"):
  145. from jobs.db_dump import restore_db_dump
  146. restore_db_dump(archive_name, backup_dir)
  147. else:
  148. raise NotImplementedError(
  149. f"Restauration non supportée pour le type '{archive_type}'."
  150. )
  151. except Exception as exc:
  152. app.logger.error(f"Restauration {archive_name} échouée : {exc}")
  153. import threading
  154. threading.Thread(target=_do_restore, daemon=True).start()
  155. flash(f"Restauration de « {archive_name} » démarrée en arrière-plan.", "success")
  156. return redirect(url_for("index"))
  157. @app.route("/jobs/<int:job_id>/toggle", methods=["POST"])
  158. def job_toggle(job_id):
  159. job = db.get_or_404(Job, job_id)
  160. job.enabled = not job.enabled
  161. job.updated_at = datetime.utcnow()
  162. db.session.commit()
  163. if job.enabled:
  164. schedule_job(job)
  165. flash(f"Job « {job.name} » activé.", "success")
  166. else:
  167. remove_job(job.id)
  168. flash(f"Job « {job.name} » désactivé.", "info")
  169. return redirect(url_for("index"))
  170. def _save_job(job):
  171. f = request.form
  172. job_type = f.get("type", "")
  173. name = f.get("name", "").strip()
  174. if not name:
  175. flash("Le nom est requis.", "error")
  176. return render_template("job_form.html", job=job, ynh_apps=_get_ynh_apps())
  177. cfg = {}
  178. if job_type == "ynh_app":
  179. cfg = {"app_id": f.get("app_id", ""), "core_only": f.get("core_only") == "1"}
  180. elif job_type == "ynh_system":
  181. cfg = {}
  182. elif job_type in ("mysql", "postgresql"):
  183. dbname = f.get("db_database", "").strip()
  184. if not dbname:
  185. flash("Le nom de la base de données est requis.", "error")
  186. return render_template("job_form.html", job=job, ynh_apps=_get_ynh_apps())
  187. cfg = {"database": dbname}
  188. elif job_type == "custom_dir":
  189. source_path = f.get("source_path", "").strip().rstrip("/")
  190. if not source_path or not source_path.startswith("/"):
  191. flash("Le chemin source doit être un chemin absolu (ex: /opt/monapp).", "error")
  192. return render_template("job_form.html", job=job, ynh_apps=_get_ynh_apps())
  193. excludes = [e.strip() for e in f.get("excludes", "").splitlines() if e.strip()]
  194. restore_cfg = {}
  195. user_name = f.get("restore_user_name", "").strip()
  196. if user_name:
  197. restore_cfg["system_user"] = {
  198. "name": user_name,
  199. "home": f.get("restore_user_home", source_path).strip() or source_path,
  200. "shell": f.get("restore_user_shell", "/bin/false").strip() or "/bin/false",
  201. }
  202. service_name = f.get("restore_service_name", "").strip()
  203. if service_name:
  204. restore_cfg["systemd_service"] = {
  205. "name": service_name,
  206. "service_file": f.get("restore_service_file", "").strip(),
  207. }
  208. owner = f.get("restore_perm_owner", "").strip()
  209. mode = f.get("restore_perm_mode", "").strip()
  210. if owner or mode:
  211. restore_cfg["permissions"] = {}
  212. if owner:
  213. restore_cfg["permissions"]["owner"] = owner
  214. if mode:
  215. restore_cfg["permissions"]["mode"] = mode
  216. post_cmds = [c.strip() for c in f.get("restore_post_cmds", "").splitlines() if c.strip()]
  217. if post_cmds:
  218. restore_cfg["post_restore_commands"] = post_cmds
  219. cfg = {"source_path": source_path, "excludes": excludes, "restore": restore_cfg}
  220. if job is None:
  221. job = Job()
  222. db.session.add(job)
  223. job.name = name
  224. job.type = job_type
  225. job.config_json = json.dumps(cfg)
  226. job.cron_expr = f.get("cron_expr", "0 3 * * *").strip()
  227. job.retention_mode = f.get("retention_mode", "count")
  228. job.retention_value = int(f.get("retention_value", 7))
  229. job.enabled = f.get("enabled") == "1"
  230. job.core_only = cfg.get("core_only", False)
  231. job.updated_at = datetime.utcnow()
  232. db.session.commit()
  233. if job.enabled:
  234. schedule_job(job)
  235. else:
  236. remove_job(job.id)
  237. flash(f"Job « {job.name} » enregistré.", "success")
  238. return redirect(url_for("index"))
  239. # --- API v1 ------------------------------------------------------------------
  240. @app.route("/api/v1/health")
  241. def api_health():
  242. return jsonify({"status": "ok", "instance": app.config.get("INSTANCE_NAME")})
  243. @app.route("/api/v1/jobs")
  244. def api_jobs():
  245. jobs = Job.query.all()
  246. return jsonify([
  247. {
  248. "id": j.id,
  249. "name": j.name,
  250. "type": j.type,
  251. "cron_expr": j.cron_expr,
  252. "enabled": j.enabled,
  253. "retention_mode": j.retention_mode,
  254. "retention_value": j.retention_value,
  255. }
  256. for j in jobs
  257. ])
  258. @app.route("/api/v1/jobs/<int:job_id>/runs")
  259. def api_job_runs(job_id):
  260. runs = Run.query.filter_by(job_id=job_id).order_by(Run.started_at.desc()).limit(50).all()
  261. return jsonify([
  262. {
  263. "id": r.id,
  264. "started_at": r.started_at.isoformat() if r.started_at else None,
  265. "finished_at": r.finished_at.isoformat() if r.finished_at else None,
  266. "status": r.status,
  267. "archive_name": r.archive_name,
  268. "size_bytes": r.size_bytes,
  269. }
  270. for r in runs
  271. ])
  272. @app.route("/api/v1/jobs/<int:job_id>/run", methods=["POST"])
  273. def api_job_run(job_id):
  274. job = db.get_or_404(Job, job_id)
  275. from scheduler import _execute_job
  276. import threading
  277. threading.Thread(target=_execute_job, args=(job.id,), daemon=True).start()
  278. return jsonify({"status": "triggered", "job_id": job_id})
  279. @app.route("/api/v1/archives")
  280. def api_archives():
  281. backup_dir = app.config["YUNOHOST_BACKUP_DIR"]
  282. archives = []
  283. try:
  284. for fname in sorted(os.listdir(backup_dir)):
  285. if fname.endswith(".tar"):
  286. path = os.path.join(backup_dir, fname)
  287. archives.append({
  288. "name": fname[:-4],
  289. "size_bytes": os.path.getsize(path),
  290. "modified_at": datetime.utcfromtimestamp(os.path.getmtime(path)).isoformat(),
  291. })
  292. except OSError:
  293. pass
  294. return jsonify(archives)
  295. @app.route("/api/v1/archives/<name>", methods=["DELETE"])
  296. def api_archive_delete(name):
  297. backup_dir = app.config["YUNOHOST_BACKUP_DIR"]
  298. for ext in (".tar", ".info.json"):
  299. path = os.path.join(backup_dir, name + ext)
  300. if os.path.exists(path):
  301. os.remove(path)
  302. return jsonify({"status": "deleted", "name": name})