db_dump.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. import json
  2. import os
  3. import subprocess
  4. import tarfile
  5. import tempfile
  6. import time
  7. from datetime import datetime
  8. def run_db_dump(job, instance, backup_dir):
  9. """Point d'entrée commun mysql et postgresql."""
  10. if job.type == "mysql":
  11. return _run_mysql(job, instance, backup_dir)
  12. elif job.type == "postgresql":
  13. return _run_postgresql(job, instance, backup_dir)
  14. raise ValueError(f"Type inconnu pour db_dump : {job.type}")
  15. # ---------------------------------------------------------------------------
  16. # MySQL
  17. # ---------------------------------------------------------------------------
  18. def _run_mysql(job, instance, backup_dir):
  19. from flask import current_app
  20. cfg = json.loads(job.config_json or "{}")
  21. dbname = cfg.get("database", "")
  22. if not dbname:
  23. raise ValueError("Nom de base de données manquant dans la configuration du job.")
  24. archive_name = _archive_name(instance, "mysql", dbname, backup_dir)
  25. with tempfile.TemporaryDirectory() as tmpdir:
  26. dump_path = os.path.join(tmpdir, f"{dbname}.sql")
  27. result = subprocess.run(
  28. [
  29. "sudo", "mysqldump",
  30. "--single-transaction",
  31. "--routines",
  32. "--triggers",
  33. "--result-file", dump_path,
  34. dbname,
  35. ],
  36. capture_output=True,
  37. text=True,
  38. timeout=7200,
  39. )
  40. log = (result.stdout + result.stderr).strip()
  41. if result.returncode != 0:
  42. raise RuntimeError(f"mysqldump a échoué (code {result.returncode}) :\n{log}")
  43. _write_tar(tmpdir, dump_path, dbname, archive_name, backup_dir, job,
  44. instance, current_app.config.get("INSTANCE_URL", ""))
  45. return archive_name, log or "mysqldump terminé sans sortie."
  46. # ---------------------------------------------------------------------------
  47. # PostgreSQL
  48. # ---------------------------------------------------------------------------
  49. def _run_postgresql(job, instance, backup_dir):
  50. from flask import current_app
  51. cfg = json.loads(job.config_json or "{}")
  52. dbname = cfg.get("database", "")
  53. if not dbname:
  54. raise ValueError("Nom de base de données manquant dans la configuration du job.")
  55. archive_name = _archive_name(instance, "postgresql", dbname, backup_dir)
  56. with tempfile.TemporaryDirectory() as tmpdir:
  57. dump_path = os.path.join(tmpdir, f"{dbname}.sql")
  58. # pg_dump doit tourner en tant qu'utilisateur postgres
  59. result = subprocess.run(
  60. ["sudo", "-u", "postgres", "pg_dump", "--format=plain", dbname],
  61. capture_output=True,
  62. timeout=7200,
  63. )
  64. if result.returncode != 0:
  65. log = result.stderr.decode("utf-8", errors="replace").strip()
  66. raise RuntimeError(f"pg_dump a échoué (code {result.returncode}) :\n{log}")
  67. with open(dump_path, "wb") as f:
  68. f.write(result.stdout)
  69. log = result.stderr.decode("utf-8", errors="replace").strip()
  70. _write_tar(tmpdir, dump_path, dbname, archive_name, backup_dir, job,
  71. instance, current_app.config.get("INSTANCE_URL", ""))
  72. return archive_name, log or "pg_dump terminé sans sortie."
  73. # ---------------------------------------------------------------------------
  74. # Helpers partagés
  75. # ---------------------------------------------------------------------------
  76. def _archive_name(instance, db_type, dbname, backup_dir):
  77. from jobs.utils import unique_archive_name
  78. date_str = datetime.utcnow().strftime("%Y%m%d")
  79. return unique_archive_name(f"{instance}_{db_type}_{dbname}_{date_str}", backup_dir)
  80. # ---------------------------------------------------------------------------
  81. # Restore
  82. # ---------------------------------------------------------------------------
  83. def restore_db_dump(archive_name, backup_dir):
  84. """Restauration d'une base MySQL ou PostgreSQL depuis une archive BackupManager."""
  85. archive_path = os.path.join(backup_dir, archive_name + ".tar")
  86. from jobs.utils import sudo_exists
  87. if not sudo_exists(archive_path):
  88. raise FileNotFoundError(f"Archive introuvable : {archive_path}")
  89. info = _read_backup_info(archive_path)
  90. db_type = info.get("type")
  91. dbname = info.get("database", "")
  92. if not dbname:
  93. raise ValueError("Nom de base de données introuvable dans backup_info.json.")
  94. with tempfile.TemporaryDirectory() as tmpdir:
  95. dump_path = os.path.join(tmpdir, f"{dbname}.sql")
  96. # Extraction du dump depuis l'archive via sudo (backup_dir est 750 root)
  97. result = subprocess.run(
  98. ["sudo", "tar", "-xOf", archive_path, f"db/{dbname}.sql"],
  99. capture_output=True,
  100. )
  101. if result.returncode != 0:
  102. err = result.stderr.decode("utf-8", errors="replace").strip()
  103. raise RuntimeError(f"Extraction du dump échouée : {err}")
  104. with open(dump_path, "wb") as dst:
  105. dst.write(result.stdout)
  106. if db_type == "mysql":
  107. return _restore_mysql(dbname, dump_path)
  108. elif db_type == "postgresql":
  109. return _restore_postgresql(dbname, dump_path)
  110. else:
  111. raise ValueError(f"Type de base inconnu dans l'archive : {db_type}")
  112. def _restore_mysql(dbname, dump_path):
  113. log_lines = []
  114. # Suppression + recréation propre de la base
  115. result = subprocess.run(
  116. ["sudo", "mysql", "-e",
  117. f"DROP DATABASE IF EXISTS `{dbname}`; CREATE DATABASE `{dbname}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"],
  118. capture_output=True, text=True, timeout=60,
  119. )
  120. if result.returncode != 0:
  121. raise RuntimeError(f"Impossible de recréer la base MySQL '{dbname}' :\n{result.stderr.strip()}")
  122. log_lines.append(f"Base MySQL '{dbname}' recréée.")
  123. # Restauration du dump
  124. with open(dump_path, "rb") as f:
  125. result = subprocess.run(
  126. ["sudo", "mysql", dbname],
  127. stdin=f,
  128. capture_output=True,
  129. timeout=7200,
  130. )
  131. log = result.stderr.decode("utf-8", errors="replace").strip()
  132. if result.returncode != 0:
  133. raise RuntimeError(f"mysql restore a échoué (code {result.returncode}) :\n{log}")
  134. log_lines.append(f"Dump restauré dans '{dbname}'.")
  135. if log:
  136. log_lines.append(log)
  137. return "\n".join(log_lines)
  138. def _restore_postgresql(dbname, dump_path):
  139. log_lines = []
  140. # Terminer les connexions actives puis drop + recreate
  141. subprocess.run(
  142. ["sudo", "-u", "postgres", "psql", "-c",
  143. f"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '{dbname}' AND pid <> pg_backend_pid();"],
  144. capture_output=True, timeout=30,
  145. )
  146. subprocess.run(
  147. ["sudo", "-u", "postgres", "dropdb", "--if-exists", dbname],
  148. capture_output=True, timeout=60,
  149. )
  150. result = subprocess.run(
  151. ["sudo", "-u", "postgres", "createdb", dbname],
  152. capture_output=True, text=True, timeout=60,
  153. )
  154. if result.returncode != 0:
  155. raise RuntimeError(f"Impossible de recréer la base PostgreSQL '{dbname}' :\n{result.stderr.strip()}")
  156. log_lines.append(f"Base PostgreSQL '{dbname}' recréée.")
  157. # Restauration du dump
  158. with open(dump_path, "rb") as f:
  159. result = subprocess.run(
  160. ["sudo", "-u", "postgres", "psql", "-d", dbname, "-v", "ON_ERROR_STOP=1"],
  161. stdin=f,
  162. capture_output=True,
  163. timeout=7200,
  164. )
  165. log = result.stderr.decode("utf-8", errors="replace").strip()
  166. if result.returncode != 0:
  167. raise RuntimeError(f"psql restore a échoué (code {result.returncode}) :\n{log}")
  168. log_lines.append(f"Dump restauré dans '{dbname}'.")
  169. if log:
  170. log_lines.append(log)
  171. return "\n".join(log_lines)
  172. def _read_backup_info(archive_path):
  173. from jobs.utils import sudo_read_backup_info
  174. return sudo_read_backup_info(archive_path)
  175. def _write_tar(tmpdir, dump_path, dbname, archive_name, backup_dir, job, instance, instance_url):
  176. """Crée le .tar dans tmpdir puis le copie dans backup_dir via sudo rsync."""
  177. import json as _json
  178. from jobs.utils import sudo_getsize
  179. # backup_info.json embarqué dans le tar
  180. info = {
  181. "instance_name": instance,
  182. "instance_url": instance_url,
  183. "type": job.type,
  184. "database": dbname,
  185. "created_at": datetime.utcnow().isoformat(),
  186. "backupmanager_version": "1.0.0",
  187. }
  188. info_path = os.path.join(tmpdir, "backup_info.json")
  189. with open(info_path, "w") as f:
  190. _json.dump(info, f, indent=2)
  191. # Créer le tar dans tmpdir (accessible par backupmanager)
  192. tmp_archive = os.path.join(tmpdir, archive_name + ".tar")
  193. with tarfile.open(tmp_archive, "w") as tar:
  194. tar.add(dump_path, arcname=f"db/{dbname}.sql")
  195. tar.add(info_path, arcname="backup_info.json")
  196. # Copier vers backup_dir via sudo rsync (backup_dir est 750 root)
  197. archive_path = os.path.join(backup_dir, archive_name + ".tar")
  198. result = subprocess.run(
  199. ["sudo", "rsync", tmp_archive, archive_path],
  200. capture_output=True, text=True,
  201. )
  202. if result.returncode != 0:
  203. raise RuntimeError(f"Copie de l'archive échouée : {result.stderr.strip()}")
  204. # .info.json YunoHost dans tmpdir puis copie via sudo rsync
  205. size = sudo_getsize(archive_path)
  206. ynh_info = {
  207. "created_at": int(time.time()),
  208. "description": f"BackupManager: {job.type} {dbname}",
  209. "size": size,
  210. "from_before_upgrade": False,
  211. "apps": {},
  212. "system": {},
  213. }
  214. tmp_ynh_info = os.path.join(tmpdir, archive_name + ".info.json")
  215. with open(tmp_ynh_info, "w") as f:
  216. _json.dump(ynh_info, f, indent=2)
  217. subprocess.run(
  218. ["sudo", "rsync", tmp_ynh_info,
  219. os.path.join(backup_dir, archive_name + ".info.json")],
  220. capture_output=True,
  221. )