Skip to content

Commit 5ce9b61

Browse files
steipetevincentkoc
andauthored
fix(doctor): preserve managed container services (#129527)
* fix(doctor): preserve managed container services * fix(doctor): scope linger checks to user services * fix(doctor): limit container repair to user services --------- Co-authored-by: Vincent Koc <[email protected]>
1 parent 75a034d commit 5ce9b61

19 files changed

Lines changed: 743 additions & 90 deletions

‎scripts/e2e/lib/doctor-install-switch/scenario.sh‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,13 @@ export npm_config_fund=false
99
export npm_config_audit=false
1010
export OPENCLAW_DISABLE_BUNDLED_PLUGINS=1
1111

12-
# Stub systemd/loginctl so doctor + daemon flows work in Docker.
12+
# Stub the systemd manager and loginctl so doctor + daemon flows work in Docker.
1313
export PATH="/tmp/openclaw-bin:$PATH"
1414
mkdir -p /tmp/openclaw-bin
1515
cp scripts/e2e/lib/doctor-install-switch/shims/systemctl /tmp/openclaw-bin/systemctl
1616
cp scripts/e2e/lib/doctor-install-switch/shims/loginctl /tmp/openclaw-bin/loginctl
17-
chmod +x /tmp/openclaw-bin/systemctl /tmp/openclaw-bin/loginctl
17+
cp scripts/e2e/lib/doctor-install-switch/shims/busctl /tmp/openclaw-bin/busctl
18+
chmod +x /tmp/openclaw-bin/systemctl /tmp/openclaw-bin/loginctl /tmp/openclaw-bin/busctl
1819

1920
package_tgz="${OPENCLAW_CURRENT_PACKAGE_TGZ:?missing OPENCLAW_CURRENT_PACKAGE_TGZ}"
2021
git_root="/tmp/openclaw-git"
@@ -101,6 +102,9 @@ assert_entrypoint() {
101102
entrypoint="${entrypoint#\"}"
102103
if [ "$entrypoint" != "$expected" ]; then
103104
echo "Expected entrypoint $expected, got $entrypoint"
105+
if [ -n "${doctor_log:-}" ] && [ -f "$doctor_log" ]; then
106+
grep -E "Gateway service entrypoint|operator-owned systemd drop-in|managed externally" "$doctor_log" || true
107+
fi
104108
exit 1
105109
fi
106110
}
Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
#!/usr/bin/env node
2+
import fs from "node:fs";
3+
import path from "node:path";
4+
5+
const manager = "org.freedesktop.systemd1";
6+
const rootObjectPath = "/org/freedesktop/systemd1";
7+
const args = process.argv.slice(2);
8+
9+
function fail() {
10+
process.stderr.write("doctor-switch busctl shim: unexpected invocation or unavailable unit\n");
11+
process.exit(1);
12+
}
13+
14+
function splitWords(value) {
15+
const words = [];
16+
let word = "";
17+
let quote = "";
18+
let escaped = false;
19+
for (const character of value) {
20+
if (escaped) {
21+
word += character;
22+
escaped = false;
23+
} else if (character === "\\" && quote !== "'") {
24+
escaped = true;
25+
} else if (quote) {
26+
if (character === quote) {
27+
quote = "";
28+
} else {
29+
word += character;
30+
}
31+
} else if (character === '"' || character === "'") {
32+
quote = character;
33+
} else if (/\s/u.test(character)) {
34+
if (word) {
35+
words.push(word);
36+
word = "";
37+
}
38+
} else {
39+
word += character;
40+
}
41+
}
42+
if (quote || escaped) {
43+
fail();
44+
}
45+
if (word) {
46+
words.push(word);
47+
}
48+
return words;
49+
}
50+
51+
function encodeUnitName(name) {
52+
return Array.from(Buffer.from(name), (byte) =>
53+
(byte >= 48 && byte <= 57) || (byte >= 65 && byte <= 90) || (byte >= 97 && byte <= 122)
54+
? String.fromCharCode(byte)
55+
: `_${byte.toString(16).padStart(2, "0")}`,
56+
).join("");
57+
}
58+
59+
function writeProperties(properties) {
60+
process.stdout.write(properties.map((property) => JSON.stringify(property)).join("\n") + "\n");
61+
}
62+
63+
if (args[0] !== "--user" || args[1] !== "--json=short") {
64+
fail();
65+
}
66+
67+
const invocation = args.slice(2);
68+
if (invocation[0] === "call") {
69+
const [command, destination, objectPath, interfaceName, method, signature, unitName] = invocation;
70+
if (
71+
invocation.length !== 7 ||
72+
command !== "call" ||
73+
destination !== manager ||
74+
objectPath !== rootObjectPath ||
75+
interfaceName !== `${manager}.Manager` ||
76+
method !== "LoadUnit" ||
77+
signature !== "s" ||
78+
!unitName.endsWith(".service") ||
79+
path.basename(unitName) !== unitName ||
80+
!fs.existsSync(path.join(process.env.HOME, ".config/systemd/user", unitName))
81+
) {
82+
fail();
83+
}
84+
writeProperties([{ type: "o", data: [`${rootObjectPath}/unit/${encodeUnitName(unitName)}`] }]);
85+
process.exit(0);
86+
}
87+
88+
if (invocation[0] !== "get-property" || invocation[1] !== manager) {
89+
fail();
90+
}
91+
92+
const unitName = `${process.env.OPENCLAW_SYSTEMD_UNIT || "openclaw-gateway"}`.replace(
93+
/(?:\.service)?$/u,
94+
".service",
95+
);
96+
const unitPath = path.join(process.env.HOME, ".config/systemd/user", unitName);
97+
if (invocation[2] !== `${rootObjectPath}/unit/${encodeUnitName(unitName)}`) {
98+
fail();
99+
}
100+
101+
if (invocation[3] === `${manager}.Unit`) {
102+
if (
103+
invocation.length !== 7 ||
104+
invocation.slice(4).join(" ") !== "FragmentPath DropInPaths NeedDaemonReload"
105+
) {
106+
fail();
107+
}
108+
writeProperties([
109+
{ type: "s", data: unitPath },
110+
{ type: "as", data: [] },
111+
{ type: "b", data: false },
112+
]);
113+
process.exit(0);
114+
}
115+
116+
if (
117+
invocation[3] !== `${manager}.Service` ||
118+
invocation.length !== 9 ||
119+
invocation.slice(4).join(" ") !==
120+
"ExecStart WorkingDirectory Environment EnvironmentFiles UnsetEnvironment"
121+
) {
122+
fail();
123+
}
124+
125+
let programArguments = [];
126+
let workingDirectory = "";
127+
const environment = new Map();
128+
const environmentFiles = [];
129+
const unsetEnvironment = [];
130+
const expandHome = (value) =>
131+
value.replace(/%%|%h/gu, (match) => (match === "%h" ? process.env.HOME : "%"));
132+
133+
let content;
134+
try {
135+
content = fs.readFileSync(unitPath, "utf8");
136+
} catch {
137+
fail();
138+
}
139+
140+
for (const rawLine of content.split(/\r?\n/u)) {
141+
const line = rawLine.trim();
142+
const separator = line.indexOf("=");
143+
if (separator < 0 || line.startsWith("#") || line.startsWith(";")) {
144+
continue;
145+
}
146+
const directive = line.slice(0, separator);
147+
const value = line.slice(separator + 1).trim();
148+
if (directive === "ExecStart") {
149+
programArguments = splitWords(value).map(expandHome);
150+
} else if (directive === "WorkingDirectory") {
151+
workingDirectory = expandHome(splitWords(value)[0] || "").replace(/^-/, "");
152+
} else if (directive === "Environment") {
153+
if (!value) {
154+
environment.clear();
155+
}
156+
for (const assignment of splitWords(value)) {
157+
const assignmentSeparator = assignment.indexOf("=");
158+
if (assignmentSeparator <= 0) {
159+
fail();
160+
}
161+
environment.set(
162+
assignment.slice(0, assignmentSeparator),
163+
expandHome(assignment.slice(assignmentSeparator + 1)),
164+
);
165+
}
166+
} else if (directive === "EnvironmentFile") {
167+
if (!value) {
168+
environmentFiles.length = 0;
169+
}
170+
for (const filename of splitWords(value)) {
171+
const optional = filename.startsWith("-");
172+
environmentFiles.push([expandHome(optional ? filename.slice(1) : filename), optional]);
173+
}
174+
} else if (directive === "UnsetEnvironment") {
175+
if (!value) {
176+
unsetEnvironment.length = 0;
177+
} else {
178+
unsetEnvironment.push(...splitWords(value));
179+
}
180+
}
181+
}
182+
183+
if (!programArguments.length) {
184+
fail();
185+
}
186+
187+
writeProperties([
188+
{
189+
type: "a(sasbttttuii)",
190+
data: [[programArguments[0], programArguments, false, 0, 0, 0, 0, 0, 0, 0]],
191+
},
192+
{ type: "s", data: workingDirectory },
193+
{ type: "as", data: Array.from(environment, ([key, value]) => `${key}=${value}`) },
194+
{ type: "a(sb)", data: environmentFiles },
195+
{ type: "as", data: unsetEnvironment },
196+
]);

‎src/commands/doctor-gateway-daemon-flow.test.ts‎

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,11 @@ const formatGatewayRuntimeSummary = vi.hoisted(() => vi.fn((): string | null =>
3939
const renderSystemdUnavailableHints = vi.hoisted(() => vi.fn((): string[] => []));
4040
const isDefaultInstallIdentity = vi.hoisted(() => vi.fn(() => true));
4141
const isContainerEnvironment = vi.hoisted(() => vi.fn(() => false));
42+
const findInstalledSystemdGatewayScope = vi.hoisted(() =>
43+
vi.fn<(typeof import("../daemon/systemd.js"))["findInstalledSystemdGatewayScope"]>(
44+
async () => null,
45+
),
46+
);
4247
const resolveGatewayBindHost = vi.hoisted(() => vi.fn(async () => "127.0.0.1"));
4348

4449
vi.mock("../config/config.js", async () => {
@@ -87,6 +92,11 @@ vi.mock("../daemon/service.js", async () => {
8792
};
8893
});
8994

95+
vi.mock("../daemon/systemd.js", async (importOriginal) => ({
96+
...(await importOriginal<typeof import("../daemon/systemd.js")>()),
97+
findInstalledSystemdGatewayScope,
98+
}));
99+
90100
vi.mock("../daemon/systemd-hints.js", () => ({
91101
renderSystemdUnavailableHints,
92102
}));
@@ -171,6 +181,7 @@ describe("maybeRepairGatewayDaemon", () => {
171181
vi.clearAllMocks();
172182
formatGatewayClosedDiagnostic.mockReset();
173183
formatGatewayClosedDiagnostic.mockReturnValue(undefined);
184+
findInstalledSystemdGatewayScope.mockReset().mockResolvedValue(null);
174185
service.isLoaded.mockResolvedValue(true);
175186
service.readRuntime.mockResolvedValue({ status: "running" });
176187
service.readCommand.mockResolvedValue(null);
@@ -341,13 +352,14 @@ describe("maybeRepairGatewayDaemon", () => {
341352
});
342353

343354
it.each([
344-
{ environment: "detected container", detected: true, kubernetes: false },
345-
{ environment: "Kubernetes pod without container markers", detected: false, kubernetes: true },
355+
{ environment: "container without an OpenClaw service", detected: true },
356+
{ environment: "Kubernetes pod without container markers", kubernetes: true },
357+
{ environment: "globally external supervisor", external: true },
346358
])(
347359
"keeps port diagnostics but never probes host services in a $environment",
348360
async (scenario) => {
349361
setPlatform("linux");
350-
isContainerEnvironment.mockReturnValue(scenario.detected);
362+
isContainerEnvironment.mockReturnValue(scenario.detected === true);
351363
inspectPortUsage.mockResolvedValueOnce({
352364
port: 18789,
353365
status: "busy",
@@ -359,16 +371,15 @@ describe("maybeRepairGatewayDaemon", () => {
359371
{
360372
KUBERNETES_SERVICE_HOST: scenario.kubernetes ? "10.96.0.1" : undefined,
361373
KUBERNETES_SERVICE_PORT: scenario.kubernetes ? "443" : undefined,
374+
OPENCLAW_SUPERVISOR_MODE: scenario.external ? "external" : undefined,
362375
},
363376
runNonInteractiveRepair,
364377
);
365378

366379
expect(inspectPortUsage).toHaveBeenCalledOnce();
367380
expect(note).toHaveBeenCalledWith("Port 18789 is already in use.", "Gateway port");
368-
expect(note).toHaveBeenCalledWith(
369-
"Container lifecycle is externally managed; skipping host service installation.",
370-
"Gateway",
371-
);
381+
expect(note).toHaveBeenCalledWith(EXTERNAL_SERVICE_REPAIR_NOTE, "Gateway");
382+
expect(findInstalledSystemdGatewayScope).toHaveBeenCalledTimes(scenario.detected ? 1 : 0);
372383
expect(service.isLoaded).not.toHaveBeenCalled();
373384
expect(service.readRuntime).not.toHaveBeenCalled();
374385
expect(service.readCommand).not.toHaveBeenCalled();
@@ -378,6 +389,22 @@ describe("maybeRepairGatewayDaemon", () => {
378389
},
379390
);
380391

392+
it("inspects an installed OpenClaw service through a reachable Docker systemd manager", async () => {
393+
setPlatform("linux");
394+
isContainerEnvironment.mockReturnValue(true);
395+
findInstalledSystemdGatewayScope.mockResolvedValue({
396+
scope: "user",
397+
unitName: "openclaw-gateway.service",
398+
unitPath: "/home/alice/.config/systemd/user/openclaw-gateway.service",
399+
});
400+
401+
await runNonInteractiveRepair();
402+
403+
expect(service.isLoaded).toHaveBeenCalledWith({ env: process.env, timeoutMs: 5_000 });
404+
expect(service.readRuntime).toHaveBeenCalledOnce();
405+
expect(note).not.toHaveBeenCalledWith(EXTERNAL_SERVICE_REPAIR_NOTE, "Gateway");
406+
});
407+
381408
it("reports recent restart handoffs during deep doctor", async () => {
382409
vi.useFakeTimers();
383410
vi.setSystemTime(40_000);

‎src/commands/doctor-gateway-daemon-flow.ts‎

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,7 @@ import {
2525
import { renderSystemdUnavailableHints } from "../daemon/systemd-hints.js";
2626
import { classifySystemdUnavailableDetail } from "../daemon/systemd-unavailable.js";
2727
import { resolveGatewayBindHost, resolveGatewayRequiredListenHosts } from "../gateway/net.js";
28-
import {
29-
isGatewayHostServiceEnvironment,
30-
NON_DEFAULT_INSTALL_SERVICE_SKIP_REASON,
31-
} from "../infra/gateway-supervision.js";
28+
import { NON_DEFAULT_INSTALL_SERVICE_SKIP_REASON } from "../infra/gateway-supervision.js";
3229
import { formatPortDiagnostics, isExpectedGatewayListeners } from "../infra/ports-format.js";
3330
import { inspectPortConnections, inspectPortUsage } from "../infra/ports-inspect.js";
3431
import type { PortConnection } from "../infra/ports-types.js";
@@ -53,6 +50,7 @@ import {
5350
isServiceRepairExternallyManaged,
5451
resolveServiceRepairPolicy,
5552
SERVICE_REPAIR_POLICY_ENV,
53+
shouldManageGatewayService,
5654
} from "./doctor-service-repair-policy.js";
5755
import { resolveGatewayInstallToken } from "./gateway-install-token.js";
5856
import { formatGatewayClosedDiagnostic, formatHealthCheckFailure } from "./health-format.js";
@@ -234,14 +232,11 @@ export async function maybeRepairGatewayDaemon(params: {
234232
return;
235233
}
236234

237-
if (!isGatewayHostServiceEnvironment()) {
235+
if (!(await shouldManageGatewayService())) {
238236
if (params.cfg.gateway?.mode !== "remote") {
239237
await noteGatewayPortDiagnostics(params.cfg, params.options.deep ?? false);
240238
}
241-
note(
242-
"Container lifecycle is externally managed; skipping host service installation.",
243-
"Gateway",
244-
);
239+
note(EXTERNAL_SERVICE_REPAIR_NOTE, "Gateway");
245240
return;
246241
}
247242

0 commit comments

Comments
 (0)