app.py 21 KB

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