bash-shutdown.test.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. import { spawn, execFile } from "node:child_process";
  2. import { mkdtemp, mkdir, readFile, rm } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { fileURLToPath } from "node:url";
  6. import { promisify } from "node:util";
  7. import { build } from "esbuild";
  8. import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
  9. const execFileAsync = promisify(execFile);
  10. const adapterSource = fileURLToPath(
  11. new URL("../src/exec/node-execution-adapter.ts", import.meta.url),
  12. );
  13. // 不能在 Vitest worker 内验证保活:框架的 IPC/定时器会掩盖 Node 在 close 尚未完成时退出。
  14. const driverSource = `
  15. import { NodeExecutionAdapter } from ${JSON.stringify(adapterSource)};
  16. import { spawn } from 'node:child_process';
  17. import { writeFile, access } from 'node:fs/promises';
  18. import { join } from 'node:path';
  19. import { setTimeout as sleep } from 'node:timers/promises';
  20. async function main() {
  21. const mode = process.argv[2], root = process.argv[3];
  22. const ready = join(root, 'worker.pid');
  23. if (mode === 'worker') {
  24. process.on('SIGTERM', () => {});
  25. await writeFile(ready, String(process.pid));
  26. setInterval(() => {}, 1000);
  27. return;
  28. }
  29. if (mode === 'root') {
  30. spawn(process.execPath, [process.argv[1], 'worker', root], { stdio: ['ignore', 1, 2] });
  31. process.stdout.write('root output');
  32. setInterval(() => {}, 1000);
  33. return;
  34. }
  35. const adapter = new NodeExecutionAdapter({ outputRootDir: root, ...(mode === 'crash' ? { bashOutputTempDir: root } : {}) });
  36. const controller = new AbortController();
  37. const request = {
  38. command: {
  39. mode: 'shell', shellProfile: 'posix-bash',
  40. shellOverride: { path: '/bin/bash', dialect: 'posix', source: 'user-config', display: { name: 'bash' } },
  41. command: '"$TEST_NODE" "$TEST_DRIVER" root "$TEST_ROOT"',
  42. },
  43. cwd: root,
  44. timeoutMs: mode === 'timeout' ? 2000 : 10000,
  45. env: { set: { TEST_NODE: process.execPath, TEST_DRIVER: process.argv[1], TEST_ROOT: root } },
  46. outputLimit: { persistOutput: 'always', ...(mode === 'output_limit' ? { maxPersistedBytes: 1 } : {}) },
  47. };
  48. const options = { signal: controller.signal, onEvent: (event) => {
  49. if (event.type === 'started') console.log('ROOT_PID ' + event.pid);
  50. } };
  51. const pending = mode === 'background' || mode === 'crash'
  52. ? adapter.runBashWithBackgroundLifecycle(request, { mode: 'explicit' }, options)
  53. : adapter.run(request, options);
  54. const background = mode === 'background' || mode === 'crash' ? await pending : undefined;
  55. if (background) console.log('ROOT_PID ' + background.task.pid);
  56. const deadline = Date.now() + 5000;
  57. while (true) {
  58. try { await access(ready); break; } catch {}
  59. if (Date.now() >= deadline) throw new Error('Worker did not start');
  60. await sleep(20);
  61. }
  62. if (mode === 'crash') {
  63. console.log('OUTPUT_PATH ' + background.task.outputPath);
  64. await new Promise(() => {});
  65. return;
  66. }
  67. if (mode === 'abort') controller.abort();
  68. if (mode === 'background') await adapter.cancelBackgroundTask(background.task.taskId);
  69. // 后台 Stop 的 ACK 可早于最终 result;close 后再读取完整结算。
  70. if (mode === 'close' || mode === 'background') await adapter.close();
  71. const result = background
  72. ? (await adapter.waitForBackgroundTask(background.task.taskId)).result
  73. : await pending;
  74. console.log('RESULT ' + result.status);
  75. await adapter.close();
  76. console.log('CLOSE_FINISHED');
  77. }
  78. main().catch((error) => { console.error(error); process.exitCode = 1; });
  79. `;
  80. async function isRunning(pid: number): Promise<boolean> {
  81. try {
  82. const { stdout } = await execFileAsync("ps", ["-o", "stat=", "-p", String(pid)]);
  83. // Linux 容器的 init 可能延迟回收孤儿 zombie;已终止的进程不算仍在执行。
  84. return stdout.trim().length > 0 && !stdout.trim().startsWith("Z");
  85. } catch {
  86. return false;
  87. }
  88. }
  89. describe.skipIf(process.platform === "win32")("Bash shutdown in an isolated Node", () => {
  90. let directory: string;
  91. let driver: string;
  92. beforeAll(async () => {
  93. directory = await mkdtemp(join(tmpdir(), "zcode-bash-shutdown-"));
  94. driver = join(directory, "driver.cjs");
  95. await build({
  96. stdin: { contents: driverSource, resolveDir: process.cwd() },
  97. bundle: true,
  98. platform: "node",
  99. format: "cjs",
  100. outfile: driver,
  101. logLevel: "silent",
  102. });
  103. });
  104. afterAll(async () => {
  105. if (directory) await rm(directory, { recursive: true, force: true });
  106. });
  107. it("keeps named tmp output when the host is killed without cleanup", async () => {
  108. const root = join(directory, "crash");
  109. await mkdir(root);
  110. const child = spawn(process.execPath, [driver, "crash", root], {
  111. stdio: ["ignore", "pipe", "pipe"],
  112. });
  113. let stdout = "";
  114. child.stdout!.on("data", (chunk) => {
  115. stdout += chunk;
  116. });
  117. const closed = new Promise<void>((resolve) => child.once("close", () => resolve()));
  118. try {
  119. await vi.waitFor(() => expect(stdout).toContain("OUTPUT_PATH "), { timeout: 10_000 });
  120. const path = /OUTPUT_PATH ([^\r\n]+)/u.exec(stdout)![1]!;
  121. expect(path).toContain("zcode-bash-");
  122. expect(await readFile(path, "utf8")).toBe("root output");
  123. child.kill("SIGKILL");
  124. await closed;
  125. expect(await readFile(path, "utf8")).toBe("root output");
  126. } finally {
  127. child.kill("SIGKILL");
  128. const pid = Number(/ROOT_PID (\d+)/u.exec(stdout)?.[1]);
  129. if (pid > 1) {
  130. try {
  131. process.kill(-pid, "SIGKILL");
  132. } catch {
  133. /* 清理测试子进程。 */
  134. }
  135. }
  136. }
  137. }, 15_000);
  138. it.each(["abort", "close", "background", "timeout", "output_limit"])(
  139. "finishes cleanup before process exit after %s",
  140. async (mode) => {
  141. const root = join(directory, mode);
  142. await mkdir(root);
  143. const child = spawn(process.execPath, [driver, mode, root], {
  144. stdio: ["ignore", "pipe", "pipe"],
  145. });
  146. let stdout = "",
  147. stderr = "";
  148. child.stdout!.on("data", (chunk) => {
  149. stdout += chunk;
  150. });
  151. child.stderr!.on("data", (chunk) => {
  152. stderr += chunk;
  153. });
  154. const deadline = setTimeout(() => child.kill("SIGKILL"), 15000);
  155. try {
  156. const code = await new Promise<number | null>((resolve, reject) => {
  157. child.once("error", reject);
  158. child.once("close", resolve);
  159. });
  160. expect(code, stderr).toBe(0);
  161. expect(stdout).toContain("CLOSE_FINISHED");
  162. expect(stdout).toContain(`RESULT ${mode === "timeout" ? "timed_out" : "cancelled"}`);
  163. const pid = Number(await readFile(join(root, "worker.pid"), "utf8"));
  164. await vi.waitFor(async () => expect(await isRunning(pid)).toBe(false));
  165. } finally {
  166. clearTimeout(deadline);
  167. child.kill("SIGKILL");
  168. const rootPid = Number(/ROOT_PID (\d+)/u.exec(stdout)?.[1]);
  169. if (rootPid > 1) {
  170. try {
  171. process.kill(-rootPid, "SIGKILL");
  172. } catch {
  173. /* 测试负责回收失败时留下的进程组。 */
  174. }
  175. }
  176. }
  177. },
  178. 20000,
  179. );
  180. });