openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
238 lines (237 loc) • 7.62 kB
JavaScript
import { h as extractErrorCode } from "./paths-0xDagtub.mjs";
import { i as isPidDefinitelyDead } from "./pid-alive-TveEV-hP.mjs";
import { spawnSync } from "node:child_process";
import { readFileSync, readdirSync, readlinkSync } from "node:fs";
import { ProcSafeError } from "@openclaw/proc-safe/errors";
import { readProcessIdentity } from "@openclaw/proc-safe/identity";
import { listProcesses, readProcessCommand } from "@openclaw/proc-safe/inspect";
//#region src/process/darwin-process-inspection.ts
var DarwinProcessInspectionError = class extends Error {
constructor(e, t) {
super(`Darwin process inspection ${e}`, t);
this.reason = e;
this.name = "DarwinProcessInspectionError";
this.code = e === "deadline" ? "ETIMEDOUT" : e === "permission" ? "EPERM" : "EIO";
}
};
function failure(e) {
if (e instanceof DarwinProcessInspectionError) return e;
const t = e && typeof e === "object" && "code" in e ? e.code : void 0;
return new DarwinProcessInspectionError(t === "ETIMEDOUT" || t === "ABORT_ERR" || t === "timeout" ? "deadline" : [
"EACCES",
"EPERM",
"ERR_ACCESS_DENIED",
"access-denied"
].includes(String(t)) ? "permission" : "unavailable", { cause: e });
}
function remaining(e) {
const t = Math.floor(e - performance.now());
if (t <= 0) throw new DarwinProcessInspectionError("deadline");
return t;
}
const states = {
running: "R",
sleeping: "S",
stopped: "T",
zombie: "Z",
idle: "I",
unknown: "?"
};
function hasReadableTopology(e) {
if (e.parentPid === void 0 || e.processGroupId === void 0 || e.state === void 0) {
if (readProcessIdentity(e.pid) === null) return false;
throw new DarwinProcessInspectionError("unavailable");
}
return true;
}
function topology(e) {
return {
pid: e.pid,
ppid: e.parentPid,
pgid: e.processGroupId,
state: states[e.state],
owner: e.owner
};
}
function census(e, t) {
try {
const n = listProcesses({
timeoutMs: remaining(e),
...t ? { pids: t } : {}
}).filter(hasReadableTopology);
remaining(e);
return n;
} catch (t) {
remaining(e);
throw failure(t);
}
}
/** Synchronous census for the process-group cleanup worker, without spawning ps. */
function* readDarwinProcessCensus(e) {
const t = performance.now() + e;
const n = census(t).map(topology);
for (const e of n) {
remaining(t);
yield e;
}
remaining(t);
}
//#endregion
//#region src/process/supervisor/service-child-group-ownership.ts
function readLinuxProcessUid(e) {
try {
const t = readFileSync(`/proc/${e}/status`, "utf8").split("\n").filter((e) => e.startsWith("Uid:"));
const n = (t.length === 1 ? /^Uid:[ \t]+(\d+)[ \t]+(\d+)[ \t]+(\d+)[ \t]+(\d+)[ \t]*$/.exec(t[0]) : null)?.slice(1).map(Number);
const r = process.getuid?.();
return n?.every((e) => Number.isSafeInteger(e) && e <= 4294967295) ? n.find((e) => e === r) ?? n[0] : void 0;
} catch {
return;
}
}
/** The caller supplies command inspection; group cleanup only reads native topology. */
function* readProcessGroupMembers(e, t) {
const n = t !== void 0;
if (process.platform === "linux") {
const t = Date.now() + e;
for (const e of readdirSync("/proc")) {
if (Date.now() >= t) throw new Error("Process group census exceeded its deadline");
if (!/^\d+$/.test(e)) continue;
const r = Number(e);
let i;
let a;
let o;
let s = false;
try {
i = readFileSync(`/proc/${e}/stat`, "utf8");
if (n) {
o = readLinuxProcessUid(r);
try {
a = readFileSync(`/proc/${e}/cmdline`, "utf8").split("\0").filter(Boolean);
} catch (e) {
const t = process.getuid?.();
s = o !== void 0 && t !== void 0 && o !== t && ["EACCES", "EPERM"].includes(extractErrorCode(e) ?? "");
if (!s) throw e;
}
}
} catch (e) {
if (r !== process.pid && ["ENOENT", "ESRCH"].includes(extractErrorCode(e) ?? "")) continue;
throw new Error(`Could not classify PID ${r}: process command inspection failed (${extractErrorCode(e) ?? "unavailable"}).`, { cause: e });
}
const c = /^(\d+) \([\s\S]*\) (\S) (\d+) (-1|\d+)(?:\s|$)/.exec(i);
if (!c || Number(c[1]) !== r || Date.now() >= t) throw new Error("Process group census is unavailable");
if (a?.length === 0) {
const e = Number(i.slice(i.lastIndexOf(")") + 2).split(/\s+/)[6]);
if (!(Number.isInteger(e) && (e & 2097152) !== 0) && !isPidDefinitelyDead(r)) {
const e = process.getuid?.();
if (o !== void 0 && e !== void 0 && o !== e) {
s = true;
a = void 0;
} else throw new Error(`Could not classify PID ${r}: live userspace process has no readable arguments.`);
}
}
yield {
pid: r,
pgid: Number(c[4]),
state: c[2],
...a ? { command: {
ppid: Number(c[3]),
argv: a,
...o === void 0 ? {} : { uid: o }
} } : s && o !== void 0 ? { command: {
ppid: Number(c[3]),
argvUnavailable: true,
uid: o
} } : {}
};
}
if (Date.now() >= t) throw new Error("Process group census exceeded its deadline");
return;
}
if (process.platform === "darwin") {
for (const r of readDarwinProcessCensus(e)) {
const e = {
pid: r.pid,
pgid: r.pgid,
state: r.state
};
let i;
try {
i = n ? r.state.startsWith("Z") || r.pid === 0 ? { argv: [] } : t?.readDarwinCommand(r.pid, r.owner) : void 0;
} catch (t) {
if (!(t instanceof ProcSafeError) || t.code !== "incomplete" && t.code !== "layout-mismatch") throw t;
yield {
...e,
ppid: r.ppid
};
continue;
}
if (n && !i) continue;
yield {
...e,
...i ? { command: {
ppid: r.ppid,
owner: r.owner,
...i
} } : {}
};
}
return;
}
if (n) throw new Error(`Exact process command census is unavailable on ${process.platform}.`);
const r = Date.now() + e;
const i = spawnSync("/bin/ps", [
"-A",
"-o",
"pid=,pgid=,stat="
], {
encoding: "utf8",
timeout: e,
maxBuffer: 4194304
});
if (i.error || i.status !== 0) throw new Error("Process group census is unavailable");
for (const e of i.stdout.split("\n")) {
if (!e.trim()) continue;
const t = /^\s*(\d+)\s+(\d+)\s+(\S+)\s*$/.exec(e);
if (!t) throw new Error("Process group census is unavailable");
const n = Number(t[1]);
if (n !== i.pid) yield {
pid: n,
pgid: Number(t[2]),
state: t[3]
};
}
if (n && Date.now() >= r) throw new Error("Process group census exceeded its deadline");
}
function isLiveCensusMember({ pid: e, state: t }) {
return !t.startsWith("Z") || process.platform === "linux" && !isPidDefinitelyDead(e);
}
/**
* Whether the process table is this PID namespace's. A nested PID namespace with the parent's
* /proc mounted still lists processes under the parent's numbers, so a pid row proves nothing;
* only /proc/self naming this pid does. Other platforms read a host-wide table.
*/
function isOwnProcfs() {
if (process.platform !== "linux") return true;
try {
return readlinkSync("/proc/self") === String(process.pid);
} catch {
return false;
}
}
/**
* Denied-probe fallback for groups whose members we only observe; callers reach it through
* `isProcessGroupGone`. A failed census, or a procfs that is not this PID namespace's, keeps the
* group alive. Accepted edge case: hidepid or a restricted `/proc` can still hide a member, so an
* otherwise empty census reads as gone.
*/
function isProcessGroupGoneByCensus(e) {
if (!isOwnProcfs()) return false;
try {
for (const t of readProcessGroupMembers(1e3)) if (t.pgid === e && isLiveCensusMember(t)) return false;
return true;
} catch {
return false;
}
}
//#endregion
export { isProcessGroupGoneByCensus as n, readProcessGroupMembers as r, isOwnProcfs as t };