Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion e2e/event-history.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ describe("event history", () => {
expect(grantOf(parseLines(stopped.stdout), leaseId)).toEqual(before);
expect(existsSync(env.socketPath)).toBe(false);
const status = await env.cli(["daemon", "status", "--json"]);
expect(status.json).toEqual({ status: "stopped" });
expect(status.json).toMatchObject({ status: "stopped" });
});

it("simlock events --since 1h after a daemon restart prints each event with the id it had before the restart", async () => {
Expand Down
23 changes: 19 additions & 4 deletions src/cli/commands/daemon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,23 @@ function serviceAccess(
): {
readonly manager: ServiceManager;
readonly definition: () => Promise<ServiceDefinition>;
readonly user: () => string;
} {
const { service } = environment;
if (service?.manager === undefined) {
throw new UsageError(`daemon ${command} is supported on macOS only`);
throw new UsageError(`daemon ${command} is supported on macOS and Linux only`);
}
return { manager: service.manager, definition: service.definition, user: service.user };
}

/** why: a container run with a uid that has no passwd entry makes the lookup throw; the hint is
* advice, so install names a placeholder instead of failing after the service is already in place. */
function userForHint(lookupUser: () => string): string {
try {
return lookupUser();
} catch {
return "<user>";
}
return { manager: service.manager, definition: service.definition };
}

async function serviceReport(
Expand Down Expand Up @@ -118,7 +129,7 @@ async function run(argv: readonly string[], context: CommandContext): Promise<nu
return 0;
}
if (command === "install") {
const { manager, definition } = serviceAccess(environment, "install");
const { manager, definition, user: lookupUser } = serviceAccess(environment, "install");
const service = await definition();
const stopped = await stopRunningDaemon(environment, token);
await manager.install(service);
Expand All @@ -138,7 +149,11 @@ async function run(argv: readonly string[], context: CommandContext): Promise<nu
if (stopped) environment.stdout.write("Stopped the running daemon; leases are kept.\n");
environment.stdout.write(`Service installed: ${service.name} (${manager.manager})\n`);
environment.stdout.write(runningLines(status));
environment.stdout.write("To start after a reboot, turn on automatic login for this user.\n");
environment.stdout.write(
manager.manager === "systemd"
? `To start after a reboot without logging in, run: loginctl enable-linger ${userForHint(lookupUser)}\n`
: "To start after a reboot, turn on automatic login for this user.\n",
);
}
return 0;
}
Expand Down
2 changes: 2 additions & 0 deletions src/cli/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,9 +266,11 @@ export function buildCliEnvironment(
service: {
manager: service.manager,
platform: service.platform,
user: service.user,
definition: async () => {
const { serviceDefinition } = await import("../ports/index.js");
return serviceDefinition({
...(service.manager === undefined ? {} : { manager: service.manager.manager }),
role: daemonHome.role,
root: service.root,
dataDirectory,
Expand Down
85 changes: 75 additions & 10 deletions src/cli/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2001,6 +2001,7 @@ async function runDaemonStatus(
service: {
manager,
platform: manager === undefined ? "linux" : "darwin",
user: () => "me",
definition: async () =>
serviceDefinition({
role: testCase.role,
Expand Down Expand Up @@ -2205,6 +2206,7 @@ describe("CLI: daemon status (ADR 0003 §11)", () => {
},
} as unknown as ServiceManager,
platform: "darwin",
user: () => "me",
definition: async () =>
serviceDefinition({
role: "worker",
Expand Down Expand Up @@ -8653,6 +8655,8 @@ describe("CLI: daemon install (#830)", () => {
readonly role: "worker" | "gateway";
readonly root: string;
readonly env?: NodeJS.ProcessEnv;
readonly linux?: boolean;
readonly user?: () => string;
}): Promise<{
readonly exitCode: number;
readonly output: ReturnType<typeof outputCapture>;
Expand All @@ -8663,6 +8667,7 @@ describe("CLI: daemon install (#830)", () => {
const filesystem = new MemoryFilesystem();
const ipcTransport = new MemoryIpcTransport();
const serviceManager = new FakeServiceManager({
...(options.linux === true ? { manager: "systemd" as const } : {}),
onInstall: async () => {
await startInMemoryDaemon({
adminTokenPath: join(dataDirectory, "admin.token"),
Expand All @@ -8680,7 +8685,15 @@ describe("CLI: daemon install (#830)", () => {
ipc: ipcTransport,
launcher: new FakeDaemonLauncher(),
daemonHome: { role: options.role, dataDirectory, gatewayPresent: false },
service: { manager: serviceManager, platform: "darwin", home, root, nodePath, mainPath },
service: {
manager: serviceManager,
platform: options.linux === true ? "linux" : "darwin",
home: options.linux === true ? "/home/me" : home,
user: options.user ?? (() => "me"),
root,
nodePath,
mainPath,
},
},
options.env,
);
Expand Down Expand Up @@ -8771,6 +8784,58 @@ describe("CLI: daemon install (#830)", () => {
});
});

it("an operator on Linux runs daemon install: the unit lands in the user config directory, and install prints systemd and the linger hint", async () => {
const cases = [
{
label: "default config directory",
env: {},
unit: "/home/me/.config/systemd/user/com.callstack.simlock.worker.service",
},
{
label: "absolute XDG_CONFIG_HOME",
env: { XDG_CONFIG_HOME: "/xdg" },
unit: "/xdg/systemd/user/com.callstack.simlock.worker.service",
},
];
for (const { label, env, unit } of cases) {
const { exitCode, output, serviceManager } = await install({
argv: ["daemon", "install"],
role: "worker",
root: "/home/me/.simlock",
env,
linux: true,
});

expect(output.stderr, label).toBe("");
expect(exitCode, label).toBe(0);
expect(serviceManager.installs[0]?.path, label).toBe(unit);
expect(output.stdout.split("\n").slice(0, 2), label).toEqual([
"Service installed: com.callstack.simlock.worker (systemd)",
"Daemon running",
]);
expect(output.stdout.trimEnd().split("\n").at(-1), label).toBe(
"To start after a reboot without logging in, run: loginctl enable-linger me",
);
}

// why: a uid with no passwd entry makes the user lookup throw; install must still succeed.
const unknownUser = (): string => {
throw new Error("ENOENT: no passwd entry for uid 1234");
};
const lookupFails = await install({
argv: ["daemon", "install"],
role: "worker",
root: "/home/me/.simlock",
linux: true,
user: unknownUser,
});
expect(lookupFails.output.stderr).toBe("");
expect(lookupFails.exitCode).toBe(0);
expect(lookupFails.output.stdout.trimEnd().split("\n").at(-1)).toBe(
"To start after a reboot without logging in, run: loginctl enable-linger <user>",
);
});

async function runWithService(options: {
readonly argv: readonly string[];
readonly running: boolean;
Expand Down Expand Up @@ -8826,6 +8891,7 @@ describe("CLI: daemon install (#830)", () => {
service: {
manager: serviceManager,
platform: "darwin",
user: () => "me",
definition: async () =>
serviceDefinition({
role: "worker",
Expand Down Expand Up @@ -9181,6 +9247,7 @@ describe("CLI: a service manager call fails, or the platform has none (#830)", (
service: {
manager,
platform: options.platform ?? "darwin",
user: () => "me",
home,
root,
nodePath,
Expand All @@ -9200,15 +9267,13 @@ describe("CLI: a service manager call fails, or the platform has none (#830)", (
).error;

it("a failed or stuck launchctl call is SERVICE_FAILED, a failed load removes the plist, and a platform without a service manager is a usage error", async () => {
for (const platform of ["linux", "win32"] as const) {
for (const command of ["install", "uninstall"]) {
const result = await run({ argv: ["daemon", command], platform });
expect(result.exitCode, `${platform} ${command}`).toBe(2);
expect(errorOf(result.stderr), `${platform} ${command}`).toEqual({
code: "USAGE",
message: `daemon ${command} is supported on macOS only`,
});
}
for (const command of ["install", "uninstall"]) {
const result = await run({ argv: ["daemon", command], platform: "win32" });
expect(result.exitCode, `win32 ${command}`).toBe(2);
expect(errorOf(result.stderr), `win32 ${command}`).toEqual({
code: "USAGE",
message: `daemon ${command} is supported on macOS and Linux only`,
});
}

const bootout = {
Expand Down
22 changes: 14 additions & 8 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,14 +91,19 @@ function extractGlobalFlags(argv: readonly string[]): {
* try, where that throw becomes the single structured error line the CLI reference promises instead
* of a raw stack trace. */
async function buildDefaultEnvironment(flag: DaemonFlag): Promise<CliEnvironment> {
const [{ join, dirname }, { fileURLToPath }, ports, { buildCliEnvironment }, { homedir }] =
await Promise.all([
import("node:path"),
import("node:url"),
import("../ports/index.js"),
import("./environment.js"),
import("node:os"),
]);
const [
{ join, dirname },
{ fileURLToPath },
ports,
{ buildCliEnvironment },
{ homedir, userInfo },
] = await Promise.all([
import("node:path"),
import("node:url"),
import("../ports/index.js"),
import("./environment.js"),
import("node:os"),
]);
const {
launcherFor,
NodeFilesystem,
Expand Down Expand Up @@ -138,6 +143,7 @@ async function buildDefaultEnvironment(flag: DaemonFlag): Promise<CliEnvironment
manager: serviceManager,
platform: process.platform,
home: homedir(),
user: () => userInfo().username,
root,
nodePath: process.execPath,
mainPath,
Expand Down
4 changes: 4 additions & 0 deletions src/cli/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ export interface ServiceSetup {
readonly manager: ServiceManager | undefined;
readonly platform: NodeJS.Platform;
readonly home: string;
/** why: read only where the linger hint needs it; the lookup throws for a uid with no passwd entry. */
readonly user: () => string;
readonly root: string;
readonly nodePath: string;
readonly mainPath: string;
Expand All @@ -42,6 +44,8 @@ export interface ServiceSetup {
export interface CliServiceAccess {
readonly manager: ServiceManager | undefined;
readonly platform: NodeJS.Platform;
/** why: read only where the linger hint needs it; the lookup throws for a uid with no passwd entry. */
readonly user: () => string;
readonly definition: () => Promise<ServiceDefinition>;
}

Expand Down
11 changes: 11 additions & 0 deletions src/daemon/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -681,6 +681,17 @@ describe("startDaemon", () => {
}),
]);
expect(productionServiceCheck("gateway", host)).toEqual({});

const systemd = productionServiceCheck("worker", {
...host,
manager: { ...manager, manager: "systemd" },
home: "/home/me",
root: "/home/me/.simlock",
});
await systemd.serviceCheck?.check();
expect(seen.at(-1)?.path).toBe(
"/home/me/.config/systemd/user/com.callstack.simlock.worker.service",
);
});

it("stores lease requests under the configured limits, with failures classified by contract code", async () => {
Expand Down
1 change: 1 addition & 0 deletions src/daemon/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1643,6 +1643,7 @@ export function productionServiceCheck(
): { readonly serviceCheck?: ServiceCheck } {
return serviceCheckFor(role, host.manager, () =>
serviceDefinition({
...(host.manager === undefined ? {} : { manager: host.manager.manager }),
role,
root: host.root,
dataDirectory: daemonDataDirectory(host.root, role),
Expand Down
Loading
Loading