remote_executor.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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 ssh_exec(cmd: str, timeout: int | None = None) -> tuple[int, str, str]:
  14. """通过 SSH 在算力节点执行命令,返回 (exit_code, stdout, stderr)。"""
  15. if not settings.use_remote_compute:
  16. raise RuntimeError("未配置算力节点(compute_node_host 为空)")
  17. target = f"{settings.compute_node_ssh_user}@{settings.compute_node_host}"
  18. ssh_args = [
  19. "ssh", *_get_ssh_prefix(),
  20. "-p", str(settings.compute_node_ssh_port),
  21. target,
  22. cmd,
  23. ]
  24. # sshpass 需要包裹 ssh 命令,而不是作为 ssh 的参数
  25. if settings.compute_node_ssh_key:
  26. ssh_args = ["ssh", "-i", settings.compute_node_ssh_key] + ssh_args[1:]
  27. elif settings.compute_node_ssh_password:
  28. ssh_args = ["sshpass", "-p", settings.compute_node_ssh_password] + ssh_args
  29. timeout = timeout or settings.compute_node_ssh_timeout
  30. try:
  31. proc = subprocess.run(
  32. ssh_args,
  33. capture_output=True,
  34. text=True,
  35. timeout=timeout,
  36. )
  37. # 过滤 known_hosts 警告,这些不算真正的错误
  38. clean_stderr = "\n".join(line for line in proc.stderr.split("\n")
  39. if not line.startswith("Warning:"))
  40. return proc.returncode, proc.stdout, clean_stderr
  41. except subprocess.TimeoutExpired:
  42. logger.error(f"SSH command timeout after {timeout}s: {cmd[:100]}")
  43. return -1, "", f"Command timed out after {timeout}s"
  44. except Exception as e:
  45. logger.error(f"SSH exec failed: {e}")
  46. return -1, "", str(e)
  47. def run_training_remote(
  48. job_id: str,
  49. model_id: str,
  50. model_type: str,
  51. dataset_id: str,
  52. config: dict[str, Any],
  53. ) -> str | None:
  54. """在算力节点启动训练任务(通过 docker exec,后台执行)。
  55. 在容器内用 nohup 启动训练,返回 PID 以便后续检测。
  56. """
  57. config_json = json.dumps(config, ensure_ascii=False)
  58. config_escaped = config_json.replace('"', '\\"')
  59. remote_cmd = (
  60. f"docker exec {settings.compute_node_docker_container} "
  61. f"bash -c 'nohup {settings.compute_node_python} -m app.engines.remote_train "
  62. f"'{job_id}' '{model_id}' '{model_type}' '{dataset_id}' '{config_escaped}' "
  63. f">/tmp/train_{job_id}.log 2>&1 & echo $!'"
  64. )
  65. code, stdout, stderr = ssh_exec(remote_cmd, timeout=30)
  66. if code != 0:
  67. logger.error(f"Remote training launch failed: {stderr}")
  68. return None
  69. pid = stdout.strip()
  70. logger.info(f"Remote training launched in container: job={job_id}, container_pid={pid}")
  71. return pid
  72. def is_process_running(pid: str) -> bool:
  73. """检查远程训练进程是否还在运行。
  74. 通过 docker exec 进入容器检查 PID 是否存在。
  75. """
  76. cmd = f"docker exec {settings.compute_node_docker_container} bash -c 'kill -0 {pid} 2>/dev/null && echo running || echo stopped'"
  77. code, stdout, stderr = ssh_exec(cmd, timeout=10)
  78. return code == 0 and "running" in stdout
  79. def run_inference_remote(
  80. model_id: str,
  81. adapter_id: str,
  82. prompt: str,
  83. max_new_tokens: int,
  84. temperature: float,
  85. top_p: float,
  86. repetition_penalty: float,
  87. do_sample: bool,
  88. ) -> dict[str, Any] | None:
  89. """在算力节点执行推理。"""
  90. safe_prompt = prompt.replace('"', '\\"').replace("'", "\\'").replace("\n", "\\n")
  91. remote_cmd = (
  92. f"docker exec {settings.compute_node_docker_container} "
  93. f"{settings.compute_node_python} -c \""
  94. "import asyncio, json; "
  95. "from app.config import get_settings; "
  96. "settings = get_settings(); "
  97. "from app.services.inference_service import run_inference_single; "
  98. f"result = asyncio.run(run_inference_single("
  99. f"'{model_id}', '{adapter_id}', '{safe_prompt}', "
  100. f"{max_new_tokens}, {temperature}, {top_p}, {repetition_penalty}, {str(do_sample).lower()}"
  101. ")); "
  102. "print(json.dumps(result, ensure_ascii=False))\" 2>&1"
  103. )
  104. code, stdout, stderr = ssh_exec(remote_cmd, timeout=600)
  105. if code != 0:
  106. logger.error(f"Remote inference failed: {stderr}")
  107. return {"error": stderr.strip() or "Remote inference failed"}
  108. # 提取最后一行 JSON
  109. for line in reversed(stdout.strip().split("\n")):
  110. line = line.strip()
  111. if line.startswith("{"):
  112. try:
  113. return json.loads(line)
  114. except json.JSONDecodeError:
  115. continue
  116. return {"error": f"Invalid JSON response: {stdout[:500]}"}