Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/daemon/service-main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ describe("the Windows supervisor (#1698)", () => {
const first = failed.runner.calls[0];
expect(first?.options.timeoutMs, "the daemon wait has no limit").toBeUndefined();
expect(first?.options.stdio).toEqual({ file: join(home, "daemon.log") });
expect(first?.options.outlivesCaller, "ending the supervisor ends its daemon").toBeUndefined();
expect(first?.options.env).toMatchObject({ PATH: "saved", KEEP: "1", SIMLOCK_HOME: home });
expect(failed.logPaths[0]).toBe(join(home, "daemon.log"));
expect(
Expand Down
11 changes: 9 additions & 2 deletions src/drivers/android/adb-server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ describe("AdbServerSupervisor.start", () => {
ANDROID_HOME: "/android-sdk",
PATH: "/usr/bin",
},
outlivesCaller: true,
stdio: { file: logPath },
},
},
Expand Down Expand Up @@ -139,6 +140,8 @@ describe("AdbServerSupervisor.start", () => {
await harness.started;

expect(harness.supervisor.signals).toEqual([{ pid: recordedPid, signal: "SIGTERM" }]);
// why: on Windows the recorded pid is the conhost wrapper's; its adb must end with it.
expect(harness.supervisor.treeSignals).toEqual([recordedPid]);
expect(harness.runner.calls.map((call) => call.command)).toEqual([adb]);
},
);
Expand Down Expand Up @@ -489,8 +492,12 @@ const ownServerCommand = `${adb} -P 5038 nodaemon server`;
class SignallingSupervisor extends FakeProcessSupervisor {
onSignal: ((pid: number, signal: NodeJS.Signals) => void) | undefined;

override signal(pid: number, signal: NodeJS.Signals): void {
super.signal(pid, signal);
override signal(
pid: number,
signal: NodeJS.Signals,
options?: { readonly tree?: boolean },
): void {
super.signal(pid, signal, options);
this.onSignal?.(pid, signal);
}
}
Expand Down
5 changes: 3 additions & 2 deletions src/drivers/android/adb-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,10 +238,10 @@ export class AdbServerSupervisor {
return;
}

this.#options.processSupervisor.signal(record.pid, "SIGTERM");
this.#options.processSupervisor.signal(record.pid, "SIGTERM", { tree: true });
if (!(await this.#waitForExit(record.pid))) {
if ((await this.#identify(record.pid)) === "own-server") {
this.#options.processSupervisor.signal(record.pid, "SIGKILL");
this.#options.processSupervisor.signal(record.pid, "SIGKILL", { tree: true });
await this.#waitForExit(record.pid);
}
}
Expand Down Expand Up @@ -317,6 +317,7 @@ export class AdbServerSupervisor {
...SCOPED_ENVIRONMENT,
ANDROID_ADB_SERVER_PORT: String(this.#options.port),
},
outlivesCaller: true,
stdio: { file: this.#options.logPath },
},
);
Expand Down
31 changes: 27 additions & 4 deletions src/drivers/android/emulator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ export const COLD_BOOT_ESTIMATE_MS = 70_000;
const PORT_POLL_INTERVAL_MS = 2_000;
// why: how long an emulator that was asked to stop may take to exit, whatever the boot deadline is.
const EMULATOR_EXIT_TIMEOUT_MS = 180_000;
// why: how long the process Node holds for an emulator may outlive the emulator once adb stopped listing it (see `shutdown`); the `emulator -kill` helpers sleep 20 s.
const WRAPPER_GRACE_MS = 30_000;
// why: After this long without an answer from a serial, the emulator's own registration is
// assumed lost and Simlock re-sends it. Long enough that a normally-booting emulator has
// already attached, short enough that a lost announcement costs seconds, not the whole
Expand Down Expand Up @@ -145,8 +147,7 @@ export class Emulator {
const startedAt = this.#options.clock.now();
let remaining = serials;
while (remaining.length > 0) {
const attached = (await this.#options.adbTools.scanSerials()).settledSerials;
remaining = remaining.filter((serial) => attached.includes(serial));
remaining = await this.#stillAttached(remaining);
if (remaining.length === 0) return;
if (this.#options.clock.now() - startedAt >= EMULATOR_EXIT_TIMEOUT_MS) {
throw new DriverCrashError(
Expand All @@ -157,6 +158,15 @@ export class Emulator {
}
}

async #serialLeft(data: AndroidDriverData): Promise<boolean> {
return (await this.#stillAttached([data.serial])).length === 0;
}

async #stillAttached(serials: string[]): Promise<string[]> {
const attached = (await this.#options.adbTools.scanSerials()).settledSerials;
return serials.filter((serial) => attached.includes(serial));
}

#logPath(data: AndroidDriverData): string {
return `${this.#options.adbTools.avdFolder(data)}/emulator.log`;
}
Expand Down Expand Up @@ -272,7 +282,7 @@ export class Emulator {
// why: on Windows a kill otherwise ends `emulator.exe` alone, and its qemu child keeps
// running with the guest's RAM. Not a tree or process-group kill: qemu's `netsimd` serves
// every emulator.
{ env: this.#env(data), killChildren: true, stdio: { file: logPath } },
{ env: this.#env(data), killChildren: true, outlivesCaller: true, stdio: { file: logPath } },
);
handle.unref();
// why: No announcement here, deliberately. adb answers `host:emulator:<port>` by connecting
Expand Down Expand Up @@ -326,17 +336,30 @@ export class Emulator {
}

async shutdown(data: AndroidDriverData, handle: ProcessHandle | undefined): Promise<void> {
let killed = false;
if (data.port > 0 && (await this.#options.ownership.serialIsOwn(data))) {
await this.#options.processRunner.run(this.#options.adb, ["-s", data.serial, "emu", "kill"], {
env: this.#options.adbTools.env(),
timeoutMs: OWNERSHIP_PROBE_TIMEOUT_MS,
});
killed = true;
}
if (handle === undefined) {
// why: an emulator of an earlier daemon has no handle to wait on, and adb lists its serial for
// a moment after the kill. The `destroy` that follows asks every listed serial for its AVD
// path, and one that no longer answers refuses the delete (#1759).
if (killed) await this.#waitForEmulatorsToExit(data, [data.serial]);
return;
}

const exited = await this.waitForExit(handle, EMULATOR_EXIT_TIMEOUT_MS);
// why: on Windows the handle is a `conhost.exe` wrapper (#1759), which lives while any process
// on its console does: the `emulator -kill` helpers for 20 s after qemu is gone, and for as long
// as another emulator runs, the `netsimd` qemu started. So a handle still running after the
// grace, with adb no longer listing the killed emulator, is the wrapper alone, and is ended.
let exited = await this.waitForExit(handle, WRAPPER_GRACE_MS);
if (!exited && !(killed && (await this.#serialLeft(data)))) {
exited = await this.waitForExit(handle, EMULATOR_EXIT_TIMEOUT_MS - WRAPPER_GRACE_MS);
}
if (!exited) {
handle.kill("SIGKILL");
await this.waitForExit(handle, SIGKILL_REAP_TIMEOUT_MS);
Expand Down
74 changes: 47 additions & 27 deletions src/drivers/android/index-boot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ describe("AndroidDriver", () => {
const adbCalls = harness.runner.calls.filter((call) => call.command === binaries.adb);
expect(emulatorCalls.length).toBeGreaterThan(0);
expect(emulatorCalls.filter((call) => call.options.killChildren !== true)).toEqual([]);
expect(emulatorCalls.filter((call) => call.options.outlivesCaller !== true)).toEqual([]);
expect(adbCalls.length).toBeGreaterThan(0);
expect(adbCalls.filter((call) => call.options.killChildren !== undefined)).toEqual([]);
});
Expand Down Expand Up @@ -461,34 +462,53 @@ describe("AndroidDriver", () => {
expect(harness.clock.pendingTimerCount, "timers still armed after shutdown").toBe(0);
});

it("kills an emulator that has not exited 180 s after a shutdown, whatever the boot timeout is", async () => {
const harness = await provisionedHarness({
afterwards: [
copyPathExpectation("emulator-5586"),
processResult(binaries.adb, ["-s", "emulator-5586", "emu", "kill"]),
],
bootTimeoutMs: 600_000,
});
const ready = await harness.driver.makeReady(harness.device);
const launch = harness.runner.calls.findLastIndex(
(call) => call.command === binaries.emulator && call.args.includes("-avd"),
);
const running = harness.runner.handles[launch];
if (running === undefined) throw new Error("no running emulator");
const kill = vi.spyOn(running, "kill");

// why: The emulator ignores `emu kill`: only the timeout can end the wait.
harness.runner.ignoresEmuKill = true;
const armedBefore = harness.clock.pendingTimerCount;
const shutdown = harness.driver.shutdown(ready);
await vi.waitFor(() => expect(harness.clock.pendingTimerCount).toBeGreaterThan(armedBefore));
expect(kill).not.toHaveBeenCalled();
harness.clock.advance(180_000);
await shutdown;
it.each([
["adb still lists it", 180_000, "List of devices attached\nemulator-5586\tdevice\n"],
["adb no longer lists it", 30_000, "List of devices attached\n"],
] as const)(
"kills an emulator that has not exited after a shutdown, whatever the boot timeout is: %s, at %s ms",
async (_listing, killedAfterMs, devices) => {
const harness = await provisionedHarness({
afterwards: [
copyPathExpectation("emulator-5586"),
processResult(binaries.adb, ["-s", "emulator-5586", "emu", "kill"]),
processResult(binaries.adb, ["devices"], devices),
],
bootTimeoutMs: 600_000,
});
const ready = await harness.driver.makeReady(harness.device);
const launch = harness.runner.calls.findLastIndex(
(call) => call.command === binaries.emulator && call.args.includes("-avd"),
);
const running = harness.runner.handles[launch];
if (running === undefined) throw new Error("no running emulator");
const kill = vi.spyOn(running, "kill");

// why: The emulator ignores `emu kill`: only the timeout can end the wait.
harness.runner.ignoresEmuKill = true;
const armedBefore = harness.clock.pendingTimerCount;
const shutdown = harness.driver.shutdown(ready);
await vi.waitFor(() => expect(harness.clock.pendingTimerCount).toBeGreaterThan(armedBefore));
expect(kill).not.toHaveBeenCalled();
harness.clock.advance(29_999);
await Promise.resolve();
expect(kill, "nothing is ended inside the 30 s grace").not.toHaveBeenCalled();
harness.clock.advance(1);
for (let tick = 0; tick < 100; tick += 1) await Promise.resolve();
if (killedAfterMs === 180_000) {
expect(kill, "adb still lists the emulator, so it keeps the 180 s").not.toHaveBeenCalled();
harness.clock.advance(150_000);
} else {
expect(kill, "adb lists it no more, so the wrapper alone is ended").toHaveBeenCalledWith(
"SIGKILL",
);
}
await shutdown;

expect(kill).toHaveBeenCalledWith("SIGKILL");
expect(harness.clock.pendingTimerCount, "timers still armed after shutdown").toBe(0);
});
expect(kill).toHaveBeenCalledWith("SIGKILL");
expect(harness.clock.pendingTimerCount, "timers still armed after shutdown").toBe(0);
},
);

it("leaves no timer armed when waiting for the emulator to exit fails", async () => {
const harness = await provisionedHarness({
Expand Down
47 changes: 47 additions & 0 deletions src/drivers/android/index-lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { home } from "./test-index.js";
const emulatorOptions = {
env: { ...scopedEnv, ANDROID_EMU_CRASH_REPORTING_DATABASE: `${avdDirectory}/emu-crash.db` },
killChildren: true,
outlivesCaller: true,
stdio: { file: `${avdDirectory}/simlock_one/simlock.avd/emulator.log` },
} as const;

Expand Down Expand Up @@ -497,6 +498,52 @@ describe("AndroidDriver console ports across a restart", () => {
expect(await filesystem.exists(`${avdDirectory}/${running.deviceId}`)).toBe(true);
});

it("shuts a discovered emulator down and deletes its AVD although adb lists its serial for a moment after the kill", async () => {
const filesystem = await androidFilesystem();
const host = new EmulatorHost(filesystem);
const before = await createDriver(filesystem, host.runner(), { ids: ["one"] });
const spec = await before.resolveSpec({ model: "Pixel 5", platform: "android" });
const running = await before.makeReady(await before.provision(spec));
const inner = host.runner();
// why: the emulator is gone at the kill, but adb keeps listing its serial for two listings, and a path asked of it fails.
let killed = false;
let staleListings = 2;
const runner: ProcessRunner = {
...inner,
run: async (command, args, options) => {
if (command === binaries.adb && killed && staleListings > 0) {
if (args[0] === "devices") {
staleListings -= 1;
return ok(`List of devices attached\n${running.address}\tdevice\n`);
}
if (args.join(" ").endsWith("emu avd path")) {
return { code: 1, stderr: "error: closed", stdout: "" };
}
}
const result = await inner.run(command, args, options);
if (command === binaries.adb && args.includes("kill")) killed = true;
return result;
},
};
const clock = new FakeClock();
const after = await createDriver(filesystem, runner, { clock });
await after.listManaged();
// why: the registry keeps the ready device's stored data, port and serial included, across the restart.
const orphan = running;

const shutDown = after.shutdown(orphan);
const state = promiseState(shutDown);
for (let step = 0; step < 10 && state.state === "pending"; step += 1) {
for (let tick = 0; tick < 100; tick += 1) await Promise.resolve();
if (clock.pendingTimerCount > 0) clock.advance(2_000);
}
expect(state.state, "shutdown returns once adb stops listing the serial").toBe("fulfilled");
expect(staleListings, "shutdown waited out the two stale listings").toBe(0);
await expect(after.destroy(orphan)).resolves.toBeUndefined();

expect(await filesystem.exists(`${avdDirectory}/${running.deviceId}`)).toBe(false);
});

it("refuses to delete the AVD when an attached emulator cannot say which AVD it runs", async () => {
const filesystem = await androidFilesystem();
const host = new EmulatorHost(filesystem);
Expand Down
54 changes: 54 additions & 0 deletions src/ports/child-window.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,57 @@ describe("the children the ports start ask Windows for no console window", () =>
);
});
});

/**
* why: Node puts every child it does not start detached on Windows into a job that kills the
* child when Node exits, and the child shares Node's console. An emulator or adb server spawned
* that way dies with the daemon while its own children live on, holding the logon task's
* console open (#1759). The supervisor's daemon must stay in that job, so that ending the
* supervisor ends it (ADR 0086 section 2). Neither the job nor the console can be seen from a
* test off Windows, so this checks the option `spawn` hands Node with the platform set.
*/
describe("a child that outlives its caller is detached on every platform, and one that does not is detached off Windows only", () => {
const original = Object.getOwnPropertyDescriptor(process, "platform");
let directory: string | undefined;

afterEach(async () => {
if (original !== undefined) Object.defineProperty(process, "platform", original);
vi.mocked(spawn).mockClear();
if (directory !== undefined) await rm(directory, { force: true, recursive: true });
directory = undefined;
});

it.each([
["win32", true, true, true],
["darwin", true, true, false],
["linux", true, true, false],
["win32", false, false, false],
["darwin", false, true, false],
["linux", false, true, false],
] as const)(
"on %s, outlivesCaller %s is started detached: %s, under conhost --headless: %s",
async (platform, outlivesCaller, detached, headless) => {
directory = await mkdtemp(join(tmpdir(), "simlock-child-detach-"));
const file = join(directory, "child.log");
Object.defineProperty(process, "platform", { value: platform });
if (headless) {
// why: conhost.exe does not exist off Windows; the quiet program stands in for it.
const actual =
await vi.importActual<typeof import("node:child_process")>("node:child_process");
vi.mocked(spawn).mockImplementationOnce(((
_command: string,
_args: string[],
options: object,
) => actual.spawn(...quiet, options)) as unknown as typeof spawn);
}

await new NodeProcessRunner().spawn(...quiet, { outlivesCaller, stdio: { file } }).wait();

expect(vi.mocked(spawn)).toHaveBeenCalledWith(
headless ? expect.stringMatching(/conhost\.exe$/i) : process.execPath,
headless ? ["--headless", process.execPath, "-e", ""] : ["-e", ""],
expect.objectContaining({ detached }),
);
},
);
});
Loading
Loading