app.py 20 KB

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