Skip to content

Commit e701b75

Browse files
authored
fix(systemd): support legacy service managers (lidge-jun#2869)
1 parent f848548 commit e701b75

3 files changed

Lines changed: 132 additions & 34 deletions

File tree

‎src/service-manager-probe.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,7 @@ function inspectLaunchd(deps: Required<Pick<ProbeDeps, "run" | "uid" | "home">>)
323323
};
324324
}
325325

326-
function systemdProperty(out: string, key: string): string | null {
326+
export function systemdProperty(out: string, key: string): string | null {
327327
for (const line of out.split("\n")) {
328328
const match = line.match(new RegExp(`^${key}=(.*)$`));
329329
if (match) return match[1].trim();

‎src/service.ts‎

Lines changed: 37 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import { windowsEnvIndirectBatchPathList, windowsEnvIndirectBatchValue } from ".
4949
import { recordOwnedConfigPath } from "./lib/config-ownership";
5050
import { killWindowsSchedulerWrappers } from "./lib/windows-service-wrappers";
5151
import { maybeShowStarPrompt } from "./cli/star-prompt";
52+
import { systemdProperty } from "./service-manager-probe";
5253

5354
const LABEL = "com.opencodex.proxy";
5455
const TASK = "opencodex-proxy";
@@ -706,12 +707,6 @@ export function resolvedProxyEnv(env: NodeJS.ProcessEnv = process.env): { name:
706707
return resolved;
707708
}
708709

709-
function systemdOutputTarget(value: string): string {
710-
// StandardOutput/StandardError use output specifiers such as append:/path.
711-
// Quoting the full specifier makes systemd reject it as an invalid output target.
712-
return value.replace(/%/g, "%%").replace(/\n/g, "\\n");
713-
}
714-
715710
function sh(cmd: string): string {
716711
return execSync(cmd, { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] }).trim();
717712
}
@@ -2549,19 +2544,18 @@ export function buildUnit(proxyEnv: { name: string; value: string }[] = resolved
25492544
opencodexHome,
25502545
...proxyEnv.map(({ name, value }) => systemdEnvironmentAssignment(name, value)),
25512546
].filter((line): line is string => Boolean(line)).join("\n");
2547+
const command = `${buildServiceShellCommand(bun, cli)} >> ${shellQuote(log)} 2>&1`;
25522548
return `[Unit]
25532549
Description=OpenCodex Proxy Server
25542550
After=network-online.target
25552551
Wants=network-online.target
25562552
25572553
[Service]
25582554
Type=simple
2559-
ExecStart=${systemdQuote("/bin/sh")} -lc ${systemdQuote(buildServiceShellCommand(bun, cli))}
2555+
ExecStart=${systemdQuote("/bin/sh")} -lc ${systemdQuote(command)}
25602556
Restart=on-failure
25612557
RestartSec=5
25622558
${envLines}
2563-
StandardOutput=${systemdOutputTarget(`append:${log}`)}
2564-
StandardError=${systemdOutputTarget(`append:${log}`)}
25652559
25662560
[Install]
25672561
WantedBy=default.target
@@ -2660,10 +2654,18 @@ function startSystemd(): void {
26602654
}
26612655
function stopSystemd(): void { try { sh(`systemctl --user stop ${TASK}`); } catch { /* not running */ } }
26622656
function statusSystemd(): string { try { return sh(`systemctl --user status ${TASK}`); } catch { return ""; } }
2663-
function uninstallSystemd(): void {
2664-
try { sh(`systemctl --user disable --now ${TASK}`); } catch { /* absent */ }
2665-
if (existsSync(unitPath())) unlinkSync(unitPath());
2666-
try { sh("systemctl --user daemon-reload"); } catch { /* best-effort */ }
2657+
export function uninstallSystemd(deps: {
2658+
run?: (command: string) => string;
2659+
unitExists?: () => boolean;
2660+
removeUnit?: () => void;
2661+
} = {}): void {
2662+
const run = deps.run ?? sh;
2663+
try { run(`systemctl --user stop ${TASK}`); } catch { /* not running */ }
2664+
try { run(`systemctl --user disable ${TASK}`); } catch { /* absent */ }
2665+
if ((deps.unitExists ?? (() => existsSync(unitPath())))()) {
2666+
(deps.removeUnit ?? (() => unlinkSync(unitPath())))();
2667+
}
2668+
try { run("systemctl --user daemon-reload"); } catch { /* best-effort */ }
26672669
}
26682670

26692671
type ServiceOps = {
@@ -2676,6 +2678,21 @@ type ServiceInstallCleanupOps = {
26762678
stop: () => void;
26772679
};
26782680

2681+
export function systemdServiceInstallCleanupOps(deps: {
2682+
run?: (command: string) => string;
2683+
} = {}): ServiceInstallCleanupOps {
2684+
const run = deps.run ?? sh;
2685+
return {
2686+
status: () => {
2687+
const output = run(`systemctl --user show -p LoadState ${TASK}`);
2688+
const loadState = systemdProperty(output, "LoadState")?.toLowerCase();
2689+
if (!loadState) throw new Error("systemd service status could not be verified.");
2690+
return loadState === "not-found" ? null : loadState;
2691+
},
2692+
stop: () => { run(`systemctl --user stop ${TASK}`); },
2693+
};
2694+
}
2695+
26792696
function platformOps(backend: ServiceBackend = "scheduler"): ServiceOps | null {
26802697
if (process.platform === "darwin")
26812698
return { install: installLaunchd, start: startLaunchd, stop: stopLaunchd, status: statusLaunchd, uninstall: uninstallLaunchd };
@@ -2744,20 +2761,13 @@ function platformServiceInstallCleanupOps(backend: ServiceBackend): ServiceInsta
27442761
};
27452762
}
27462763
if (process.platform === "linux") {
2747-
return {
2748-
status: () => {
2749-
// `list-unit-files <name>` exits non-zero when the unit has never been
2750-
// installed, which made a clean first install look like an unknown manager
2751-
// failure. `show LoadState` gives us the tri-state we actually need: a
2752-
// healthy user manager returns `not-found` for a missing unit, while an
2753-
// unreachable/permission-denied manager still makes `sh()` throw and the
2754-
// caller therefore fails closed.
2755-
const loadState = sh(`systemctl --user show ${TASK} --property=LoadState --value`).trim().toLowerCase();
2756-
if (!loadState) throw new Error("systemd service status could not be verified.");
2757-
return loadState === "not-found" ? null : loadState;
2758-
},
2759-
stop: () => { sh(`systemctl --user stop ${TASK}`); },
2760-
};
2764+
// `list-unit-files <name>` exits non-zero when the unit has never been
2765+
// installed, which made a clean first install look like an unknown manager
2766+
// failure. `show LoadState` gives us the tri-state we actually need: a
2767+
// healthy user manager returns `not-found` for a missing unit, while an
2768+
// unreachable/permission-denied manager still makes `sh()` throw and the
2769+
// caller therefore fails closed.
2770+
return systemdServiceInstallCleanupOps();
27612771
}
27622772
return null;
27632773
}

‎tests/service.test.ts‎

Lines changed: 94 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { isAbsolute, join, posix, win32 } from "node:path";
55
import * as serviceModule from "../src/service";
66
import { saveConfig } from "../src/config";
77
import { windowsEnvIndirectBatchValue } from "../src/lib/win-paths";
8-
import { assertServiceAuthEnvironment, assertServiceEnvironmentMatchesInstall, bakedServicePathsDiagnostic, confirmServiceServing, launchdListenPort, systemdListenPort, buildPlist, buildUnit, buildWindowsLauncherVbs, buildWindowsSchtasksCreateArgs, buildWindowsSchtasksCreateArgsForXml, buildWindowsServiceScript, buildWindowsTaskXml, deriveWindowsServiceDiagnostic, installFreshWindowsSchedulerSafely, installServiceSafely, launchctlLoadFailed, launchdJobMatchesPlist, normalizeServiceSubcommand, parseServiceArgs, parseServiceInstallState, planServiceCommand, prepareServiceInstall, probeServiceInstallation, readWindowsSchedulerXmlState, registerFreshWindowsSchedulerTask, removeNativeWindowsServiceForScheduler, repairService, resolveServiceListenPort, runLaunchctl, selectServiceSubcommand, serviceLogPath, serviceStartableFromTray, serviceStatusReport, serviceRetryCommand, serviceStatusSummary, systemdNeedsDaemonReload, windowsListenPort, winswListenPort, startLaunchd, windowsTaskRegistrationHealthy } from "../src/service";
8+
import { assertServiceAuthEnvironment, assertServiceEnvironmentMatchesInstall, bakedServicePathsDiagnostic, confirmServiceServing, launchdListenPort, systemdListenPort, buildPlist, buildUnit, buildWindowsLauncherVbs, buildWindowsSchtasksCreateArgs, buildWindowsSchtasksCreateArgsForXml, buildWindowsServiceScript, buildWindowsTaskXml, deriveWindowsServiceDiagnostic, installFreshWindowsSchedulerSafely, installServiceSafely, launchctlLoadFailed, launchdJobMatchesPlist, normalizeServiceSubcommand, parseServiceArgs, parseServiceInstallState, planServiceCommand, prepareServiceInstall, probeServiceInstallation, readWindowsSchedulerXmlState, registerFreshWindowsSchedulerTask, removeNativeWindowsServiceForScheduler, repairService, resolveServiceListenPort, runLaunchctl, selectServiceSubcommand, serviceLogPath, serviceStartableFromTray, serviceStatusReport, serviceRetryCommand, serviceStatusSummary, systemdNeedsDaemonReload, systemdServiceInstallCleanupOps, uninstallSystemd, windowsListenPort, winswListenPort, startLaunchd, windowsTaskRegistrationHealthy } from "../src/service";
99
import type { ServiceDiagnostic } from "../src/service";
1010
import { definitionCarriesCredential, resolvedProxyEnv, writeServiceDefinitionFile } from "../src/service";
1111
import { buildWinswXml } from "../src/lib/winsw";
@@ -185,13 +185,12 @@ describe("systemd service unit", () => {
185185
expect(nativeUnknown.detail).toContain("WinSW status");
186186
});
187187

188-
test("uses unquoted append targets for service logs", () => {
188+
test("redirects service output through the ExecStart shell for legacy systemd", () => {
189189
const unit = buildUnit();
190190

191-
expect(unit).toContain("StandardOutput=append:");
192-
expect(unit).toContain("StandardError=append:");
193-
expect(unit).not.toContain('StandardOutput="append:');
194-
expect(unit).not.toContain('StandardError="append:');
191+
expect(unit).toMatch(/ExecStart=.* start --port \d+ >> '[^'\n]*service\.log' 2>&1/);
192+
expect(unit).not.toContain("StandardOutput=");
193+
expect(unit).not.toContain("StandardError=");
195194
});
196195

197196
test("bakes outbound proxy env into the unit so the service is not cut off from upstream (#2107)", () => {
@@ -1449,6 +1448,95 @@ describe("service lifecycle cleanup ordering", () => {
14491448
]);
14501449
});
14511450

1451+
test("legacy systemd reports an absent unit without stopping cleanup or blocking install", async () => {
1452+
const commands: string[] = [];
1453+
const manager = systemdServiceInstallCleanupOps({
1454+
run: command => {
1455+
commands.push(command);
1456+
return "LoadState=not-found\n";
1457+
},
1458+
});
1459+
1460+
expect(manager.status()).toBeNull();
1461+
expect(commands).toEqual(["systemctl --user show -p LoadState opencodex-proxy"]);
1462+
expect(commands[0]).not.toContain("--value");
1463+
1464+
commands.length = 0;
1465+
let installed = false;
1466+
await installServiceSafely("scheduler", () => { installed = true; }, {
1467+
platform: "linux",
1468+
managerOps: () => manager,
1469+
stopTrackedProxy: async () => {},
1470+
});
1471+
1472+
expect(installed).toBe(true);
1473+
expect(commands).toEqual(["systemctl --user show -p LoadState opencodex-proxy"]);
1474+
});
1475+
1476+
test("legacy systemd still stops a loaded unit before installation", async () => {
1477+
const commands: string[] = [];
1478+
const manager = systemdServiceInstallCleanupOps({
1479+
run: command => {
1480+
commands.push(command);
1481+
return command.includes(" show ") ? "LoadState=loaded\n" : "";
1482+
},
1483+
});
1484+
let installed = false;
1485+
1486+
await installServiceSafely("scheduler", () => { installed = true; }, {
1487+
platform: "linux",
1488+
managerOps: () => manager,
1489+
stopTrackedProxy: async () => {},
1490+
});
1491+
1492+
expect(installed).toBe(true);
1493+
expect(commands).toEqual([
1494+
"systemctl --user show -p LoadState opencodex-proxy",
1495+
"systemctl --user stop opencodex-proxy",
1496+
]);
1497+
});
1498+
1499+
test("legacy systemd status fails closed when LoadState is missing or empty", async () => {
1500+
for (const output of ["ActiveState=inactive\n", "LoadState=\n"]) {
1501+
const commands: string[] = [];
1502+
let installed = false;
1503+
const manager = systemdServiceInstallCleanupOps({
1504+
run: command => {
1505+
commands.push(command);
1506+
return output;
1507+
},
1508+
});
1509+
1510+
await expect(installServiceSafely("scheduler", () => { installed = true; }, {
1511+
platform: "linux",
1512+
managerOps: () => manager,
1513+
stopTrackedProxy: async () => {},
1514+
})).rejects.toThrow("systemd service status could not be verified");
1515+
expect(installed).toBe(false);
1516+
expect(commands).toEqual(["systemctl --user show -p LoadState opencodex-proxy"]);
1517+
}
1518+
});
1519+
1520+
test("legacy systemd uninstall stops and disables separately even when stop fails", () => {
1521+
const commands: string[] = [];
1522+
1523+
uninstallSystemd({
1524+
run: command => {
1525+
commands.push(command);
1526+
if (command.includes(" stop ")) throw new Error("not running");
1527+
return "";
1528+
},
1529+
unitExists: () => false,
1530+
});
1531+
1532+
expect(commands).toEqual([
1533+
"systemctl --user stop opencodex-proxy",
1534+
"systemctl --user disable opencodex-proxy",
1535+
"systemctl --user daemon-reload",
1536+
]);
1537+
expect(commands.join(" ")).not.toContain("--now");
1538+
});
1539+
14521540
test("service install fails closed before install on manager or standalone cleanup errors", async () => {
14531541
for (const failure of ["status", "stop", "standalone"] as const) {
14541542
let installed = false;

0 commit comments

Comments
 (0)