Files
zhou.han 9e86a2c7b7 proc: a Linux zombie no longer holds a lock (#1198)
yetihan (#1198): a lock whose owner is a Linux zombie was held for
good. process.kill(pid, 0) succeeds on a zombie, so 15 packages' lock
and liveness checks counted an exited, unreaped owner as alive.

- scripts/proc.mjs: processStatus(pid) is dead on ESRCH, and on Linux
  also when /proc/<pid>/stat says Z or X; EPERM is "permission", any
  other error "unknown". processAlive / processExists keep each
  caller's old EPERM and unknown-error meaning.
- scripts/sync-proc.mjs copies it into each package (--check in the
  tests); every package's own check keeps its old semantics, now with
  zombies dead. agent-console's daemon bundle and window-warmup's dist
  are rebuilt.
- 15 packages bumped.

Review run at 28ef6622 (mote, HOME=$(mktemp -d)):
- node scripts/sync-proc.mjs --check: ok.
- bun test (whole repo): 8934 pass, 0 fail.
- bun scripts/check.mjs: every package ok.
- window-warmup's build reproduces its dist/plugin.js byte for byte.
  agent-console's bundle diff read line by line: the proc module plus
  esbuild's renumbered imports, nothing else (esbuild isn't installed
  on mote, so it wasn't rebuilt there).
- Real zombie on Linux (WSL, magpie-desktop): a bash child left
  unreaped by an exec'd sleep, /proc stat "Z": the old kill(0) check
  says alive, processStatus says dead; the running process says alive.

Not tried: each package's lock contention end to end.
2026-11-16 12:19:09 +08:00

99 lines
4.2 KiB
JavaScript

import { mkdir, readdir, writeFile, readFile, unlink, rmdir, lstat } from 'node:fs/promises';
import { join } from 'node:path';
import { randomBytes } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import { processStatus } from './proc.mjs';
export function alive(pid, deps = {}) {
if (!Number.isSafeInteger(pid) || pid <= 0) return true;
const status = processStatus(pid, deps);
if (status.state === 'unknown') throw status.error;
return status.state !== 'dead';
}
async function removeEmpty(path) {
for (let attempt = 0; ; attempt++) {
try { await rmdir(path); return true; }
catch (error) {
if (['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) return false;
if (process.platform === 'win32' && ['EPERM', 'EBUSY'].includes(error.code)) {
// Windows can briefly retain a directory handle; an empty lock remains recoverable.
if (attempt === 2) return false;
await delay(25); continue;
}
throw error;
}
}
}
export async function acquireLock(path, { waitMs = 5000 } = {}) {
const deadline = Date.now() + Math.max(waitMs, 100);
let first = true;
while (true) {
if (!first && Date.now() >= deadline) throw new Error('lock-busy');
first = false;
try {
await mkdir(path, { mode: 0o700 });
const owner = `${process.pid}-${randomBytes(12).toString('hex')}.owner`;
try {
await writeFile(join(path, owner), String(Date.now()), { flag: 'wx', mode: 0o600 });
const owners = await readdir(path);
// An empty directory may be recovered while its creator is publishing ownership.
if (owners.length === 1 && owners[0] === owner) return async () => {
await unlink(join(path, owner)); await removeEmpty(path);
};
await unlink(join(path, owner));
} catch (error) {
// Concurrent parent removal reports EPERM on Windows and EINVAL on macOS.
const racedOpen = (process.platform === 'win32' && error.code === 'EPERM')
|| (process.platform === 'darwin' && error.code === 'EINVAL');
if (racedOpen && error.syscall === 'open' && error.path === join(path, owner)) {
if (Date.now() >= deadline) throw error;
await delay(25); continue;
}
if (error.code !== 'ENOENT') throw error;
}
} catch (error) {
// Windows can keep a released directory delete-pending before the next mkdir.
if (process.platform === 'win32' && error.code === 'EPERM' && error.syscall === 'mkdir' && error.path === path) {
if (Date.now() >= deadline) throw error;
await delay(25); continue;
}
if (error.code !== 'EEXIST') throw error;
try {
if ((await lstat(path)).isDirectory()) {
for (const name of await readdir(path)) {
const match = /^([1-9]\d*)-[a-f0-9]+\.owner$/.exec(name);
if (match && !alive(Number(match[1]))) {
try { await unlink(join(path, name)); } catch (e) { if (e.code !== 'ENOENT') throw e; }
}
}
if (await removeEmpty(path)) continue;
} else {
// Older workers used a PID file. Never unlink an unknown or live owner.
const pid = Number(await readFile(path, 'utf8'));
if (!alive(pid)) {
try { await unlink(path); } catch (e) { if (!['ENOENT', 'EISDIR', 'EPERM'].includes(e.code)) throw e; }
continue;
}
}
} catch (e) {
if (['ENOENT', 'EISDIR', 'ENOTDIR'].includes(e.code)) continue;
// Recheck legacy ownership after Windows releases a busy PID-file handle.
if (process.platform === 'win32' && e.code === 'EBUSY' && e.syscall === 'unlink' && e.path === path) {
if (Date.now() >= deadline) throw e;
await delay(25); continue;
}
// A competing release can leave the lock directory delete-pending during a probe.
if (process.platform === 'win32' && e.code === 'EPERM' && e.syscall === 'scandir' && e.path === path) {
if (Date.now() >= deadline) throw e;
await delay(25); continue;
}
throw e;
}
}
if (waitMs === 0 || Date.now() >= deadline) throw new Error('lock-busy');
await delay(25);
}
}