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
10 changes: 10 additions & 0 deletions .changeset/install-checks-linger.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'local-review': patch
---

**`service install` checks linger on Linux** (cli-contract SPEC §7) instead of always printing a reminder. It asks
`loginctl show-user <user> -p Linger`, and only when linger is off does it say why it matters (the service stops when
you log out) and print `sudo loginctl enable-linger <user>`, the same line `doctor` gives. It never runs `sudo`. When
linger is on, or `loginctl` can't answer (no logind, a container), it says nothing about it. With `--json`, the
advice is in the document's `warnings`. The old reminder line, `loginctl enable-linger $USER` without `sudo`, has
gone from the install output.
15 changes: 2 additions & 13 deletions server/doctor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,8 @@
//
// It only reads, apart from <data>/update-check.json: like `update --check`, it writes what it found there, so
// `service status` can repeat it (SPEC §3). It asks the npm registry only because a person ran it; --offline doesn't.
import { execFile } from 'node:child_process';
import fs from 'node:fs';
import net from 'node:net';
import os from 'node:os';
import path from 'node:path';
import { describeInstall, detectInstall, updateCommand, type InstallInfo } from './contract/install-method.js';
import { fetchHealth } from './contract/health.js';
Expand All @@ -21,6 +19,7 @@ import { updateNotice, writeUpdateCheck } from './contract/update-check.js';
import { DEFAULT_PORT } from './port.js';
import { type ServiceContext, changelogUrl, statusReport } from './service/index.js';
import { which } from './service/spec.js';
import { lingerOf, lingerUser } from './service/linger.js';

export type CheckStatus = 'pass' | 'warn' | 'fail' | 'skip';

Expand Down Expand Up @@ -126,7 +125,7 @@ export async function diagnose(i: DoctorInput): Promise<{ checks: Check[]; notic
// ---- linger, on Linux: without it the service stops when you log out
if (ctx.platform !== 'linux') add({ id: 'linger', status: 'skip', message: 'linger is a Linux thing' });
else {
const user = ctx.env.USER || os.userInfo().username;
const user = lingerUser(ctx.env);
const on = await (i.linger ?? (() => lingerOf(user)))();
if (on === true) add({ id: 'linger', status: 'pass', message: `linger is on for ${user}: the service runs while you're logged out, and starts at boot` });
else if (on === false && report?.installed)
Expand Down Expand Up @@ -216,13 +215,3 @@ const defaultIsListening = (port: number) =>
s.once('timeout', () => (s.destroy(), resolve(false)));
s.once('error', () => resolve(false));
});

/** `loginctl show-user <user> -p Linger`: true, false, or null when it can't say (no loginctl, no logind). */
export function lingerOf(user: string): Promise<boolean | null> {
return new Promise((resolve) => {
execFile('loginctl', ['show-user', user, '-p', 'Linger'], { timeout: 5000 }, (err, stdout) => {
const m = /^Linger=(yes|no)$/m.exec(String(stdout ?? ''));
resolve(err || !m ? null : m[1] === 'yes');
});
});
}
16 changes: 15 additions & 1 deletion server/service/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { createOutput } from '../contract/output.js';
import { readLiveRuntimeFile } from '../contract/runtime-file.js';
import { updateNotice, updateSummary, type UpdateSummary } from '../contract/update-check.js';
import { BUSY_NOUNS } from '../busy.js';
import { lingerAdvice, lingerOf, lingerUser } from './linger.js';
import { CARRIED_ENV, LOG_FILE, type PlatformContext, RefusalError, buildSpec, isCheckout, managerFor, portOf, refusal, which } from './spec.js';

export interface ServiceContext extends PlatformContext {
Expand Down Expand Up @@ -51,6 +52,8 @@ export interface ServiceContext extends PlatformContext {
version?: string;
/** With `--json` (withJson): what a command adds to its JSON document, beyond the status report. */
facts?: Record<string, unknown>;
/** Linux's linger for this user: true, false, or null when loginctl can't say. (Mocked in tests.) */
linger?: () => Promise<boolean | null>;
}

/** Record what `--json` should carry: a no-op without it. */
Expand Down Expand Up @@ -274,6 +277,15 @@ export async function install(ctx: ServiceContext, flags: InstallFlags): Promise
if (flags.refresh) return 0;
ctx.out(`${m.lifetime}\n`);
ctx.out(`Data: ${t(home)}. Log: ${t(spec.log)} (\`local-review service logs\`).\n`);
// Linux: linger is checked, never set; it takes sudo, which Local Review never runs (cli-contract SPEC §7)
if (ctx.platform === 'linux') {
const user = lingerUser(ctx.env);
const advice = lingerAdvice(await (ctx.linger ?? (() => lingerOf(user)))(), user);
if (advice) {
ctx.out(`\n${advice}\n`);
note(ctx, { warnings: [advice] });
}
}
return 0;
}

Expand Down Expand Up @@ -395,7 +407,9 @@ export async function withJson(ctx: ServiceContext, action: ServiceAction, run:
} catch {
/* no service manager to ask: the document says what the command found */
}
ctx.out(JSON.stringify({ ok: code === 0, action, ...(error ? { error } : {}), ...facts, ...report }, null, 2) + '\n');
// what the command warned of (linger, on an install) comes first, then what status warns of
const warnings = [...((facts.warnings as string[] | undefined) ?? []), ...(report.warnings ?? [])];
ctx.out(JSON.stringify({ ok: code === 0, action, ...(error ? { error } : {}), ...facts, ...report, ...(facts.warnings || report.warnings ? { warnings } : {}) }, null, 2) + '\n');
if (thrown) throw thrown;
return code;
}
Expand Down
28 changes: 28 additions & 0 deletions server/service/linger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Linux's linger (cli-contract SPEC §7): without it, systemd stops the user's manager, and the service with it, at
// their last logout, SSH sessions included. `service install` and `doctor` ask `loginctl`, and print the
// `sudo loginctl enable-linger` line only when it's off. Local Review never runs sudo itself, and says nothing when
// loginctl can't answer (no loginctl, no logind: a container).
import { execFile } from 'node:child_process';
import os from 'node:os';

/** `loginctl show-user <user> -p Linger`: true, false, or null when it can't say (no loginctl, no logind). */
export function lingerOf(user: string): Promise<boolean | null> {
return new Promise((resolve) => {
execFile('loginctl', ['show-user', user, '-p', 'Linger'], { timeout: 5000 }, (err, stdout) => {
const m = /^Linger=(yes|no)$/m.exec(String(stdout ?? ''));
resolve(err || !m ? null : m[1] === 'yes');
});
});
}

/** Whose linger: $USER, else the account running this. */
export const lingerUser = (env: NodeJS.ProcessEnv): string => env.USER || os.userInfo().username;

/**
* What `service install` prints for a linger that's off (from cli-contract reference/service/index.ts's
* `lingerAdvice`): undefined when it's on, or when loginctl couldn't say.
*/
export function lingerAdvice(on: boolean | null, user: string): string | undefined {
if (on !== false) return undefined;
return `Linger is off for ${user}, so the service stops when you log out, SSH sessions included, and starts only when you log in. To keep Local Review running, once:\n sudo loginctl enable-linger ${user}`;
}
4 changes: 2 additions & 2 deletions server/service/systemd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,8 @@ export function systemdManager({ dir, label, run = defaultRunner }: SystemdOptio
return {
kind: 'systemd',
noun: 'systemd user unit',
lifetime:
"It starts with your user session and is restarted if it exits. To keep it running while you're logged out, and start it at boot, enable lingering once: `loginctl enable-linger $USER`.",
// what linger adds is `service install`'s to say, and only when it's off (linger.ts)
lifetime: 'It starts with your user session and is restarted if it exits.',
stopped: 'It starts again with your next login session (or at boot, with lingering on), or with `local-review service start`.',
file,
render: renderUnit,
Expand Down
65 changes: 64 additions & 1 deletion test/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,8 @@ function world(platform: 'darwin' | 'linux', { where = 'global', git = true }: {
waitMs: 0,
isListening: async () => false,
health: async () => (state.running ? { version: '9.9.9' } : null),
// loginctl can't say, as in a container, unless a test says otherwise
linger: async () => null,
// /api/busy: nothing answers, unless a test says otherwise
fetch: async () => {
throw new Error('connection refused');
Expand Down Expand Up @@ -352,13 +354,54 @@ describe('service install, on Linux (systemd)', () => {
[
"Installed Local Review as a systemd user unit: ~/.config/systemd/user/local-review-server.service",
"It's running: http://localhost:5622",
"It starts with your user session and is restarted if it exits. To keep it running while you're logged out, and start it at boot, enable lingering once: `loginctl enable-linger $USER`.",
'It starts with your user session and is restarted if it exits.',
'Data: ~/.local-review. Log: ~/.local-review/logs/service.log (`local-review service logs`).',
'',
].join('\n'),
);
});

test('linger (cli-contract SPEC §7): off prints the sudo line and why; on, or a loginctl that can\'t say, prints nothing', async () => {
const advice = [
'',
'Linger is off for ed, so the service stops when you log out, SSH sessions included, and starts only when you log in. To keep Local Review running, once:',
' sudo loginctl enable-linger ed',
'',
].join('\n');
for (const [on, said] of [
[false, advice],
[true, ''],
[null, ''],
] as const) {
const w = world('linux');
w.ctx.env.USER = 'ed';
let asked = 0;
w.ctx.linger = async () => (asked++, on);
assert.equal(await install(w.ctx, {}), 0);
const { out, err } = w.take();
assert.equal(asked, 1, `linger ${on}: asked once`);
assert.ok(out.endsWith('(`local-review service logs`).\n' + said), `linger ${on}:\n${out}`);
if (on !== false) assert.doesNotMatch(out + err, /linger|sudo/i, `linger ${on}: not a word`);
assert.ok(!w.calls.some((c) => /sudo|loginctl/.test(c)), 'it never runs sudo, or loginctl through the service manager');
}
});

test("linger: not asked on macOS, by a dry run, or by `update`'s --refresh", async () => {
const mac = world('darwin');
mac.ctx.linger = async () => assert.fail('asked on macOS');
assert.equal(await install(mac.ctx, {}), 0);
assert.doesNotMatch(mac.take().out, /linger/i);
const w = world('linux');
w.ctx.linger = async () => assert.fail('asked by a dry run');
assert.equal(await install(w.ctx, { dryRun: true }), 0);
w.ctx.linger = async () => false;
assert.equal(await install(w.ctx, {}), 0);
assert.match(w.take().out, /sudo loginctl enable-linger/);
w.ctx.linger = async () => assert.fail('asked by a refresh');
assert.equal(await install(w.ctx, { refresh: true }), 0);
assert.doesNotMatch(w.take().out, /linger/i);
});

test('again: idempotent, then a new port rewrites and restarts it, and a bare reinstall keeps that port', async () => {
const w = world('linux');
await install(w.ctx, {});
Expand Down Expand Up @@ -521,6 +564,26 @@ describe('--json on install, uninstall, start, stop and restart (cli-contract SP
assert.match(err, /It's running: http:\/\/localhost:5622/);
});

test("install with linger off: the advice is in the document's warnings, not on stdout; on, or unknown, it isn't", async () => {
for (const on of [false, true, null]) {
const w = world('linux');
w.ctx.env.USER = 'ed';
w.ctx.linger = async () => on;
assert.equal(await withJson(w.ctx, 'install', (c) => install(c, {})), 0);
const { out, err } = w.take();
const d = doc(out);
const advice = d.warnings.filter((x: string) => /linger/i.test(x));
if (on === false) {
assert.equal(advice.length, 1);
assert.match(advice[0], /^Linger is off for ed, so the service stops when you log out.*\n sudo loginctl enable-linger ed$/s);
assert.match(err, /^ sudo loginctl enable-linger ed$/m, 'and the prose, on stderr');
} else {
assert.deepEqual(advice, [], `linger ${on}`);
assert.doesNotMatch(err, /linger/i);
}
}
});

test('install --dry-run: the definition it would write, and nothing written', async () => {
const w = world('darwin');
assert.equal(await withJson(w.ctx, 'install', (c) => install(c, { dryRun: true })), 0);
Expand Down
17 changes: 15 additions & 2 deletions website/src/content/docs/getting-started/service.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,21 @@ while you're logged out, and starts at boot. Turn it on once:
sudo loginctl enable-linger $USER
```

`install` reminds you of it, and [`doctor`](/reference/cli/#local-review-doctor) checks, and prints
`sudo loginctl enable-linger <user>` when it's off. **Local Review never runs `sudo` itself.**
**`install` and [`doctor`](/reference/cli/#local-review-doctor) check** (`loginctl show-user <user> -p Linger`), and
print `sudo loginctl enable-linger <user>` when it's off. **Local Review never runs `sudo` itself.** When linger is on,
or `loginctl` can't answer (in a container, say), `install` says nothing about it. With `--json`, the advice is in the
document's `warnings`.

```text
$ local-review service install
Installed Local Review as a systemd user unit: ~/.config/systemd/user/local-review-server.service
It's running: http://localhost:5622
It starts with your user session and is restarted if it exits.
Data: ~/.local-review. Log: ~/.local-review/logs/service.log (`local-review service logs`).

Linger is off for ed, so the service stops when you log out, SSH sessions included, and starts only when you log in. To keep Local Review running, once:
sudo loginctl enable-linger ed
```

### Not from npx

Expand Down
Loading