mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 16:37:32 +00:00
fix(cli): Windows kills end only the process the CLI started, never a reused pid (#8382)
* test(cli): the Windows Chrome watchdog spares a pid that now runs another program * fix(cli): the Windows Chrome watchdog kills only its own Chrome, never a reused pid * test(cli): no preview lifecycle test may end a real process by a made-up pid * fix(cli): the log-path preview test stops its made-up child through a fake, not a real kill * test(cli): the Windows child reaper spares a held pid that now runs another program * fix(cli): the Windows child reaper kills only the child it started, never a reused pid * test(cli): the reaper's stand-ins outlive the fixture, so only the reaper can end them * test(cli): the kill-failure test keeps processTree's other exports, which the reaper reads
This commit is contained in:
@@ -208,7 +208,7 @@ async function launchOwnedBrowser(
|
||||
const newPage = browser.newPage;
|
||||
browser.newPage = async (...args) => closeOnRendererCrash(await newPage.apply(browser, args));
|
||||
child.once("exit", () => {
|
||||
watchdog?.release(true);
|
||||
void watchdog?.release(true);
|
||||
browsers.delete(browser);
|
||||
destroyBrowserPipes(child);
|
||||
});
|
||||
@@ -287,7 +287,7 @@ async function closeBrowser(browser: Browser): Promise<void> {
|
||||
try {
|
||||
clean = await closedWithoutKill(browser);
|
||||
} finally {
|
||||
watchdogs.get(browser)?.release(clean);
|
||||
void watchdogs.get(browser)?.release(clean);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { testProcessIsAlive, waitForTestCondition } from "../utils/processTestUtils.js";
|
||||
import { watchChromeTree } from "./windowsChromeWatchdog.js";
|
||||
|
||||
const started: ChildProcess[] = [];
|
||||
afterEach(() => {
|
||||
for (const child of started.splice(0)) child.kill("SIGKILL");
|
||||
});
|
||||
|
||||
/** A live process standing where the watched Chrome was: `program` is what the watchdog was told it runs. */
|
||||
function standIn(program: string): ChildProcess {
|
||||
const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" });
|
||||
started.push(child);
|
||||
Object.defineProperty(child, "spawnfile", { value: program });
|
||||
return child;
|
||||
}
|
||||
|
||||
describe.skipIf(process.platform !== "win32")("the Windows Chrome watchdog", () => {
|
||||
// fails without the fix: an unclean release ran taskkill /T on the saved pid whatever now held it, so a pid
|
||||
// Windows had given to another program (a test worker on CI) was ended with its whole tree.
|
||||
it("leaves a process alone once its pid runs another program", async () => {
|
||||
const other = standIn("C:\\chrome\\chrome-headless-shell.exe");
|
||||
await waitForTestCondition(() => testProcessIsAlive(other.pid!), 5_000);
|
||||
await watchChromeTree(other)!.release(false);
|
||||
expect(testProcessIsAlive(other.pid!)).toBe(true);
|
||||
});
|
||||
|
||||
it("still ends the Chrome it watches on an unclean release", async () => {
|
||||
const chrome = standIn(process.execPath);
|
||||
await waitForTestCondition(() => testProcessIsAlive(chrome.pid!), 5_000);
|
||||
await watchChromeTree(chrome)!.release(false);
|
||||
await waitForTestCondition(() => !testProcessIsAlive(chrome.pid!), 5_000);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import { ChildProcess, spawn } from "node:child_process";
|
||||
import { windowsImageOf, windowsOwnTreeKillArgs } from "../utils/processTree.js";
|
||||
|
||||
const WATCHDOG = `let clean = false;
|
||||
const killArgs = ${windowsOwnTreeKillArgs};
|
||||
const done = () => {
|
||||
if (!clean) require("node:child_process").spawnSync("taskkill", ["/PID", process.env.HF_CHROME_PID, "/T", "/F"], { windowsHide: true, stdio: "ignore", timeout: 20000 });
|
||||
if (!clean) require("node:child_process").spawnSync("taskkill", killArgs(process.env.HF_CHROME_PID, process.env.HF_CHROME_IMAGE), { windowsHide: true, stdio: "ignore", timeout: 20000 });
|
||||
process.exit(0);
|
||||
};
|
||||
process.stdin.on("data", (data) => { clean ||= String(data).includes("clean"); });
|
||||
@@ -10,7 +12,7 @@ process.stdin.on("end", done);
|
||||
process.stdin.on("error", done);`;
|
||||
|
||||
export interface ChromeWatchdog {
|
||||
release(clean: boolean): void;
|
||||
release(clean: boolean): Promise<void>;
|
||||
}
|
||||
|
||||
export function watchChromeTree(chrome: ChildProcess): ChromeWatchdog | undefined {
|
||||
@@ -18,7 +20,11 @@ export function watchChromeTree(chrome: ChildProcess): ChromeWatchdog | undefine
|
||||
return undefined;
|
||||
const watchdog = spawn(process.execPath, ["-e", WATCHDOG], {
|
||||
detached: true,
|
||||
env: { ...process.env, HF_CHROME_PID: String(chrome.pid) },
|
||||
env: {
|
||||
...process.env,
|
||||
HF_CHROME_PID: String(chrome.pid),
|
||||
HF_CHROME_IMAGE: windowsImageOf(chrome.spawnfile),
|
||||
},
|
||||
stdio: ["pipe", "ignore", "ignore"],
|
||||
windowsHide: true,
|
||||
});
|
||||
@@ -26,12 +32,13 @@ export function watchChromeTree(chrome: ChildProcess): ChromeWatchdog | undefine
|
||||
watchdog.stdin?.on("error", () => {});
|
||||
watchdog.unref();
|
||||
(watchdog.stdin as unknown as { unref?: () => void } | null)?.unref?.();
|
||||
const ended = new Promise<void>((resolve) => watchdog.once("close", () => resolve()));
|
||||
let released = false;
|
||||
return {
|
||||
release(clean) {
|
||||
if (released) return;
|
||||
if (!released) watchdog.stdin?.end(clean ? "clean" : "");
|
||||
released = true;
|
||||
watchdog.stdin?.end(clean ? "clean" : "");
|
||||
return ended;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -9,8 +9,17 @@ import {
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { describe, expect, it, onTestFinished, vi } from "vitest";
|
||||
import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest";
|
||||
import type { ActiveServer } from "../server/portUtils.js";
|
||||
|
||||
const realKills = vi.hoisted(() => [] as number[]);
|
||||
// fails without the fix: a case that faked spawn but not kill sent a real taskkill /T to its made-up pid, ending
|
||||
// whatever process held that number (a test worker on a Windows runner).
|
||||
vi.mock("../utils/processTree.js", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("../utils/processTree.js")>()),
|
||||
terminateProcessTree: async (pid: number) => void realKills.push(pid),
|
||||
}));
|
||||
afterEach(() => expect(realKills.splice(0), "a real process kill").toEqual([]));
|
||||
import { PreviewServerPortMismatchError } from "../utils/studioSelectionClient.js";
|
||||
import {
|
||||
PreviewPortUnavailableError,
|
||||
@@ -1601,6 +1610,7 @@ describe("background preview log warning", () => {
|
||||
forceNew: true,
|
||||
scan: async () => [],
|
||||
spawn: () => ({ pid: 5432, unref: vi.fn() }),
|
||||
kill: vi.fn(),
|
||||
sleep: async () => {},
|
||||
stateHome: join(blocker, `state${bell}home`),
|
||||
}).catch(() => {});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("./processTree.js", () => ({
|
||||
vi.mock("./processTree.js", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("./processTree.js")>()),
|
||||
terminateProcessTree: () => Promise.reject(new Error("taskkill exited with status 128")),
|
||||
}));
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { spawn, type ChildProcess, type SpawnOptions } from "node:child_process"
|
||||
import { StringDecoder } from "node:string_decoder";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { killWithThisProcess } from "./childReaper.js";
|
||||
import { terminateProcessTree } from "./processTree.js";
|
||||
import { terminateProcessTree, windowsImageOf } from "./processTree.js";
|
||||
import { renderSetupFailureFrom, renderSetupResultFrom } from "../renderSetupWorkerLifecycle.js";
|
||||
|
||||
export interface CancellableProcessResult {
|
||||
@@ -77,7 +77,9 @@ export function runCancellableProcess(
|
||||
return;
|
||||
}
|
||||
|
||||
const release = child.pid ? killWithThisProcess(child.pid, detached) : undefined;
|
||||
const release = child.pid
|
||||
? killWithThisProcess(child.pid, detached, windowsImageOf(child.spawnfile))
|
||||
: undefined;
|
||||
if (child.pid) options.onSpawn?.(child.pid);
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
// fallow-ignore-file unused-file
|
||||
import { spawn } from "node:child_process";
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { killWithThisProcess } from "./childReaper.js";
|
||||
|
||||
const [readyPath] = process.argv.slice(2);
|
||||
if (!readyPath) throw new Error("Missing fixture arguments");
|
||||
|
||||
const standIn = () => {
|
||||
const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
});
|
||||
child.unref();
|
||||
return child.pid!;
|
||||
};
|
||||
const own = standIn();
|
||||
const reused = standIn();
|
||||
killWithThisProcess(reused, false, "ffmpeg.exe");
|
||||
killWithThisProcess(own, false, "node.exe");
|
||||
writeFileSync(readyPath, JSON.stringify({ own, reused }));
|
||||
@@ -6,7 +6,8 @@ import { fileURLToPath } from "node:url";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { testProcessIsAlive, waitForTestCondition } from "./processTestUtils.js";
|
||||
|
||||
const fixturePath = join(dirname(fileURLToPath(import.meta.url)), "childReaper.fixture.ts");
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const fixturePath = join(here, "childReaper.fixture.ts");
|
||||
const leftovers: number[] = [];
|
||||
let parent: ChildProcess | undefined;
|
||||
|
||||
@@ -47,3 +48,32 @@ describe.skipIf(process.platform === "win32")("a CLI killed outright", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe.skipIf(process.platform !== "win32")(
|
||||
"a Windows CLI that ends with children still held",
|
||||
() => {
|
||||
// fails without the fix: the reaper ran taskkill /T on each held pid whatever now held it, so a pid Windows had
|
||||
// given to another program was ended with its whole tree.
|
||||
it("ends the child it started and leaves a pid that now runs another program", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "hyperframes-child-reaper-image-"));
|
||||
const readyPath = join(dir, "ready");
|
||||
try {
|
||||
parent = spawn(
|
||||
process.execPath,
|
||||
["--import", "tsx", join(here, "childReaper.image.fixture.ts"), readyPath],
|
||||
{ stdio: "ignore" },
|
||||
);
|
||||
await new Promise((resolve) => parent!.once("exit", resolve));
|
||||
const { own, reused } = JSON.parse(readFileSync(readyPath, "utf8")) as {
|
||||
own: number;
|
||||
reused: number;
|
||||
};
|
||||
leftovers.push(own, reused);
|
||||
await waitForTestCondition(() => !testProcessIsAlive(own), 10_000);
|
||||
expect(testProcessIsAlive(reused)).toBe(true);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,23 +1,25 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { windowsOwnTreeKillArgs } from "./processTree.js";
|
||||
|
||||
// Ends with this process's end of its stdin, however this process died, and kills what is still held.
|
||||
const REAPER = `const held = new Map();
|
||||
let rest = "";
|
||||
const kill = (pid, group) => {
|
||||
const killArgs = ${windowsOwnTreeKillArgs};
|
||||
const kill = (pid, { group, image }) => {
|
||||
try {
|
||||
if (process.platform === "win32")
|
||||
require("node:child_process").spawnSync("taskkill", ["/PID", pid, "/T", "/F"], { windowsHide: true, timeout: 10000 });
|
||||
require("node:child_process").spawnSync("taskkill", killArgs(pid, image), { windowsHide: true, timeout: 10000 });
|
||||
else process.kill(group ? -Number(pid) : Number(pid), "SIGKILL");
|
||||
} catch {}
|
||||
};
|
||||
process.stdin.on("data", (data) => {
|
||||
const lines = (rest + data).split("\\n");
|
||||
rest = lines.pop();
|
||||
for (const [op, pid, group] of lines.map((line) => line.split(" ")))
|
||||
op === "+" ? held.set(pid, group === "g") : held.delete(pid);
|
||||
for (const [op, pid, group, ...image] of lines.map((line) => line.split(" ")))
|
||||
op === "+" ? held.set(pid, { group: group === "g", image: image.join(" ") }) : held.delete(pid);
|
||||
});
|
||||
const done = () => {
|
||||
for (const [pid, group] of held) kill(pid, group);
|
||||
for (const [pid, child] of held) kill(pid, child);
|
||||
process.exit(0);
|
||||
};
|
||||
process.stdin.on("end", done);
|
||||
@@ -40,9 +42,9 @@ function lifeline(): NodeJS.WritableStream | null {
|
||||
return reaper.stdin;
|
||||
}
|
||||
|
||||
/** Kills `pid`, its whole process group when `group`, if this process ends before the returned release runs. */
|
||||
export function killWithThisProcess(pid: number, group: boolean): () => void {
|
||||
/** Kills `pid` (its group when `group`; on Windows only while it runs `image`) if this process ends before release. */
|
||||
export function killWithThisProcess(pid: number, group: boolean, image: string): () => void {
|
||||
const stdin = lifeline();
|
||||
stdin?.write(`+ ${pid} ${group ? "g" : "p"}\n`);
|
||||
stdin?.write(`+ ${pid} ${group ? "g" : "p"} ${image}\n`);
|
||||
return () => void stdin?.write(`- ${pid}\n`);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { execFileSync, spawn, type ChildProcess, type SpawnOptions } from "node:child_process";
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { win32 } from "node:path";
|
||||
|
||||
interface SpawnedProcess {
|
||||
once(event: "error", listener: (error: Error) => void): unknown;
|
||||
@@ -58,6 +59,15 @@ export function windowsProcessTreeKillArgs(pid: number): string[] {
|
||||
return ["/PID", String(pid), "/T", "/F"];
|
||||
}
|
||||
|
||||
export function windowsOwnTreeKillArgs(pid: string, image: string): string[] {
|
||||
return ["/F", "/T", "/FI", `PID eq ${pid}`, "/FI", `IMAGENAME eq ${image}`];
|
||||
}
|
||||
|
||||
export function windowsImageOf(spawnfile: string): string {
|
||||
const name = win32.basename(spawnfile);
|
||||
return win32.extname(name) ? name : `${name}.exe`;
|
||||
}
|
||||
|
||||
export function terminateWindowsProcessTree(
|
||||
pid: number,
|
||||
spawnProcess: SpawnProcess = (command, args, options) => spawn(command, [...args], options),
|
||||
|
||||
Reference in New Issue
Block a user