Skip to content

Commit a672065

Browse files
authored
fix(daemon): legacy systemd unit removal reloads the user manager and stops masking failures (#120027)
* fix(daemon): reload systemd user manager after removing legacy units uninstallLegacySystemdUnits removed unit files without a daemon-reload, so the user manager kept the deleted unit definitions loaded and startable until an unrelated reload. Legacy-unit removal now reuses the shared disable-or-tolerate-missing helper, surfaces non-ENOENT unlink failures instead of swallowing them, and reloads the user manager once after any unit file was removed (matching uninstallUserSystemdGatewayUnit). * chore: re-fire CI * chore: re-fire CI against fixed main baseline
1 parent 441a9b9 commit a672065

2 files changed

Lines changed: 138 additions & 19 deletions

File tree

‎src/daemon/systemd.test.ts‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ import {
103103
startSystemdService,
104104
stageSystemdService,
105105
stopSystemdService,
106+
uninstallLegacySystemdUnits,
106107
uninstallSystemdService,
107108
isSystemUnitActiveAndEnabled,
108109
uninstallUserSystemdGatewayUnit,
@@ -2774,6 +2775,48 @@ describe("isSystemUnitActiveAndEnabled", () => {
27742775
);
27752776
});
27762777

2778+
describe("uninstallLegacySystemdUnits", () => {
2779+
beforeEach(() => {
2780+
vi.restoreAllMocks();
2781+
execFileMock.mockReset();
2782+
});
2783+
2784+
it("preserves a legacy unit file when systemctl cannot disable it", async () => {
2785+
const tempHomeRoot = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-legacy-unit-"));
2786+
const env = { HOME: path.join(tempHomeRoot, "home") };
2787+
const unitPath = path.join(env.HOME, ".config", "systemd", "user", "clawdbot-gateway.service");
2788+
try {
2789+
await fs.mkdir(path.dirname(unitPath), { recursive: true });
2790+
await fs.writeFile(unitPath, "[Unit]\nDescription=Clawdbot Gateway\n", "utf8");
2791+
execFileMock
2792+
.mockImplementationOnce((_cmd, args, _opts, cb) => {
2793+
assertUserSystemctlArgs(args, "status");
2794+
cb(null, "", "");
2795+
})
2796+
.mockImplementationOnce((_cmd, args, _opts, cb) => {
2797+
assertUserSystemctlArgs(args, "is-enabled", "clawdbot-gateway.service");
2798+
cb(null, "enabled\n", "");
2799+
})
2800+
.mockImplementationOnce((_cmd, args, _opts, cb) => {
2801+
assertUserSystemctlArgs(args, "status");
2802+
cb(null, "", "");
2803+
})
2804+
.mockImplementationOnce((_cmd, args, _opts, cb) => {
2805+
assertUserSystemctlArgs(args, "disable", "--now", "clawdbot-gateway.service");
2806+
cb(createExecFileError("permission denied", { code: 1 }), "", "Permission denied");
2807+
});
2808+
2809+
const { stdout } = createWritableStreamMock();
2810+
await expect(uninstallLegacySystemdUnits({ env, stdout })).rejects.toThrow(
2811+
"systemctl disable failed: Permission denied",
2812+
);
2813+
await expect(fs.access(unitPath)).resolves.toBeUndefined();
2814+
} finally {
2815+
await fs.rm(tempHomeRoot, { recursive: true, force: true });
2816+
}
2817+
});
2818+
});
2819+
27772820
describe("uninstallUserSystemdGatewayUnit", () => {
27782821
async function withUserUnitFixture(
27792822
run: (context: { env: Record<string, string>; unitPath: string }) => Promise<void>,
@@ -2863,6 +2906,53 @@ describe("uninstallUserSystemdGatewayUnit", () => {
28632906
expect(writes).toContain("systemctl unavailable; removing unit file only");
28642907
});
28652908
});
2909+
2910+
it("preserves the unit file when systemctl cannot disable the service", async () => {
2911+
await withUserUnitFixture(async ({ env, unitPath }) => {
2912+
await fs.writeFile(unitPath, "[Unit]\nDescription=OpenClaw Gateway\n", "utf8");
2913+
execFileMock
2914+
.mockImplementationOnce((_cmd, args, _opts, cb) => {
2915+
assertUserSystemctlArgs(args, "status");
2916+
cb(null, "", "");
2917+
})
2918+
.mockImplementationOnce((_cmd, args, _opts, cb) => {
2919+
assertUserSystemctlArgs(args, "disable", "--now", GATEWAY_SERVICE);
2920+
cb(createExecFileError("permission denied", { code: 1 }), "", "Permission denied");
2921+
});
2922+
2923+
const { stdout } = createWritableStreamMock();
2924+
await expect(uninstallUserSystemdGatewayUnit({ env, stdout })).rejects.toThrow(
2925+
"systemctl disable failed: Permission denied",
2926+
);
2927+
await expect(fs.access(unitPath)).resolves.toBeUndefined();
2928+
expect(execFileMock).toHaveBeenCalledTimes(2);
2929+
});
2930+
});
2931+
2932+
it("surfaces daemon-reload failure after removing the disabled unit", async () => {
2933+
await withUserUnitFixture(async ({ env, unitPath }) => {
2934+
await fs.writeFile(unitPath, "[Unit]\nDescription=OpenClaw Gateway\n", "utf8");
2935+
execFileMock
2936+
.mockImplementationOnce((_cmd, args, _opts, cb) => {
2937+
assertUserSystemctlArgs(args, "status");
2938+
cb(null, "", "");
2939+
})
2940+
.mockImplementationOnce((_cmd, args, _opts, cb) => {
2941+
assertUserSystemctlArgs(args, "disable", "--now", GATEWAY_SERVICE);
2942+
cb(null, "", "");
2943+
})
2944+
.mockImplementationOnce((_cmd, args, _opts, cb) => {
2945+
assertUserSystemctlArgs(args, "daemon-reload");
2946+
cb(createExecFileError("bus unavailable", { code: 1 }), "", "Bus unavailable");
2947+
});
2948+
2949+
const { stdout } = createWritableStreamMock();
2950+
await expect(uninstallUserSystemdGatewayUnit({ env, stdout })).rejects.toThrow(
2951+
"systemctl daemon-reload failed: Bus unavailable",
2952+
);
2953+
await expect(fs.access(unitPath)).rejects.toMatchObject({ code: "ENOENT" });
2954+
});
2955+
});
28662956
});
28672957

28682958
describe("systemd service control", () => {

‎src/daemon/systemd.ts‎

Lines changed: 48 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -863,6 +863,17 @@ function isSystemdUnitMissingDetail(detail: string): boolean {
863863
);
864864
}
865865

866+
function isSystemdUnitAlreadyMissingOrInactive(detail: string, unitName: string): boolean {
867+
const escapedUnitName = escapeRegExp(normalizeLowercaseStringOrEmpty(unitName));
868+
return new RegExp(
869+
`^(?:failed to (?:disable unit|stop\\s+${escapedUnitName}):\\s*)?` +
870+
`(?:unit file\\s+${escapedUnitName}\\s+does not exist|` +
871+
`unit\\s+${escapedUnitName}(?:\\s+is)?\\s+` +
872+
`(?:inactive|not\\s+active|not\\s+loaded|not-found|could not be found))[.!]?$`,
873+
"u",
874+
).test(normalizeLowercaseStringOrEmpty(detail));
875+
}
876+
866877
const isSystemctlBusUnavailable = isSystemdUserBusUnavailableDetail;
867878

868879
function isSystemdUserScopeUnavailable(detail: string): boolean {
@@ -1054,6 +1065,30 @@ async function execSystemctlUser(
10541065
return await execSystemctl([...machineScopeArgs, ...args], env, timeoutMs);
10551066
}
10561067

1068+
async function disableSystemdUserUnitForRemoval(
1069+
env: GatewayServiceEnv,
1070+
unitName: string,
1071+
): Promise<void> {
1072+
const result = await execSystemctlUser(env, ["disable", "--now", unitName]);
1073+
if (result.code === 0) {
1074+
return;
1075+
}
1076+
const detail = readSystemctlDetail(result);
1077+
if (isSystemdUnitAlreadyMissingOrInactive(detail, unitName)) {
1078+
return;
1079+
}
1080+
throw new Error(`systemctl disable failed: ${detail || "unknown error"}`);
1081+
}
1082+
1083+
async function reloadSystemdUserManager(env: GatewayServiceEnv): Promise<void> {
1084+
const result = await execSystemctlUser(env, ["daemon-reload"]);
1085+
if (result.code !== 0) {
1086+
throw new Error(
1087+
`systemctl daemon-reload failed: ${readSystemctlDetail(result) || "unknown error"}`,
1088+
);
1089+
}
1090+
}
1091+
10571092
export async function isSystemdUserServiceAvailable(
10581093
env: GatewayServiceEnv = process.env as GatewayServiceEnv,
10591094
): Promise<boolean> {
@@ -1543,21 +1578,7 @@ export async function uninstallSystemdService({
15431578
await assertSystemdAvailable(env);
15441579
const serviceName = resolveSystemdServiceName(env);
15451580
const unitName = `${serviceName}.service`;
1546-
const disabled = await execSystemctlUser(env, ["disable", "--now", unitName]);
1547-
if (disabled.code !== 0) {
1548-
const detail = readSystemctlDetail(disabled);
1549-
const escapedUnitName = escapeRegExp(normalizeLowercaseStringOrEmpty(unitName));
1550-
const alreadyMissingOrInactive = new RegExp(
1551-
`^(?:failed to (?:disable unit|stop\\s+${escapedUnitName}):\\s*)?` +
1552-
`(?:unit file\\s+${escapedUnitName}\\s+does not exist|` +
1553-
`unit\\s+${escapedUnitName}(?:\\s+is)?\\s+` +
1554-
`(?:inactive|not\\s+active|not\\s+loaded|not-found|could not be found))[.!]?$`,
1555-
"u",
1556-
).test(normalizeLowercaseStringOrEmpty(detail));
1557-
if (!alreadyMissingOrInactive) {
1558-
throw new Error(`systemctl disable failed: ${detail || "unknown error"}`);
1559-
}
1560-
}
1581+
await disableSystemdUserUnitForRemoval(env, unitName);
15611582

15621583
const unitPath = resolveSystemdUnitPath(env);
15631584
let removed = false;
@@ -1800,20 +1821,28 @@ export async function uninstallLegacySystemdUnits({
18001821
}
18011822

18021823
const systemctlAvailable = await isSystemctlAvailable(env);
1824+
let removedAny = false;
18031825
for (const unit of units) {
18041826
if (systemctlAvailable) {
1805-
await execSystemctlUser(env, ["disable", "--now", `${unit.name}.service`]);
1827+
await disableSystemdUserUnitForRemoval(env, `${unit.name}.service`);
18061828
} else {
18071829
stdout.write(`systemctl unavailable; removed legacy unit file only: ${unit.name}.service\n`);
18081830
}
18091831

18101832
try {
18111833
await fs.unlink(unit.unitPath);
1834+
removedAny = true;
18121835
stdout.write(`${formatLine("Removed legacy systemd service", unit.unitPath)}\n`);
1813-
} catch {
1836+
} catch (error) {
1837+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
1838+
throw error;
1839+
}
18141840
stdout.write(`Legacy systemd unit not found at ${unit.unitPath}\n`);
18151841
}
18161842
}
1843+
if (systemctlAvailable && removedAny) {
1844+
await reloadSystemdUserManager(env);
1845+
}
18171846

18181847
return units;
18191848
}
@@ -1844,7 +1873,7 @@ export async function uninstallUserSystemdGatewayUnit({
18441873
const unitPath = resolveSystemdUnitPath(env);
18451874
let disabled = false;
18461875
if (await isSystemctlAvailable(env)) {
1847-
await execSystemctlUser(env, ["disable", "--now", unitName]);
1876+
await disableSystemdUserUnitForRemoval(env, unitName);
18481877
disabled = true;
18491878
} else {
18501879
stdout.write(
@@ -1865,7 +1894,7 @@ export async function uninstallUserSystemdGatewayUnit({
18651894
// The manager keeps a deleted unit's definition loaded until it reloads, so
18661895
// without this the unit stays startable while the detector reports it gone.
18671896
if (removed && disabled) {
1868-
await execSystemctlUser(env, ["daemon-reload"]);
1897+
await reloadSystemdUserManager(env);
18691898
}
18701899
return { unitName, unitPath, removed, disabled };
18711900
}

0 commit comments

Comments
 (0)