settings.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import json
  2. import subprocess
  3. from datetime import datetime
  4. from flask import (
  5. Blueprint,
  6. Response,
  7. current_app,
  8. flash,
  9. jsonify,
  10. redirect,
  11. render_template,
  12. request,
  13. url_for,
  14. )
  15. from db import db, Setting
  16. bp = Blueprint("cfg", __name__)
  17. _SETTING_KEYS = [
  18. "smtp_host", "smtp_port", "smtp_user", "smtp_password",
  19. "smtp_from", "smtp_to", "smtp_tls", "smtp_ssl",
  20. "notify_on_success", "notify_on_error",
  21. ]
  22. def _get_setting(key, default=""):
  23. s = Setting.query.filter_by(key=key).first()
  24. return s.value if s else default
  25. @bp.route("/settings", methods=["GET", "POST"])
  26. def settings():
  27. if request.method == "POST":
  28. action = request.form.get("action")
  29. if action == "test_smtp":
  30. from notifications import send_test_email
  31. try:
  32. send_test_email(
  33. host=request.form.get("smtp_host", "").strip(),
  34. port=int(request.form.get("smtp_port", 587) or 587),
  35. user=request.form.get("smtp_user", "").strip(),
  36. password=request.form.get("smtp_password", ""),
  37. from_addr=request.form.get("smtp_from", "").strip(),
  38. to_addr=request.form.get("smtp_to", "").strip(),
  39. use_ssl=request.form.get("smtp_ssl") == "1",
  40. use_tls=request.form.get("smtp_tls") == "1",
  41. )
  42. flash("Email de test envoyé avec succès.", "success")
  43. except Exception as exc:
  44. flash(f"Échec du test SMTP : {exc}", "error")
  45. else:
  46. for key in _SETTING_KEYS:
  47. if key in ("smtp_tls", "smtp_ssl", "notify_on_success", "notify_on_error"):
  48. value = "1" if request.form.get(key) == "1" else "0"
  49. else:
  50. value = request.form.get(key, "").strip()
  51. s = Setting.query.filter_by(key=key).first()
  52. if s is None:
  53. s = Setting(key=key, value=value)
  54. db.session.add(s)
  55. else:
  56. s.value = value
  57. db.session.commit()
  58. flash("Paramètres enregistrés.", "success")
  59. return redirect(url_for("cfg.settings"))
  60. from db import Destination, RemoteInstance
  61. cfg = {k: _get_setting(k) for k in _SETTING_KEYS}
  62. cfg.setdefault("smtp_port", "587")
  63. cfg["smtp_tls"] = cfg.get("smtp_tls") or "1"
  64. cfg["smtp_ssl"] = cfg.get("smtp_ssl") or "0"
  65. cfg["notify_on_error"] = cfg.get("notify_on_error") or "1"
  66. api_token = current_app.config.get("API_TOKEN", "")
  67. instance_url = current_app.config.get("INSTANCE_URL", "")
  68. destinations = Destination.query.order_by(Destination.name).all()
  69. instances = RemoteInstance.query.order_by(RemoteInstance.name).all()
  70. return render_template("settings.html", cfg=cfg, api_token=api_token,
  71. instance_url=instance_url, destinations=destinations,
  72. instances=instances)
  73. @bp.route("/settings/export-config")
  74. def export_config():
  75. from db import Job, Destination, RemoteInstance
  76. jobs_data = []
  77. for j in Job.query.order_by(Job.name).all():
  78. dest_name = j.destination.name if j.destination_id and j.destination else None
  79. inst_name = j.remote_instance.name if j.remote_instance_id and j.remote_instance else None
  80. jobs_data.append({
  81. "name": j.name,
  82. "type": j.type,
  83. "config_json": j.config_json,
  84. "cron_expr": j.cron_expr,
  85. "retention_mode": j.retention_mode,
  86. "retention_value": j.retention_value,
  87. "retention_gfs_config": j.retention_gfs_config,
  88. "enabled": j.enabled,
  89. "core_only": j.core_only,
  90. "destination_name": dest_name,
  91. "remote_instance_name": inst_name,
  92. })
  93. dest_data = []
  94. for d in Destination.query.order_by(Destination.name).all():
  95. dest_data.append({
  96. "name": d.name,
  97. "host": d.host,
  98. "port": d.port,
  99. "user": d.user,
  100. "remote_path": d.remote_path,
  101. "key_name": d.key_name,
  102. "enabled": d.enabled,
  103. })
  104. inst_data = []
  105. for i in RemoteInstance.query.order_by(RemoteInstance.name).all():
  106. inst_data.append({
  107. "name": i.name,
  108. "url": i.url,
  109. "api_key": i.api_key,
  110. })
  111. settings_data = {k: _get_setting(k) for k in _SETTING_KEYS}
  112. payload = {
  113. "version": 1,
  114. "exported_at": datetime.utcnow().isoformat(),
  115. "instance_name": current_app.config.get("INSTANCE_NAME", ""),
  116. "jobs": jobs_data,
  117. "destinations": dest_data,
  118. "remote_instances": inst_data,
  119. "settings": settings_data,
  120. }
  121. filename = f"backupmanager_config_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
  122. return Response(
  123. json.dumps(payload, ensure_ascii=False, indent=2),
  124. mimetype="application/json",
  125. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  126. )
  127. @bp.route("/settings/import-config", methods=["POST"])
  128. def import_config():
  129. from db import Job, Destination, RemoteInstance
  130. from scheduler import schedule_job, remove_job
  131. f = request.files.get("config_file")
  132. if not f or not f.filename:
  133. flash("Aucun fichier sélectionné.", "error")
  134. return redirect(url_for("cfg.settings") + "?tab=config")
  135. try:
  136. payload = json.loads(f.read().decode("utf-8"))
  137. except Exception:
  138. flash("Fichier invalide — JSON attendu.", "error")
  139. return redirect(url_for("cfg.settings") + "?tab=config")
  140. if payload.get("version") != 1:
  141. flash("Format de fichier non reconnu (version != 1).", "error")
  142. return redirect(url_for("cfg.settings") + "?tab=config")
  143. counts = {"destinations": 0, "instances": 0, "jobs": 0, "settings": 0}
  144. # --- Destinations ---
  145. for d_data in payload.get("destinations", []):
  146. name = d_data.get("name", "").strip()
  147. if not name:
  148. continue
  149. dest = Destination.query.filter_by(name=name).first()
  150. if dest is None:
  151. dest = Destination()
  152. db.session.add(dest)
  153. dest.name = name
  154. dest.host = d_data.get("host", "")
  155. dest.port = int(d_data.get("port", 22))
  156. dest.user = d_data.get("user", "root")
  157. dest.remote_path = d_data.get("remote_path", "")
  158. dest.key_name = d_data.get("key_name") or None
  159. dest.enabled = bool(d_data.get("enabled", True))
  160. counts["destinations"] += 1
  161. db.session.flush()
  162. # --- Instances distantes ---
  163. for i_data in payload.get("remote_instances", []):
  164. name = i_data.get("name", "").strip()
  165. if not name:
  166. continue
  167. inst = RemoteInstance.query.filter_by(name=name).first()
  168. if inst is None:
  169. inst = RemoteInstance()
  170. db.session.add(inst)
  171. inst.name = name
  172. inst.url = i_data.get("url", "").rstrip("/")
  173. inst.api_key = i_data.get("api_key", "")
  174. counts["instances"] += 1
  175. db.session.flush()
  176. # --- Jobs ---
  177. dest_by_name = {d.name: d for d in Destination.query.all()}
  178. inst_by_name = {i.name: i for i in RemoteInstance.query.all()}
  179. for j_data in payload.get("jobs", []):
  180. name = j_data.get("name", "").strip()
  181. if not name:
  182. continue
  183. job = Job.query.filter_by(name=name).first()
  184. if job is None:
  185. job = Job()
  186. db.session.add(job)
  187. else:
  188. remove_job(job.id)
  189. job.name = name
  190. job.type = j_data.get("type", "ynh_app")
  191. job.config_json = j_data.get("config_json") or "{}"
  192. job.cron_expr = j_data.get("cron_expr") or ""
  193. job.retention_mode = j_data.get("retention_mode", "count")
  194. job.retention_value = int(j_data.get("retention_value", 2))
  195. job.retention_gfs_config = j_data.get("retention_gfs_config")
  196. job.enabled = bool(j_data.get("enabled", True))
  197. job.core_only = bool(j_data.get("core_only", False))
  198. job.updated_at = datetime.utcnow()
  199. dest_name = j_data.get("destination_name")
  200. inst_name = j_data.get("remote_instance_name")
  201. job.destination_id = dest_by_name[dest_name].id if dest_name and dest_name in dest_by_name else None
  202. job.remote_instance_id = inst_by_name[inst_name].id if inst_name and inst_name in inst_by_name else None
  203. counts["jobs"] += 1
  204. db.session.flush()
  205. # --- Paramètres SMTP ---
  206. for key, value in payload.get("settings", {}).items():
  207. if key not in _SETTING_KEYS:
  208. continue
  209. s = Setting.query.filter_by(key=key).first()
  210. if s is None:
  211. s = Setting(key=key, value=value)
  212. db.session.add(s)
  213. else:
  214. s.value = value
  215. counts["settings"] += 1
  216. db.session.commit()
  217. # Replanifier les jobs actifs
  218. for job in Job.query.filter_by(enabled=True).all():
  219. schedule_job(job)
  220. flash(
  221. f"Import réussi — {counts['jobs']} job(s), "
  222. f"{counts['destinations']} destination(s), "
  223. f"{counts['instances']} instance(s), "
  224. f"{counts['settings']} paramètre(s).",
  225. "success",
  226. )
  227. return redirect(url_for("cfg.settings") + "?tab=config")
  228. @bp.route("/internal/databases/<db_type>")
  229. def internal_databases(db_type):
  230. """Liste les bases de données disponibles pour le formulaire job."""
  231. databases = []
  232. try:
  233. if db_type == "mysql":
  234. result = subprocess.run(
  235. ["sudo", "mysql", "--skip-column-names", "-e", "SHOW DATABASES;"],
  236. capture_output=True, text=True, timeout=10,
  237. )
  238. if result.returncode == 0:
  239. exclude = {"information_schema", "performance_schema", "mysql", "sys"}
  240. databases = [d.strip() for d in result.stdout.splitlines()
  241. if d.strip() and d.strip() not in exclude]
  242. elif db_type == "postgresql":
  243. result = subprocess.run(
  244. ["sudo", "-u", "postgres", "psql", "-Atc",
  245. "SELECT datname FROM pg_database WHERE datistemplate = false;"],
  246. capture_output=True, text=True, timeout=10,
  247. )
  248. if result.returncode == 0:
  249. databases = [d.strip() for d in result.stdout.splitlines() if d.strip()]
  250. except Exception:
  251. pass
  252. return jsonify(databases)