transfer.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. import os
  2. import re
  3. import subprocess
  4. def generate_key(dest_name, data_dir):
  5. """Génère une paire de clés ed25519 pour cette destination si elle n'existe pas encore."""
  6. key_name = f"dest_{_slugify(dest_name)}_ed25519"
  7. os.makedirs(os.path.join(data_dir, "keys"), exist_ok=True)
  8. key_path = os.path.join(data_dir, "keys", key_name)
  9. if not os.path.exists(key_path):
  10. subprocess.run(
  11. [
  12. "ssh-keygen", "-t", "ed25519",
  13. "-f", key_path,
  14. "-N", "",
  15. "-C", f"backupmanager@{dest_name}",
  16. ],
  17. check=True,
  18. capture_output=True,
  19. )
  20. os.chmod(key_path, 0o600)
  21. return key_name
  22. def get_public_key(key_name, data_dir):
  23. """Retourne la clé publique à copier dans authorized_keys sur le serveur distant."""
  24. pub_path = os.path.join(data_dir, "keys", key_name + ".pub")
  25. try:
  26. with open(pub_path) as f:
  27. return f.read().strip()
  28. except FileNotFoundError:
  29. return None
  30. def transfer_archive(archive_name, destination, backup_dir, data_dir):
  31. """Transfère .tar + .info.json vers la destination via rsync SSH."""
  32. key_path = os.path.join(data_dir, "keys", destination.key_name)
  33. if not os.path.exists(key_path):
  34. raise FileNotFoundError(
  35. f"Clé SSH introuvable : {key_path}\n"
  36. "Accédez à la page de la destination pour afficher la clé publique."
  37. )
  38. from jobs.utils import sudo_exists
  39. files = []
  40. for ext in (".tar", ".info.json"):
  41. path = os.path.join(backup_dir, archive_name + ext)
  42. if sudo_exists(path):
  43. files.append(path)
  44. if not files:
  45. raise FileNotFoundError(f"Aucun fichier à transférer pour {archive_name}.")
  46. remote = f"{destination.user}@{destination.host}:{destination.remote_path}/"
  47. ssh_opts = (
  48. f"ssh -i {key_path} -p {destination.port}"
  49. " -o StrictHostKeyChecking=accept-new"
  50. " -o BatchMode=yes"
  51. " -o ConnectTimeout=30"
  52. )
  53. # sudo car les archives YNH (ynh_app/ynh_system) sont owned root
  54. cmd = ["sudo", "rsync", "-az", "--stats", "-e", ssh_opts] + files + [remote]
  55. result = subprocess.run(cmd, capture_output=True, text=True, timeout=7200)
  56. log = (result.stdout + result.stderr).strip()
  57. if result.returncode != 0:
  58. raise RuntimeError(
  59. f"rsync vers {destination.host} échoué (code {result.returncode}) :\n{log}"
  60. )
  61. return log
  62. def test_connection(destination, data_dir):
  63. """Teste la connexion SSH vers la destination. Retourne (True, msg) ou (False, msg)."""
  64. key_path = os.path.join(data_dir, "keys", destination.key_name)
  65. if not os.path.exists(key_path):
  66. return False, "Clé SSH non générée. Affichez la destination pour la créer."
  67. result = subprocess.run(
  68. [
  69. "ssh",
  70. "-i", key_path,
  71. "-p", str(destination.port),
  72. "-o", "StrictHostKeyChecking=accept-new",
  73. "-o", "BatchMode=yes",
  74. "-o", "ConnectTimeout=10",
  75. f"{destination.user}@{destination.host}",
  76. "echo ok",
  77. ],
  78. capture_output=True,
  79. text=True,
  80. timeout=20,
  81. )
  82. if result.returncode == 0:
  83. return True, f"Connexion réussie vers {destination.host}:{destination.port}."
  84. return False, result.stderr.strip() or f"Connexion échouée (code {result.returncode})."
  85. def push_archive_to_instance(archive_name, instance, backup_dir):
  86. """Pousse .tar + .info.json vers une instance fédérée via HTTP chunked. Retourne un log texte."""
  87. import hashlib
  88. from federation.client import FederationClient
  89. from jobs.utils import sudo_exists
  90. archive_path = os.path.join(backup_dir, archive_name + ".tar")
  91. tmp_tar = f"/tmp/backupmanager_push_{archive_name}.tar"
  92. tmp_info = f"/tmp/backupmanager_push_{archive_name}.info.json"
  93. try:
  94. result = subprocess.run(["sudo", "rsync", archive_path, tmp_tar],
  95. capture_output=True, text=True)
  96. if result.returncode != 0:
  97. raise RuntimeError(f"Copie locale échouée : {result.stderr.strip()}")
  98. total_size = os.path.getsize(tmp_tar)
  99. sha256 = hashlib.sha256()
  100. chunk_size = 50 * 1024 * 1024
  101. with open(tmp_tar, "rb") as f:
  102. while True:
  103. data = f.read(65536)
  104. if not data:
  105. break
  106. sha256.update(data)
  107. checksum = sha256.hexdigest()
  108. client = FederationClient(instance)
  109. upload_info = client.upload_start(archive_name + ".tar", total_size, checksum, chunk_size)
  110. upload_id = upload_info["upload_id"]
  111. with open(tmp_tar, "rb") as f:
  112. n = 0
  113. while True:
  114. data = f.read(chunk_size)
  115. if not data:
  116. break
  117. client.upload_chunk(upload_id, n, data)
  118. n += 1
  119. info_json_content = None
  120. info_path = os.path.join(backup_dir, archive_name + ".info.json")
  121. if sudo_exists(info_path):
  122. r = subprocess.run(["sudo", "rsync", info_path, tmp_info], capture_output=True)
  123. if r.returncode == 0:
  124. try:
  125. with open(tmp_info, "r", encoding="utf-8", errors="replace") as fh:
  126. info_json_content = fh.read()
  127. finally:
  128. subprocess.run(["sudo", "rm", "-rf", tmp_info], capture_output=True)
  129. client.upload_finish_with_info(upload_id, info_json_content)
  130. return f"Transfert HTTP chunked vers {instance.name} ({instance.url}) — {total_size // (1024*1024)} Mo en {n} chunks."
  131. finally:
  132. if os.path.exists(tmp_tar):
  133. os.unlink(tmp_tar)
  134. def _slugify(s):
  135. return re.sub(r'[^a-z0-9]+', '-', s.lower().strip()).strip('-')