app.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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, Destination, Setting
  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. destinations=Destination.query.filter_by(enabled=True).all())
  104. @app.route("/jobs/<int:job_id>/edit", methods=["GET", "POST"])
  105. def job_edit(job_id):
  106. job = db.get_or_404(Job, job_id)
  107. if request.method == "POST":
  108. return _save_job(job)
  109. return render_template("job_form.html", job=job, ynh_apps=_get_ynh_apps(),
  110. destinations=Destination.query.filter_by(enabled=True).all())
  111. @app.route("/jobs/<int:job_id>/delete", methods=["POST"])
  112. def job_delete(job_id):
  113. job = db.get_or_404(Job, job_id)
  114. remove_job(job.id)
  115. db.session.delete(job)
  116. db.session.commit()
  117. flash(f"Job « {job.name} » supprimé.", "success")
  118. return redirect(url_for("index"))
  119. @app.route("/jobs/<int:job_id>/run", methods=["POST"])
  120. def job_run_now(job_id):
  121. job = db.get_or_404(Job, job_id)
  122. from scheduler import _execute_job
  123. import threading
  124. t = threading.Thread(target=_execute_job, args=(job.id,), daemon=True)
  125. t.start()
  126. flash(f"Job « {job.name} » lancé manuellement.", "success")
  127. return redirect(url_for("index"))
  128. @app.route("/jobs/<int:job_id>/history")
  129. def job_history(job_id):
  130. job = db.get_or_404(Job, job_id)
  131. runs = Run.query.filter_by(job_id=job_id).order_by(Run.started_at.desc()).limit(100).all()
  132. return render_template("job_history.html", job=job, runs=runs)
  133. @app.route("/archives/<path:archive_name>/restore", methods=["GET", "POST"])
  134. def archive_restore(archive_name):
  135. info = _read_archive_info(archive_name)
  136. archive_type = info.get("type", "")
  137. if request.method == "GET":
  138. return render_template("restore_confirm.html", archive_name=archive_name, info=info)
  139. def _do_restore():
  140. with app.app_context():
  141. try:
  142. backup_dir = app.config["YUNOHOST_BACKUP_DIR"]
  143. if archive_type == "custom_dir":
  144. from jobs.custom_dir import restore_custom_dir
  145. restore_custom_dir(archive_name, backup_dir)
  146. elif archive_type in ("mysql", "postgresql"):
  147. from jobs.db_dump import restore_db_dump
  148. restore_db_dump(archive_name, backup_dir)
  149. else:
  150. raise NotImplementedError(
  151. f"Restauration non supportée pour le type '{archive_type}'."
  152. )
  153. except Exception as exc:
  154. app.logger.error(f"Restauration {archive_name} échouée : {exc}")
  155. import threading
  156. threading.Thread(target=_do_restore, daemon=True).start()
  157. flash(f"Restauration de « {archive_name} » démarrée en arrière-plan.", "success")
  158. return redirect(url_for("index"))
  159. @app.route("/jobs/<int:job_id>/toggle", methods=["POST"])
  160. def job_toggle(job_id):
  161. job = db.get_or_404(Job, job_id)
  162. job.enabled = not job.enabled
  163. job.updated_at = datetime.utcnow()
  164. db.session.commit()
  165. if job.enabled:
  166. schedule_job(job)
  167. flash(f"Job « {job.name} » activé.", "success")
  168. else:
  169. remove_job(job.id)
  170. flash(f"Job « {job.name} » désactivé.", "info")
  171. return redirect(url_for("index"))
  172. def _save_job(job):
  173. f = request.form
  174. job_type = f.get("type", "")
  175. name = f.get("name", "").strip()
  176. if not name:
  177. flash("Le nom est requis.", "error")
  178. return render_template("job_form.html", job=job, ynh_apps=_get_ynh_apps())
  179. cfg = {}
  180. if job_type == "ynh_app":
  181. cfg = {"app_id": f.get("app_id", ""), "core_only": f.get("core_only") == "1"}
  182. elif job_type == "ynh_system":
  183. cfg = {}
  184. elif job_type in ("mysql", "postgresql"):
  185. dbname = f.get("db_database", "").strip()
  186. if not dbname:
  187. flash("Le nom de la base de données est requis.", "error")
  188. return render_template("job_form.html", job=job, ynh_apps=_get_ynh_apps())
  189. cfg = {"database": dbname}
  190. elif job_type == "custom_dir":
  191. source_path = f.get("source_path", "").strip().rstrip("/")
  192. if not source_path or not source_path.startswith("/"):
  193. flash("Le chemin source doit être un chemin absolu (ex: /opt/monapp).", "error")
  194. return render_template("job_form.html", job=job, ynh_apps=_get_ynh_apps())
  195. excludes = [e.strip() for e in f.get("excludes", "").splitlines() if e.strip()]
  196. restore_cfg = {}
  197. user_name = f.get("restore_user_name", "").strip()
  198. if user_name:
  199. restore_cfg["system_user"] = {
  200. "name": user_name,
  201. "home": f.get("restore_user_home", source_path).strip() or source_path,
  202. "shell": f.get("restore_user_shell", "/bin/false").strip() or "/bin/false",
  203. }
  204. service_name = f.get("restore_service_name", "").strip()
  205. if service_name:
  206. restore_cfg["systemd_service"] = {
  207. "name": service_name,
  208. "service_file": f.get("restore_service_file", "").strip(),
  209. }
  210. owner = f.get("restore_perm_owner", "").strip()
  211. mode = f.get("restore_perm_mode", "").strip()
  212. if owner or mode:
  213. restore_cfg["permissions"] = {}
  214. if owner:
  215. restore_cfg["permissions"]["owner"] = owner
  216. if mode:
  217. restore_cfg["permissions"]["mode"] = mode
  218. post_cmds = [c.strip() for c in f.get("restore_post_cmds", "").splitlines() if c.strip()]
  219. if post_cmds:
  220. restore_cfg["post_restore_commands"] = post_cmds
  221. cfg = {"source_path": source_path, "excludes": excludes, "restore": restore_cfg}
  222. if job is None:
  223. job = Job()
  224. db.session.add(job)
  225. dest_id = f.get("destination_id", "").strip()
  226. job.name = name
  227. job.type = job_type
  228. job.config_json = json.dumps(cfg)
  229. job.cron_expr = f.get("cron_expr", "0 3 * * *").strip()
  230. job.retention_mode = f.get("retention_mode", "count")
  231. job.retention_value = int(f.get("retention_value", 7))
  232. job.enabled = f.get("enabled") == "1"
  233. job.core_only = cfg.get("core_only", False)
  234. job.destination_id = int(dest_id) if dest_id else None
  235. job.updated_at = datetime.utcnow()
  236. db.session.commit()
  237. if job.enabled:
  238. schedule_job(job)
  239. else:
  240. remove_job(job.id)
  241. flash(f"Job « {job.name} » enregistré.", "success")
  242. return redirect(url_for("index"))
  243. # --- Destinations ------------------------------------------------------------
  244. @app.route("/destinations")
  245. def destinations_list():
  246. destinations = Destination.query.order_by(Destination.name).all()
  247. return render_template("destinations.html", destinations=destinations)
  248. @app.route("/destinations/new", methods=["GET", "POST"])
  249. def destination_new():
  250. if request.method == "POST":
  251. return _save_destination(None)
  252. return render_template("destination_form.html", dest=None)
  253. @app.route("/destinations/<int:dest_id>/edit", methods=["GET", "POST"])
  254. def destination_edit(dest_id):
  255. dest = db.get_or_404(Destination, dest_id)
  256. if request.method == "POST":
  257. return _save_destination(dest)
  258. pub_key = _get_pub_key(dest)
  259. return render_template("destination_form.html", dest=dest, pub_key=pub_key)
  260. @app.route("/destinations/<int:dest_id>/delete", methods=["POST"])
  261. def destination_delete(dest_id):
  262. dest = db.get_or_404(Destination, dest_id)
  263. db.session.delete(dest)
  264. db.session.commit()
  265. flash(f"Destination « {dest.name} » supprimée.", "success")
  266. return redirect(url_for("destinations_list"))
  267. @app.route("/destinations/<int:dest_id>/test", methods=["POST"])
  268. def destination_test(dest_id):
  269. dest = db.get_or_404(Destination, dest_id)
  270. from jobs.transfer import test_connection
  271. ok, msg = test_connection(dest, app.config["DATA_DIR"])
  272. flash(msg, "success" if ok else "error")
  273. return redirect(url_for("destinations_list"))
  274. @app.route("/archives/<path:archive_name>/transfer", methods=["POST"])
  275. def archive_transfer(archive_name):
  276. dest_id = request.form.get("destination_id", type=int)
  277. dest = db.get_or_404(Destination, dest_id)
  278. def _do_transfer():
  279. with app.app_context():
  280. try:
  281. from jobs.transfer import transfer_archive
  282. transfer_archive(archive_name, dest, app.config["YUNOHOST_BACKUP_DIR"],
  283. app.config["DATA_DIR"])
  284. app.logger.info(f"Transfert {archive_name} → {dest.remote_str} OK")
  285. except Exception as exc:
  286. app.logger.error(f"Transfert {archive_name} échoué : {exc}")
  287. import threading
  288. threading.Thread(target=_do_transfer, daemon=True).start()
  289. flash(f"Transfert de « {archive_name} » vers {dest.remote_str} démarré.", "success")
  290. return redirect(request.referrer or url_for("index"))
  291. def _save_destination(dest):
  292. f = request.form
  293. name = f.get("name", "").strip()
  294. host = f.get("host", "").strip()
  295. if not name or not host:
  296. flash("Nom et hôte sont requis.", "error")
  297. return render_template("destination_form.html", dest=dest)
  298. is_new = dest is None
  299. if is_new:
  300. dest = Destination()
  301. db.session.add(dest)
  302. dest.name = name
  303. dest.host = host
  304. dest.port = int(f.get("port", 22) or 22)
  305. dest.user = f.get("user", "root").strip() or "root"
  306. dest.remote_path = f.get("remote_path", "/home/yunohost.backup/archives").strip()
  307. dest.enabled = f.get("enabled") == "1"
  308. db.session.flush() # obtenir l'id si nouveau
  309. # Génération de la clé SSH si absente
  310. if not dest.key_name:
  311. from jobs.transfer import generate_key
  312. dest.key_name = generate_key(dest.name, app.config["DATA_DIR"])
  313. db.session.commit()
  314. flash(f"Destination « {dest.name} » enregistrée.", "success")
  315. return redirect(url_for("destination_edit", dest_id=dest.id))
  316. def _get_pub_key(dest):
  317. if not dest.key_name:
  318. return None
  319. from jobs.transfer import get_public_key
  320. return get_public_key(dest.key_name, app.config["DATA_DIR"])
  321. # --- Paramètres --------------------------------------------------------------
  322. _SETTING_KEYS = [
  323. "smtp_host", "smtp_port", "smtp_user", "smtp_password",
  324. "smtp_from", "smtp_to", "smtp_tls", "smtp_ssl",
  325. "notify_on_success", "notify_on_error",
  326. ]
  327. def _get_setting(key, default=""):
  328. s = Setting.query.filter_by(key=key).first()
  329. return s.value if s else default
  330. @app.route("/settings", methods=["GET", "POST"])
  331. def settings():
  332. if request.method == "POST":
  333. action = request.form.get("action")
  334. if action == "test_smtp":
  335. from notifications import send_test_email
  336. try:
  337. send_test_email(
  338. host=request.form.get("smtp_host", "").strip(),
  339. port=int(request.form.get("smtp_port", 587) or 587),
  340. user=request.form.get("smtp_user", "").strip(),
  341. password=request.form.get("smtp_password", ""),
  342. from_addr=request.form.get("smtp_from", "").strip(),
  343. to_addr=request.form.get("smtp_to", "").strip(),
  344. use_ssl=request.form.get("smtp_ssl") == "1",
  345. use_tls=request.form.get("smtp_tls") == "1",
  346. )
  347. flash("Email de test envoyé avec succès.", "success")
  348. except Exception as exc:
  349. flash(f"Échec du test SMTP : {exc}", "error")
  350. else:
  351. for key in _SETTING_KEYS:
  352. if key in ("smtp_tls", "smtp_ssl", "notify_on_success", "notify_on_error"):
  353. value = "1" if request.form.get(key) == "1" else "0"
  354. else:
  355. value = request.form.get(key, "").strip()
  356. s = Setting.query.filter_by(key=key).first()
  357. if s is None:
  358. s = Setting(key=key, value=value)
  359. db.session.add(s)
  360. else:
  361. s.value = value
  362. db.session.commit()
  363. flash("Paramètres enregistrés.", "success")
  364. return redirect(url_for("settings"))
  365. cfg = {k: _get_setting(k) for k in _SETTING_KEYS}
  366. # valeurs par défaut pour l'affichage
  367. cfg.setdefault("smtp_port", "587")
  368. cfg["smtp_tls"] = cfg.get("smtp_tls") or "1"
  369. cfg["smtp_ssl"] = cfg.get("smtp_ssl") or "0"
  370. cfg["notify_on_error"] = cfg.get("notify_on_error") or "1"
  371. return render_template("settings.html", cfg=cfg)
  372. # --- API v1 ------------------------------------------------------------------
  373. @app.route("/api/v1/health")
  374. def api_health():
  375. return jsonify({"status": "ok", "instance": app.config.get("INSTANCE_NAME")})
  376. @app.route("/api/v1/jobs")
  377. def api_jobs():
  378. jobs = Job.query.all()
  379. return jsonify([
  380. {
  381. "id": j.id,
  382. "name": j.name,
  383. "type": j.type,
  384. "cron_expr": j.cron_expr,
  385. "enabled": j.enabled,
  386. "retention_mode": j.retention_mode,
  387. "retention_value": j.retention_value,
  388. }
  389. for j in jobs
  390. ])
  391. @app.route("/api/v1/jobs/<int:job_id>/runs")
  392. def api_job_runs(job_id):
  393. runs = Run.query.filter_by(job_id=job_id).order_by(Run.started_at.desc()).limit(50).all()
  394. return jsonify([
  395. {
  396. "id": r.id,
  397. "started_at": r.started_at.isoformat() if r.started_at else None,
  398. "finished_at": r.finished_at.isoformat() if r.finished_at else None,
  399. "status": r.status,
  400. "archive_name": r.archive_name,
  401. "size_bytes": r.size_bytes,
  402. }
  403. for r in runs
  404. ])
  405. @app.route("/api/v1/jobs/<int:job_id>/run", methods=["POST"])
  406. def api_job_run(job_id):
  407. job = db.get_or_404(Job, job_id)
  408. from scheduler import _execute_job
  409. import threading
  410. threading.Thread(target=_execute_job, args=(job.id,), daemon=True).start()
  411. return jsonify({"status": "triggered", "job_id": job_id})
  412. @app.route("/api/v1/archives")
  413. def api_archives():
  414. backup_dir = app.config["YUNOHOST_BACKUP_DIR"]
  415. archives = []
  416. try:
  417. for fname in sorted(os.listdir(backup_dir)):
  418. if fname.endswith(".tar"):
  419. path = os.path.join(backup_dir, fname)
  420. archives.append({
  421. "name": fname[:-4],
  422. "size_bytes": os.path.getsize(path),
  423. "modified_at": datetime.utcfromtimestamp(os.path.getmtime(path)).isoformat(),
  424. })
  425. except OSError:
  426. pass
  427. return jsonify(archives)
  428. @app.route("/api/v1/archives/<name>", methods=["DELETE"])
  429. def api_archive_delete(name):
  430. backup_dir = app.config["YUNOHOST_BACKUP_DIR"]
  431. for ext in (".tar", ".info.json"):
  432. path = os.path.join(backup_dir, name + ext)
  433. if os.path.exists(path):
  434. os.remove(path)
  435. return jsonify({"status": "deleted", "name": name})