Skip to content

Commit 2923dc7

Browse files
fix(systemd): remove service backups on uninstall
1 parent b6aff3e commit 2923dc7

5 files changed

Lines changed: 251 additions & 44 deletions

File tree

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2809,8 +2809,7 @@ src/daemon/schtasks-process.ts 2
28092809
src/daemon/schtasks-runtime.ts 4
28102810
src/daemon/service.ts 1
28112811
src/daemon/systemd-exec.ts 2
2812-
src/daemon/systemd-install.ts 5
2813-
src/daemon/systemd-lifecycle.ts 2
2812+
src/daemon/systemd-install.ts 3
28142813
src/daemon/systemd-runtime.ts 1
28152814
src/entry.compile-cache.ts 3
28162815
src/entry.respawn.ts 1

‎docs/install/uninstall.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ Default unit name is `openclaw-gateway.service` (or `openclaw-gateway-<profile>.
120120

121121
```bash
122122
systemctl --user disable --now openclaw-gateway.service
123-
rm -f ~/.config/systemd/user/openclaw-gateway.service
123+
rm -f ~/.config/systemd/user/openclaw-gateway.service ~/.config/systemd/user/openclaw-gateway.service.bak
124124
systemctl --user daemon-reload
125125
```
126126

‎src/daemon/systemd-install.ts‎

Lines changed: 67 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
isUnresolvedShellReference,
88
readStateDirDotEnvFromStateDir,
99
} from "../config/state-dir-dotenv.js";
10+
import { hasErrnoCode } from "../infra/errors.js";
1011
import { resolveGatewayServiceDescription } from "./constants.js";
1112
import { formatLine, writeFormattedLines } from "./output.js";
1213
import {
@@ -121,7 +122,7 @@ function sanitizeSystemdUnitBackupContent(params: {
121122
// Backups should not retain file-managed secrets that OpenClaw moved into the
122123
// generated EnvironmentFile during this rewrite.
123124
const sanitizedLines: string[] = [];
124-
for (const rawLine of params.content.split("\n")) {
125+
for (const rawLine of params.content.replace(/\\\r?\n\s*/gu, " ").split("\n")) {
125126
const line = rawLine.trim();
126127
if (!line.startsWith("Environment=")) {
127128
sanitizedLines.push(rawLine);
@@ -153,6 +154,11 @@ function sanitizeSystemdUnitBackupContent(params: {
153154
return sanitizedLines.join("\n");
154155
}
155156

157+
const SYSTEMD_MANAGED_CREDENTIAL_KEYS = normalizeServiceEnvKeys([
158+
"OPENCLAW_GATEWAY_TOKEN",
159+
"OPENCLAW_GATEWAY_PASSWORD",
160+
]);
161+
156162
async function writeSystemdUnit({
157163
env,
158164
programArguments,
@@ -169,7 +175,7 @@ async function writeSystemdUnit({
169175
resolveManagedGatewayServiceCommand(await readSystemdServiceExecStart(env))?.environment,
170176
);
171177
await fs.mkdir(path.dirname(unitPath), { recursive: true });
172-
await assertSystemdManagedPathIsNotSymlink(unitPath);
178+
await assertSystemdManagedPathIsRegularOrMissing(unitPath);
173179
const fileManagedKeys = collectSystemdFileManagedKeys({
174180
environmentValueSources,
175181
});
@@ -179,17 +185,22 @@ async function writeSystemdUnit({
179185
try {
180186
const backupPath = `${unitPath}.bak`;
181187
const existingUnit = await fs.readFile(unitPath, "utf8");
182-
const existingStat = await fs.stat(unitPath);
183-
const backupMode = existingStat.mode & 0o777 || 0o600;
188+
await assertSystemdManagedPathIsRegularOrMissing(backupPath);
184189
const backupUnit = sanitizeSystemdUnitBackupContent({
185190
content: existingUnit,
186-
fileManagedKeys,
191+
fileManagedKeys: normalizeServiceEnvKeys([
192+
...fileManagedKeys,
193+
...priorManagedKeys,
194+
...readManagedServiceEnvKeysFromEnvironment(environment),
195+
...SYSTEMD_MANAGED_CREDENTIAL_KEYS,
196+
]),
187197
});
188-
await fs.writeFile(backupPath, backupUnit, { encoding: "utf8", mode: backupMode });
189-
await fs.chmod(backupPath, backupMode);
198+
await publishSystemdPrivateFile(backupPath, backupUnit);
190199
backedUp = true;
191-
} catch {
192-
// File does not exist yet — nothing to back up.
200+
} catch (error) {
201+
if (!hasErrnoCode(error, "ENOENT")) {
202+
throw error;
203+
}
193204
}
194205

195206
const serviceDescription = resolveGatewayServiceDescription({ env, description });
@@ -281,18 +292,58 @@ async function writeSystemdUnit({
281292

282293
type SystemdFileSnapshot = { contents: Buffer; mode: number } | null;
283294

284-
async function assertSystemdManagedPathIsNotSymlink(filePath: string): Promise<void> {
295+
async function assertSystemdManagedPathIsRegularOrMissing(filePath: string): Promise<boolean> {
285296
try {
286297
const stat = await fs.lstat(filePath);
287298
if (stat.isSymbolicLink()) {
288299
throw new Error(`Refusing to rewrite symlinked managed systemd file: ${filePath}`);
289300
}
301+
if (
302+
stat.isDirectory() ||
303+
stat.isBlockDevice() ||
304+
stat.isCharacterDevice() ||
305+
stat.isFIFO() ||
306+
stat.isSocket()
307+
) {
308+
throw new Error(`Refusing to rewrite non-regular managed systemd file: ${filePath}`);
309+
}
290310
} catch (error) {
291-
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
292-
return;
311+
if (hasErrnoCode(error, "ENOENT")) {
312+
return false;
293313
}
294314
throw error;
295315
}
316+
return true;
317+
}
318+
319+
async function publishSystemdPrivateFile(filePath: string, contents: string): Promise<void> {
320+
const temporaryPath = `${filePath}.openclaw-${randomUUID()}.tmp`;
321+
try {
322+
await fs.writeFile(temporaryPath, contents, { encoding: "utf8", flag: "wx", mode: 0o600 });
323+
await fs.chmod(temporaryPath, 0o600);
324+
await fs.rename(temporaryPath, filePath);
325+
} finally {
326+
await fs.unlink(temporaryPath).catch(() => undefined);
327+
}
328+
}
329+
330+
export async function removeSystemdUnitArtifacts(unitPath: string): Promise<boolean> {
331+
// The generated unit and its recovery copy share one lifecycle. Validate both
332+
// before unlinking either so an unexpected artifact cannot cause partial cleanup.
333+
const backupPath = `${unitPath}.bak`;
334+
const unitExists = await assertSystemdManagedPathIsRegularOrMissing(unitPath);
335+
if (await assertSystemdManagedPathIsRegularOrMissing(backupPath)) {
336+
await fs.unlink(backupPath);
337+
}
338+
if (unitExists) {
339+
await fs.unlink(unitPath);
340+
}
341+
return unitExists;
342+
}
343+
344+
export async function assertSystemdUnitArtifactsRemovable(unitPath: string): Promise<void> {
345+
await assertSystemdManagedPathIsRegularOrMissing(unitPath);
346+
await assertSystemdManagedPathIsRegularOrMissing(`${unitPath}.bak`);
296347
}
297348

298349
async function readSystemdFileSnapshot(filePath: string): Promise<SystemdFileSnapshot> {
@@ -481,11 +532,10 @@ async function removeNodeSystemdManagedEnvironmentKeys(env: GatewayServiceEnv):
481532
} catch {
482533
return;
483534
}
484-
const managedKeys = new Set(["OPENCLAW_GATEWAY_TOKEN", "OPENCLAW_GATEWAY_PASSWORD"]);
485535
const remaining = Object.fromEntries(
486536
Object.entries(existingFile.environment).filter(([key, value]) => {
487537
const normalized = normalizeServiceEnvKey(key);
488-
if (normalized && managedKeys.has(normalized)) {
538+
if (normalized && SYSTEMD_MANAGED_CREDENTIAL_KEYS.has(normalized)) {
489539
return false;
490540
}
491541
return existingFile.literalShellReferenceKeys.has(key) || !isUnresolvedShellReference(value);
@@ -616,19 +666,10 @@ export async function uninstallSystemdService({
616666
await assertSystemdAvailable(env);
617667
const serviceName = resolveSystemdServiceName(env);
618668
const unitName = `${serviceName}.service`;
619-
await disableSystemdUserUnitForRemoval(env, unitName);
620-
621669
const unitPath = resolveSystemdUnitPath(env);
622-
let removed = false;
623-
try {
624-
await fs.unlink(unitPath);
625-
removed = true;
626-
} catch (error) {
627-
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
628-
throw error;
629-
}
630-
// Unit file was already absent; still clean generated node env state below.
631-
}
670+
await assertSystemdUnitArtifactsRemovable(unitPath);
671+
await disableSystemdUserUnitForRemoval(env, unitName);
672+
const removed = await removeSystemdUnitArtifacts(unitPath);
632673
await removeNodeSystemdManagedEnvironmentKeys(env);
633674
if (removed) {
634675
stdout.write(`${formatLine("Removed systemd service", unitPath)}\n`);

‎src/daemon/systemd-lifecycle.ts‎

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ import {
1717
isSystemctlAvailable,
1818
reloadSystemdUserManager,
1919
} from "./systemd-exec.js";
20+
import {
21+
assertSystemdUnitArtifactsRemovable,
22+
removeSystemdUnitArtifacts,
23+
} from "./systemd-install.js";
2024
import {
2125
assertNoSystemGatewayOwnership,
2226
findInstalledSystemdGatewayScope,
@@ -141,6 +145,12 @@ async function findLegacySystemdUnits(env: GatewayServiceEnv): Promise<LegacySys
141145
} catch {
142146
// ignore
143147
}
148+
try {
149+
await fs.lstat(`${unitPath}.bak`);
150+
exists = true;
151+
} catch {
152+
// ignore
153+
}
144154
let enabled = false;
145155
if (systemctlAvailable) {
146156
const res = await execSystemctlUser(env, ["is-enabled", `${name}.service`]);
@@ -165,20 +175,18 @@ export async function uninstallLegacySystemdUnits({
165175
const systemctlAvailable = await isSystemctlAvailable(env);
166176
let removedAny = false;
167177
for (const unit of units) {
178+
await assertSystemdUnitArtifactsRemovable(unit.unitPath);
168179
if (systemctlAvailable) {
169180
await disableSystemdUserUnitForRemoval(env, `${unit.name}.service`);
170181
} else {
171182
stdout.write(`systemctl unavailable; removed legacy unit file only: ${unit.name}.service\n`);
172183
}
173184

174-
try {
175-
await fs.unlink(unit.unitPath);
176-
removedAny = true;
185+
const removed = await removeSystemdUnitArtifacts(unit.unitPath);
186+
removedAny ||= removed;
187+
if (removed) {
177188
stdout.write(`${formatLine("Removed legacy systemd service", unit.unitPath)}\n`);
178-
} catch (error) {
179-
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
180-
throw error;
181-
}
189+
} else {
182190
stdout.write(`Legacy systemd unit not found at ${unit.unitPath}\n`);
183191
}
184192
}
@@ -213,6 +221,7 @@ export async function uninstallUserSystemdGatewayUnit({
213221
}: GatewayServiceManageArgs): Promise<UninstallUserSystemdGatewayUnitResult> {
214222
const unitName = `${resolveSystemdServiceName(env)}.service`;
215223
const unitPath = resolveSystemdUnitPath(env);
224+
await assertSystemdUnitArtifactsRemovable(unitPath);
216225
let disabled = false;
217226
if (await isSystemctlAvailable(env)) {
218227
await disableSystemdUserUnitForRemoval(env, unitName);
@@ -222,15 +231,10 @@ export async function uninstallUserSystemdGatewayUnit({
222231
`systemctl unavailable; removing unit file only: ${unitName}. A loaded unit keeps running until systemd reloads.\n`,
223232
);
224233
}
225-
let removed = false;
226-
try {
227-
await fs.unlink(unitPath);
228-
removed = true;
234+
const removed = await removeSystemdUnitArtifacts(unitPath);
235+
if (removed) {
229236
stdout.write(`${formatLine("Removed user-scope systemd service", unitPath)}\n`);
230-
} catch (error) {
231-
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
232-
throw error;
233-
}
237+
} else {
234238
stdout.write(`User-scope systemd unit not found at ${unitPath}\n`);
235239
}
236240
// The manager keeps a deleted unit's definition loaded until it reloads, so

0 commit comments

Comments
 (0)