455 lines
20 KiB
JavaScript
455 lines
20 KiB
JavaScript
"use strict";
|
|
|
|
// Cross-process operation mutex for sensitive admin operations.
|
|
//
|
|
// The panel runs under pm2 cluster mode (scripts/generate-ecosystem.sh sets
|
|
// INSTANCES = cores - 2), so any host with >= 3 cores runs several worker
|
|
// processes. Three admin-operation mutexes used to be plain in-process
|
|
// closures: two admin requests landing on DIFFERENT workers could interleave
|
|
// their load → mutate → save cycles on database-config.json /
|
|
// mongodb-config.json / pgadmin-config.json, and the last writer silently
|
|
// erased the other's bookkeeping entry while the live database account stayed
|
|
// on the server — the "unseeable, unrevokable credential" bug class.
|
|
//
|
|
// This factory keeps the exact interface call sites already use —
|
|
// tryAcquire() returning a release function or null (fail-fast, callers
|
|
// answer 429), plus acquire()/runExclusive() for queued serialization — but
|
|
// the ownership now lives in a lock file, so exclusion holds across workers:
|
|
//
|
|
// 1. Ownership is an atomic O_EXCL create (fs.openSync 'wx') of the lock
|
|
// file, stamped with { pid, startTicks?, token, acquiredAt }. startTicks
|
|
// (Linux /proc/<pid>/stat, field 22) closes the PID-reuse hole.
|
|
// 2. While held, a heartbeat setInterval rewrites the file (atomically, via
|
|
// utils/atomic-file.js) to refresh acquiredAt every heartbeatMs. This is
|
|
// the critical addition over the webhook config write lock
|
|
// (index.js acquireWebhooksConfigFileLock), whose 15s hard TTL is only
|
|
// safe because its critical sections are fully synchronous. THESE
|
|
// mutexes are held across awaited installs that legitimately run for
|
|
// minutes (the /mongodb/* setup IIFE and the pgAdmin4 install hold their
|
|
// mutex end-to-end), so liveness must be proven continuously, not
|
|
// assumed from age.
|
|
// 3. A contender treats the lock as stale — and steals it with a
|
|
// token-re-verified unlink followed by an O_EXCL create — when the
|
|
// recorded owner provably died (zombie state "Z", recycled PID via a
|
|
// startTicks mismatch, or ESRCH from the kill(pid, 0) probe), or when
|
|
// acquiredAt aged past staleAfterMs. The re-verification (re-read the
|
|
// file and only unlink the exact stale record) closes the two-stealer
|
|
// race in which the slower contender would unlink the faster one's
|
|
// freshly created LIVE lock and leave two processes holding the mutex.
|
|
// Death recovery is near-instant; the TTL is the fail-safe
|
|
// last resort for everything ambiguous (non-Linux, hidepid, EPERM).
|
|
//
|
|
// Why staleAfterMs defaults to 45000 (and heartbeatMs to 3000): the worst
|
|
// case synchronous event-loop stall inside these sections is the
|
|
// privileged-runner execSync calls (_privRunnerExecSync uses 20s timeouts)
|
|
// and several may chain; a live-but-blocked holder must never be stolen
|
|
// from, so the TTL must comfortably exceed the longest plausible stall. A
|
|
// SIGKILLed worker (pm2 kill_timeout, OOM, max_memory_restart) is recovered
|
|
// immediately by the /proc start-ticks and kill(2) probes; the 45s TTL only
|
|
// catches the cases those probes cannot see. 3000ms heartbeats keep the
|
|
// refreshed acquiredAt far away from the TTL even with several missed ticks.
|
|
//
|
|
// Not reentrant: a locked handler must not call another locked handler on the
|
|
// same mutex (a second tryAcquire in the same holder sees the live lock file
|
|
// and fails fast, exactly like a foreign contender).
|
|
|
|
const fs = require("fs");
|
|
const crypto = require("crypto");
|
|
const { spawnSync } = require("node:child_process");
|
|
const { atomicWriteFileSync } = require("./atomic-file");
|
|
|
|
const DEFAULT_HEARTBEAT_MS = 3000;
|
|
const DEFAULT_STALE_MS = 45000;
|
|
const DEFAULT_ACQUIRE_TIMEOUT_MS = 10000;
|
|
const ACQUIRE_RETRY_DELAY_MS = 250;
|
|
|
|
// Linux /proc/<pid>/stat exposes two liveness facts kill(pid, 0) cannot: the
|
|
// process start time (clock ticks since boot, field 22) and the process state
|
|
// (field 3). The start time closes the PID-reuse hole in the ESRCH-only
|
|
// check: a recycled PID owned by a different process answers kill(pid, 0)
|
|
// with success (same uid) or EPERM (different uid), and both would read as
|
|
// "the lock owner is still alive", delaying stale-lock recovery to the hard
|
|
// TTL. The state field also flags zombies ("Z"), which kill(pid, 0) reports
|
|
// as alive even though a zombie can never resume writing. Both checks only
|
|
// ever fire on positive evidence that the recorded owner is gone; every
|
|
// ambiguous case (non-Linux, hidepid mounts, locks written before this field
|
|
// existed) falls back to the kill(2) probe and the hard TTL, which fail safe
|
|
// — delayed recovery, never a premature steal.
|
|
function getProcessStartTicks(pid) {
|
|
try {
|
|
const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
// Field 2 (comm) may itself contain spaces and parens, so everything up to
|
|
// the LAST ")" is skipped; the remaining fields start at field 3 (state),
|
|
// which puts starttime (field 22) at index 19.
|
|
const fields = stat.slice(stat.lastIndexOf(")") + 2).trim().split(" ");
|
|
const startTicks = Number(fields[19]);
|
|
return Number.isFinite(startTicks) ? { state: fields[0], startTicks } : null;
|
|
} catch (_) {
|
|
return null; // no /proc, hidepid, or the process vanished mid-read
|
|
}
|
|
}
|
|
|
|
// This process's own start ticks, constant for the process lifetime, computed
|
|
// once and shared by every mutex instance. NaN outside Linux.
|
|
const SELF_START_TICKS = (() => {
|
|
try {
|
|
const pid = typeof process !== "undefined" ? process.pid : NaN;
|
|
if (!Number.isInteger(pid) || pid <= 0) return NaN;
|
|
return getProcessStartTicks(pid)?.startTicks ?? NaN;
|
|
} catch (_) {
|
|
return NaN;
|
|
}
|
|
})();
|
|
|
|
function positiveInt(value, fallback) {
|
|
const n = Number(value);
|
|
return Number.isInteger(n) && n > 0 ? n : fallback;
|
|
}
|
|
|
|
/**
|
|
* Creates a file-lock-backed mutex serializing one shared resource across
|
|
* processes.
|
|
*
|
|
* @param {object} options
|
|
* @param {string} options.label log prefix, e.g. "[database]"
|
|
* @param {string} options.lockFilePath absolute lock file path
|
|
* @param {string} [options.lockDirectoryPath] lock an existing directory inode with Linux flock instead
|
|
* @param {boolean} [options.sharedDirectoryLock] use a shared rather than exclusive directory flock
|
|
* @param {number} [options.heartbeatMs] held-lock refresh interval (default 3000)
|
|
* @param {number} [options.staleAfterMs] age at which an un-refreshed lock
|
|
* becomes stealable (default 45000)
|
|
* @param {boolean} [options.respectLiveOwner] use age only when no owner PID is available
|
|
* @param {number} [options.acquireTimeoutMs] budget for acquire() (default 10000)
|
|
* @returns {{ tryAcquire: () => (function|null), acquire: () => Promise<function>,
|
|
* runExclusive: (fn: () => Promise) => Promise }}
|
|
* tryAcquire() is synchronous: it returns a release function on success or
|
|
* null when the lock is busy (fail-fast contract). The release function is
|
|
* idempotent — a double release is a silent no-op — and never unlinks a
|
|
* lock this holder does not own.
|
|
*/
|
|
function createCrossProcessOperationMutex(options) {
|
|
const opts = options || {};
|
|
const label = String(opts.label || "[cross-process]");
|
|
const lockDirectoryPath = opts.lockDirectoryPath;
|
|
const lockFilePath = String(lockDirectoryPath || opts.lockFilePath || "");
|
|
if (!lockFilePath) {
|
|
throw new Error("createCrossProcessOperationMutex: lockFilePath is required");
|
|
}
|
|
const heartbeatMs = positiveInt(opts.heartbeatMs, DEFAULT_HEARTBEAT_MS);
|
|
const staleAfterMs = positiveInt(opts.staleAfterMs, DEFAULT_STALE_MS);
|
|
const acquireTimeoutMs = positiveInt(opts.acquireTimeoutMs, DEFAULT_ACQUIRE_TIMEOUT_MS);
|
|
const respectLiveOwner = opts.respectLiveOwner === true;
|
|
if (heartbeatMs >= staleAfterMs) {
|
|
throw new Error(
|
|
`${label} cross-process mutex: heartbeatMs (${heartbeatMs}) must be smaller than staleAfterMs (${staleAfterMs})`
|
|
);
|
|
}
|
|
|
|
// The owner record of the lock currently held by THIS mutex instance, or
|
|
// null. Deliberately NOT cleared when the lock is stolen from us mid-section
|
|
// (heartbeat detects the theft): the running critical section stays the
|
|
// single owner of this instance, so a nested tryAcquire keeps failing fast
|
|
// and release() still runs its token-checked cleanup exactly once.
|
|
let current = null;
|
|
let heartbeatTimer = null;
|
|
|
|
function readOwner() {
|
|
try {
|
|
return JSON.parse(fs.readFileSync(lockFilePath, "utf8"));
|
|
} catch (_) {
|
|
return null; // missing, unreadable or half-written (create/write window)
|
|
}
|
|
}
|
|
|
|
// Mirrors isWebhooksConfigLockStale (index.js), with the lock path and TTL
|
|
// parameterized. An unreadable/empty owner falls back to the file's mtime so
|
|
// a lock that is being created right now never looks stale — stealing it
|
|
// would break mutual exclusion between the two writers.
|
|
function isOwnerStale(owner) {
|
|
let acquiredAt = owner && typeof owner === "object" ? Number(owner.acquiredAt) : NaN;
|
|
if (!Number.isFinite(acquiredAt) || acquiredAt <= 0) {
|
|
try {
|
|
acquiredAt = fs.statSync(lockFilePath).mtimeMs;
|
|
} catch (_) {
|
|
return false; // file already gone; the next O_EXCL create decides
|
|
}
|
|
}
|
|
const expired = Date.now() - acquiredAt > staleAfterMs;
|
|
if (expired && !respectLiveOwner) return true;
|
|
const pid = owner && typeof owner === "object" ? Number(owner.pid) : NaN;
|
|
if (Number.isInteger(pid) && pid > 0) {
|
|
const ownerStartTicks = Number(owner.startTicks);
|
|
if (Number.isFinite(ownerStartTicks) && Number.isFinite(SELF_START_TICKS)) {
|
|
if (pid === process.pid) {
|
|
// The lock names this PID: same start ticks means another mutex
|
|
// instance of this very process incarnation owns it (treat as
|
|
// alive); different ticks mean this PID was recycled since — the
|
|
// lock is orphaned.
|
|
return ownerStartTicks !== SELF_START_TICKS;
|
|
}
|
|
const live = getProcessStartTicks(pid);
|
|
if (live) {
|
|
if (live.state === "Z") return true; // dead but unreaped: kill(2) says alive
|
|
if (live.startTicks !== ownerStartTicks) return true; // PID recycled
|
|
return false; // the recorded owner process is genuinely alive
|
|
}
|
|
// /proc unreadable for that PID — fall through to the kill(2) probe.
|
|
}
|
|
if (pid !== process.pid) {
|
|
try {
|
|
process.kill(pid, 0);
|
|
} catch (err) {
|
|
if (err.code === "ESRCH") return true; // owner is gone; the lock is orphaned
|
|
// EPERM: the PID answers to a process we may not signal (recycled by
|
|
// another uid, or a hardened sandbox). Without a readable /proc
|
|
// there is no way to tell it from the recorded owner, so keep
|
|
// treating the lock as alive and let the hard TTL decide.
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
return expired;
|
|
}
|
|
|
|
// O_EXCL-create + write the owner record. Throws on any failure (the EEXIST
|
|
// case is handled by the caller); on a write failure the half-owned file is
|
|
// removed first so the next contender's O_EXCL create arbitrates cleanly.
|
|
function createLockFile() {
|
|
const owner = { pid: process.pid, token: crypto.randomUUID(), acquiredAt: Date.now() };
|
|
if (Number.isFinite(SELF_START_TICKS)) {
|
|
owner.startTicks = SELF_START_TICKS;
|
|
}
|
|
const fd = fs.openSync(lockFilePath, "wx", 0o600);
|
|
try {
|
|
fs.writeFileSync(fd, JSON.stringify(owner), "utf8");
|
|
} catch (err) {
|
|
try { fs.unlinkSync(lockFilePath); } catch (_) { }
|
|
throw err;
|
|
} finally {
|
|
fs.closeSync(fd);
|
|
}
|
|
return owner;
|
|
}
|
|
|
|
function stopHeartbeat() {
|
|
if (heartbeatTimer) {
|
|
clearInterval(heartbeatTimer);
|
|
heartbeatTimer = null;
|
|
}
|
|
}
|
|
|
|
// Refreshes acquiredAt so a live-but-slow holder is never mistaken for a
|
|
// dead one. Never throws into the holder's event loop: transient failures
|
|
// are logged and retried on the next tick. If the file is gone or carries a
|
|
// different token, this holder was stolen from (only possible when this
|
|
// worker's event loop was blocked longer than staleAfterMs, or someone
|
|
// removed the file): log ONE loud error and stop heartbeating — NEVER
|
|
// re-create the lock, that would race the new owner.
|
|
function heartbeatTick() {
|
|
const owner = current;
|
|
if (!owner) {
|
|
stopHeartbeat();
|
|
return;
|
|
}
|
|
let onDisk;
|
|
try {
|
|
onDisk = JSON.parse(fs.readFileSync(lockFilePath, "utf8"));
|
|
} catch (err) {
|
|
if (err && err.code === "ENOENT") {
|
|
console.error(
|
|
`${label} cross-process mutex: lock file at ${lockFilePath} vanished while held — this holder was stolen from ` +
|
|
`(its event loop was blocked past the stale TTL) or the file was removed externally. ` +
|
|
`Stopping the heartbeat; the lock is NOT re-created because a new owner may hold the exclusion now.`
|
|
);
|
|
stopHeartbeat();
|
|
return;
|
|
}
|
|
console.error(`${label} cross-process mutex: heartbeat refresh read failed (will retry): ${err && err.message}`);
|
|
return;
|
|
}
|
|
if (!onDisk || typeof onDisk !== "object" || onDisk.token !== owner.token) {
|
|
console.error(
|
|
`${label} cross-process mutex: lock at ${lockFilePath} was stolen from this holder ` +
|
|
`(its event loop was blocked longer than the stale TTL, so another process took over). ` +
|
|
`Stopping the heartbeat; the lock is NOT re-created because the new owner now arbitrates this section.`
|
|
);
|
|
stopHeartbeat();
|
|
return;
|
|
}
|
|
try {
|
|
atomicWriteFileSync(
|
|
lockFilePath,
|
|
JSON.stringify({ ...owner, acquiredAt: Date.now() }),
|
|
{ mode: 0o600 }
|
|
);
|
|
} catch (err) {
|
|
console.error(`${label} cross-process mutex: heartbeat refresh failed (will retry): ${err && err.message}`);
|
|
}
|
|
}
|
|
|
|
function startHeartbeat() {
|
|
stopHeartbeat();
|
|
heartbeatTimer = setInterval(heartbeatTick, heartbeatMs);
|
|
// A timer must never keep a pm2 worker alive just because a lock is held.
|
|
if (typeof heartbeatTimer.unref === "function") heartbeatTimer.unref();
|
|
}
|
|
|
|
// Removes the lock only if it is still ours. If the TTL expired and another
|
|
// process stole and re-created the lock, unlinking would release someone
|
|
// else's section.
|
|
function releaseFile(owner) {
|
|
let onDisk;
|
|
try {
|
|
onDisk = JSON.parse(fs.readFileSync(lockFilePath, "utf8"));
|
|
} catch (err) {
|
|
if (err && err.code === "ENOENT") {
|
|
// The token check could not happen: the file vanished, i.e. this
|
|
// holder was stolen from. Nothing of ours is left to unlink.
|
|
console.error(
|
|
`${label} cross-process mutex: lock file at ${lockFilePath} vanished before release ` +
|
|
`(this holder was stolen from) — nothing to unlink`
|
|
);
|
|
} else {
|
|
console.error(`${label} cross-process mutex: release could not read the lock file: ${err && err.message}`);
|
|
}
|
|
return;
|
|
}
|
|
if (!onDisk || typeof onDisk !== "object" || onDisk.token !== owner.token) {
|
|
console.error(
|
|
`${label} cross-process mutex: release skipped — the lock at ${lockFilePath} is no longer owned by this holder`
|
|
);
|
|
return;
|
|
}
|
|
// Re-verify immediately before unlinking (TOCTOU): a thief that stole
|
|
// this lock between the token check above and the unlink must not lose
|
|
// its fresh lock to this late release. Both reads are adjacent
|
|
// synchronous calls, so the remaining window is minimal.
|
|
const recheck = readOwner();
|
|
if (!recheck || recheck.token !== owner.token) {
|
|
console.error(
|
|
`${label} cross-process mutex: release skipped — the lock at ${lockFilePath} changed owner between the checks`
|
|
);
|
|
return;
|
|
}
|
|
try {
|
|
fs.unlinkSync(lockFilePath);
|
|
} catch (err) {
|
|
if (err.code !== "ENOENT") {
|
|
console.error(`${label} cross-process mutex: release error: ${err.message}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
function makeRelease(owner) {
|
|
let done = false;
|
|
return () => {
|
|
if (done) return; // a double release is a silent no-op
|
|
done = true;
|
|
stopHeartbeat();
|
|
if (current === owner) current = null;
|
|
releaseFile(owner);
|
|
};
|
|
}
|
|
|
|
function tryAcquireDirectory() {
|
|
// adpanel:update-lock - the inherited descriptor and this descriptor share
|
|
// one open file description. Closing the last reference releases the lock.
|
|
const fd = fs.openSync(lockDirectoryPath, fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
|
|
let locked = false;
|
|
try {
|
|
const result = spawnSync("flock", [opts.sharedDirectoryLock ? "-sn" : "-xn", "-E", "75", "3"], {
|
|
stdio: ["ignore", "ignore", "ignore", fd], timeout: 5000, env: { PATH: "/usr/bin:/bin" },
|
|
});
|
|
if (result.status === 75) return null;
|
|
if (result.status !== 0) throw result.error || new Error(`${label} could not lock ${lockDirectoryPath}`);
|
|
locked = true;
|
|
} finally {
|
|
if (!locked) fs.closeSync(fd);
|
|
}
|
|
return () => {
|
|
if (!locked) return;
|
|
locked = false;
|
|
fs.closeSync(fd);
|
|
};
|
|
}
|
|
|
|
const tryAcquire = () => {
|
|
if (lockDirectoryPath) return tryAcquireDirectory();
|
|
if (current) return null; // fast path: already held by this instance
|
|
let owner;
|
|
try {
|
|
owner = createLockFile();
|
|
} catch (err) {
|
|
if (err.code !== "EEXIST") {
|
|
// Fail CLOSED as "busy" rather than throwing: every caller answers
|
|
// 429, so no async handler is crashed by an unhandled rejection (a
|
|
// broken/unwritable lock location makes the operation unavailable,
|
|
// never unprotected). The loud log keeps it diagnosable — a silent
|
|
// 429 storm would hide a misconfigured lock directory.
|
|
console.error(
|
|
`${label} cross-process mutex: could not create lock file ${lockFilePath}: ${err.message}`
|
|
);
|
|
return null;
|
|
}
|
|
// EEXIST: somebody owns the lock. Steal it only on positive evidence of
|
|
// death or age; anything ambiguous is treated as held (fail safe).
|
|
const staleOwner = readOwner();
|
|
if (!isOwnerStale(staleOwner)) return null;
|
|
// Re-verify immediately before unlinking (TOCTOU between two healthy
|
|
// stealers): a contender that judged the same record stale may have
|
|
// already removed it and created a LIVE lock here — a blind unlinkSync
|
|
// would silently delete that fresh lock and let both processes hold
|
|
// the mutex. Only unlink the exact record we judged stale (same token,
|
|
// or the same unreadable-garbage state); anything else means another
|
|
// owner is mid-steal or holds the lock now, and the O_EXCL create
|
|
// below arbitrates who actually wins.
|
|
const currentOwner = readOwner();
|
|
if (staleOwner) {
|
|
if (!currentOwner || currentOwner.token !== staleOwner.token) return null;
|
|
} else if (currentOwner) {
|
|
return null;
|
|
}
|
|
try { fs.unlinkSync(lockFilePath); } catch (_) { }
|
|
try {
|
|
owner = createLockFile();
|
|
} catch (_) {
|
|
return null; // lost the steal race, or the write failed — not ours
|
|
}
|
|
}
|
|
current = owner;
|
|
startHeartbeat();
|
|
return makeRelease(owner);
|
|
};
|
|
|
|
const acquire = async () => {
|
|
const immediate = tryAcquire();
|
|
if (immediate) return immediate;
|
|
const deadline = Date.now() + acquireTimeoutMs;
|
|
for (;;) {
|
|
await new Promise((resolve) => setTimeout(resolve, ACQUIRE_RETRY_DELAY_MS));
|
|
const release = tryAcquire();
|
|
if (release) return release;
|
|
if (Date.now() >= deadline) {
|
|
const err = new Error(
|
|
`${label} cross-process mutex: could not acquire ${lockFilePath} within ${acquireTimeoutMs}ms`
|
|
);
|
|
err.code = "MUTEX_LOCK_TIMEOUT";
|
|
throw err;
|
|
}
|
|
}
|
|
};
|
|
|
|
const runExclusive = async (fn) => {
|
|
const release = await acquire();
|
|
try {
|
|
return await fn();
|
|
} finally {
|
|
release();
|
|
}
|
|
};
|
|
|
|
return { tryAcquire, acquire, runExclusive };
|
|
}
|
|
|
|
module.exports = { createCrossProcessOperationMutex, getProcessStartTicks };
|