Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeChildProcess from "node:child_process";
3import * as NodeCrypto from "node:crypto";
4import * as NodeFS from "node:fs";
5import * as NodeOS from "node:os";
6import * as NodePath from "node:path";
7
8import { describe, expect, it, vi } from "@effect/vitest";
9
10import { AGENT_OOM_SCORE_ADJ, SCOPE_WATCH_SCRIPT, agentScopeCommand } from "./AgentScope.ts";
11import * as HostProcess from "./HostProcess.ts";
12
13describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("agentScopeCommand", () => {
14 it("raises the OOM score and execs the command with its arguments in the same process", () => {
15 const launch = agentScopeCommand({
16 command: "/bin/sh",
17 args: [
18 "-c",
19 'printf "%s\\n" "$$" "$(cat /proc/self/oom_score_adj)" "$@"',
20 "agent",
21 "a b",
22 "$HOME",
23 ],
24 });
25 const child = NodeChildProcess.spawnSync(launch.command, [...launch.args], {
26 encoding: "utf8",
27 });
28 const [pid, score, ...args] = child.stdout.trimEnd().split("\n");
29 // The command runs as the spawned process, so signals and PIDs still reach it.
30 expect(Number(pid)).toBe(child.pid);
31 expect(Number(score)).toBe(AGENT_OOM_SCORE_ADJ);
32 expect(args).toEqual(["a b", "$HOME"]);
33 });
34
35 const setpriv = ["/usr/bin/setpriv", "/bin/setpriv"].find((path) => NodeFS.existsSync(path));
36
37 it.skipIf(setpriv === undefined)(
38 "stops the agent when the process that spawned it is killed",
39 async () => {
40 const launch = agentScopeCommand({ command: "sleep", args: ["300"], setpriv });
41 const server = NodeChildProcess.spawn(
42 "/bin/sh",
43 ["-c", '"$@" & echo $!; exec sleep 300', "server", launch.command, ...launch.args],
44 { stdio: ["ignore", "pipe", "ignore"] },
45 );
46 const agentPid = await new Promise<number>((resolve) =>
47 server.stdout.once("data", (chunk: Buffer) => resolve(Number(chunk.toString().trim()))),
48 );
49 const isAlive = () => {
50 try {
51 process.kill(agentPid, 0);
52 return true;
53 } catch {
54 return false;
55 }
56 };
57 try {
58 await vi.waitFor(() =>
59 expect(NodeFS.readFileSync(`/proc/${agentPid}/cmdline`, "utf8")).toBe(
60 "sleep\u0000300\u0000",
61 ),
62 );
63
64 server.kill("SIGKILL");
65
66 await vi.waitFor(() => expect(isAlive()).toBe(false), { timeout: 5_000 });
67 } finally {
68 server.kill("SIGKILL");
69 server.stdout.destroy();
70 if (isAlive()) process.kill(agentPid, "SIGKILL");
71 }
72 },
73 );
74
75 const hasUserScopes =
76 setpriv !== undefined &&
77 NodeChildProcess.spawnSync("systemd-run", ["--user", "--scope", "--quiet", "true"]).status ===
78 0;
79
80 it.skipIf(!hasUserScopes)(
81 "stops the agent and its children when the process that spawned it is killed",
82 async () => {
83 const unit = `t3code-test-${process.pid}-${NodeCrypto.randomUUID().slice(0, 8)}.scope`;
84 const launch = agentScopeCommand({
85 command: "/bin/sh",
86 args: ["-c", "sleep 300 & echo child:$!; exec sleep 300"],
87 setpriv,
88 scope: {
89 systemdRun: "systemd-run",
90 systemctl: "systemctl",
91 slice: "app.slice",
92 unit,
93 runtimeDir: process.env.XDG_RUNTIME_DIR ?? `/run/user/${process.getuid?.()}`,
94 options: ["--collect"],
95 },
96 });
97 const server = NodeChildProcess.spawn(
98 "/bin/sh",
99 ["-c", '"$@" & echo agent:$!; exec sleep 300', "server", launch.command, ...launch.args],
100 { stdio: ["ignore", "pipe", "ignore"] },
101 );
102 const pids = new Map<string, number>();
103 server.stdout.on("data", (chunk: Buffer) => {
104 for (const line of chunk.toString().split("\n")) {
105 const [name, pid] = line.split(":");
106 if (name !== undefined && pid !== undefined) pids.set(name, Number(pid));
107 }
108 });
109 const isAlive = (pid: number | undefined) => {
110 if (pid === undefined) return false;
111 try {
112 process.kill(pid, 0);
113 return true;
114 } catch {
115 return false;
116 }
117 };
118 try {
119 await vi.waitFor(() => expect(pids.size).toBe(2));
120 await vi.waitFor(() =>
121 expect(NodeFS.readFileSync(`/proc/${pids.get("agent")}/cmdline`, "utf8")).toBe(
122 "sleep\u0000300\u0000",
123 ),
124 );
125
126 server.kill("SIGKILL");
127
128 await vi.waitFor(() => expect(isAlive(pids.get("agent"))).toBe(false), {
129 timeout: 5_000,
130 });
131 await vi.waitFor(() => expect(isAlive(pids.get("child"))).toBe(false), {
132 timeout: 5_000,
133 });
134 } finally {
135 server.kill("SIGKILL");
136 server.stdout.destroy();
137 NodeChildProcess.spawnSync("systemctl", ["--user", "stop", unit]);
138 for (const pid of pids.values()) if (isAlive(pid)) process.kill(pid, "SIGKILL");
139 }
140 },
141 );
142
143 describe("scope watcher started after its agent already exited", () => {
144 const deadPid = () => NodeChildProcess.spawnSync("true").pid;
145 const runWatcher = (serverPid: number) => {
146 const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-scope-watch-"));
147 try {
148 const log = NodePath.join(dir, "calls");
149 const systemctl = NodePath.join(dir, "systemctl");
150 NodeFS.writeFileSync(systemctl, `#!/bin/sh\necho "$@" >> "${log}"\n`, { mode: 0o755 });
151 const result = NodeChildProcess.spawnSync(
152 "/bin/sh",
153 [
154 "-c",
155 SCOPE_WATCH_SCRIPT,
156 "watch",
157 String(serverPid),
158 systemctl,
159 "a.scope",
160 String(deadPid()),
161 ],
162 { timeout: 5_000 },
163 );
164 const calls = NodeFS.existsSync(log) ? NodeFS.readFileSync(log, "utf8") : "";
165 return { status: result.status, calls };
166 } finally {
167 NodeFS.rmSync(dir, { recursive: true, force: true });
168 }
169 };
170
171 it("stops the scope when the server is gone too", () => {
172 expect(runWatcher(deadPid())).toEqual({ status: 0, calls: "--user stop a.scope\n" });
173 });
174
175 it("leaves the scope alone while the server is alive", () => {
176 expect(runWatcher(process.pid)).toEqual({ status: 0, calls: "" });
177 });
178 });
179});