Skip to content

Commit 99224f0

Browse files
fix(server): launcher repoints the unit the systemd manager loads (#35966)
1 parent b2078c2 commit 99224f0

4 files changed

Lines changed: 124 additions & 21 deletions

File tree

‎apps/server/src/cloud/bootService.ts‎

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ import {
4545
parseServiceState,
4646
serviceStateActiveVersion,
4747
serviceStateHasPendingUpdate,
48+
systemdUnitDirectoryOf,
4849
type ServiceState,
4950
} from "./serviceProtocol.ts";
5051

@@ -550,7 +551,7 @@ const decodeSystemdUnitPaths = Schema.decodeUnknownEffect(
550551

551552
// The manager may not share the installer's environment; JSON preserves spaces in its paths.
552553
const readSystemdUnitDirectory = Effect.fn("cloud.boot_service.read_systemd_unit_directory")(
553-
function* (runner: ProcessRunner.ProcessRunner["Service"], path: Path.Path) {
554+
function* (runner: ProcessRunner.ProcessRunner["Service"]) {
554555
const result = yield* runner.run({
555556
command: "busctl",
556557
args: [
@@ -566,14 +567,7 @@ const readSystemdUnitDirectory = Effect.fn("cloud.boot_service.read_systemd_unit
566567
});
567568
if (result.code !== 0) return undefined;
568569
const { data } = yield* decodeSystemdUnitPaths(result.stdout);
569-
// The persistent control directory identifies the manager's config root despite UnitPath overrides.
570-
const controlDirectory = data.find(
571-
(directory) =>
572-
path.isAbsolute(directory) &&
573-
directory.endsWith("/systemd/user.control") &&
574-
data.includes(directory.slice(0, -".control".length)),
575-
);
576-
return controlDirectory?.slice(0, -".control".length);
570+
return systemdUnitDirectoryOf(data);
577571
},
578572
Effect.orElseSucceed(() => undefined),
579573
);
@@ -591,7 +585,7 @@ export const bootServiceUnitPath = Effect.fn("cloud.boot_service.unit_path")(fun
591585
}
592586
if (platform !== "linux") return undefined;
593587
const unitDir =
594-
(yield* readSystemdUnitDirectory(yield* ProcessRunner.ProcessRunner, path)) ??
588+
(yield* readSystemdUnitDirectory(yield* ProcessRunner.ProcessRunner)) ??
595589
defaultSystemdUnitDir(path, homeDir, (yield* HostProcess.Environment).XDG_CONFIG_HOME ?? "");
596590
return path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
597591
});
@@ -972,8 +966,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
972966
};
973967
return { manager, unitPath, plan };
974968
};
975-
let systemdUnitDir =
976-
platform === "linux" ? yield* readSystemdUnitDirectory(runner, path) : undefined;
969+
let systemdUnitDir = platform === "linux" ? yield* readSystemdUnitDirectory(runner) : undefined;
977970
let { manager: detectedManager, unitPath, plan } = resolveTarget(systemdUnitDir);
978971
const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
979972
const restartPendingPath = path.join(input.baseDir, "runtime", SERVICE_RESTART_PENDING_FILE);
@@ -1205,7 +1198,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
12051198
// Without a session the manager was unreachable at construction, and the one lingering
12061199
// started may use another config root than this shell's XDG_CONFIG_HOME.
12071200
if (systemdUnitDir === undefined) {
1208-
systemdUnitDir = yield* readSystemdUnitDirectory(runner, path);
1201+
systemdUnitDir = yield* readSystemdUnitDirectory(runner);
12091202
({ manager: detectedManager, unitPath, plan } = resolveTarget(systemdUnitDir));
12101203
manager = yield* requireManager;
12111204
yield* refuseOtherBaseDir;

‎apps/server/src/cloud/serviceProtocol.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,20 @@ export function serviceUnitBaseDirOf(contents: string): string | undefined {
6363
return task === undefined ? undefined : unquoteWindowsArgument(task);
6464
}
6565

66+
/**
67+
* The user unit directory a systemd manager reads, from its UnitPath property. The persistent
68+
* control directory identifies the manager's config root despite UnitPath overrides.
69+
*/
70+
export function systemdUnitDirectoryOf(unitPath: ReadonlyArray<string>): string | undefined {
71+
const controlDirectory = unitPath.find(
72+
(directory) =>
73+
directory.startsWith("/") &&
74+
directory.endsWith("/systemd/user.control") &&
75+
unitPath.includes(directory.slice(0, -".control".length)),
76+
);
77+
return controlDirectory?.slice(0, -".control".length);
78+
}
79+
6680
/** The file systemd or launchd appends the service's output to. */
6781
export function serviceUnitLogPathOf(contents: string): string | undefined {
6882
const systemd = /^StandardOutput=append:(.*)$/m.exec(contents)?.[1];

‎apps/server/src/serviceLauncher.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,70 @@ it.layer(NodeServices.layer)("service state persistence", (it) => {
318318
}),
319319
);
320320

321+
it.effect(
322+
"repoints the systemd unit the manager loads when environment.d moves XDG_CONFIG_HOME",
323+
() =>
324+
Effect.gen(function* () {
325+
const fs = yield* FileSystem.FileSystem;
326+
const path = yield* Path.Path;
327+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-xdg-" });
328+
const home = path.join(root, "home");
329+
const managerUnitDir = path.join(home, ".config", "systemd", "user");
330+
const unitPath = path.join(managerUnitDir, "t3code.service");
331+
const render = (version: string) =>
332+
renderBootServiceUnit({ ...unitPlan(root, version), unitPath });
333+
yield* fs.makeDirectory(managerUnitDir, { recursive: true });
334+
yield* fs.writeFileString(unitPath, render("1.0.0"));
335+
// Fake manager: busctl reports the unit search path, systemctl reloads.
336+
const bin = path.join(root, "bin");
337+
yield* fs.makeDirectory(bin, { recursive: true });
338+
const unitPathJson = JSON.stringify({
339+
type: "as",
340+
data: [`${managerUnitDir}.control`, managerUnitDir, "/usr/lib/systemd/user"],
341+
});
342+
yield* fs.writeFileString(
343+
path.join(bin, "busctl"),
344+
`#!/bin/sh\nprintf '%s\\n' '${unitPathJson}'\n`,
345+
);
346+
yield* fs.writeFileString(
347+
path.join(bin, "systemctl"),
348+
`#!/bin/sh\necho reload >> '${path.join(root, "reloads")}'\n`,
349+
);
350+
yield* fs.chmod(path.join(bin, "busctl"), 0o755);
351+
yield* fs.chmod(path.join(bin, "systemctl"), 0o755);
352+
yield* writeFakeRuntime(
353+
fs,
354+
path,
355+
path.join(root, "runtime", "versions", "1.1.0"),
356+
"process.exit(0);\n",
357+
);
358+
yield* Effect.promise(() =>
359+
writeServiceState(path.join(root, "runtime", "service-state.json"), {
360+
protocol: SERVICE_LAUNCHER_PROTOCOL,
361+
activeVersion: "1.1.0",
362+
update: {
363+
id: "update-1",
364+
fromVersion: "1.0.0",
365+
targetVersion: "1.1.0",
366+
status: "committed",
367+
},
368+
}),
369+
);
370+
vi.stubEnv("PATH", bin);
371+
vi.stubEnv("HOME", home);
372+
// environment.d changes what services inherit, not where the manager reads units.
373+
vi.stubEnv("XDG_CONFIG_HOME", path.join(home, "service-config"));
374+
vi.stubEnv("T3_BOOT_SERVICE_UNIT", "t3code.service");
375+
376+
yield* Effect.promise(() =>
377+
expect(runLauncher(root)).rejects.toThrow("Active child exited unexpectedly (0)."),
378+
);
379+
380+
assert.equal(yield* fs.readFileString(unitPath), render("1.1.0"));
381+
assert.equal(yield* fs.readFileString(path.join(root, "reloads")), "reload\n");
382+
}),
383+
);
384+
321385
it.effect("keeps the service manager's append log bounded when it starts", () =>
322386
Effect.gen(function* () {
323387
const fs = yield* FileSystem.FileSystem;

‎apps/server/src/serviceLauncher.ts‎

Lines changed: 40 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import {
3535
SERVICE_RESTART_PENDING_FILE,
3636
SERVICE_STOP_MARKER_FILE,
3737
SERVICE_UNIT_ENV,
38+
systemdUnitDirectoryOf,
3839
} from "./cloud/serviceProtocol.ts";
3940
import {
4041
legacyOwnerStartedBeforeRecord,
@@ -123,7 +124,34 @@ export async function registerServiceTask(
123124
}
124125
}
125126

126-
function serviceUnitFromEnvironment(env: NodeJS.ProcessEnv = process.env): ServiceUnit | undefined {
127+
// The manager's environment can differ from the one it gives services (environment.d).
128+
async function readSystemdUnitDirectory(): Promise<string | undefined> {
129+
try {
130+
const { stdout } = await NodeUtil.promisify(NodeChildProcess.execFile)(
131+
"busctl",
132+
[
133+
"--user",
134+
"--json=short",
135+
"get-property",
136+
"org.freedesktop.systemd1",
137+
"/org/freedesktop/systemd1",
138+
"org.freedesktop.systemd1.Manager",
139+
"UnitPath",
140+
],
141+
{ timeout: 5_000 },
142+
);
143+
const { data } = JSON.parse(stdout) as { readonly data?: unknown };
144+
return Array.isArray(data) && data.every((entry) => typeof entry === "string")
145+
? systemdUnitDirectoryOf(data)
146+
: undefined;
147+
} catch {
148+
return undefined;
149+
}
150+
}
151+
152+
async function serviceUnitFromEnvironment(
153+
env: NodeJS.ProcessEnv = process.env,
154+
): Promise<ServiceUnit | undefined> {
127155
const unitName = env[SERVICE_UNIT_ENV]?.trim();
128156
if (!unitName) return undefined;
129157
if (unitName.endsWith(".xml")) {
@@ -141,14 +169,18 @@ function serviceUnitFromEnvironment(env: NodeJS.ProcessEnv = process.env): Servi
141169
reload: () => Promise.resolve(),
142170
};
143171
}
144-
// The manager's own environment, which decides where it reads user units.
145172
const xdgConfigHome = env.XDG_CONFIG_HOME?.trim();
146-
const configHome =
147-
xdgConfigHome && NodePath.isAbsolute(xdgConfigHome)
148-
? xdgConfigHome
149-
: NodePath.join(home, ".config");
173+
const unitDir =
174+
(await readSystemdUnitDirectory()) ??
175+
NodePath.join(
176+
xdgConfigHome && NodePath.isAbsolute(xdgConfigHome)
177+
? xdgConfigHome
178+
: NodePath.join(home, ".config"),
179+
"systemd",
180+
"user",
181+
);
150182
return {
151-
path: NodePath.join(configHome, "systemd", "user", unitName),
183+
path: NodePath.join(unitDir, unitName),
152184
reload: () =>
153185
new Promise((resolve, reject) => {
154186
NodeChildProcess.spawn("systemctl", ["--user", "daemon-reload"], {
@@ -1403,7 +1435,7 @@ export async function main(options: LauncherOptions = {}): Promise<void> {
14031435
throw new Error(`Selected t3@${state.activeVersion} runtime is missing or incomplete.`);
14041436
}
14051437
}
1406-
const serviceUnit = serviceUnitFromEnvironment(managerEnvironment);
1438+
const serviceUnit = await serviceUnitFromEnvironment(managerEnvironment);
14071439
const logPath = await serviceLogPath(options, serviceUnit);
14081440
if (logPath !== undefined) {
14091441
await boundServiceLog(logPath);

0 commit comments

Comments
 (0)