@gtkx/utils 2.0.0-beta.1 → 2.0.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/process/index.d.ts +1 -0
- package/dist/process/index.d.ts.map +1 -1
- package/dist/process/index.js +1 -0
- package/dist/process/index.js.map +1 -1
- package/dist/process/kill-marked-processes.d.ts +3 -2
- package/dist/process/kill-marked-processes.d.ts.map +1 -1
- package/dist/process/kill-marked-processes.js +44 -13
- package/dist/process/kill-marked-processes.js.map +1 -1
- package/dist/process/kill-process-group.d.ts +16 -0
- package/dist/process/kill-process-group.d.ts.map +1 -0
- package/dist/process/kill-process-group.js +72 -0
- package/dist/process/kill-process-group.js.map +1 -0
- package/dist/process/process-guard.js +77 -2
- package/dist/process/process-guard.js.map +1 -1
- package/dist/process/spawn-with-parent-death-signal.d.ts +1 -0
- package/dist/process/spawn-with-parent-death-signal.d.ts.map +1 -1
- package/dist/process/spawn-with-parent-death-signal.js +66 -3
- package/dist/process/spawn-with-parent-death-signal.js.map +1 -1
- package/package.json +1 -1
- package/src/process/index.ts +5 -0
- package/src/process/kill-marked-processes.ts +62 -13
- package/src/process/kill-process-group.ts +104 -0
- package/src/process/process-guard.ts +106 -2
- package/src/process/spawn-with-parent-death-signal.ts +106 -3
package/dist/process/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { exitCodeForSignal } from "./exit-code-for-signal.ts";
|
|
2
2
|
export { installGracefulShutdown } from "./install-graceful-shutdown.ts";
|
|
3
|
+
export { killProcessGroup, type ProcessGroupIdentity, processGroupIdentity, } from "./kill-process-group.ts";
|
|
3
4
|
export { resolveExecutable, tryResolveExecutable } from "./resolve-executable.ts";
|
|
4
5
|
export { spawnWithParentDeathSignal } from "./spawn-with-parent-death-signal.ts";
|
|
5
6
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/process/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAClF,OAAO,EAAE,0BAA0B,EAAE,MAAM,qCAAqC,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/process/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,EACH,gBAAgB,EAChB,KAAK,oBAAoB,EACzB,oBAAoB,GACvB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAClF,OAAO,EAAE,0BAA0B,EAAE,MAAM,qCAAqC,CAAC"}
|
package/dist/process/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { exitCodeForSignal } from "./exit-code-for-signal.js";
|
|
2
2
|
export { installGracefulShutdown } from "./install-graceful-shutdown.js";
|
|
3
|
+
export { killProcessGroup, processGroupIdentity, } from "./kill-process-group.js";
|
|
3
4
|
export { resolveExecutable, tryResolveExecutable } from "./resolve-executable.js";
|
|
4
5
|
export { spawnWithParentDeathSignal } from "./spawn-with-parent-death-signal.js";
|
|
5
6
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/process/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAClF,OAAO,EAAE,0BAA0B,EAAE,MAAM,qCAAqC,CAAC","sourcesContent":["export { exitCodeForSignal } from \"./exit-code-for-signal.ts\";\nexport { installGracefulShutdown } from \"./install-graceful-shutdown.ts\";\nexport { resolveExecutable, tryResolveExecutable } from \"./resolve-executable.ts\";\nexport { spawnWithParentDeathSignal } from \"./spawn-with-parent-death-signal.ts\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/process/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,EACH,gBAAgB,EAEhB,oBAAoB,GACvB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAClF,OAAO,EAAE,0BAA0B,EAAE,MAAM,qCAAqC,CAAC","sourcesContent":["export { exitCodeForSignal } from \"./exit-code-for-signal.ts\";\nexport { installGracefulShutdown } from \"./install-graceful-shutdown.ts\";\nexport {\n killProcessGroup,\n type ProcessGroupIdentity,\n processGroupIdentity,\n} from \"./kill-process-group.ts\";\nexport { resolveExecutable, tryResolveExecutable } from \"./resolve-executable.ts\";\nexport { spawnWithParentDeathSignal } from \"./spawn-with-parent-death-signal.ts\";\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
declare const PROCESS_MARKER = "GTKX_PROCESS_GUARD";
|
|
2
|
-
declare
|
|
3
|
-
|
|
2
|
+
declare const killMarkedProcesses: (marker: string) => void;
|
|
3
|
+
declare const killMarkedProcessRun: (runPrefix: string) => void;
|
|
4
|
+
export { PROCESS_MARKER, killMarkedProcessRun, killMarkedProcesses };
|
|
4
5
|
//# sourceMappingURL=kill-marked-processes.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"kill-marked-processes.d.ts","sourceRoot":"","sources":["../../src/process/kill-marked-processes.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"kill-marked-processes.d.ts","sourceRoot":"","sources":["../../src/process/kill-marked-processes.ts"],"names":[],"mappings":"AAUA,QAAA,MAAM,cAAc,uBAAuB,CAAC;AAwE5C,QAAA,MAAM,mBAAmB,GAAI,QAAQ,MAAM,KAAG,IAE7C,CAAC;AAEF,QAAA,MAAM,oBAAoB,GAAI,WAAW,MAAM,KAAG,IAIjD,CAAC;AAEF,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,CAAC"}
|
|
@@ -1,38 +1,69 @@
|
|
|
1
1
|
import { readdirSync, readFileSync } from "node:fs";
|
|
2
2
|
const PROCESS_MARKER = "GTKX_PROCESS_GUARD";
|
|
3
3
|
const MAX_KILL_PASSES = 8;
|
|
4
|
-
const
|
|
4
|
+
const JOB_ID_PATTERN = /^[0-9a-f]{8}$/;
|
|
5
|
+
const processIdentity = (pid) => {
|
|
6
|
+
try {
|
|
7
|
+
const stat = readFileSync(`/proc/${String(pid)}/stat`, "utf8");
|
|
8
|
+
const fields = stat.slice(stat.lastIndexOf(") ") + 2).split(" ");
|
|
9
|
+
const sessionId = Number(fields[3]);
|
|
10
|
+
const startTime = fields[19];
|
|
11
|
+
return startTime !== undefined && Number.isSafeInteger(sessionId)
|
|
12
|
+
? { pid, sessionId, startTime }
|
|
13
|
+
: undefined;
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
const isMarked = (pid, isMatch) => {
|
|
5
20
|
try {
|
|
6
21
|
return readFileSync(`/proc/${String(pid)}/environ`, "utf8")
|
|
7
22
|
.split("\0")
|
|
8
|
-
.some((assignment) => assignment
|
|
23
|
+
.some((assignment) => isMatch(assignment));
|
|
9
24
|
}
|
|
10
25
|
catch {
|
|
11
26
|
return false;
|
|
12
27
|
}
|
|
13
28
|
};
|
|
14
|
-
const
|
|
29
|
+
const markedProcesses = (isMatch) => readdirSync("/proc")
|
|
15
30
|
.map(Number)
|
|
16
31
|
.filter((pid) => Number.isSafeInteger(pid) && pid > 1 && pid !== process.pid)
|
|
17
|
-
.filter((pid) => isMarked(pid,
|
|
18
|
-
|
|
32
|
+
.filter((pid) => isMarked(pid, isMatch))
|
|
33
|
+
.map((pid) => processIdentity(pid))
|
|
34
|
+
.filter((identity) => identity !== undefined);
|
|
35
|
+
const killProcess = (identity, isMatch) => {
|
|
36
|
+
if (!isMarked(identity.pid, isMatch)) {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
const current = processIdentity(identity.pid);
|
|
40
|
+
if (current?.sessionId !== identity.sessionId ||
|
|
41
|
+
current.startTime !== identity.startTime) {
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
19
44
|
try {
|
|
20
|
-
process.kill(pid, "SIGKILL");
|
|
45
|
+
process.kill(identity.pid, "SIGKILL");
|
|
21
46
|
}
|
|
22
47
|
catch {
|
|
23
48
|
return;
|
|
24
49
|
}
|
|
25
50
|
};
|
|
26
|
-
|
|
51
|
+
const killMatchingProcesses = (isMatch) => {
|
|
27
52
|
for (let pass = 0; pass < MAX_KILL_PASSES; pass += 1) {
|
|
28
|
-
const
|
|
29
|
-
if (
|
|
53
|
+
const processes = markedProcesses(isMatch);
|
|
54
|
+
if (processes.length === 0) {
|
|
30
55
|
return;
|
|
31
56
|
}
|
|
32
|
-
for (const
|
|
33
|
-
|
|
57
|
+
for (const identity of processes) {
|
|
58
|
+
killProcess(identity, isMatch);
|
|
34
59
|
}
|
|
35
60
|
}
|
|
36
|
-
}
|
|
37
|
-
|
|
61
|
+
};
|
|
62
|
+
const killMarkedProcesses = (marker) => {
|
|
63
|
+
killMatchingProcesses((assignment) => assignment === marker);
|
|
64
|
+
};
|
|
65
|
+
const killMarkedProcessRun = (runPrefix) => {
|
|
66
|
+
killMatchingProcesses((assignment) => assignment.startsWith(runPrefix) && JOB_ID_PATTERN.test(assignment.slice(runPrefix.length)));
|
|
67
|
+
};
|
|
68
|
+
export { PROCESS_MARKER, killMarkedProcessRun, killMarkedProcesses };
|
|
38
69
|
//# sourceMappingURL=kill-marked-processes.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"kill-marked-processes.js","sourceRoot":"","sources":["../../src/process/kill-marked-processes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"kill-marked-processes.js","sourceRoot":"","sources":["../../src/process/kill-marked-processes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAUpD,MAAM,cAAc,GAAG,oBAAoB,CAAC;AAC5C,MAAM,eAAe,GAAG,CAAC,CAAC;AAC1B,MAAM,cAAc,GAAG,eAAe,CAAC;AAEvC,MAAM,eAAe,GAAG,CAAC,GAAW,EAA+B,EAAE;IACjE,IAAI,CAAC;QACD,MAAM,IAAI,GAAG,YAAY,CAAC,SAAS,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC/D,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACjE,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QACpC,MAAM,SAAS,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;QAE7B,OAAO,SAAS,KAAK,SAAS,IAAI,MAAM,CAAC,aAAa,CAAC,SAAS,CAAC;YAC7D,CAAC,CAAC,EAAE,GAAG,EAAE,SAAS,EAAE,SAAS,EAAE;YAC/B,CAAC,CAAC,SAAS,CAAC;IACpB,CAAC;IAAC,MAAM,CAAC;QACL,OAAO,SAAS,CAAC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AS,EAC1C,CAAC;QACC,OAAO;IACX,CAAC;IAED,IAAI,CAAC;QACD,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;IAC1C,CAAC;IAAC,MAAM,CAAC;QACL,OAAO;IACX,CAAC;AACL,CAAC,CAAC;AAEF,MAAM,qBAAqB,GAAG,CAAC,OAAsB,EAAQ,EAAE;IAC3D,KAAK,IAAI,IAAI,GAAG,CAAC,EAAE,IAAI,GAAG,eAAe,EAAE,IAAI,IAAI,CAAC,EAAE,CAAC;QACnD,MAAM,SAAS,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;QAE3C,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACzB,OAAO;QACX,CAAC;QAED,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;YAC/B,WAAW,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;QACnC,CAAC;IACL,CAAC;AACL,CAAC,CAAC;AAEF,MAAM,mBAAmB,GAAG,CAAC,MAAc,EAAQ,EAAE;IACjD,qBAAqB,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,KAAK,MAAM,CAAC,CAAC;AACjE,CAAC,CAAC;AAEF,MAAM,oBAAoB,GAAG,CAAC,SAAiB,EAAQ,EAAE;IACrD,qBAAqB,CAAC,CAAC,UAAU,EAAE,EAAE,CACjC,UAAU,CAAC,UAAU,CAAC,SAAS,CAAC,IAAI,cAAc,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAC9F,CAAC;AACN,CAAC,CAAC;AAEF,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,CAAC","sourcesContent":["import { readdirSync, readFileSync } from \"node:fs\";\n\ntype ProcessIdentity = {\n pid: number;\n sessionId: number;\n startTime: string;\n};\n\ntype MarkerMatcher = (assignment: string) => boolean;\n\nconst PROCESS_MARKER = \"GTKX_PROCESS_GUARD\";\nconst MAX_KILL_PASSES = 8;\nconst JOB_ID_PATTERN = /^[0-9a-f]{8}$/;\n\nconst processIdentity = (pid: number): ProcessIdentity | undefined => {\n try {\n const stat = readFileSync(`/proc/${String(pid)}/stat`, \"utf8\");\n const fields = stat.slice(stat.lastIndexOf(\") \") + 2).split(\" \");\n const sessionId = Number(fields[3]);\n const startTime = fields[19];\n\n return startTime !== undefined && Number.isSafeInteger(sessionId)\n ? { pid, sessionId, startTime }\n : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst isMarked = (pid: number, isMatch: MarkerMatcher): boolean => {\n try {\n return readFileSync(`/proc/${String(pid)}/environ`, \"utf8\")\n .split(\"\\0\")\n .some((assignment) => isMatch(assignment));\n } catch {\n return false;\n }\n};\n\nconst markedProcesses = (isMatch: MarkerMatcher): ProcessIdentity[] =>\n readdirSync(\"/proc\")\n .map(Number)\n .filter((pid) => Number.isSafeInteger(pid) && pid > 1 && pid !== process.pid)\n .filter((pid) => isMarked(pid, isMatch))\n .map((pid) => processIdentity(pid))\n .filter((identity): identity is ProcessIdentity => identity !== undefined);\n\nconst killProcess = (identity: ProcessIdentity, isMatch: MarkerMatcher): void => {\n if (!isMarked(identity.pid, isMatch)) {\n return;\n }\n\n const current = processIdentity(identity.pid);\n\n if (\n current?.sessionId !== identity.sessionId ||\n current.startTime !== identity.startTime\n ) {\n return;\n }\n\n try {\n process.kill(identity.pid, \"SIGKILL\");\n } catch {\n return;\n }\n};\n\nconst killMatchingProcesses = (isMatch: MarkerMatcher): void => {\n for (let pass = 0; pass < MAX_KILL_PASSES; pass += 1) {\n const processes = markedProcesses(isMatch);\n\n if (processes.length === 0) {\n return;\n }\n\n for (const identity of processes) {\n killProcess(identity, isMatch);\n }\n }\n};\n\nconst killMarkedProcesses = (marker: string): void => {\n killMatchingProcesses((assignment) => assignment === marker);\n};\n\nconst killMarkedProcessRun = (runPrefix: string): void => {\n killMatchingProcesses((assignment) =>\n assignment.startsWith(runPrefix) && JOB_ID_PATTERN.test(assignment.slice(runPrefix.length)),\n );\n};\n\nexport { PROCESS_MARKER, killMarkedProcessRun, killMarkedProcesses };\n"]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
type ProcessGroupIdentity = {
|
|
2
|
+
processGroupId: number;
|
|
3
|
+
leaderStartTime: string;
|
|
4
|
+
};
|
|
5
|
+
type CleanupDirectoryIdentity = {
|
|
6
|
+
path: string;
|
|
7
|
+
device: string;
|
|
8
|
+
inode: string;
|
|
9
|
+
userId: string;
|
|
10
|
+
};
|
|
11
|
+
declare const processGroupIdentity: (processGroupId: number) => ProcessGroupIdentity | undefined;
|
|
12
|
+
declare const killProcessGroup: (identity: ProcessGroupIdentity) => void;
|
|
13
|
+
declare const cleanupDirectoryIdentity: (path: string) => CleanupDirectoryIdentity | undefined;
|
|
14
|
+
declare const removeCleanupDirectory: (identity: CleanupDirectoryIdentity) => void;
|
|
15
|
+
export { type CleanupDirectoryIdentity, cleanupDirectoryIdentity, killProcessGroup, type ProcessGroupIdentity, processGroupIdentity, removeCleanupDirectory, };
|
|
16
|
+
//# sourceMappingURL=kill-process-group.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kill-process-group.d.ts","sourceRoot":"","sources":["../../src/process/kill-process-group.ts"],"names":[],"mappings":"AAGA,KAAK,oBAAoB,GAAG;IACxB,cAAc,EAAE,MAAM,CAAC;IACvB,eAAe,EAAE,MAAM,CAAC;CAC3B,CAAC;AAEF,KAAK,wBAAwB,GAAG;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CAClB,CAAC;AAIF,QAAA,MAAM,oBAAoB,GAAI,gBAAgB,MAAM,KAAG,oBAAoB,GAAG,SAkB7E,CAAC;AAQF,QAAA,MAAM,gBAAgB,GAAI,UAAU,oBAAoB,KAAG,IAU1D,CAAC;AAEF,QAAA,MAAM,wBAAwB,GAAI,MAAM,MAAM,KAAG,wBAAwB,GAAG,SAqB3E,CAAC;AAEF,QAAA,MAAM,sBAAsB,GAAI,UAAU,wBAAwB,KAAG,IAgBpE,CAAC;AAEF,OAAO,EACH,KAAK,wBAAwB,EAC7B,wBAAwB,EACxB,gBAAgB,EAChB,KAAK,oBAAoB,EACzB,oBAAoB,EACpB,sBAAsB,GACzB,CAAC"}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { lstatSync, readFileSync, rmSync } from "node:fs";
|
|
2
|
+
import { isAbsolute, resolve } from "node:path";
|
|
3
|
+
const isProcessGroupId = (value) => Number.isSafeInteger(value) && value > 1;
|
|
4
|
+
const processGroupIdentity = (processGroupId) => {
|
|
5
|
+
if (!isProcessGroupId(processGroupId)) {
|
|
6
|
+
return undefined;
|
|
7
|
+
}
|
|
8
|
+
try {
|
|
9
|
+
const stat = readFileSync(`/proc/${String(processGroupId)}/stat`, "utf8");
|
|
10
|
+
const fields = stat.slice(stat.lastIndexOf(") ") + 2).split(" ");
|
|
11
|
+
const actualProcessGroupId = Number(fields[2]);
|
|
12
|
+
const sessionId = Number(fields[3]);
|
|
13
|
+
const leaderStartTime = fields[19];
|
|
14
|
+
return actualProcessGroupId === processGroupId && sessionId === processGroupId && leaderStartTime !== undefined
|
|
15
|
+
? { processGroupId, leaderStartTime }
|
|
16
|
+
: undefined;
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
const isCurrentProcessGroup = (identity) => {
|
|
23
|
+
const current = processGroupIdentity(identity.processGroupId);
|
|
24
|
+
return current?.leaderStartTime === identity.leaderStartTime;
|
|
25
|
+
};
|
|
26
|
+
const killProcessGroup = (identity) => {
|
|
27
|
+
if (!isCurrentProcessGroup(identity)) {
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
try {
|
|
31
|
+
process.kill(-identity.processGroupId, "SIGKILL");
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
const cleanupDirectoryIdentity = (path) => {
|
|
38
|
+
const absolutePath = resolve(path);
|
|
39
|
+
if (absolutePath === "/" || !isAbsolute(path)) {
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
try {
|
|
43
|
+
const entry = lstatSync(absolutePath, { bigint: true });
|
|
44
|
+
return entry.isDirectory()
|
|
45
|
+
? {
|
|
46
|
+
path: absolutePath,
|
|
47
|
+
device: entry.dev.toString(),
|
|
48
|
+
inode: entry.ino.toString(),
|
|
49
|
+
userId: entry.uid.toString(),
|
|
50
|
+
}
|
|
51
|
+
: undefined;
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
const removeCleanupDirectory = (identity) => {
|
|
58
|
+
const current = cleanupDirectoryIdentity(identity.path);
|
|
59
|
+
if (current?.device !== identity.device ||
|
|
60
|
+
current.inode !== identity.inode ||
|
|
61
|
+
current.userId !== identity.userId) {
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
rmSync(identity.path, { recursive: true, force: true });
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
export { cleanupDirectoryIdentity, killProcessGroup, processGroupIdentity, removeCleanupDirectory, };
|
|
72
|
+
//# sourceMappingURL=kill-process-group.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kill-process-group.js","sourceRoot":"","sources":["../../src/process/kill-process-group.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAchD,MAAM,gBAAgB,G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AC;QACD,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC5D,CAAC;IAAC,MAAM,CAAC;QACL,OAAO;IACX,CAAC;AACL,CAAC,CAAC;AAEF,OAAO,EAEH,wBAAwB,EACxB,gBAAgB,EAEhB,oBAAoB,EACpB,sBAAsB,GACzB,CAAC","sourcesContent":["import { lstatSync, readFileSync, rmSync } from \"node:fs\";\nimport { isAbsolute, resolve } from \"node:path\";\n\ntype ProcessGroupIdentity = {\n processGroupId: number;\n leaderStartTime: string;\n};\n\ntype CleanupDirectoryIdentity = {\n path: string;\n device: string;\n inode: string;\n userId: string;\n};\n\nconst isProcessGroupId = (value: number): boolean => Number.isSafeInteger(value) && value > 1;\n\nconst processGroupIdentity = (processGroupId: number): ProcessGroupIdentity | undefined => {\n if (!isProcessGroupId(processGroupId)) {\n return undefined;\n }\n\n try {\n const stat = readFileSync(`/proc/${String(processGroupId)}/stat`, \"utf8\");\n const fields = stat.slice(stat.lastIndexOf(\") \") + 2).split(\" \");\n const actualProcessGroupId = Number(fields[2]);\n const sessionId = Number(fields[3]);\n const leaderStartTime = fields[19];\n\n return actualProcessGroupId === processGroupId && sessionId === processGroupId && leaderStartTime !== undefined\n ? { processGroupId, leaderStartTime }\n : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst isCurrentProcessGroup = (identity: ProcessGroupIdentity): boolean => {\n const current = processGroupIdentity(identity.processGroupId);\n\n return current?.leaderStartTime === identity.leaderStartTime;\n};\n\nconst killProcessGroup = (identity: ProcessGroupIdentity): void => {\n if (!isCurrentProcessGroup(identity)) {\n return;\n }\n\n try {\n process.kill(-identity.processGroupId, \"SIGKILL\");\n } catch {\n return;\n }\n};\n\nconst cleanupDirectoryIdentity = (path: string): CleanupDirectoryIdentity | undefined => {\n const absolutePath = resolve(path);\n\n if (absolutePath === \"/\" || !isAbsolute(path)) {\n return undefined;\n }\n\n try {\n const entry = lstatSync(absolutePath, { bigint: true });\n\n return entry.isDirectory()\n ? {\n path: absolutePath,\n device: entry.dev.toString(),\n inode: entry.ino.toString(),\n userId: entry.uid.toString(),\n }\n : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst removeCleanupDirectory = (identity: CleanupDirectoryIdentity): void => {\n const current = cleanupDirectoryIdentity(identity.path);\n\n if (\n current?.device !== identity.device ||\n current.inode !== identity.inode ||\n current.userId !== identity.userId\n ) {\n return;\n }\n\n try {\n rmSync(identity.path, { recursive: true, force: true });\n } catch {\n return;\n }\n};\n\nexport {\n type CleanupDirectoryIdentity,\n cleanupDirectoryIdentity,\n killProcessGroup,\n type ProcessGroupIdentity,\n processGroupIdentity,\n removeCleanupDirectory,\n};\n"]}
|
|
@@ -1,13 +1,88 @@
|
|
|
1
|
-
import { killMarkedProcesses } from "./kill-marked-processes.js";
|
|
1
|
+
import { killMarkedProcesses, killMarkedProcessRun } from "./kill-marked-processes.js";
|
|
2
|
+
import { killProcessGroup, removeCleanupDirectory, } from "./kill-process-group.js";
|
|
2
3
|
const GUARD_PREFIX = process.argv[2] ?? "";
|
|
3
4
|
const WATCHED_SIGNALS = ["SIGTERM", "SIGINT", "SIGHUP"];
|
|
5
|
+
const state = {
|
|
6
|
+
bufferedCommands: "",
|
|
7
|
+
isSweeping: false,
|
|
8
|
+
jobs: new Map(),
|
|
9
|
+
};
|
|
10
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
11
|
+
const isProcessGroupIdentity = (value) => isRecord(value) &&
|
|
12
|
+
typeof value.processGroupId === "number" &&
|
|
13
|
+
Number.isSafeInteger(value.processGroupId) &&
|
|
14
|
+
value.processGroupId > 1 &&
|
|
15
|
+
typeof value.leaderStartTime === "string" &&
|
|
16
|
+
/^\d+$/.test(value.leaderStartTime);
|
|
17
|
+
const isCleanupDirectoryIdentity = (value) => isRecord(value) &&
|
|
18
|
+
typeof value.path === "string" &&
|
|
19
|
+
typeof value.device === "string" &&
|
|
20
|
+
typeof value.inode === "string" &&
|
|
21
|
+
typeof value.userId === "string";
|
|
22
|
+
const isGuardJob = (value) => isRecord(value) &&
|
|
23
|
+
typeof value.marker === "string" &&
|
|
24
|
+
isProcessGroupIdentity(value.processGroup) &&
|
|
25
|
+
Array.isArray(value.cleanupDirectories) &&
|
|
26
|
+
value.cleanupDirectories.every(isCleanupDirectoryIdentity);
|
|
27
|
+
const applyCommand = (command) => {
|
|
28
|
+
const operation = command[0];
|
|
29
|
+
let value;
|
|
30
|
+
try {
|
|
31
|
+
value = JSON.parse(command.slice(1));
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
if (!isGuardJob(value)) {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
if (operation === "+") {
|
|
40
|
+
state.jobs.set(value.marker, value);
|
|
41
|
+
}
|
|
42
|
+
else if (operation === "-") {
|
|
43
|
+
state.jobs.delete(value.marker);
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
const receiveCommands = (chunk) => {
|
|
47
|
+
state.bufferedCommands += chunk.toString();
|
|
48
|
+
const commands = state.bufferedCommands.split("\n");
|
|
49
|
+
state.bufferedCommands = commands.pop() ?? "";
|
|
50
|
+
for (const command of commands) {
|
|
51
|
+
applyCommand(command);
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
const killJobs = () => {
|
|
55
|
+
for (const job of state.jobs.values()) {
|
|
56
|
+
killProcessGroup(job.processGroup);
|
|
57
|
+
killMarkedProcesses(job.marker);
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
const removeCleanupDirectories = () => {
|
|
61
|
+
const cleanupDirectories = new Map();
|
|
62
|
+
for (const job of state.jobs.values()) {
|
|
63
|
+
for (const identity of job.cleanupDirectories) {
|
|
64
|
+
cleanupDirectories.set(`${identity.device}:${identity.inode}`, identity);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
for (const identity of cleanupDirectories.values()) {
|
|
68
|
+
removeCleanupDirectory(identity);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
4
71
|
const sweep = () => {
|
|
72
|
+
if (state.isSweeping) {
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
state.isSweeping = true;
|
|
76
|
+
applyCommand(state.bufferedCommands);
|
|
77
|
+
killJobs();
|
|
5
78
|
if (GUARD_PREFIX.length > 0) {
|
|
6
|
-
|
|
79
|
+
killMarkedProcessRun(GUARD_PREFIX);
|
|
7
80
|
}
|
|
81
|
+
removeCleanupDirectories();
|
|
8
82
|
process.exit(0);
|
|
9
83
|
};
|
|
10
84
|
process.stdin.resume();
|
|
85
|
+
process.stdin.on("data", receiveCommands);
|
|
11
86
|
process.stdin.on("end", sweep);
|
|
12
87
|
process.stdin.on("error", sweep);
|
|
13
88
|
for (const signal of WATCHED_SIGNALS) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"process-guard.js","sourceRoot":"","sources":["../../src/process/process-guard.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;
|
|
1
|
+
{"version":3,"file":"process-guard.js","sourceRoot":"","sources":["../../src/process/process-guard.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AACvF,OAAO,EAEH,gBAAgB,EAEhB,sBAAsB,GACzB,MAAM,yBAAyB,CAAC;AAEjC,MAAM,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;AAC3C,MAAM,eAAe,GAAG,CAAC,SAAS,EAAE,QAAQ,EAAE,QAAQ,CAAqC,CAAC;AAO5F,MAAM,KAAK,GAAmF;IAC1F,gBAAgB,EAAE,EAAE;IACpB,UAAU,EAAE,KAAK;IACjB,IAAI,EAAE,IAAI,GAAG,EAAE;CAClB,CAAC;AAEF,MAAM,QAAQ,GAAG,CAAC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cessGroup,\n type ProcessGroupIdentity,\n removeCleanupDirectory,\n} from \"./kill-process-group.ts\";\n\nconst GUARD_PREFIX = process.argv[2] ?? \"\";\nconst WATCHED_SIGNALS = [\"SIGTERM\", \"SIGINT\", \"SIGHUP\"] as const satisfies NodeJS.Signals[];\ntype GuardJob = {\n marker: string;\n processGroup: ProcessGroupIdentity;\n cleanupDirectories: CleanupDirectoryIdentity[];\n};\n\nconst state: { bufferedCommands: string; isSweeping: boolean; jobs: Map<string, GuardJob> } = {\n bufferedCommands: \"\",\n isSweeping: false,\n jobs: new Map(),\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isProcessGroupIdentity = (value: unknown): value is ProcessGroupIdentity =>\n isRecord(value) &&\n typeof value.processGroupId === \"number\" &&\n Number.isSafeInteger(value.processGroupId) &&\n value.processGroupId > 1 &&\n typeof value.leaderStartTime === \"string\" &&\n /^\\d+$/.test(value.leaderStartTime);\n\nconst isCleanupDirectoryIdentity = (value: unknown): value is CleanupDirectoryIdentity =>\n isRecord(value) &&\n typeof value.path === \"string\" &&\n typeof value.device === \"string\" &&\n typeof value.inode === \"string\" &&\n typeof value.userId === \"string\";\n\nconst isGuardJob = (value: unknown): value is GuardJob =>\n isRecord(value) &&\n typeof value.marker === \"string\" &&\n isProcessGroupIdentity(value.processGroup) &&\n Array.isArray(value.cleanupDirectories) &&\n value.cleanupDirectories.every(isCleanupDirectoryIdentity);\n\nconst applyCommand = (command: string): void => {\n const operation = command[0];\n let value: unknown;\n\n try {\n value = JSON.parse(command.slice(1));\n } catch {\n return;\n }\n\n if (!isGuardJob(value)) {\n return;\n }\n\n if (operation === \"+\") {\n state.jobs.set(value.marker, value);\n } else if (operation === \"-\") {\n state.jobs.delete(value.marker);\n }\n};\n\nconst receiveCommands = (chunk: Buffer | string): void => {\n state.bufferedCommands += chunk.toString();\n const commands = state.bufferedCommands.split(\"\\n\");\n state.bufferedCommands = commands.pop() ?? \"\";\n\n for (const command of commands) {\n applyCommand(command);\n }\n};\n\nconst killJobs = (): void => {\n for (const job of state.jobs.values()) {\n killProcessGroup(job.processGroup);\n killMarkedProcesses(job.marker);\n }\n};\n\nconst removeCleanupDirectories = (): void => {\n const cleanupDirectories: Map<string, CleanupDirectoryIdentity> = new Map();\n\n for (const job of state.jobs.values()) {\n for (const identity of job.cleanupDirectories) {\n cleanupDirectories.set(`${identity.device}:${identity.inode}`, identity);\n }\n }\n\n for (const identity of cleanupDirectories.values()) {\n removeCleanupDirectory(identity);\n }\n};\n\nconst sweep = (): void => {\n if (state.isSweeping) {\n return;\n }\n\n state.isSweeping = true;\n applyCommand(state.bufferedCommands);\n killJobs();\n\n if (GUARD_PREFIX.length > 0) {\n killMarkedProcessRun(GUARD_PREFIX);\n }\n\n removeCleanupDirectories();\n process.exit(0);\n};\n\nprocess.stdin.resume();\nprocess.stdin.on(\"data\", receiveCommands);\nprocess.stdin.on(\"end\", sweep);\nprocess.stdin.on(\"error\", sweep);\n\nfor (const signal of WATCHED_SIGNALS) {\n process.on(signal, sweep);\n}\n"]}
|
|
@@ -2,6 +2,7 @@ import { type ChildProcess, type StdioOptions } from "node:child_process";
|
|
|
2
2
|
type ParentDeathSpawnOptions = {
|
|
3
3
|
stdio?: StdioOptions;
|
|
4
4
|
env?: NodeJS.ProcessEnv;
|
|
5
|
+
cleanupDirectories?: string[];
|
|
5
6
|
};
|
|
6
7
|
declare function spawnWithParentDeathSignal(command: string, args: string[], options?: ParentDeathSpawnOptions): ChildProcess;
|
|
7
8
|
export { spawnWithParentDeathSignal };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spawn-with-parent-death-signal.d.ts","sourceRoot":"","sources":["../../src/process/spawn-with-parent-death-signal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,YAAY,EAAS,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"spawn-with-parent-death-signal.d.ts","sourceRoot":"","sources":["../../src/process/spawn-with-parent-death-signal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,YAAY,EAAS,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAgBjF,KAAK,uBAAuB,GAAG;IAC3B,KAAK,CAAC,EAAE,YAAY,CAAC;IACrB,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,kBAAkB,CAAC,EAAE,MAAM,EAAE,CAAC;CACjC,CAAC;AA0GF,iBAAS,0BAA0B,CAC/B,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EAAE,EACd,OAAO,GAAE,uBAA4B,GACtC,YAAY,CA4Cd;AAED,OAAO,EAAE,0BAA0B,EAAE,CAAC"}
|
|
@@ -4,12 +4,16 @@ import { Socket } from "node:net";
|
|
|
4
4
|
import { dirname, extname, join } from "node:path";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
import { killMarkedProcesses, PROCESS_MARKER } from "./kill-marked-processes.js";
|
|
7
|
+
import { cleanupDirectoryIdentity, killProcessGroup, processGroupIdentity, removeCleanupDirectory, } from "./kill-process-group.js";
|
|
7
8
|
import { resolveExecutable } from "./resolve-executable.js";
|
|
8
9
|
const MODULE_PATH = fileURLToPath(import.meta.url);
|
|
9
10
|
const GUARD_PATH = join(dirname(MODULE_PATH), `process-guard${extname(MODULE_PATH)}`);
|
|
10
11
|
const RUN_ID = randomBytes(8).toString("hex");
|
|
11
12
|
const RUN_PREFIX = `${PROCESS_MARKER}=${RUN_ID}/`;
|
|
12
|
-
const guard = {};
|
|
13
|
+
const guard = { jobs: new Map() };
|
|
14
|
+
const writeGuardCommand = (child, operation, job) => {
|
|
15
|
+
child.stdin?.write(`${operation}${JSON.stringify(job)}\n`);
|
|
16
|
+
};
|
|
13
17
|
const releaseGuard = (child) => {
|
|
14
18
|
child.unref();
|
|
15
19
|
const { stdin } = child;
|
|
@@ -26,23 +30,82 @@ const startGuard = () => {
|
|
|
26
30
|
stdio: ["pipe", "ignore", "ignore"],
|
|
27
31
|
});
|
|
28
32
|
child.on("error", () => {
|
|
29
|
-
guard.child
|
|
33
|
+
if (guard.child === child) {
|
|
34
|
+
guard.child = undefined;
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
child.on("exit", () => {
|
|
38
|
+
if (guard.child === child) {
|
|
39
|
+
guard.child = undefined;
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
child.stdin.on("error", () => {
|
|
43
|
+
if (guard.child === child) {
|
|
44
|
+
guard.child = undefined;
|
|
45
|
+
}
|
|
30
46
|
});
|
|
31
47
|
guard.child = child;
|
|
48
|
+
for (const job of guard.jobs.values()) {
|
|
49
|
+
writeGuardCommand(child, "+", job);
|
|
50
|
+
}
|
|
32
51
|
releaseGuard(child);
|
|
33
52
|
};
|
|
53
|
+
const registerJob = (job) => {
|
|
54
|
+
guard.jobs.set(job.marker, job);
|
|
55
|
+
if (guard.child) {
|
|
56
|
+
writeGuardCommand(guard.child, "+", job);
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
const unregisterJob = (job) => {
|
|
60
|
+
guard.jobs.delete(job.marker);
|
|
61
|
+
if (guard.child) {
|
|
62
|
+
writeGuardCommand(guard.child, "-", job);
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
const rollbackSpawn = ({ child, marker, processGroup, cleanupDirectories = [] }) => {
|
|
66
|
+
if (processGroup === undefined) {
|
|
67
|
+
child.kill("SIGKILL");
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
killProcessGroup(processGroup);
|
|
71
|
+
}
|
|
72
|
+
killMarkedProcesses(marker);
|
|
73
|
+
for (const identity of cleanupDirectories) {
|
|
74
|
+
removeCleanupDirectory(identity);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
34
77
|
function spawnWithParentDeathSignal(command, args, options = {}) {
|
|
35
78
|
const executable = resolveExecutable(command);
|
|
36
79
|
const setpriv = resolveExecutable("setpriv");
|
|
37
80
|
const jobValue = `${RUN_ID}/${randomBytes(4).toString("hex")}`;
|
|
81
|
+
const marker = `${PROCESS_MARKER}=${jobValue}`;
|
|
38
82
|
startGuard();
|
|
39
83
|
const child = spawn(setpriv, ["--pdeathsig", "SIGKILL", executable, ...args], {
|
|
40
84
|
detached: true,
|
|
41
85
|
stdio: options.stdio ?? "ignore",
|
|
42
86
|
env: { ...(options.env ?? process.env), [PROCESS_MARKER]: jobValue },
|
|
43
87
|
});
|
|
88
|
+
const processGroupId = child.pid;
|
|
89
|
+
const group = processGroupId === undefined ? undefined : processGroupIdentity(processGroupId);
|
|
90
|
+
if (group === undefined) {
|
|
91
|
+
rollbackSpawn({ child, marker });
|
|
92
|
+
throw new Error(`Failed to identify process group for ${command}`);
|
|
93
|
+
}
|
|
94
|
+
const cleanupDirectories = (options.cleanupDirectories ?? []).map((path) => cleanupDirectoryIdentity(path));
|
|
95
|
+
if (cleanupDirectories.includes(undefined)) {
|
|
96
|
+
const captured = cleanupDirectories.filter((identity) => identity !== undefined);
|
|
97
|
+
rollbackSpawn({ child, marker, processGroup: group, cleanupDirectories: captured });
|
|
98
|
+
throw new Error(`Failed to identify a cleanup directory for ${command}`);
|
|
99
|
+
}
|
|
100
|
+
const job = {
|
|
101
|
+
marker,
|
|
102
|
+
processGroup: group,
|
|
103
|
+
cleanupDirectories: cleanupDirectories.filter((identity) => identity !== undefined),
|
|
104
|
+
};
|
|
105
|
+
registerJob(job);
|
|
44
106
|
child.on("exit", () => {
|
|
45
|
-
killMarkedProcesses(
|
|
107
|
+
killMarkedProcesses(job.marker);
|
|
108
|
+
unregisterJob(job);
|
|
46
109
|
});
|
|
47
110
|
return child;
|
|
48
111
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spawn-with-parent-death-signal.js","sourceRoot":"","sources":["../../src/process/spawn-with-parent-death-signal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,KAAK,EAAqB,MAAM,oBAAoB,CAAC;AACj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,CAAC;KACtC,CAAC,CAAC;IAEH,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE;QACnB,KAAK,CAAC,KAAK,GAAG,SAAS,CAAC;IAC5B,CAAC,CAAC,CAAC;IAEH,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC;IACpB,YAAY,CAAC,KAAK,CAAC,CAAC;AACxB,CAAC,CAAC;AAEF,SAAS,0BAA0B,CAC/B,OAAe,EACf,IAAc,EACd,UAAmC,EAAE;IAErC,MAAM,UAAU,GAAG,iBAAiB,CAAC,OAAO,CAAC,CAAC;IAC9C,MAAM,OAAO,GAAG,iBAAiB,CAAC,SAAS,CAAC,CAAC;IAC7C,MAAM,QAAQ,GAAG,GAAG,MAAM,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;IAC/D,UAAU,EAAE,CAAC;IAEb,MAAM,KAAK,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC,aAAa,EAAE,SAAS,EAAE,UAAU,EAAE,GAAG,IAAI,CAAC,EAAE;QAC1E,QAAQ,EAAE,IAAI;QACd,KAAK,EAAE,OAAO,CAAC,KAAK,IAAI,QAAQ;QAChC,GAAG,EAAE,EAAE,GAAG,CAAC,OAAO,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,cAAc,CAAC,EAAE,QAAQ,EAAE;KACvE,CAAC,CAAC;IAEH,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE;QAClB,mBAAmB,CAAC,GAAG,cAAc,IAAI,QAAQ,EAAE,CAAC,CAAC;IACzD,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACjB,CAAC;AAED,OAAO,EAAE,0BAA0B,EAAE,CAAC","sourcesContent":["import { type ChildProcess, spawn, type StdioOptions } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport { Socket } from \"node:net\";\nimport { dirname, extname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { killMarkedProcesses, PROCESS_MARKER } from \"./kill-marked-processes.ts\";\nimport { resolveExecutable } from \"./resolve-executable.ts\";\n\ntype ParentDeathSpawnOptions = {\n stdio?: StdioOptions;\n env?: NodeJS.ProcessEnv;\n};\n\ntype GuardState = {\n child?: ChildProcess | undefined;\n};\n\nconst MODULE_PATH = fileURLToPath(import.meta.url);\nconst GUARD_PATH = join(dirname(MODULE_PATH), `process-guard${extname(MODULE_PATH)}`);\nconst RUN_ID = randomBytes(8).toString(\"hex\");\nconst RUN_PREFIX = `${PROCESS_MARKER}=${RUN_ID}/`;\nconst guard: GuardState = {};\n\nconst releaseGuard = (child: ChildProcess): void => {\n child.unref();\n const { stdin } = child;\n\n if (stdin instanceof Socket) {\n stdin.unref();\n }\n};\n\nconst startGuard = (): void => {\n if (guard.child) {\n return;\n }\n\n const child = spawn(process.execPath, [GUARD_PATH, RUN_PREFIX], {\n detached: true,\n stdio: [\"pipe\", \"ignore\", \"ignore\"],\n });\n\n child.on(\"error\", () => {\n guard.child = undefined;\n });\n\n guard.child = child;\n releaseGuard(child);\n};\n\nfunction spawnWithParentDeathSignal(\n command: string,\n args: string[],\n options: ParentDeathSpawnOptions = {},\n): ChildProcess {\n const executable = resolveExecutable(command);\n const setpriv = resolveExecutable(\"setpriv\");\n const jobValue = `${RUN_ID}/${randomBytes(4).toString(\"hex\")}`;\n startGuard();\n\n const child = spawn(setpriv, [\"--pdeathsig\", \"SIGKILL\", executable, ...args], {\n detached: true,\n stdio: options.stdio ?? \"ignore\",\n env: { ...(options.env ?? process.env), [PROCESS_MARKER]: jobValue },\n });\n\n child.on(\"exit\", () => {\n killMarkedProcesses(`${PROCESS_MARKER}=${jobValue}`);\n });\n\n return child;\n}\n\nexport { spawnWithParentDeathSignal };\n"]}
|
|
1
|
+
{"version":3,"file":"spawn-with-parent-death-signal.js","sourceRoot":"","sources":["../../src/process/spawn-with-parent-death-signal.ts"],"names":[],"mappings":"AAAA,OA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AAkB,EAAE,QAAQ,EAAE,CAAC,CAAC;QACpF,MAAM,IAAI,KAAK,CAAC,8CAA8C,OAAO,EAAE,CAAC,CAAC;IAC7E,CAAC;IAED,MAAM,GAAG,GAAa;QAClB,MAAM;QACN,YAAY,EAAE,KAAK;QACnB,kBAAkB,EAAE,kBAAkB,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,KAAK,SAAS,CAAC;KACtF,CAAC;IACF,WAAW,CAAC,GAAG,CAAC,CAAC;IAEjB,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE;QAClB,mBAAmB,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAChC,aAAa,CAAC,GAAG,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACjB,CAAC;AAED,OAAO,EAAE,0BAA0B,EAAE,CAAC","sourcesContent":["import { type ChildProcess, spawn, type StdioOptions } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport { Socket } from \"node:net\";\nimport { dirname, extname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { killMarkedProcesses, PROCESS_MARKER } from \"./kill-marked-processes.ts\";\nimport {\n type CleanupDirectoryIdentity,\n cleanupDirectoryIdentity,\n killProcessGroup,\n type ProcessGroupIdentity,\n processGroupIdentity,\n removeCleanupDirectory,\n} from \"./kill-process-group.ts\";\nimport { resolveExecutable } from \"./resolve-executable.ts\";\n\ntype ParentDeathSpawnOptions = {\n stdio?: StdioOptions;\n env?: NodeJS.ProcessEnv;\n cleanupDirectories?: string[];\n};\n\ntype GuardJob = {\n marker: string;\n processGroup: ProcessGroupIdentity;\n cleanupDirectories: CleanupDirectoryIdentity[];\n};\n\ntype GuardState = {\n child?: ChildProcess | undefined;\n jobs: Map<string, GuardJob>;\n};\n\ntype SpawnRollback = {\n child: ChildProcess;\n marker: string;\n processGroup?: ProcessGroupIdentity | undefined;\n cleanupDirectories?: CleanupDirectoryIdentity[] | undefined;\n};\n\nconst MODULE_PATH = fileURLToPath(import.meta.url);\nconst GUARD_PATH = join(dirname(MODULE_PATH), `process-guard${extname(MODULE_PATH)}`);\nconst RUN_ID = randomBytes(8).toString(\"hex\");\nconst RUN_PREFIX = `${PROCESS_MARKER}=${RUN_ID}/`;\nconst guard: GuardState = { jobs: new Map() };\n\nconst writeGuardCommand = (child: ChildProcess, operation: \"+\" | \"-\", job: GuardJob): void => {\n child.stdin?.write(`${operation}${JSON.stringify(job)}\\n`);\n};\n\nconst releaseGuard = (child: ChildProcess): void => {\n child.unref();\n const { stdin } = child;\n\n if (stdin instanceof Socket) {\n stdin.unref();\n }\n};\n\nconst startGuard = (): void => {\n if (guard.child) {\n return;\n }\n\n const child = spawn(process.execPath, [GUARD_PATH, RUN_PREFIX], {\n detached: true,\n stdio: [\"pipe\", \"ignore\", \"ignore\"],\n });\n\n child.on(\"error\", () => {\n if (guard.child === child) {\n guard.child = undefined;\n }\n });\n\n child.on(\"exit\", () => {\n if (guard.child === child) {\n guard.child = undefined;\n }\n });\n\n child.stdin.on(\"error\", () => {\n if (guard.child === child) {\n guard.child = undefined;\n }\n });\n\n guard.child = child;\n\n for (const job of guard.jobs.values()) {\n writeGuardCommand(child, \"+\", job);\n }\n\n releaseGuard(child);\n};\n\nconst registerJob = (job: GuardJob): void => {\n guard.jobs.set(job.marker, job);\n\n if (guard.child) {\n writeGuardCommand(guard.child, \"+\", job);\n }\n};\n\nconst unregisterJob = (job: GuardJob): void => {\n guard.jobs.delete(job.marker);\n\n if (guard.child) {\n writeGuardCommand(guard.child, \"-\", job);\n }\n};\n\nconst rollbackSpawn = ({ child, marker, processGroup, cleanupDirectories = [] }: SpawnRollback): void => {\n if (processGroup === undefined) {\n child.kill(\"SIGKILL\");\n } else {\n killProcessGroup(processGroup);\n }\n\n killMarkedProcesses(marker);\n\n for (const identity of cleanupDirectories) {\n removeCleanupDirectory(identity);\n }\n};\n\nfunction spawnWithParentDeathSignal(\n command: string,\n args: string[],\n options: ParentDeathSpawnOptions = {},\n): ChildProcess {\n const executable = resolveExecutable(command);\n const setpriv = resolveExecutable(\"setpriv\");\n const jobValue = `${RUN_ID}/${randomBytes(4).toString(\"hex\")}`;\n const marker = `${PROCESS_MARKER}=${jobValue}`;\n startGuard();\n\n const child = spawn(setpriv, [\"--pdeathsig\", \"SIGKILL\", executable, ...args], {\n detached: true,\n stdio: options.stdio ?? \"ignore\",\n env: { ...(options.env ?? process.env), [PROCESS_MARKER]: jobValue },\n });\n\n const processGroupId = child.pid;\n const group = processGroupId === undefined ? undefined : processGroupIdentity(processGroupId);\n\n if (group === undefined) {\n rollbackSpawn({ child, marker });\n throw new Error(`Failed to identify process group for ${command}`);\n }\n\n const cleanupDirectories = (options.cleanupDirectories ?? []).map((path) => cleanupDirectoryIdentity(path));\n\n if (cleanupDirectories.includes(undefined)) {\n const captured = cleanupDirectories.filter(\n (identity): identity is CleanupDirectoryIdentity => identity !== undefined,\n );\n rollbackSpawn({ child, marker, processGroup: group, cleanupDirectories: captured });\n throw new Error(`Failed to identify a cleanup directory for ${command}`);\n }\n\n const job: GuardJob = {\n marker,\n processGroup: group,\n cleanupDirectories: cleanupDirectories.filter((identity) => identity !== undefined),\n };\n registerJob(job);\n\n child.on(\"exit\", () => {\n killMarkedProcesses(job.marker);\n unregisterJob(job);\n });\n\n return child;\n}\n\nexport { spawnWithParentDeathSignal };\n"]}
|
package/package.json
CHANGED
package/src/process/index.ts
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
export { exitCodeForSignal } from "./exit-code-for-signal.ts";
|
|
2
2
|
export { installGracefulShutdown } from "./install-graceful-shutdown.ts";
|
|
3
|
+
export {
|
|
4
|
+
killProcessGroup,
|
|
5
|
+
type ProcessGroupIdentity,
|
|
6
|
+
processGroupIdentity,
|
|
7
|
+
} from "./kill-process-group.ts";
|
|
3
8
|
export { resolveExecutable, tryResolveExecutable } from "./resolve-executable.ts";
|
|
4
9
|
export { spawnWithParentDeathSignal } from "./spawn-with-parent-death-signal.ts";
|
|
@@ -1,44 +1,93 @@
|
|
|
1
1
|
import { readdirSync, readFileSync } from "node:fs";
|
|
2
2
|
|
|
3
|
+
type ProcessIdentity = {
|
|
4
|
+
pid: number;
|
|
5
|
+
sessionId: number;
|
|
6
|
+
startTime: string;
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
type MarkerMatcher = (assignment: string) => boolean;
|
|
10
|
+
|
|
3
11
|
const PROCESS_MARKER = "GTKX_PROCESS_GUARD";
|
|
4
12
|
const MAX_KILL_PASSES = 8;
|
|
13
|
+
const JOB_ID_PATTERN = /^[0-9a-f]{8}$/;
|
|
5
14
|
|
|
6
|
-
const
|
|
15
|
+
const processIdentity = (pid: number): ProcessIdentity | undefined => {
|
|
16
|
+
try {
|
|
17
|
+
const stat = readFileSync(`/proc/${String(pid)}/stat`, "utf8");
|
|
18
|
+
const fields = stat.slice(stat.lastIndexOf(") ") + 2).split(" ");
|
|
19
|
+
const sessionId = Number(fields[3]);
|
|
20
|
+
const startTime = fields[19];
|
|
21
|
+
|
|
22
|
+
return startTime !== undefined && Number.isSafeInteger(sessionId)
|
|
23
|
+
? { pid, sessionId, startTime }
|
|
24
|
+
: undefined;
|
|
25
|
+
} catch {
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const isMarked = (pid: number, isMatch: MarkerMatcher): boolean => {
|
|
7
31
|
try {
|
|
8
32
|
return readFileSync(`/proc/${String(pid)}/environ`, "utf8")
|
|
9
33
|
.split("\0")
|
|
10
|
-
.some((assignment) => assignment
|
|
34
|
+
.some((assignment) => isMatch(assignment));
|
|
11
35
|
} catch {
|
|
12
36
|
return false;
|
|
13
37
|
}
|
|
14
38
|
};
|
|
15
39
|
|
|
16
|
-
const
|
|
40
|
+
const markedProcesses = (isMatch: MarkerMatcher): ProcessIdentity[] =>
|
|
17
41
|
readdirSync("/proc")
|
|
18
42
|
.map(Number)
|
|
19
43
|
.filter((pid) => Number.isSafeInteger(pid) && pid > 1 && pid !== process.pid)
|
|
20
|
-
.filter((pid) => isMarked(pid,
|
|
44
|
+
.filter((pid) => isMarked(pid, isMatch))
|
|
45
|
+
.map((pid) => processIdentity(pid))
|
|
46
|
+
.filter((identity): identity is ProcessIdentity => identity !== undefined);
|
|
47
|
+
|
|
48
|
+
const killProcess = (identity: ProcessIdentity, isMatch: MarkerMatcher): void => {
|
|
49
|
+
if (!isMarked(identity.pid, isMatch)) {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const current = processIdentity(identity.pid);
|
|
54
|
+
|
|
55
|
+
if (
|
|
56
|
+
current?.sessionId !== identity.sessionId ||
|
|
57
|
+
current.startTime !== identity.startTime
|
|
58
|
+
) {
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
21
61
|
|
|
22
|
-
const killPid = (pid: number): void => {
|
|
23
62
|
try {
|
|
24
|
-
process.kill(pid, "SIGKILL");
|
|
63
|
+
process.kill(identity.pid, "SIGKILL");
|
|
25
64
|
} catch {
|
|
26
65
|
return;
|
|
27
66
|
}
|
|
28
67
|
};
|
|
29
68
|
|
|
30
|
-
|
|
69
|
+
const killMatchingProcesses = (isMatch: MarkerMatcher): void => {
|
|
31
70
|
for (let pass = 0; pass < MAX_KILL_PASSES; pass += 1) {
|
|
32
|
-
const
|
|
71
|
+
const processes = markedProcesses(isMatch);
|
|
33
72
|
|
|
34
|
-
if (
|
|
73
|
+
if (processes.length === 0) {
|
|
35
74
|
return;
|
|
36
75
|
}
|
|
37
76
|
|
|
38
|
-
for (const
|
|
39
|
-
|
|
77
|
+
for (const identity of processes) {
|
|
78
|
+
killProcess(identity, isMatch);
|
|
40
79
|
}
|
|
41
80
|
}
|
|
42
|
-
}
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const killMarkedProcesses = (marker: string): void => {
|
|
84
|
+
killMatchingProcesses((assignment) => assignment === marker);
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const killMarkedProcessRun = (runPrefix: string): void => {
|
|
88
|
+
killMatchingProcesses((assignment) =>
|
|
89
|
+
assignment.startsWith(runPrefix) && JOB_ID_PATTERN.test(assignment.slice(runPrefix.length)),
|
|
90
|
+
);
|
|
91
|
+
};
|
|
43
92
|
|
|
44
|
-
export { PROCESS_MARKER, killMarkedProcesses };
|
|
93
|
+
export { PROCESS_MARKER, killMarkedProcessRun, killMarkedProcesses };
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { lstatSync, readFileSync, rmSync } from "node:fs";
|
|
2
|
+
import { isAbsolute, resolve } from "node:path";
|
|
3
|
+
|
|
4
|
+
type ProcessGroupIdentity = {
|
|
5
|
+
processGroupId: number;
|
|
6
|
+
leaderStartTime: string;
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
type CleanupDirectoryIdentity = {
|
|
10
|
+
path: string;
|
|
11
|
+
device: string;
|
|
12
|
+
inode: string;
|
|
13
|
+
userId: string;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const isProcessGroupId = (value: number): boolean => Number.isSafeInteger(value) && value > 1;
|
|
17
|
+
|
|
18
|
+
const processGroupIdentity = (processGroupId: number): ProcessGroupIdentity | undefined => {
|
|
19
|
+
if (!isProcessGroupId(processGroupId)) {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
try {
|
|
24
|
+
const stat = readFileSync(`/proc/${String(processGroupId)}/stat`, "utf8");
|
|
25
|
+
const fields = stat.slice(stat.lastIndexOf(") ") + 2).split(" ");
|
|
26
|
+
const actualProcessGroupId = Number(fields[2]);
|
|
27
|
+
const sessionId = Number(fields[3]);
|
|
28
|
+
const leaderStartTime = fields[19];
|
|
29
|
+
|
|
30
|
+
return actualProcessGroupId === processGroupId && sessionId === processGroupId && leaderStartTime !== undefined
|
|
31
|
+
? { processGroupId, leaderStartTime }
|
|
32
|
+
: undefined;
|
|
33
|
+
} catch {
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const isCurrentProcessGroup = (identity: ProcessGroupIdentity): boolean => {
|
|
39
|
+
const current = processGroupIdentity(identity.processGroupId);
|
|
40
|
+
|
|
41
|
+
return current?.leaderStartTime === identity.leaderStartTime;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const killProcessGroup = (identity: ProcessGroupIdentity): void => {
|
|
45
|
+
if (!isCurrentProcessGroup(identity)) {
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
try {
|
|
50
|
+
process.kill(-identity.processGroupId, "SIGKILL");
|
|
51
|
+
} catch {
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const cleanupDirectoryIdentity = (path: string): CleanupDirectoryIdentity | undefined => {
|
|
57
|
+
const absolutePath = resolve(path);
|
|
58
|
+
|
|
59
|
+
if (absolutePath === "/" || !isAbsolute(path)) {
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
try {
|
|
64
|
+
const entry = lstatSync(absolutePath, { bigint: true });
|
|
65
|
+
|
|
66
|
+
return entry.isDirectory()
|
|
67
|
+
? {
|
|
68
|
+
path: absolutePath,
|
|
69
|
+
device: entry.dev.toString(),
|
|
70
|
+
inode: entry.ino.toString(),
|
|
71
|
+
userId: entry.uid.toString(),
|
|
72
|
+
}
|
|
73
|
+
: undefined;
|
|
74
|
+
} catch {
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const removeCleanupDirectory = (identity: CleanupDirectoryIdentity): void => {
|
|
80
|
+
const current = cleanupDirectoryIdentity(identity.path);
|
|
81
|
+
|
|
82
|
+
if (
|
|
83
|
+
current?.device !== identity.device ||
|
|
84
|
+
current.inode !== identity.inode ||
|
|
85
|
+
current.userId !== identity.userId
|
|
86
|
+
) {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
try {
|
|
91
|
+
rmSync(identity.path, { recursive: true, force: true });
|
|
92
|
+
} catch {
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
export {
|
|
98
|
+
type CleanupDirectoryIdentity,
|
|
99
|
+
cleanupDirectoryIdentity,
|
|
100
|
+
killProcessGroup,
|
|
101
|
+
type ProcessGroupIdentity,
|
|
102
|
+
processGroupIdentity,
|
|
103
|
+
removeCleanupDirectory,
|
|
104
|
+
};
|
|
@@ -1,17 +1,121 @@
|
|
|
1
|
-
import { killMarkedProcesses } from "./kill-marked-processes.ts";
|
|
1
|
+
import { killMarkedProcesses, killMarkedProcessRun } from "./kill-marked-processes.ts";
|
|
2
|
+
import {
|
|
3
|
+
type CleanupDirectoryIdentity,
|
|
4
|
+
killProcessGroup,
|
|
5
|
+
type ProcessGroupIdentity,
|
|
6
|
+
removeCleanupDirectory,
|
|
7
|
+
} from "./kill-process-group.ts";
|
|
2
8
|
|
|
3
9
|
const GUARD_PREFIX = process.argv[2] ?? "";
|
|
4
10
|
const WATCHED_SIGNALS = ["SIGTERM", "SIGINT", "SIGHUP"] as const satisfies NodeJS.Signals[];
|
|
11
|
+
type GuardJob = {
|
|
12
|
+
marker: string;
|
|
13
|
+
processGroup: ProcessGroupIdentity;
|
|
14
|
+
cleanupDirectories: CleanupDirectoryIdentity[];
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const state: { bufferedCommands: string; isSweeping: boolean; jobs: Map<string, GuardJob> } = {
|
|
18
|
+
bufferedCommands: "",
|
|
19
|
+
isSweeping: false,
|
|
20
|
+
jobs: new Map(),
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
24
|
+
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
25
|
+
|
|
26
|
+
const isProcessGroupIdentity = (value: unknown): value is ProcessGroupIdentity =>
|
|
27
|
+
isRecord(value) &&
|
|
28
|
+
typeof value.processGroupId === "number" &&
|
|
29
|
+
Number.isSafeInteger(value.processGroupId) &&
|
|
30
|
+
value.processGroupId > 1 &&
|
|
31
|
+
typeof value.leaderStartTime === "string" &&
|
|
32
|
+
/^\d+$/.test(value.leaderStartTime);
|
|
33
|
+
|
|
34
|
+
const isCleanupDirectoryIdentity = (value: unknown): value is CleanupDirectoryIdentity =>
|
|
35
|
+
isRecord(value) &&
|
|
36
|
+
typeof value.path === "string" &&
|
|
37
|
+
typeof value.device === "string" &&
|
|
38
|
+
typeof value.inode === "string" &&
|
|
39
|
+
typeof value.userId === "string";
|
|
40
|
+
|
|
41
|
+
const isGuardJob = (value: unknown): value is GuardJob =>
|
|
42
|
+
isRecord(value) &&
|
|
43
|
+
typeof value.marker === "string" &&
|
|
44
|
+
isProcessGroupIdentity(value.processGroup) &&
|
|
45
|
+
Array.isArray(value.cleanupDirectories) &&
|
|
46
|
+
value.cleanupDirectories.every(isCleanupDirectoryIdentity);
|
|
47
|
+
|
|
48
|
+
const applyCommand = (command: string): void => {
|
|
49
|
+
const operation = command[0];
|
|
50
|
+
let value: unknown;
|
|
51
|
+
|
|
52
|
+
try {
|
|
53
|
+
value = JSON.parse(command.slice(1));
|
|
54
|
+
} catch {
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (!isGuardJob(value)) {
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (operation === "+") {
|
|
63
|
+
state.jobs.set(value.marker, value);
|
|
64
|
+
} else if (operation === "-") {
|
|
65
|
+
state.jobs.delete(value.marker);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const receiveCommands = (chunk: Buffer | string): void => {
|
|
70
|
+
state.bufferedCommands += chunk.toString();
|
|
71
|
+
const commands = state.bufferedCommands.split("\n");
|
|
72
|
+
state.bufferedCommands = commands.pop() ?? "";
|
|
73
|
+
|
|
74
|
+
for (const command of commands) {
|
|
75
|
+
applyCommand(command);
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const killJobs = (): void => {
|
|
80
|
+
for (const job of state.jobs.values()) {
|
|
81
|
+
killProcessGroup(job.processGroup);
|
|
82
|
+
killMarkedProcesses(job.marker);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const removeCleanupDirectories = (): void => {
|
|
87
|
+
const cleanupDirectories: Map<string, CleanupDirectoryIdentity> = new Map();
|
|
88
|
+
|
|
89
|
+
for (const job of state.jobs.values()) {
|
|
90
|
+
for (const identity of job.cleanupDirectories) {
|
|
91
|
+
cleanupDirectories.set(`${identity.device}:${identity.inode}`, identity);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
for (const identity of cleanupDirectories.values()) {
|
|
96
|
+
removeCleanupDirectory(identity);
|
|
97
|
+
}
|
|
98
|
+
};
|
|
5
99
|
|
|
6
100
|
const sweep = (): void => {
|
|
101
|
+
if (state.isSweeping) {
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
state.isSweeping = true;
|
|
106
|
+
applyCommand(state.bufferedCommands);
|
|
107
|
+
killJobs();
|
|
108
|
+
|
|
7
109
|
if (GUARD_PREFIX.length > 0) {
|
|
8
|
-
|
|
110
|
+
killMarkedProcessRun(GUARD_PREFIX);
|
|
9
111
|
}
|
|
10
112
|
|
|
113
|
+
removeCleanupDirectories();
|
|
11
114
|
process.exit(0);
|
|
12
115
|
};
|
|
13
116
|
|
|
14
117
|
process.stdin.resume();
|
|
118
|
+
process.stdin.on("data", receiveCommands);
|
|
15
119
|
process.stdin.on("end", sweep);
|
|
16
120
|
process.stdin.on("error", sweep);
|
|
17
121
|
|
|
@@ -4,22 +4,49 @@ import { Socket } from "node:net";
|
|
|
4
4
|
import { dirname, extname, join } from "node:path";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
import { killMarkedProcesses, PROCESS_MARKER } from "./kill-marked-processes.ts";
|
|
7
|
+
import {
|
|
8
|
+
type CleanupDirectoryIdentity,
|
|
9
|
+
cleanupDirectoryIdentity,
|
|
10
|
+
killProcessGroup,
|
|
11
|
+
type ProcessGroupIdentity,
|
|
12
|
+
processGroupIdentity,
|
|
13
|
+
removeCleanupDirectory,
|
|
14
|
+
} from "./kill-process-group.ts";
|
|
7
15
|
import { resolveExecutable } from "./resolve-executable.ts";
|
|
8
16
|
|
|
9
17
|
type ParentDeathSpawnOptions = {
|
|
10
18
|
stdio?: StdioOptions;
|
|
11
19
|
env?: NodeJS.ProcessEnv;
|
|
20
|
+
cleanupDirectories?: string[];
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
type GuardJob = {
|
|
24
|
+
marker: string;
|
|
25
|
+
processGroup: ProcessGroupIdentity;
|
|
26
|
+
cleanupDirectories: CleanupDirectoryIdentity[];
|
|
12
27
|
};
|
|
13
28
|
|
|
14
29
|
type GuardState = {
|
|
15
30
|
child?: ChildProcess | undefined;
|
|
31
|
+
jobs: Map<string, GuardJob>;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
type SpawnRollback = {
|
|
35
|
+
child: ChildProcess;
|
|
36
|
+
marker: string;
|
|
37
|
+
processGroup?: ProcessGroupIdentity | undefined;
|
|
38
|
+
cleanupDirectories?: CleanupDirectoryIdentity[] | undefined;
|
|
16
39
|
};
|
|
17
40
|
|
|
18
41
|
const MODULE_PATH = fileURLToPath(import.meta.url);
|
|
19
42
|
const GUARD_PATH = join(dirname(MODULE_PATH), `process-guard${extname(MODULE_PATH)}`);
|
|
20
43
|
const RUN_ID = randomBytes(8).toString("hex");
|
|
21
44
|
const RUN_PREFIX = `${PROCESS_MARKER}=${RUN_ID}/`;
|
|
22
|
-
const guard: GuardState = {};
|
|
45
|
+
const guard: GuardState = { jobs: new Map() };
|
|
46
|
+
|
|
47
|
+
const writeGuardCommand = (child: ChildProcess, operation: "+" | "-", job: GuardJob): void => {
|
|
48
|
+
child.stdin?.write(`${operation}${JSON.stringify(job)}\n`);
|
|
49
|
+
};
|
|
23
50
|
|
|
24
51
|
const releaseGuard = (child: ChildProcess): void => {
|
|
25
52
|
child.unref();
|
|
@@ -41,13 +68,62 @@ const startGuard = (): void => {
|
|
|
41
68
|
});
|
|
42
69
|
|
|
43
70
|
child.on("error", () => {
|
|
44
|
-
guard.child
|
|
71
|
+
if (guard.child === child) {
|
|
72
|
+
guard.child = undefined;
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
child.on("exit", () => {
|
|
77
|
+
if (guard.child === child) {
|
|
78
|
+
guard.child = undefined;
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
child.stdin.on("error", () => {
|
|
83
|
+
if (guard.child === child) {
|
|
84
|
+
guard.child = undefined;
|
|
85
|
+
}
|
|
45
86
|
});
|
|
46
87
|
|
|
47
88
|
guard.child = child;
|
|
89
|
+
|
|
90
|
+
for (const job of guard.jobs.values()) {
|
|
91
|
+
writeGuardCommand(child, "+", job);
|
|
92
|
+
}
|
|
93
|
+
|
|
48
94
|
releaseGuard(child);
|
|
49
95
|
};
|
|
50
96
|
|
|
97
|
+
const registerJob = (job: GuardJob): void => {
|
|
98
|
+
guard.jobs.set(job.marker, job);
|
|
99
|
+
|
|
100
|
+
if (guard.child) {
|
|
101
|
+
writeGuardCommand(guard.child, "+", job);
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
const unregisterJob = (job: GuardJob): void => {
|
|
106
|
+
guard.jobs.delete(job.marker);
|
|
107
|
+
|
|
108
|
+
if (guard.child) {
|
|
109
|
+
writeGuardCommand(guard.child, "-", job);
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const rollbackSpawn = ({ child, marker, processGroup, cleanupDirectories = [] }: SpawnRollback): void => {
|
|
114
|
+
if (processGroup === undefined) {
|
|
115
|
+
child.kill("SIGKILL");
|
|
116
|
+
} else {
|
|
117
|
+
killProcessGroup(processGroup);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
killMarkedProcesses(marker);
|
|
121
|
+
|
|
122
|
+
for (const identity of cleanupDirectories) {
|
|
123
|
+
removeCleanupDirectory(identity);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
|
|
51
127
|
function spawnWithParentDeathSignal(
|
|
52
128
|
command: string,
|
|
53
129
|
args: string[],
|
|
@@ -56,6 +132,7 @@ function spawnWithParentDeathSignal(
|
|
|
56
132
|
const executable = resolveExecutable(command);
|
|
57
133
|
const setpriv = resolveExecutable("setpriv");
|
|
58
134
|
const jobValue = `${RUN_ID}/${randomBytes(4).toString("hex")}`;
|
|
135
|
+
const marker = `${PROCESS_MARKER}=${jobValue}`;
|
|
59
136
|
startGuard();
|
|
60
137
|
|
|
61
138
|
const child = spawn(setpriv, ["--pdeathsig", "SIGKILL", executable, ...args], {
|
|
@@ -64,8 +141,34 @@ function spawnWithParentDeathSignal(
|
|
|
64
141
|
env: { ...(options.env ?? process.env), [PROCESS_MARKER]: jobValue },
|
|
65
142
|
});
|
|
66
143
|
|
|
144
|
+
const processGroupId = child.pid;
|
|
145
|
+
const group = processGroupId === undefined ? undefined : processGroupIdentity(processGroupId);
|
|
146
|
+
|
|
147
|
+
if (group === undefined) {
|
|
148
|
+
rollbackSpawn({ child, marker });
|
|
149
|
+
throw new Error(`Failed to identify process group for ${command}`);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const cleanupDirectories = (options.cleanupDirectories ?? []).map((path) => cleanupDirectoryIdentity(path));
|
|
153
|
+
|
|
154
|
+
if (cleanupDirectories.includes(undefined)) {
|
|
155
|
+
const captured = cleanupDirectories.filter(
|
|
156
|
+
(identity): identity is CleanupDirectoryIdentity => identity !== undefined,
|
|
157
|
+
);
|
|
158
|
+
rollbackSpawn({ child, marker, processGroup: group, cleanupDirectories: captured });
|
|
159
|
+
throw new Error(`Failed to identify a cleanup directory for ${command}`);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const job: GuardJob = {
|
|
163
|
+
marker,
|
|
164
|
+
processGroup: group,
|
|
165
|
+
cleanupDirectories: cleanupDirectories.filter((identity) => identity !== undefined),
|
|
166
|
+
};
|
|
167
|
+
registerJob(job);
|
|
168
|
+
|
|
67
169
|
child.on("exit", () => {
|
|
68
|
-
killMarkedProcesses(
|
|
170
|
+
killMarkedProcesses(job.marker);
|
|
171
|
+
unregisterJob(job);
|
|
69
172
|
});
|
|
70
173
|
|
|
71
174
|
return child;
|