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
19 changes: 11 additions & 8 deletions lib/hosts/daemon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ function updateCompatibility(value: unknown): HostUpdateCompatibility {
export interface HostDaemon {
stop(): Promise<void>;
done: Promise<number>;
/** Settles once startup work (upload sweep, session recovery, omp version read) is done; until then drain reports busy. */
started: Promise<void>;
control(command: HostControlCommand): HostControlStatus;
}
type DaemonOptions = { allowHttp: boolean; url?: string; token?: string; links?: HostLink[] };
Expand Down Expand Up @@ -121,12 +123,12 @@ export function runHostDaemon(options: DaemonOptions): HostDaemon {
});
const uploadRetention = new UploadRetention();
if (!drained) void uploadRetention.start();
function sweepUploads(): void {
function sweepUploads(): Promise<void> | undefined {
if (drained || stopped) return;
operationsInFlight++;
void uploads.sweep().finally(() => operationsInFlight--);
return uploads.sweep().finally(() => operationsInFlight--);
}
sweepUploads();
const startupSweep = sweepUploads();
const sweepTimer = setInterval(sweepUploads, UPLOAD_SWEEP_INTERVAL_MS); sweepTimer.unref?.();
const configDir = join(getAgentDir(), "omp-web"); mkdirSync(configDir, { recursive: true, mode: 0o700 });
const watcher = watch(configDir, (_event, name) => {
Expand Down Expand Up @@ -375,21 +377,22 @@ export function runHostDaemon(options: DaemonOptions): HostDaemon {
let interrupted: HostResumeEntry[] = [];
try { interrupted = resume.takeRunning(); } catch (error) { log("could not recover interrupted sessions: " + reason(error)); }
let recovering = false;
function recover(): void {
function recover(): Promise<void> | undefined {
if (drained || stopped || recovering) return;
recovering = true;
operationsInFlight++;
void channels.recover(interrupted).then(failed => resume.retireClaim(channels.running(), failed))
return channels.recover(interrupted).then(failed => resume.retireClaim(channels.running(), failed))
.catch(error => log("could not retire recovered sessions: " + reason(error)))
.finally(() => operationsInFlight--);
}
recover();
const startupRecovery = recover();
for (const saved of initial) makeLink({ ...saved, url: saved.url.replace(/\/+$/, "") }, saved.url.replace(/\/+$/, "") === primaryUrl);
operationsInFlight++;
void getOmpVersion().then(version => { ompVersion = version; }).catch(error => log("could not read omp version: " + reason(error)))
const versionRead = getOmpVersion().then(version => { ompVersion = version; }).catch(error => log("could not read omp version: " + reason(error)))
.finally(() => {
operationsInFlight--;
if (!stopped) for (const link of links.values()) link.start();
});
return { stop: () => shutdown(0), done, control };
const started = Promise.all([startupSweep, startupRecovery, versionRead]).then(() => {});
return { stop: () => shutdown(0), done, control, started };
}
34 changes: 18 additions & 16 deletions lib/hosts/host-control.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async function until(check, label) {
}
}

function fixture(t) {
async function fixture(t) {
const scratch = mkdtempSync(join(tmpdir(), "ompweb-host-control-"));
const agent = join(scratch, "agent");
const path = process.platform === "win32" ? null : hostControlPath(agent);
Expand All @@ -38,6 +38,8 @@ function fixture(t) {
if (path) rmSync(dirname(path), { recursive: true, force: true });
rmSync(scratch, { recursive: true, force: true });
});
// Drain refuses while startup work runs; tests exercise admission, not that race.
await daemon.started;
return { scratch, agent, path, daemon };
}

Expand All @@ -55,7 +57,7 @@ async function rawRequest(path, input) {
}

test("a real daemon is controlled through an owned private Unix endpoint without disclosing its login", unixOnly, async (t) => {
const f = fixture(t);
const f = await fixture(t);
const server = await createHostControlServer(f.daemon.control, f.agent);
t.after(() => server.close());
assert.equal(server.path, f.path);
Expand All @@ -77,7 +79,7 @@ test("a real daemon is controlled through an owned private Unix endpoint without
});

test("agent identity gives a short deterministic isolated path even under long Darwin roots", unixOnly, async (t) => {
const f = fixture(t);
const f = await fixture(t);
const agent = join(f.scratch, "long-agent-root-".repeat(12), "agent");
const path = hostControlPath(agent);
t.after(() => rmSync(dirname(path), { recursive: true, force: true }));
Expand All @@ -90,7 +92,7 @@ test("agent identity gives a short deterministic isolated path even under long D
});

test("a second endpoint acquisition refuses the live daemon and preserves its inode and connection", unixOnly, async (t) => {
const f = fixture(t);
const f = await fixture(t);
const server = await createHostControlServer(f.daemon.control, f.agent);
t.after(() => server.close());
const before = lstatSync(f.path);
Expand All @@ -100,7 +102,7 @@ test("a second endpoint acquisition refuses the live daemon and preserves its in
});

test("non-socket and symlink endpoints are never removed by either client or server", unixOnly, async (t) => {
const f = fixture(t);
const f = await fixture(t);
mkdirSync(dirname(f.path), { recursive: true, mode: 0o700 });
const target = join(f.scratch, "preserve-me");
writeFileSync(target, "foreign data");
Expand All @@ -117,7 +119,7 @@ test("non-socket and symlink endpoints are never removed by either client or ser
});

test("a symlink or non-private runtime directory is refused without changing it", unixOnly, async (t) => {
const f = fixture(t);
const f = await fixture(t);
const dir = dirname(f.path);
const target = join(f.scratch, "foreign-directory");
mkdirSync(target, { mode: 0o700 });
Expand All @@ -131,7 +133,7 @@ test("a symlink or non-private runtime directory is refused without changing it"
});

test("an actual refused stale owned socket is recovered after its process dies", unixOnly, async (t) => {
const f = fixture(t);
const f = await fixture(t);
mkdirSync(dirname(f.path), { recursive: true, mode: 0o700 });
const source = `const fs=require('node:fs');require('node:net').createServer().listen(${JSON.stringify(f.path)},()=>{fs.chmodSync(${JSON.stringify(f.path)},0o600);console.log('listening')});`;
const child = spawn(process.execPath, ["-e", source], { stdio: ["ignore", "pipe", "pipe"] });
Expand All @@ -150,7 +152,7 @@ test("an actual refused stale owned socket is recovered after its process dies",
});

test("closing an endpoint never unlinks a replacement created after acquisition", unixOnly, async (t) => {
const f = fixture(t);
const f = await fixture(t);
const server = await createHostControlServer(f.daemon.control, f.agent);
unlinkSync(f.path);
writeFileSync(f.path, "replacement must survive", { mode: 0o600 });
Expand All @@ -161,7 +163,7 @@ test("closing an endpoint never unlinks a replacement created after acquisition"
});

test("foreign-owned sockets are not reclaimed", { ...unixOnly, skip: process.platform === "win32" || process.getuid?.() !== 0 ? "Requires Unix root to create an actually foreign-owned endpoint" : false }, async (t) => {
const f = fixture(t);
const f = await fixture(t);
mkdirSync(dirname(f.path), { recursive: true, mode: 0o700 });
const listener = createServer();
await new Promise((resolve, reject) => { listener.once("error", reject); listener.listen(f.path, resolve); });
Expand All @@ -174,7 +176,7 @@ test("foreign-owned sockets are not reclaimed", { ...unixOnly, skip: process.pla
});

test("malformed and oversized control messages cannot change daemon admission", unixOnly, async (t) => {
const f = fixture(t);
const f = await fixture(t);
const server = await createHostControlServer(f.daemon.control, f.agent);
t.after(() => server.close());
for (const line of ['not-json\n', '{"command":"spawn"}\n', '{"command":"drain","token":"untrusted"}\n', 'x'.repeat(8192) + '\n']) {
Expand All @@ -187,7 +189,7 @@ test("malformed and oversized control messages cannot change daemon admission",
});

test("clients reject insecure socket permissions instead of sending a command", unixOnly, async (t) => {
const f = fixture(t);
const f = await fixture(t);
const server = await createHostControlServer(f.daemon.control, f.agent);
t.after(() => server.close());
chmodSync(f.path, 0o666);
Expand All @@ -196,7 +198,7 @@ test("clients reject insecure socket permissions instead of sending a command",
});

test("losing a real resume response does not undo admission or permit the caller to assume drain remains held", unixOnly, async (t) => {
const f = fixture(t);
const f = await fixture(t);
const server = await createHostControlServer(f.daemon.control, f.agent);
t.after(() => server.close());
assert.equal((await requestHostControl("drain", f.agent)).drained, true);
Expand All @@ -214,7 +216,7 @@ test("losing a real resume response does not undo admission or permit the caller
});

test("Windows: a real daemon is controlled through a random named pipe and a per-start token", windowsOnly, async (t) => {
const f = fixture(t);
const f = await fixture(t);
const server = await createHostControlServer(f.daemon.control, f.agent);
t.after(() => server.close());
assert.match(server.path, /^\\\\\.\\pipe\\ompweb-host-[0-9a-f]{32}$/);
Expand All @@ -233,7 +235,7 @@ test("Windows: a real daemon is controlled through a random named pipe and a per
});

test("Windows: requests without the current token cannot change daemon admission", windowsOnly, async (t) => {
const f = fixture(t);
const f = await fixture(t);
const server = await createHostControlServer(f.daemon.control, f.agent);
t.after(() => server.close());
const { token } = JSON.parse(readFileSync(hostControlDescriptorPath(f.agent), "utf8"));
Expand All @@ -247,7 +249,7 @@ test("Windows: requests without the current token cannot change daemon admission
});

test("Windows: a second start refuses the live pipe and keeps its descriptor; a stale descriptor is replaced", windowsOnly, async (t) => {
const f = fixture(t);
const f = await fixture(t);
const file = hostControlDescriptorPath(f.agent);
const server = await createHostControlServer(f.daemon.control, f.agent);
const live = readFileSync(file, "utf8");
Expand All @@ -264,7 +266,7 @@ test("Windows: a second start refuses the live pipe and keeps its descriptor; a
});

test("Windows: clients never connect to a pipe outside the descriptor contract", windowsOnly, async (t) => {
const f = fixture(t);
const f = await fixture(t);
const file = hostControlDescriptorPath(f.agent);
await assert.rejects(requestHostControl("status", f.agent), /No host daemon is running/);
const decoy = createServer((socket) => { socket.destroy(); assert.fail("the client connected to a decoy pipe"); });
Expand Down
Loading