diff --git a/e2e/event-history.test.ts b/e2e/event-history.test.ts index 8a3cf1bfb..cdb878150 100644 --- a/e2e/event-history.test.ts +++ b/e2e/event-history.test.ts @@ -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 () => { diff --git a/src/cli/commands/daemon.ts b/src/cli/commands/daemon.ts index 400031f2b..c6f7df832 100644 --- a/src/cli/commands/daemon.ts +++ b/src/cli/commands/daemon.ts @@ -13,12 +13,23 @@ function serviceAccess( ): { readonly manager: ServiceManager; readonly definition: () => Promise; + 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 ""; } - return { manager: service.manager, definition: service.definition }; } async function serviceReport( @@ -118,7 +129,7 @@ async function run(argv: readonly string[], context: CommandContext): Promise { const { serviceDefinition } = await import("../ports/index.js"); return serviceDefinition({ + ...(service.manager === undefined ? {} : { manager: service.manager.manager }), role: daemonHome.role, root: service.root, dataDirectory, diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 734596c8b..95501732e 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -2001,6 +2001,7 @@ async function runDaemonStatus( service: { manager, platform: manager === undefined ? "linux" : "darwin", + user: () => "me", definition: async () => serviceDefinition({ role: testCase.role, @@ -2205,6 +2206,7 @@ describe("CLI: daemon status (ADR 0003 §11)", () => { }, } as unknown as ServiceManager, platform: "darwin", + user: () => "me", definition: async () => serviceDefinition({ role: "worker", @@ -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; @@ -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"), @@ -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, ); @@ -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 ", + ); + }); + async function runWithService(options: { readonly argv: readonly string[]; readonly running: boolean; @@ -8826,6 +8891,7 @@ describe("CLI: daemon install (#830)", () => { service: { manager: serviceManager, platform: "darwin", + user: () => "me", definition: async () => serviceDefinition({ role: "worker", @@ -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, @@ -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 = { diff --git a/src/cli/index.ts b/src/cli/index.ts index 1cfc9bf34..f113b14de 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -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 { - 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, @@ -138,6 +143,7 @@ async function buildDefaultEnvironment(flag: DaemonFlag): Promise userInfo().username, root, nodePath: process.execPath, mainPath, diff --git a/src/cli/types.ts b/src/cli/types.ts index bda7f6892..1eafd1622 100644 --- a/src/cli/types.ts +++ b/src/cli/types.ts @@ -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; @@ -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; } diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 106a11e74..7cc17db9a 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -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 () => { diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 047c10702..a195e032c 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -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), diff --git a/src/ports/AGENTS.md b/src/ports/AGENTS.md index 816d42f81..0feec39cc 100644 --- a/src/ports/AGENTS.md +++ b/src/ports/AGENTS.md @@ -7,32 +7,32 @@ Uses: nothing from other components. Imported by: every component that touches t ## Ports -| Port | File | Node adapter | Fake | What it covers | -| ------------------------------------------ | --------------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `Clock` | `clock.ts` | `SystemClock` | `FakeClock` | `now`, `setTimer`, `cancel` | -| `Filesystem` | `filesystem.ts` | `NodeFilesystem` | `MemoryFilesystem` | Read, atomic write, stat, delete, disk free | -| `ProcessRunner` | `process-runner.ts` | `NodeProcessRunner` | `ScriptedProcessRunner` | Run or stream a command, capture output | -| (wrapper) | `logging-process-runner.ts` | `LoggingProcessRunner` | — | One `process` log line per command, at `debug` only | -| `ProcessSupervisor` | `process-supervisor.ts` | `NodeProcessSupervisor` | `FakeProcessSupervisor` | Is a pid alive; signal it | -| `ParentWatch` | `parent-watch.ts` | `NodeParentWatch` | `FakeParentWatch` | Call once when a pid exits (polls) | -| `DaemonLauncher` | `daemon-launcher.ts` | `NodeDaemonLauncher` | `FakeDaemonLauncher` | Detached daemon, its log, `DAEMON_STARTUP_TIMEOUT_MS`; `launch()` answers a `LaunchedDaemon` (`exited`, `readOutput` of the log since the launch); `startErrorFrom` | -| `ServiceManager` | `service-manager.ts` | `LaunchdServiceManager` (`productionServiceManager(platform)`; `undefined` where none) | `FakeServiceManager` | A per-user service for one role: `state` (`not-installed`, `installed`, `not-loaded`, `broken`), `install`, `uninstall`, `start` (kickstart); every `launchctl`/`plutil` call has a 10 s limit; `serviceDefinition` builds the name, path, command and saved variables | -| (factory) | `service-launcher.ts` | `launcherFor` | — | The one start choice for the CLI and the MCP server: kickstart a loaded service (`readOutput` is `daemon.log` since the start), else notice and spawn through `NodeDaemonLauncher`; `startTimeoutMessage` adds those lines at the deadline | -| `IpcConnector`, `IpcListenerFactory` | `ipc.ts` | `NodeIpcTransport` | `MemoryIpcTransport` | The daemon's unix socket | -| `UplinkConnector`, `UplinkListenerFactory` | `uplink.ts` | `WebSocketUplinkConnector`, `WebSocketUplinkListenerFactory` | `MemoryUplinkTransport` | A worker's uplink to its gateway | -| `Logger`, `LogSink` | `logger.ts` | `JsonLinesLogger`, `NodeFileLogSink` | `NoopLogger`, `MemoryLogSink` | JSON-line logs, `child(module)`, rotation | -| `SystemStats` | `system-stats.ts` | `NodeSystemStats` | `FakeSystemStats` | CPU count, total RAM | -| `HostInfo` | `host-info.ts` | `NodeHostInfo` | `FakeHostInfo` | OS, version (`sw_vers` on macOS), arch | -| `HostLoadProbe` | `host-load.ts` | `DarwinHostLoadProbe`, `LinuxHostLoadProbe` | `FakeHostLoadProbe` | CPU, memory, disk counters | -| `TcpProbe` | `tcp-probe.ts` | `NodeTcpProbe` | `FakeTcpProbe` | Is a loopback port listening; send bytes | -| `TcpStreamConnector` | `tcp-stream.ts` | `NodeTcpStreamConnector` | `FakeTcpStreamConnector` | A long-lived loopback connection, bytes both ways | -| `BytePipeLauncher` | `byte-pipe.ts` | `NodeBytePipeLauncher` | `FakeBytePipeLauncher` | A child with binary stdout and stdin as its liveness | -| `KeySetFetcher` | `key-set-fetcher.ts` | `NodeKeySetFetcher` | `FakeKeySetFetcher` | One GET of a key-set URL: no redirects, body capped at 64 KiB | -| `SqliteOpener` | `sqlite.ts` | `NodeSqliteOpener` | none; tests use the adapter on a temp file | Open a SQLite file (`:memory:` is not pre-created); `exec`, `prepare`, `close`. `sqlite.ts` also holds `SqliteSchemaOwner` (`name`, `version`, `migrations[i]` takes version `i` to `i + 1`), `passesQuickCheck` and `isLockError` | -| `WebhookPoster` | `webhook-poster.ts` | `FetchWebhookPoster` | `FakeWebhookPoster` (`testing.ts`) | POST to an operator-named URL; a redirect is not followed | -| `IdGenerator` | `id-generator.ts` | `CryptoIdGenerator` | none; tests inline one | Random ids | -| `TokenSecrets` | `token-secrets.ts` | `CryptoTokenSecrets` | none; tests inline one | New secret, its hash | -| Paths | `paths.ts` | `resolveSimlockHome`, `daemonDataDirectory`, `resolveDaemonHome`, `resolveDaemonSocketPath` | — | `SIMLOCK_HOME` (test root; default `~/.simlock`), a gateway in `/gateway`, socket path length; `resolveDaemonHome` picks the folder from the flag (`gateway`, `local`) or, with none, the gateway only when `/gateway/{instance,config}.json` exists and `/instance.json` does not | +| Port | File | Node adapter | Fake | What it covers | +| ------------------------------------------ | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `Clock` | `clock.ts` | `SystemClock` | `FakeClock` | `now`, `setTimer`, `cancel` | +| `Filesystem` | `filesystem.ts` | `NodeFilesystem` | `MemoryFilesystem` | Read, atomic write, stat, delete, disk free | +| `ProcessRunner` | `process-runner.ts` | `NodeProcessRunner` | `ScriptedProcessRunner` | Run or stream a command, capture output | +| (wrapper) | `logging-process-runner.ts` | `LoggingProcessRunner` | — | One `process` log line per command, at `debug` only | +| `ProcessSupervisor` | `process-supervisor.ts` | `NodeProcessSupervisor` | `FakeProcessSupervisor` | Is a pid alive; signal it | +| `ParentWatch` | `parent-watch.ts` | `NodeParentWatch` | `FakeParentWatch` | Call once when a pid exits (polls) | +| `DaemonLauncher` | `daemon-launcher.ts` | `NodeDaemonLauncher` | `FakeDaemonLauncher` | Detached daemon, its log, `DAEMON_STARTUP_TIMEOUT_MS`; `launch()` answers a `LaunchedDaemon` (`exited`, `readOutput` of the log since the launch); `startErrorFrom` | +| `ServiceManager` | `service-manager.ts` | `LaunchdServiceManager`, `SystemdServiceManager` (`productionServiceManager(platform)`: `darwin`, `linux`; `undefined` elsewhere) | `FakeServiceManager` | A per-user service for one role: `state` (`not-installed`, `installed`, `not-loaded`, `broken`), `install`, `uninstall`, `start` (kickstart); every `launchctl`/`plutil`/`systemctl --user` call has a 10 s limit; systemd writes `$XDG_CONFIG_HOME/systemd/user/.service` (absolute only, else `~/.config`); `serviceDefinition` builds the name, path, command and saved variables | +| (factory) | `service-launcher.ts` | `launcherFor` | — | The one start choice for the CLI and the MCP server: kickstart a loaded service (`readOutput` is `daemon.log` since the start), else notice and spawn through `NodeDaemonLauncher`; `startTimeoutMessage` adds those lines at the deadline | +| `IpcConnector`, `IpcListenerFactory` | `ipc.ts` | `NodeIpcTransport` | `MemoryIpcTransport` | The daemon's unix socket | +| `UplinkConnector`, `UplinkListenerFactory` | `uplink.ts` | `WebSocketUplinkConnector`, `WebSocketUplinkListenerFactory` | `MemoryUplinkTransport` | A worker's uplink to its gateway | +| `Logger`, `LogSink` | `logger.ts` | `JsonLinesLogger`, `NodeFileLogSink` | `NoopLogger`, `MemoryLogSink` | JSON-line logs, `child(module)`, rotation | +| `SystemStats` | `system-stats.ts` | `NodeSystemStats` | `FakeSystemStats` | CPU count, total RAM | +| `HostInfo` | `host-info.ts` | `NodeHostInfo` | `FakeHostInfo` | OS, version (`sw_vers` on macOS), arch | +| `HostLoadProbe` | `host-load.ts` | `DarwinHostLoadProbe`, `LinuxHostLoadProbe` | `FakeHostLoadProbe` | CPU, memory, disk counters | +| `TcpProbe` | `tcp-probe.ts` | `NodeTcpProbe` | `FakeTcpProbe` | Is a loopback port listening; send bytes | +| `TcpStreamConnector` | `tcp-stream.ts` | `NodeTcpStreamConnector` | `FakeTcpStreamConnector` | A long-lived loopback connection, bytes both ways | +| `BytePipeLauncher` | `byte-pipe.ts` | `NodeBytePipeLauncher` | `FakeBytePipeLauncher` | A child with binary stdout and stdin as its liveness | +| `KeySetFetcher` | `key-set-fetcher.ts` | `NodeKeySetFetcher` | `FakeKeySetFetcher` | One GET of a key-set URL: no redirects, body capped at 64 KiB | +| `SqliteOpener` | `sqlite.ts` | `NodeSqliteOpener` | none; tests use the adapter on a temp file | Open a SQLite file (`:memory:` is not pre-created); `exec`, `prepare`, `close`. `sqlite.ts` also holds `SqliteSchemaOwner` (`name`, `version`, `migrations[i]` takes version `i` to `i + 1`), `passesQuickCheck` and `isLockError` | +| `WebhookPoster` | `webhook-poster.ts` | `FetchWebhookPoster` | `FakeWebhookPoster` (`testing.ts`) | POST to an operator-named URL; a redirect is not followed | +| `IdGenerator` | `id-generator.ts` | `CryptoIdGenerator` | none; tests inline one | Random ids | +| `TokenSecrets` | `token-secrets.ts` | `CryptoTokenSecrets` | none; tests inline one | New secret, its hash | +| Paths | `paths.ts` | `resolveSimlockHome`, `daemonDataDirectory`, `resolveDaemonHome`, `resolveDaemonSocketPath` | — | `SIMLOCK_HOME` (test root; default `~/.simlock`), a gateway in `/gateway`, socket path length; `resolveDaemonHome` picks the folder from the flag (`gateway`, `local`) or, with none, the gateway only when `/gateway/{instance,config}.json` exists and `/instance.json` does not | `productionHostLoadProbe` picks the Darwin or Linux probe. `NodeFileLogSink` rotates to `.1` and keeps that one generation; the files it opens, and the log `NodeDaemonLauncher` diff --git a/src/ports/daemon-launcher.test.ts b/src/ports/daemon-launcher.test.ts index 151351b9b..179024a3a 100644 --- a/src/ports/daemon-launcher.test.ts +++ b/src/ports/daemon-launcher.test.ts @@ -303,3 +303,41 @@ describe("launcherFor's fallback to spawning", () => { } }); }); + +describe("launcherFor with an installed service", () => { + it("starts an installed service through the manager that owns it, with that manager's definition", async () => { + const cases = [ + { manager: "systemd" as const, path: "/home/me/.config/systemd/user/" }, + { manager: "launchd" as const, path: "/home/me/Library/LaunchAgents/" }, + ]; + for (const testCase of cases) { + const serviceManager = new FakeServiceManager({ + manager: testCase.manager, + state: { state: "installed", path: testCase.path }, + }); + const spawner = new FakeDaemonLauncher(); + const launcher = launcherFor({ + role: "worker", + root: "/home/me/.simlock", + dataDirectory: "/home/me/.simlock", + mainPath: "/opt/simlock/dist/daemon/main.js", + nodePath: "/opt/node/bin/node", + home: "/home/me", + env: {}, + serviceManager, + notify: () => undefined, + spawner, + }); + + await launcher.launch(); + + expect(spawner.launches, testCase.manager).toBe(0); + expect( + serviceManager.starts.map((definition) => definition.path), + testCase.manager, + ).toEqual([ + `${testCase.path}com.callstack.simlock.worker.${testCase.manager === "systemd" ? "service" : "plist"}`, + ]); + } + }); +}); diff --git a/src/ports/service-launcher.ts b/src/ports/service-launcher.ts index c764b64df..2bb84d980 100644 --- a/src/ports/service-launcher.ts +++ b/src/ports/service-launcher.ts @@ -35,6 +35,7 @@ export function launcherFor(options: LauncherForOptions): DaemonLauncher { const { serviceManager } = options; if (serviceManager === undefined) return spawner; const definition = serviceDefinition({ + manager: serviceManager.manager, role: options.role, root: options.root, dataDirectory: options.dataDirectory, diff --git a/src/ports/service-manager.test.ts b/src/ports/service-manager.test.ts index 6bdad0894..786e38155 100644 --- a/src/ports/service-manager.test.ts +++ b/src/ports/service-manager.test.ts @@ -3,10 +3,16 @@ import { dirname } from "node:path"; import { describe, expect, it } from "vitest"; import { MemoryFilesystem } from "./filesystem.js"; -import { ScriptedProcessRunner } from "./process-runner.js"; +import { + ScriptedProcessRunner, + type ProcessResult, + type ProcessRunner, + type ProcessRunOptions, +} from "./process-runner.js"; import { LaunchdServiceManager, productionServiceManager, + SystemdServiceManager, serviceDefinition, ServiceFailedError, type ServiceDefinition, @@ -335,14 +341,14 @@ describe("LaunchdServiceManager (#830)", () => { await expect(install).rejects.toThrow("denied"); }); - it("productionServiceManager is the launchd adapter on macOS and nothing elsewhere", () => { + it("productionServiceManager is the launchd adapter on macOS, the systemd adapter on Linux and nothing elsewhere", () => { const dependencies = { runner: new ScriptedProcessRunner([]), filesystem: new MemoryFilesystem(), uid: 501, }; expect(productionServiceManager("darwin", dependencies)).toBeInstanceOf(LaunchdServiceManager); - expect(productionServiceManager("linux", dependencies)).toBeUndefined(); + expect(productionServiceManager("linux", dependencies)).toBeInstanceOf(SystemdServiceManager); expect(productionServiceManager("win32", dependencies)).toBeUndefined(); }); @@ -363,3 +369,346 @@ describe("LaunchdServiceManager (#830)", () => { expect(runner.calls[0]?.options.timeoutMs).toBe(10_000); }); }); + +const linuxHome = "/home/me"; +const linuxRoot = "/home/me/.simlock"; + +function systemdDefinition( + role: "worker" | "gateway", + env: NodeJS.ProcessEnv = {}, +): ServiceDefinition { + return serviceDefinition({ + manager: "systemd", + role, + root: linuxRoot, + dataDirectory: role === "gateway" ? `${linuxRoot}/gateway` : linuxRoot, + home: linuxHome, + nodePath: "/usr/bin/node", + mainPath: "/opt/simlock/dist/daemon/main.js", + env, + }); +} + +type Unit = Record>; + +// why: the test reads the unit the way systemd does, as sections of keys that may repeat, so it +// does not depend on the order or the spacing the adapter writes. +function parseUnit(text: string): Unit { + const unit: Unit = {}; + let section = ""; + for (const line of text.split("\n")) { + const header = /^\[(\w+)\]$/.exec(line); + if (header !== null) { + section = header[1] ?? ""; + unit[section] = {}; + } else if (line.includes("=") && section !== "") { + const [key = "", ...rest] = line.split("="); + (unit[section]![key] ??= []).push(rest.join("=")); + } + } + return unit; +} + +const bus = "Failed to connect to bus: No medium found"; +const systemctl = (...args: string[]) => ({ command: "systemctl", args: ["--user", ...args] }); +const reply = (code: number, stdout = "", stderr = "") => ({ code, stdout, stderr }); + +class MissingSystemctlRunner implements ProcessRunner { + readonly calls: string[] = []; + async run( + command: string, + args: readonly string[], + _options?: ProcessRunOptions, + ): Promise { + this.calls.push([command, ...args].join(" ")); + throw Object.assign(new Error(`spawn ${command} ENOENT`), { code: "ENOENT" }); + } + spawn(): never { + throw new Error("unused"); + } + spawnStreaming(): never { + throw new Error("unused"); + } +} + +describe("SystemdServiceManager (#832)", () => { + const definition = systemdDefinition("worker"); + const unit = `${definition.name}.service`; + + async function put(filesystem: MemoryFilesystem, path: string, text = ""): Promise { + await filesystem.mkdirp(dirname(path)); + await filesystem.writeFileAtomic(path, text); + } + + async function checkUnitText(): Promise { + const saved = { PATH: "/usr/bin:/opt/bin", ANDROID_HOME: "/sdk", JAVA_HOME: "/jdk" }; + const textCases = [ + { + label: "worker, saved variables set, secrets in the shell", + role: "worker" as const, + env: { ...saved, SIMLOCK_ADMIN_TOKEN: "secret" }, + execStart: "/usr/bin/node /opt/simlock/dist/daemon/main.js", + environment: [ + `"SIMLOCK_HOME=${linuxRoot}"`, + '"PATH=/usr/bin:/opt/bin"', + '"ANDROID_HOME=/sdk"', + '"JAVA_HOME=/jdk"', + ], + log: `append:${linuxRoot}/daemon.log`, + }, + { + label: "gateway, no variable set", + role: "gateway" as const, + env: {}, + execStart: "/usr/bin/node /opt/simlock/dist/daemon/main.js --gateway", + environment: [`"SIMLOCK_HOME=${linuxRoot}"`], + log: `append:${linuxRoot}/gateway/daemon.log`, + }, + ]; + for (const testCase of textCases) { + const definition = systemdDefinition(testCase.role, testCase.env); + const filesystem = new MemoryFilesystem(); + const runner = new ScriptedProcessRunner([ + { match: systemctl("daemon-reload"), result: reply(0) }, + { match: systemctl("enable", "--now", `${definition.name}.service`), result: reply(0) }, + ]); + + await new SystemdServiceManager({ runner, filesystem }).install(definition); + + expect(await filesystem.exists(definition.path), `${testCase.label}: unit exists`).toBe(true); + expect(parseUnit(await filesystem.readFile(definition.path)), testCase.label).toEqual({ + Unit: { Description: [`simlock ${testCase.role} daemon`], StartLimitIntervalSec: ["0"] }, + Service: { + ExecStart: [testCase.execStart], + Environment: testCase.environment, + Restart: ["on-failure"], + RestartSec: ["10"], + KillMode: ["process"], + TimeoutStopSec: ["300"], + StandardOutput: [testCase.log], + StandardError: [testCase.log], + }, + Install: { WantedBy: ["default.target"] }, + }); + expect( + runner.calls.map((call) => call.args.join(" ")), + testCase.label, + ).toEqual(["--user daemon-reload", `--user enable --now ${definition.name}.service`]); + for (const call of runner.calls) expect(call.options.timeoutMs, testCase.label).toBe(10_000); + expect((await filesystem.stat(definition.logPath)).mode, testCase.label).toBe(0o600); + } + } + + function checkUnitPath(): void { + const name = systemdDefinition("worker").name; + const pathCases = [ + { xdg: "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/xdg/config", path: `/xdg/config/systemd/user/${name}.service` }, + { xdg: "relative/config", path: `${linuxHome}/.config/systemd/user/${name}.service` }, + { xdg: undefined, path: `${linuxHome}/.config/systemd/user/${name}.service` }, + ]; + for (const testCase of pathCases) { + const env = testCase.xdg === undefined ? {} : { XDG_CONFIG_HOME: testCase.xdg }; + expect(systemdDefinition("worker", env).path, String(testCase.xdg)).toBe(testCase.path); + } + } + + async function checkStart(): Promise { + const started = new ScriptedProcessRunner([ + { match: systemctl("start", unit), result: reply(0) }, + ]); + await new SystemdServiceManager({ runner: started, filesystem: new MemoryFilesystem() }).start( + definition, + ); + expect(started.calls[0]?.options.timeoutMs).toBe(10_000); + const refused = new SystemdServiceManager({ + runner: new ScriptedProcessRunner([ + { match: systemctl("start", unit), result: reply(1, "", "Unit not found.\nsecond") }, + ]), + filesystem: new MemoryFilesystem(), + }).start(definition); + await expect(refused).rejects.toBeInstanceOf(ServiceFailedError); + await expect(refused).rejects.toThrow(`systemctl --user start ${unit} failed: Unit not found.`); + } + + async function checkInstallFailures(): Promise { + const failures = [ + { + label: "no user bus", + runner: new ScriptedProcessRunner([ + { match: systemctl("daemon-reload"), result: reply(1, "", `${bus}\nmore`) }, + ]), + message: `systemctl --user daemon-reload failed: ${bus}`, + }, + { + label: "enable refused", + runner: new ScriptedProcessRunner([ + { match: systemctl("daemon-reload"), result: reply(0) }, + { match: systemctl("enable", "--now", unit), result: reply(1, "", "Boom") }, + ]), + message: `systemctl --user enable --now ${unit} failed: Boom`, + }, + { + label: "systemctl missing", + runner: new MissingSystemctlRunner(), + message: "systemctl --user daemon-reload failed: spawn systemctl ENOENT", + }, + ]; + for (const testCase of failures) { + const filesystem = new MemoryFilesystem(); + const install = new SystemdServiceManager({ runner: testCase.runner, filesystem }).install( + definition, + ); + await expect(install, testCase.label).rejects.toBeInstanceOf(ServiceFailedError); + await expect(install, testCase.label).rejects.toThrow(testCase.message); + expect(await filesystem.exists(definition.path), testCase.label).toBe(false); + } + } + + async function checkStates(): Promise { + const node = definition.command; + const main = definition.args[0] ?? ""; + const isEnabled = (result: ReturnType) => ({ + match: systemctl("is-enabled", unit), + result, + }); + const unitText = (execStart: string) => `[Service]\nExecStart=${execStart}\n`; + const stateCases = [ + { + label: "no unit file", + present: [], + text: undefined, + script: [], + state: { state: "not-installed" }, + }, + { + label: "Node path gone", + present: [main], + text: unitText(`${node} ${main}`), + script: [], + state: { state: "broken", path: definition.path, missing: [node] }, + }, + { + label: "both paths gone", + present: [], + text: unitText(`${node} ${main}`), + script: [], + state: { state: "broken", path: definition.path, missing: [node, main] }, + }, + { + label: "no readable ExecStart", + present: [node, main], + text: "[Service]\nRestart=on-failure\n", + script: [], + state: { state: "broken", path: definition.path, missing: [definition.path] }, + }, + { + label: "enabled", + present: [node, main], + text: unitText(`${node} ${main}`), + script: [isEnabled(reply(0, "enabled\n"))], + state: { state: "installed", path: definition.path }, + }, + { + label: "disabled", + present: [node, main], + text: unitText(`${node} ${main}`), + script: [isEnabled(reply(1, "disabled\n"))], + state: { state: "not-loaded", path: definition.path }, + }, + { + label: "no user bus", + present: [node, main], + text: unitText(`${node} ${main}`), + script: [isEnabled(reply(1, "", bus))], + state: { state: "not-loaded", path: definition.path }, + }, + ]; + const filesystem = new MemoryFilesystem(); + for (const path of [node, main]) await put(filesystem, path); + await put(filesystem, definition.path, unitText(`${node} ${main}`)); + const missing = new MissingSystemctlRunner(); + expect( + await new SystemdServiceManager({ runner: missing, filesystem }).state(definition), + "systemctl missing", + ).toEqual({ state: "not-loaded", path: definition.path }); + for (const testCase of stateCases) { + const filesystem = new MemoryFilesystem(); + for (const present of testCase.present) await put(filesystem, present); + if (testCase.text !== undefined) await put(filesystem, definition.path, testCase.text); + const runner = new ScriptedProcessRunner(testCase.script); + + const state = await new SystemdServiceManager({ runner, filesystem }).state(definition); + + expect(state, testCase.label).toEqual(testCase.state); + expect(runner.calls.length, testCase.label).toBe(testCase.script.length); + for (const call of runner.calls) expect(call.options.timeoutMs, testCase.label).toBe(10_000); + } + } + + async function checkUninstall(): Promise { + const removal = new MemoryFilesystem(); + await put(removal, definition.path, "[Service]\n"); + const removeRunner = new ScriptedProcessRunner([ + { match: systemctl("disable", "--now", unit), result: reply(0) }, + { match: systemctl("daemon-reload"), result: reply(0) }, + ]); + await new SystemdServiceManager({ runner: removeRunner, filesystem: removal }).uninstall( + definition, + ); + expect(removeRunner.calls.map((call) => call.args.join(" "))).toEqual([ + `--user disable --now ${unit}`, + "--user daemon-reload", + ]); + expect(await removal.exists(definition.path)).toBe(false); + + const kept = new MemoryFilesystem(); + await put(kept, definition.path, "[Service]\n"); + const refusal = new SystemdServiceManager({ + runner: new ScriptedProcessRunner([ + { match: systemctl("disable", "--now", unit), result: reply(1, "", "Nope") }, + ]), + filesystem: kept, + }).uninstall(definition); + await expect(refusal).rejects.toBeInstanceOf(ServiceFailedError); + await expect(refusal).rejects.toThrow(`systemctl --user disable --now ${unit} failed: Nope`); + expect(await kept.exists(definition.path)).toBe(true); + + const reloadFails = new MemoryFilesystem(); + await put(reloadFails, definition.path, "[Service]\nExecStart=a b\n"); + const reload = new SystemdServiceManager({ + runner: new ScriptedProcessRunner([ + { match: systemctl("disable", "--now", unit), result: reply(0) }, + { match: systemctl("daemon-reload"), result: reply(1, "", "Reload refused") }, + ]), + filesystem: reloadFails, + }).uninstall(definition); + await expect(reload).rejects.toThrow(`systemctl --user daemon-reload failed: Reload refused`); + expect(await reloadFails.readFile(definition.path)).toBe("[Service]\nExecStart=a b\n"); + + const stuck = new MemoryFilesystem(); + await put(stuck, definition.path, "[Service]\n"); + const timeout = new SystemdServiceManager({ + runner: new ScriptedProcessRunner([ + { + match: systemctl("disable", "--now", unit), + result: { code: null, stdout: "", stderr: "" }, + }, + ]), + filesystem: stuck, + }).uninstall(definition); + await expect(timeout).rejects.toBeInstanceOf(ServiceFailedError); + await expect(timeout).rejects.toThrow( + `systemctl --user disable --now ${unit} did not finish within 10 s`, + ); + expect(await stuck.exists(definition.path)).toBe(true); + } + + it("an operator on Linux installs, starts and removes a systemd user unit", async () => { + await checkUnitText(); + checkUnitPath(); + await checkStart(); + await checkInstallFailures(); + await checkStates(); + await checkUninstall(); + }); +}); diff --git a/src/ports/service-manager.ts b/src/ports/service-manager.ts index cf3a5d6ba..5f62b39dc 100644 --- a/src/ports/service-manager.ts +++ b/src/ports/service-manager.ts @@ -1,5 +1,5 @@ import { createHash } from "node:crypto"; -import { dirname, join } from "node:path"; +import { dirname, isAbsolute, join } from "node:path"; import type { Filesystem } from "./filesystem.js"; import type { DaemonRole } from "./paths.js"; @@ -21,6 +21,7 @@ export interface ServiceDefinition { } export interface ServiceDefinitionInput { + readonly manager?: ServiceManagerName; readonly role: DaemonRole; readonly root: string; readonly dataDirectory: string; @@ -47,19 +48,30 @@ function homeHash(root: string): string { return createHash("sha256").update(root).digest("hex").slice(0, 6); } +function unitDirectory(input: ServiceDefinitionInput): string { + const configured = input.env.XDG_CONFIG_HOME; + const config = + configured !== undefined && isAbsolute(configured) ? configured : join(input.home, ".config"); + return join(config, "systemd", "user"); +} + export function serviceDefinition(input: ServiceDefinitionInput): ServiceDefinition { const environment: Record = { SIMLOCK_HOME: input.root }; for (const variable of SAVED_VARIABLES) { const value = input.env[variable]; if (value !== undefined) environment[variable] = value; } + const manager = input.manager ?? "launchd"; const base = `com.callstack.simlock.${input.role}`; const name = input.root === join(input.home, ".simlock") ? base : `${base}.${homeHash(input.root)}`; return { role: input.role, name, - path: join(input.home, "Library", "LaunchAgents", `${name}.plist`), + path: + manager === "systemd" + ? join(unitDirectory(input), `${name}.service`) + : join(input.home, "Library", "LaunchAgents", `${name}.plist`), command: input.nodePath, args: [input.mainPath, ...(input.role === "gateway" ? ["--gateway"] : [])], environment, @@ -194,6 +206,15 @@ function isExistsError(error: unknown): boolean { return typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST"; } +async function ensureLog(filesystem: Filesystem, logPath: string): Promise { + await filesystem.mkdirp(dirname(logPath)); + try { + await filesystem.writeFileExclusive(logPath, "", { mode: 0o600 }); + } catch (error: unknown) { + if (!isExistsError(error)) throw error; + } +} + export class LaunchdServiceManager implements ServiceManager { readonly manager = "launchd"; @@ -234,12 +255,7 @@ export class LaunchdServiceManager implements ServiceManager { async install(definition: ServiceDefinition): Promise { const { filesystem } = this.options; await this.launchctl(["bootout", `${this.domain()}/${definition.name}`]); - await filesystem.mkdirp(dirname(definition.logPath)); - try { - await filesystem.writeFileExclusive(definition.logPath, "", { mode: 0o600 }); - } catch (error: unknown) { - if (!isExistsError(error)) throw error; - } + await ensureLog(filesystem, definition.logPath); await filesystem.mkdirp(dirname(definition.path)); await filesystem.writeFileAtomic(definition.path, plistFor(definition)); const bootstrapArgs = ["bootstrap", this.domain(), definition.path]; @@ -264,6 +280,117 @@ export class LaunchdServiceManager implements ServiceManager { } } +export interface SystemdServiceManagerOptions { + readonly runner: ProcessRunner; + readonly filesystem: Filesystem; +} + +function unitFor(definition: ServiceDefinition): string { + const variables = Object.entries(definition.environment) + .map(([key, value]) => `Environment="${key}=${value}"`) + .join("\n"); + return `[Unit] +Description=simlock ${definition.role} daemon +StartLimitIntervalSec=0 + +[Service] +ExecStart=${[definition.command, ...definition.args].join(" ")} +${variables} +Restart=on-failure +RestartSec=10 +KillMode=process +TimeoutStopSec=${String(STOP_LIMIT_SECONDS)} +StandardOutput=append:${definition.logPath} +StandardError=append:${definition.logPath} + +[Install] +WantedBy=default.target +`; +} + +function savedUnitPaths(unit: string): readonly string[] { + const line = unit.split("\n").find((candidate) => candidate.startsWith("ExecStart=")); + return (line?.slice("ExecStart=".length).trim().split(/\s+/) ?? []) + .slice(0, 2) + .filter((path) => path !== ""); +} + +export class SystemdServiceManager implements ServiceManager { + readonly manager = "systemd"; + + constructor(private readonly options: SystemdServiceManagerOptions) {} + + private async systemctl(args: readonly string[]): Promise { + const userArgs = ["--user", ...args]; + let result: ProcessResult; + try { + result = await this.options.runner.run("systemctl", userArgs, { + timeoutMs: LAUNCHCTL_TIMEOUT_MS, + }); + } catch (error: unknown) { + const reason = error instanceof Error ? error.message : String(error); + throw new ServiceFailedError(`systemctl ${userArgs.join(" ")} failed: ${reason}`); + } + if (result.code === null) { + throw new ServiceFailedError(`systemctl ${userArgs.join(" ")} did not finish within 10 s`); + } + return result; + } + + private async checked(args: readonly string[]): Promise { + const result = await this.systemctl(args); + if (result.code !== 0) failure("systemctl", ["--user", ...args], result); + } + + async state(definition: ServiceDefinition): Promise { + const { filesystem } = this.options; + if (!(await filesystem.exists(definition.path))) return { state: "not-installed" }; + const saved = savedUnitPaths(await filesystem.readFile(definition.path)); + if (saved.length === 0) { + return { state: "broken", path: definition.path, missing: [definition.path] }; + } + const missing: string[] = []; + for (const path of saved) if (!(await filesystem.exists(path))) missing.push(path); + if (missing.length > 0) return { state: "broken", path: definition.path, missing }; + const enabled = await this.systemctl(["is-enabled", `${definition.name}.service`]).catch( + () => undefined, + ); + const loaded = enabled?.code === 0 && enabled.stdout.trim() === "enabled"; + return { state: loaded ? "installed" : "not-loaded", path: definition.path }; + } + + async install(definition: ServiceDefinition): Promise { + const { filesystem } = this.options; + await ensureLog(filesystem, definition.logPath); + await filesystem.mkdirp(dirname(definition.path)); + await filesystem.writeFileAtomic(definition.path, unitFor(definition)); + try { + await this.checked(["daemon-reload"]); + await this.checked(["enable", "--now", `${definition.name}.service`]); + } catch (error: unknown) { + await filesystem.rm(definition.path); + throw error; + } + } + + async uninstall(definition: ServiceDefinition): Promise { + await this.checked(["disable", "--now", `${definition.name}.service`]); + const { filesystem } = this.options; + const text = await filesystem.readFile(definition.path); + await filesystem.rm(definition.path); + try { + await this.checked(["daemon-reload"]); + } catch (error: unknown) { + await filesystem.writeFileAtomic(definition.path, text); + throw error; + } + } + + async start(definition: ServiceDefinition): Promise { + await this.checked(["start", `${definition.name}.service`]); + } +} + export function productionServiceManager( platform: NodeJS.Platform, dependencies: { @@ -272,5 +399,6 @@ export function productionServiceManager( readonly uid: number; }, ): ServiceManager | undefined { + if (platform === "linux") return new SystemdServiceManager(dependencies); return platform === "darwin" ? new LaunchdServiceManager(dependencies) : undefined; } diff --git a/website/src/content/docs/docs/reference/cli.mdx b/website/src/content/docs/docs/reference/cli.mdx index 05b28386c..098f93d8e 100644 --- a/website/src/content/docs/docs/reference/cli.mdx +++ b/website/src/content/docs/docs/reference/cli.mdx @@ -293,10 +293,10 @@ simlock daemon uninstall [--json] | --- | --- | | `start` | Start the daemon if it is not running and print `Daemon running` with the console address. `simlock --gateway daemon start` creates the gateway on first run. | | `stop` | Ask the daemon to stop and print `Daemon stopping`. Needs the admin role. Never starts a daemon. | -| `status` | Print the daemon's status, or `Daemon stopped` when none is running, then on macOS one `Service:` line: `not installed`, `installed (launchd, )`, `not loaded (launchd, ): commands start the daemon without it` or `broken (launchd, ): is gone; run simlock daemon install` (`, are gone` for two). Never starts a daemon. Exits 1 when a daemon answers but refuses the connection, with no `Service:` line. | +| `status` | Print the daemon's status, or `Daemon stopped` when none is running, then on macOS and Linux one `Service:` line: `not installed`, `installed (launchd, )`, `not loaded (launchd, ): commands start the daemon without it` or `broken (launchd, ): is gone; run simlock daemon install` (`, are gone` for two). Never starts a daemon. Exits 1 when a daemon answers but refuses the connection, with no `Service:` line. | | `logs` | Print the last 100 lines of `daemon.log`. | -| `install` | macOS only. Stop a running daemon (leases are kept), add a LaunchAgent for this role and start the daemon through it. Prints `Service installed: (launchd)`, `Daemon running` and the hint `To start after a reboot, turn on automatic login for this user.` On another platform it is a usage error: `daemon install is supported on macOS only`. | -| `uninstall` | Stop a running daemon, unload the LaunchAgent and delete its file. Prints `Service removed: (launchd)`, or `Service not installed: ` when there is none (exit 0). | +| `install` | macOS and Linux only. Stop a running daemon (leases are kept), add a LaunchAgent (macOS) or a systemd user unit at `$XDG_CONFIG_HOME/systemd/user/.service`, else `~/.config/systemd/user/.service` (Linux) for this role and start the daemon through it. Prints `Service installed: (launchd)` or `(systemd)`, `Daemon running` and a hint: `To start after a reboot, turn on automatic login for this user.` on macOS, `To start after a reboot without logging in, run: loginctl enable-linger ` on Linux. Without linger the last logout stops the user's systemd, the daemon and its emulators with it. On another platform it is a usage error: `daemon install is supported on macOS and Linux only`. | +| `uninstall` | Stop a running daemon, unload the LaunchAgent or systemd unit and delete its file. Prints `Service removed: (launchd)`, or `Service not installed: ` when there is none (exit 0). | | Flag | Meaning | Default | | --- | --- | --- | diff --git a/website/src/content/docs/docs/worker/running-the-daemon.mdx b/website/src/content/docs/docs/worker/running-the-daemon.mdx index 9b8c01bb1..2b26fe084 100644 --- a/website/src/content/docs/docs/worker/running-the-daemon.mdx +++ b/website/src/content/docs/docs/worker/running-the-daemon.mdx @@ -28,7 +28,7 @@ Console: http://127.0.0.1:4701/ If the daemon is already running, `daemon start` does nothing and prints the same lines. A daemon process started by hand beside a running one logs `Daemon already running` to `daemon.log` and exits 0. -The daemon runs detached from your terminal: closing the terminal does not stop it. Without a service, it does not survive a reboot. See [Start at login](#start-at-login-macos). +The daemon runs detached from your terminal: closing the terminal does not stop it. Without a service, it does not survive a reboot. See [Start at login (macOS)](#start-at-login-macos) and [Start at login (Linux)](#start-at-login-linux). ## Start at login (macOS) @@ -57,7 +57,25 @@ If a start through the service fails, the command reports `DAEMON_STARTUP_FAILED simlock daemon uninstall ``` -stops the daemon, unloads the service and deletes its file, and prints `Service removed: (launchd)`. On Linux and Windows both commands are a usage error. +stops the daemon, unloads the service and deletes its file, and prints `Service removed: (launchd)`. On Linux it unloads and removes the systemd user unit (see below). On Windows both commands are a usage error. + +## Start at login (Linux) + +```sh +simlock daemon install +``` + +```text +Service installed: com.callstack.simlock.worker (systemd) +Daemon running +To start after a reboot without logging in, run: loginctl enable-linger +``` + +This writes a systemd user unit to `$XDG_CONFIG_HOME/systemd/user/.service` (when `XDG_CONFIG_HOME` is an absolute path, else `~/.config/systemd/user/.service`), runs `systemctl --user daemon-reload` and `systemctl --user enable --now .service`. The name is the one the macOS service gets. The unit holds `ExecStart` (Node and `main.js`, plus `--gateway` for a gateway), one `Environment=` line per saved variable that is set, `Restart=on-failure`, `RestartSec=10`, `StartLimitIntervalSec=0`, `KillMode=process`, `TimeoutStopSec=300`, and `StandardOutput` and `StandardError` appended to `daemon.log`. systemd runs the daemon whenever the user has a session, or always with linger, and starts it again 10 seconds after a failure exit. + +Stopping the unit kills only the daemon, so emulators it booted keep running. Without linger, the last logout stops the user's whole systemd, and the daemon and its emulators with it. Run `loginctl enable-linger ` to keep them. Simlock does not turn linger on. + +With no user bus (no session and no linger), `daemon install` fails with `SERVICE_FAILED` (`systemctl --user daemon-reload failed: Failed to connect to bus: ...`) and removes the unit file. Other commands then start the daemon without the service and say `Service is not loaded; started the daemon without it.` The `Service:` line reads `not loaded (systemd, )`. If a start through the service fails, the command reports `DAEMON_STARTUP_FAILED` as on macOS; if `systemctl` fails, `SERVICE_FAILED`. ## Check whether it is running @@ -73,7 +91,7 @@ Daemon: running (worker) `starting` means it is still reading the machine's devices; devices, leases and capacity appear once it finishes. See [Monitoring](/simlock/docs/worker/monitoring) for the rest of the report. -On macOS the last line says what state the service is in, whether the daemon runs or not: +On macOS and Linux the last line says what state the service is in, whether the daemon runs or not: ```text Service: not installed @@ -82,9 +100,9 @@ Service: not loaded (launchd, com.callstack.simlock.worker): commands start the Service: broken (launchd, com.callstack.simlock.worker): /Users/me/.nvm/versions/node/v22.13.0/bin/node is gone; run simlock daemon install ``` -`not loaded` is what you see over SSH with nobody logged in at the screen. `broken` means the service names a Node or `main.js` that is gone, for example after an nvm or Homebrew upgrade; with two paths gone the line reads `, are gone`. On another platform there is no `Service:` line. A gateway prints its own service name. +`not loaded` is what you see over SSH with nobody logged in at the screen. `broken` means the service names a Node or `main.js` that is gone, for example after an nvm or Homebrew upgrade; with two paths gone the line reads `, are gone`. On another platform there is no `Service:` line. On Linux the manager reads `systemd`. A gateway prints its own service name. -Add `--json` for a machine-readable answer: `{"status":"stopped"}` when nothing runs. On macOS the answer gains a `service` field, for example `{"status":"stopped","service":{"state":"broken","manager":"launchd","name":"com.callstack.simlock.worker","path":"/Users/me/Library/LaunchAgents/com.callstack.simlock.worker.plist","missing":["/Users/me/.nvm/versions/node/v22.13.0/bin/node"]}}`. `state` is `not-installed`, `installed`, `not-loaded` or `broken`; `path` is absent when not installed and `missing` appears only when broken. +Add `--json` for a machine-readable answer: `{"status":"stopped"}` when nothing runs. On macOS and Linux the answer gains a `service` field, for example `{"status":"stopped","service":{"state":"broken","manager":"launchd","name":"com.callstack.simlock.worker","path":"/Users/me/Library/LaunchAgents/com.callstack.simlock.worker.plist","missing":["/Users/me/.nvm/versions/node/v22.13.0/bin/node"]}}`. `state` is `not-installed`, `installed`, `not-loaded` or `broken`; `path` is absent when not installed and `missing` appears only when broken. ## Stop the daemon