bash-shutdown.test.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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 });
  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'
  52. ? adapter.runBashWithBackgroundLifecycle(request, { mode: 'explicit' }, options)
  53. : adapter.run(request, options);
  54. const background = mode === 'background' ? 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 === 'abort') controller.abort();
  63. if (mode === 'background') await adapter.cancelBackgroundTask(background.task.taskId);
  64. // 后台 Stop 的 ACK 可早于最终 result;close 后再读取完整结算。
  65. if (mode === 'close' || mode === 'background') await adapter.close();
  66. const result = background
  67. ? (await adapter.waitForBackgroundTask(background.task.taskId)).result
  68. : await pending;
  69. console.log('RESULT ' + result.status);
  70. await adapter.close();
  71. console.log('CLOSE_FINISHED');
  72. }
  73. main().catch((error) => { console.error(error); process.exitCode = 1; });
  74. `;
  75. async function isRunning(pid: number): Promise<boolean> {
  76. try {
  77. const { stdout } = await execFileAsync("ps", ["-o", "stat=", "-p", String(pid)]);
  78. // Linux 容器的 init 可能延迟回收孤儿 zombie;已终止的进程不算仍在执行。
  79. return stdout.trim().length > 0 && !stdout.trim().startsWith("Z");
  80. } catch {
  81. return false;
  82. }
  83. }
  84. describe.skipIf(process.platform === "win32")("Bash shutdown in an isolated Node", () => {
  85. let directory: string;
  86. let driver: string;
  87. beforeAll(async () => {
  88. directory = await mkdtemp(join(tmpdir(), "zcode-bash-shutdown-"));
  89. driver = join(directory, "driver.cjs");
  90. await build({
  91. stdin: { contents: driverSource, resolveDir: process.cwd() },
  92. bundle: true,
  93. platform: "node",
  94. format: "cjs",
  95. outfile: driver,
  96. logLevel: "silent",
  97. });
  98. });
  99. afterAll(async () => {
  100. if (directory) await rm(directory, { recursive: true, force: true });
  101. });
  102. it.each(["abort", "close", "background", "timeout", "output_limit"])(
  103. "finishes cleanup before process exit after %s",
  104. async (mode) => {
  105. const root = join(directory, mode);
  106. await mkdir(root);
  107. const child = spawn(process.execPath, [driver, mode, root], {
  108. stdio: ["ignore", "pipe", "pipe"],
  109. });
  110. let stdout = "",
  111. stderr = "";
  112. child.stdout!.on("data", (chunk) => {
  113. stdout += chunk;
  114. });
  115. child.stderr!.on("data", (chunk) => {
  116. stderr += chunk;
  117. });
  118. const deadline = setTimeout(() => child.kill("SIGKILL"), 15000);
  119. try {
  120. const code = await new Promise<number | null>((resolve, reject) => {
  121. child.once("error", reject);
  122. child.once("close", resolve);
  123. });
  124. expect(code, stderr).toBe(0);
  125. expect(stdout).toContain("CLOSE_FINISHED");
  126. expect(stdout).toContain(`RESULT ${mode === "timeout" ? "timed_out" : "cancelled"}`);
  127. const pid = Number(await readFile(join(root, "worker.pid"), "utf8"));
  128. await vi.waitFor(async () => expect(await isRunning(pid)).toBe(false));
  129. } finally {
  130. clearTimeout(deadline);
  131. child.kill("SIGKILL");
  132. const rootPid = Number(/ROOT_PID (\d+)/u.exec(stdout)?.[1]);
  133. if (rootPid > 1) {
  134. try {
  135. process.kill(-rootPid, "SIGKILL");
  136. } catch {
  137. /* 测试负责回收失败时留下的进程组。 */
  138. }
  139. }
  140. }
  141. },
  142. 20000,
  143. );
  144. });