remote_executor.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. """SSH 远程执行模块 — 在算力节点上运行 GPU 任务。"""
  2. import json
  3. import os
  4. import subprocess
  5. from typing import Any
  6. from app.config import get_settings
  7. from app.core.logging import logger
  8. settings = get_settings()
  9. def _get_ssh_prefix() -> list[str]:
  10. """构建 ssh/scp 命令前缀,支持密钥或密码登录。"""
  11. prefix = ["-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=10"]
  12. return prefix
  13. def scp_to_remote(local_path: str, remote_path: str) -> tuple[int, str, str]:
  14. """通过 SCP 把本地文件复制到远端主机,返回 (exit_code, stdout, stderr)。"""
  15. target = f"{settings.compute_node_ssh_user}@{settings.compute_node_host}"
  16. scp_args = ["scp", *_get_ssh_prefix(), "-P", str(settings.compute_node_ssh_port)]
  17. if settings.compute_node_ssh_key:
  18. scp_args += ["-i", settings.compute_node_ssh_key]
  19. elif settings.compute_node_ssh_password:
  20. scp_args = ["sshpass", "-p", settings.compute_node_ssh_password] + scp_args
  21. scp_args += [local_path, f"{target}:{remote_path}"]
  22. try:
  23. proc = subprocess.run(scp_args, capture_output=True, text=True, timeout=30)
  24. clean_stderr = "\n".join(line for line in proc.stderr.split("\n")
  25. if not line.startswith("Warning:"))
  26. return proc.returncode, proc.stdout, clean_stderr
  27. except Exception as e:
  28. logger.error(f"SCP failed: {e}")
  29. return -1, "", str(e)
  30. def scp_to_remote_dir(local_path: str, remote_path: str) -> tuple[int, str, str]:
  31. """通过 SCP 把本地目录递归复制到远端主机。"""
  32. target = f"{settings.compute_node_ssh_user}@{settings.compute_node_host}"
  33. scp_args = ["scp", "-r", *_get_ssh_prefix(), "-P", str(settings.compute_node_ssh_port)]
  34. if settings.compute_node_ssh_key:
  35. scp_args += ["-i", settings.compute_node_ssh_key]
  36. elif settings.compute_node_ssh_password:
  37. scp_args = ["sshpass", "-p", settings.compute_node_ssh_password] + scp_args
  38. scp_args += [local_path, f"{target}:{remote_path}"]
  39. try:
  40. proc = subprocess.run(scp_args, capture_output=True, text=True, timeout=120)
  41. clean_stderr = "\n".join(line for line in proc.stderr.split("\n")
  42. if not line.startswith("Warning:"))
  43. return proc.returncode, proc.stdout, clean_stderr
  44. except Exception as e:
  45. logger.error(f"SCP dir failed: {e}")
  46. return -1, "", str(e)
  47. def ssh_exec(cmd: str, timeout: int | None = None) -> tuple[int, str, str]:
  48. """通过 SSH 在算力节点执行命令,返回 (exit_code, stdout, stderr)。"""
  49. if not settings.use_remote_compute:
  50. raise RuntimeError("未配置算力节点(compute_node_host 为空)")
  51. target = f"{settings.compute_node_ssh_user}@{settings.compute_node_host}"
  52. ssh_args = [
  53. "ssh", *_get_ssh_prefix(),
  54. "-p", str(settings.compute_node_ssh_port),
  55. target,
  56. cmd,
  57. ]
  58. # sshpass 需要包裹 ssh 命令,而不是作为 ssh 的参数
  59. if settings.compute_node_ssh_key:
  60. ssh_args = ["ssh", "-i", settings.compute_node_ssh_key] + ssh_args[1:]
  61. elif settings.compute_node_ssh_password:
  62. ssh_args = ["sshpass", "-p", settings.compute_node_ssh_password] + ssh_args
  63. timeout = timeout or settings.compute_node_ssh_timeout
  64. try:
  65. proc = subprocess.run(
  66. ssh_args,
  67. capture_output=True,
  68. text=True,
  69. timeout=timeout,
  70. )
  71. # 过滤 known_hosts 警告,这些不算真正的错误
  72. clean_stderr = "\n".join(line for line in proc.stderr.split("\n")
  73. if not line.startswith("Warning:"))
  74. return proc.returncode, proc.stdout, clean_stderr
  75. except subprocess.TimeoutExpired:
  76. logger.error(f"SSH command timeout after {timeout}s: {cmd[:100]}")
  77. return -1, "", f"Command timed out after {timeout}s"
  78. except Exception as e:
  79. logger.error(f"SSH exec failed: {e}")
  80. return -1, "", str(e)
  81. def run_training_remote(
  82. job_id: str,
  83. model_id: str,
  84. model_type: str,
  85. dataset_path: str,
  86. config: dict[str, Any],
  87. ) -> str | None:
  88. """在算力节点启动训练任务(通过 docker exec,后台执行)。
  89. 通过 SCP 把配置文件传到远端宿主机,再在容器内启动训练。
  90. dataset_path 由主节点预先查好,直接传给远程脚本。
  91. """
  92. import tempfile
  93. # 在 151 宿主机创建临时配置文件
  94. config_tmp = tempfile.mktemp(suffix=".json", prefix=f"config_{job_id}_")
  95. with open(config_tmp, "w", encoding="utf-8") as f:
  96. json.dump(config, f, ensure_ascii=False)
  97. # SCP 到远端宿主机(使用 data_dir,这个目录已通过 bind mount 共享给容器)
  98. remote_config_path = f"{settings.compute_node_remote_data_dir}/config_{job_id}.json"
  99. ret_code, _, _ = scp_to_remote(config_tmp, f"{remote_config_path}")
  100. os.unlink(config_tmp) # 删除本地临时文件
  101. if ret_code != 0:
  102. logger.error(f"SCP config file failed: ret_code={ret_code}")
  103. return None
  104. # 把数据集路径也传到远程(SCP 到 data/uploads/ 目录)
  105. remote_dataset_name = os.path.basename(dataset_path)
  106. remote_dataset_path = f"{settings.compute_node_remote_data_dir}/datasets/{remote_dataset_name}"
  107. if os.path.isdir(dataset_path):
  108. # 目录:用 scp -r
  109. ret_code, _, _ = scp_to_remote_dir(dataset_path, remote_dataset_path)
  110. else:
  111. # 文件:普通 scp
  112. ret_code, _, _ = scp_to_remote(dataset_path, remote_dataset_path)
  113. if ret_code != 0:
  114. logger.error(f"SCP dataset failed: ret_code={ret_code}")
  115. return None
  116. # 在容器内启动训练
  117. remote_cmd = (
  118. f"docker exec -w {settings.compute_node_workdir} "
  119. f"{settings.compute_node_docker_container} "
  120. f"bash -c '"
  121. f"nohup {settings.compute_node_python} -m app.engines.remote_train "
  122. f"{job_id} {model_id} {model_type} {remote_dataset_path} {remote_config_path} "
  123. f"</dev/null >/tmp/train_{job_id}.log 2>&1 & echo $!'"
  124. )
  125. code, stdout, stderr = ssh_exec(remote_cmd, timeout=30)
  126. if code != 0:
  127. logger.error(f"Remote training launch failed: {stderr}")
  128. return None
  129. pid = stdout.strip()
  130. logger.info(f"Remote training launched in container: job={job_id}, container_pid={pid}")
  131. return pid
  132. def is_process_running(pid: str) -> bool:
  133. """检查远程训练进程是否还在运行。
  134. 通过 docker exec 进入容器检查 PID 是否存在。
  135. """
  136. cmd = f"docker exec {settings.compute_node_docker_container} bash -c 'kill -0 {pid} 2>/dev/null && echo running || echo stopped'"
  137. code, stdout, stderr = ssh_exec(cmd, timeout=30)
  138. return code == 0 and "running" in stdout
  139. def run_inference_remote(
  140. model_id: str,
  141. adapter_id: str,
  142. prompt: str,
  143. max_new_tokens: int,
  144. temperature: float,
  145. top_p: float,
  146. repetition_penalty: float,
  147. do_sample: bool,
  148. ) -> dict[str, Any] | None:
  149. """在算力节点执行推理。"""
  150. safe_prompt = prompt.replace('"', '\\"').replace("'", "\\'").replace("\n", "\\n")
  151. remote_cmd = (
  152. f"docker exec {settings.compute_node_docker_container} "
  153. f"{settings.compute_node_python} -c \""
  154. "import asyncio, json; "
  155. "from app.config import get_settings; "
  156. "settings = get_settings(); "
  157. "from app.services.inference_service import run_inference_single; "
  158. f"result = asyncio.run(run_inference_single("
  159. f"'{model_id}', '{adapter_id}', '{safe_prompt}', "
  160. f"{max_new_tokens}, {temperature}, {top_p}, {repetition_penalty}, {str(do_sample).lower()}"
  161. ")); "
  162. "print(json.dumps(result, ensure_ascii=False))\" 2>&1"
  163. )
  164. code, stdout, stderr = ssh_exec(remote_cmd, timeout=600)
  165. if code != 0:
  166. logger.error(f"Remote inference failed: {stderr}")
  167. return {"error": stderr.strip() or "Remote inference failed"}
  168. # 提取最后一行 JSON
  169. for line in reversed(stdout.strip().split("\n")):
  170. line = line.strip()
  171. if line.startswith("{"):
  172. try:
  173. return json.loads(line)
  174. except json.JSONDecodeError:
  175. continue
  176. return {"error": f"Invalid JSON response: {stdout[:500]}"}