remote-docker-target.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import { spawn } from "node:child_process";
  2. import { connect } from "node:net";
  3. // 远端容器操作 helper:本机 Docker runner 与服务器 runner 都注入 ZCODE_E2E_SSH_CONTAINER,
  4. // 用例用这些 helper 读写容器内文件、注入权限故障、模拟设备离线/恢复,不区分运行宿主。
  5. // 默认以 dev 用户执行(远端 zcode-server 的运行用户),这样权限故障对产品真实生效。
  6. export interface RemoteContainerExecOptions {
  7. /** 容器内用户,默认 dev;需要 root 时传 "0"。 */
  8. user?: string;
  9. /** 经 stdin 传入的内容。 */
  10. input?: string;
  11. }
  12. export interface RemoteContainerExecResult {
  13. stdout: string;
  14. stderr: string;
  15. }
  16. /** 读取 runner 注入的容器名;缺失时说明需要用本机 Docker runner 或服务器队列运行。 */
  17. export function readRemoteDockerContainer(caseMarker: string): string {
  18. const container = process.env.ZCODE_E2E_SSH_CONTAINER?.trim();
  19. if (!container) {
  20. throw new Error(
  21. `${caseMarker}: 缺少 ZCODE_E2E_SSH_CONTAINER;请用本机 Docker 远端 runner 或服务器队列运行`,
  22. );
  23. }
  24. return container;
  25. }
  26. function runDocker(args: string[], input?: string): Promise<RemoteContainerExecResult> {
  27. return new Promise((resolve, reject) => {
  28. const child = spawn("docker", args, {
  29. stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
  30. });
  31. let stdout = "";
  32. let stderr = "";
  33. child.stdout?.setEncoding("utf8").on("data", (chunk: string) => (stdout += chunk));
  34. child.stderr?.setEncoding("utf8").on("data", (chunk: string) => (stderr += chunk));
  35. if (input !== undefined) {
  36. child.stdin?.on("error", () => undefined);
  37. child.stdin?.end(input);
  38. }
  39. child.once("error", reject);
  40. child.once("close", (code) => {
  41. if (code === 0) resolve({ stdout, stderr });
  42. else
  43. reject(
  44. new Error(`docker ${args.join(" ").slice(0, 200)} 退出码 ${code}: ${stderr.trim()}`),
  45. );
  46. });
  47. });
  48. }
  49. /** 在容器内执行命令(argv 形式,不经 shell 拼接)。非零退出码抛错。 */
  50. export function execInRemoteContainer(
  51. container: string,
  52. command: string[],
  53. options: RemoteContainerExecOptions = {},
  54. ): Promise<RemoteContainerExecResult> {
  55. return runDocker(
  56. [
  57. "exec",
  58. ...(options.input === undefined ? [] : ["--interactive"]),
  59. "--user",
  60. options.user ?? "dev",
  61. container,
  62. ...command,
  63. ],
  64. options.input,
  65. );
  66. }
  67. export async function readRemoteContainerFile(container: string, path: string): Promise<string> {
  68. return (await execInRemoteContainer(container, ["cat", "--", path])).stdout;
  69. }
  70. /** 写入容器内文件(自动创建父目录),用于预置远端已有内容。 */
  71. export async function writeRemoteContainerFile(
  72. container: string,
  73. path: string,
  74. content: string,
  75. ): Promise<void> {
  76. await execInRemoteContainer(
  77. container,
  78. ["sh", "-c", 'mkdir -p "$(dirname "$1")" && cat > "$1"', "sh", path],
  79. { input: content },
  80. );
  81. }
  82. /** 目录内的条目名(含隐藏项,已排序);目录不存在时抛错。 */
  83. export async function listRemoteContainerDirectory(
  84. container: string,
  85. path: string,
  86. ): Promise<string[]> {
  87. const { stdout } = await execInRemoteContainer(container, ["ls", "-A1", "--", path]);
  88. return stdout.split("\n").filter(Boolean).sort();
  89. }
  90. export async function remoteContainerPathExists(container: string, path: string): Promise<boolean> {
  91. try {
  92. await execInRemoteContainer(container, ["test", "-e", path]);
  93. return true;
  94. } catch {
  95. return false;
  96. }
  97. }
  98. /** 修改权限,例如 `chmodRemoteContainerPath(c, "a-w", dir)` 制造写失败;用例结束要恢复。 */
  99. export async function chmodRemoteContainerPath(
  100. container: string,
  101. mode: string,
  102. path: string,
  103. options: { recursive?: boolean } = {},
  104. ): Promise<void> {
  105. await execInRemoteContainer(container, [
  106. "chmod",
  107. ...(options.recursive ? ["-R"] : []),
  108. mode,
  109. "--",
  110. path,
  111. ]);
  112. }
  113. /** 让设备离线:停止容器(sshd 与远端 zcode-server 一起停止,容器内文件保留)。 */
  114. export async function takeRemoteDeviceOffline(container: string): Promise<void> {
  115. await runDocker(["stop", "--time", "2", container]);
  116. }
  117. /**
  118. * 让设备恢复:启动容器并等待 sshd 发出握手横幅。runner 把端口固定写进 -p,
  119. * 容器 stop/start 后主机端口不变,用例可以继续使用原来的 ZCODE_E2E_SSH_PORT。
  120. */
  121. export async function bringRemoteDeviceOnline(
  122. container: string,
  123. target: { host: string; port: number; timeoutMs?: number },
  124. ): Promise<void> {
  125. await runDocker(["start", container]);
  126. const deadline = Date.now() + (target.timeoutMs ?? 60_000);
  127. while (Date.now() < deadline) {
  128. if (await readSshBanner(target.host, target.port)) return;
  129. await new Promise((resolve) => setTimeout(resolve, 500));
  130. }
  131. throw new Error(`远端容器 ${container} 重新启动后 sshd 未就绪:${target.host}:${target.port}`);
  132. }
  133. function readSshBanner(host: string, port: number): Promise<boolean> {
  134. return new Promise((resolve) => {
  135. const socket = connect({ host, port });
  136. const finish = (value: boolean) => {
  137. socket.destroy();
  138. resolve(value);
  139. };
  140. socket.setTimeout(2_000, () => finish(false));
  141. socket.once("data", (chunk) => finish(chunk.toString().startsWith("SSH-")));
  142. socket.once("error", () => finish(false));
  143. socket.once("close", () => finish(false));
  144. });
  145. }