remote_executor.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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. return proc.returncode, proc.stdout, proc.stderr
  38. except subprocess.TimeoutExpired:
  39. logger.error(f"SSH command timeout after {timeout}s: {cmd[:100]}")
  40. return -1, "", f"Command timed out after {timeout}s"
  41. except Exception as e:
  42. logger.error(f"SSH exec failed: {e}")
  43. return -1, "", str(e)
  44. def run_training_remote(
  45. job_id: str,
  46. model_id: str,
  47. model_type: str,
  48. dataset_id: str,
  49. config: dict[str, Any],
  50. ) -> str | None:
  51. """在算力节点启动训练任务(通过 docker exec,后台执行)。
  52. 在容器内用 nohup 启动训练,返回 PID 以便后续检测。
  53. """
  54. config_json = json.dumps(config, ensure_ascii=False)
  55. config_escaped = config_json.replace('"', '\\"')
  56. remote_cmd = (
  57. f"docker exec {settings.compute_node_docker_container} "
  58. f"bash -c 'nohup {settings.compute_node_python} -m app.engines.remote_train "
  59. f"'{job_id}' '{model_id}' '{model_type}' '{dataset_id}' '{config_escaped}' "
  60. f">/tmp/train_{job_id}.log 2>&1 & echo $!'"
  61. )
  62. code, stdout, stderr = ssh_exec(remote_cmd, timeout=30)
  63. if code != 0:
  64. logger.error(f"Remote training launch failed: {stderr}")
  65. return None
  66. pid = stdout.strip()
  67. logger.info(f"Remote training launched in container: job={job_id}, container_pid={pid}")
  68. return pid
  69. def is_process_running(pid: str) -> bool:
  70. """检查远程训练进程是否还在运行。
  71. 通过 docker exec 进入容器检查 PID 是否存在。
  72. """
  73. cmd = f"docker exec {settings.compute_node_docker_container} bash -c 'kill -0 {pid} 2>/dev/null && echo running || echo stopped'"
  74. code, stdout, stderr = ssh_exec(cmd, timeout=10)
  75. return code == 0 and "running" in stdout
  76. def run_inference_remote(
  77. model_id: str,
  78. adapter_id: str,
  79. prompt: str,
  80. max_new_tokens: int,
  81. temperature: float,
  82. top_p: float,
  83. repetition_penalty: float,
  84. do_sample: bool,
  85. ) -> dict[str, Any] | None:
  86. """在算力节点执行推理。"""
  87. safe_prompt = prompt.replace('"', '\\"').replace("'", "\\'").replace("\n", "\\n")
  88. remote_cmd = (
  89. f"docker exec {settings.compute_node_docker_container} "
  90. f"{settings.compute_node_python} -c \""
  91. "import asyncio, json; "
  92. "from app.config import get_settings; "
  93. "settings = get_settings(); "
  94. "from app.services.inference_service import run_inference_single; "
  95. f"result = asyncio.run(run_inference_single("
  96. f"'{model_id}', '{adapter_id}', '{safe_prompt}', "
  97. f"{max_new_tokens}, {temperature}, {top_p}, {repetition_penalty}, {str(do_sample).lower()}"
  98. ")); "
  99. "print(json.dumps(result, ensure_ascii=False))\" 2>&1"
  100. )
  101. code, stdout, stderr = ssh_exec(remote_cmd, timeout=600)
  102. if code != 0:
  103. logger.error(f"Remote inference failed: {stderr}")
  104. return {"error": stderr.strip() or "Remote inference failed"}
  105. # 提取最后一行 JSON
  106. for line in reversed(stdout.strip().split("\n")):
  107. line = line.strip()
  108. if line.startswith("{"):
  109. try:
  110. return json.loads(line)
  111. except json.JSONDecodeError:
  112. continue
  113. return {"error": f"Invalid JSON response: {stdout[:500]}"}