@rhizogrip/spore-cli 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,567 @@
1
+ /**
2
+ * The services spore ships and those its installed plugins offer, as systemd user units: written,
3
+ * started, enabled and removed by `spore service`, so nobody writes one by hand.
4
+ *
5
+ * Spore's own list and each plugin's manifest, not arbitrary units. Each unit carries `X-Spore-Service=<name>` — systemd
6
+ * ignores `X-` keys — and that marker is how spore knows a unit is its own: it rewrites and
7
+ * removes only those, and refuses to touch a unit of the same name it did not write.
8
+ *
9
+ * The verbs are systemd's and mean what they mean there: `start` and `stop` act now,
10
+ * `enable` and `disable` decide whether the service starts at login. A service that runs spore
11
+ * names the Node running this command and this package in `ExecStart`, and there is no
12
+ * `EnvironmentFile=`: every command reads `environment` beside `config.json` itself
13
+ * (`loadEnvironment`).
14
+ */
15
+
16
+ import { spawnSync } from 'node:child_process'
17
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
18
+ import { createRequire } from 'node:module'
19
+ import { homedir, userInfo } from 'node:os'
20
+ import { dirname, join } from 'node:path'
21
+
22
+ import { CONFIG_DIR, pluginRoots, pluginServices, SERVICE_STATE_DIR, SporeError, versionAt } from '@rhizogrip/spore'
23
+
24
+ const ROOT = dirname(createRequire(import.meta.url).resolve('@rhizogrip/spore/package.json'))
25
+
26
+ export const UNIT_DIR = join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'systemd', 'user')
27
+
28
+ const MARKER = 'X-Spore-Service'
29
+
30
+ const quoted = (path) => `"${path}"`
31
+
32
+ /**
33
+ * The keys the ssh-agent service loads: every private key in this folder beside `config.json`,
34
+ * never inside a workspace, so no spore can read one. Adding or retiring a key is putting it in
35
+ * or taking it out, then restarting the service.
36
+ */
37
+ export const SSH_KEYS_DIR = join(CONFIG_DIR, 'ssh')
38
+ export const SSH_AGENT_SOCKET = 'spore-ssh-agent.socket'
39
+
40
+ const sshKeysCheck = (keys) => [
41
+ 'command -v ssh-agent >/dev/null && command -v ssh-add >/dev/null || { echo "no ssh-agent or ssh-add — install the OpenSSH client" >&2; exit 1; }',
42
+ `set -- $(find ${quoted(keys)} -maxdepth 1 -type f ! -name '*.pub' 2>/dev/null)`,
43
+ `[ $# -gt 0 ] || { echo "no private key in ${keys} — put the keys spores may use there: mkdir -m 700 -p ${keys} && ssh-keygen -t ed25519 -N '' -C '<what it is for>' -f ${keys}/<name>" >&2; exit 1; }`,
44
+ 'for key; do ssh-keygen -y -P \'\' -f "$key" >/dev/null 2>&1 || { echo "$key cannot be loaded unattended — it needs a passphrase, is readable by others (chmod 600), or is not a private key" >&2; exit 1; }; done',
45
+ 'echo "$# key(s) ready"'
46
+ ].join('\n')
47
+
48
+ /**
49
+ * The sluice broker spores reach: its rules and the list its agents read are the operator's, in
50
+ * sluice's own config folder; the binary is the one on PATH, or where `cargo install` puts it.
51
+ */
52
+ const SLUICE_DIR = join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'sluice')
53
+ const SLUICE_RULES = join(SLUICE_DIR, 'spore.rules')
54
+ const SLUICE_LIST = join(SLUICE_DIR, 'spore.md')
55
+ const sluiceBinary = () => (process.env.PATH ?? '').split(':').filter(Boolean).map(dir => join(dir, 'sluice')).find(path => existsSync(path)) ??
56
+ join(homedir(), '.cargo', 'bin', 'sluice')
57
+
58
+ const sluiceCheck = (binary) => [
59
+ `[ -x ${quoted(binary)} ] || { echo "no sluice at ${binary} — cargo install sluicify" >&2; exit 1; }`,
60
+ `[ -f ${quoted(SLUICE_RULES)} ] || { echo "no ${SLUICE_RULES} — the commands spores may run; the plugin's examples/spore.rules is a start" >&2; exit 1; }`,
61
+ `[ -f ${quoted(SLUICE_LIST)} ] || { echo "no ${SLUICE_LIST} — what the agent reads with --list; the plugin's examples/spore.md is a start" >&2; exit 1; }`,
62
+ `${quoted(binary)} check ${quoted(SLUICE_RULES)}`
63
+ ].join('\n')
64
+
65
+ /**
66
+ * What each service is. `primary` is the unit `start`, `stop`, `enable` and `disable` act on;
67
+ * `runs` the one that starts the program, whose journal says what it did. `check` runs the
68
+ * service's own start-up checks and exits, so one that cannot start is refused before its unit
69
+ * is written.
70
+ *
71
+ * A service with `instances` runs once per file in that folder beside `config.json`, as
72
+ * `<name>@<instance>`: one template unit, and an instance of it per file, each started, enabled and
73
+ * logged on its own.
74
+ */
75
+ export const SERVICES = Object.freeze({
76
+ webhook: {
77
+ what: 'webhooks from any sender, each a message to the spore its hook names',
78
+ records: true,
79
+ primary: 'spore-webhook.service',
80
+ runs: 'spore-webhook.service',
81
+ check: ({ node, root }) => [node, [join(root, 'bin', 'spore-webhook.js'), '--check']],
82
+ next: () => 'give each sender http://<host>/hook/<name> through your reverse proxy — it listens on 127.0.0.1:8742, or SPORE_WEBHOOK_LISTEN in environment',
83
+ units: ({ node, root }) => ({
84
+ 'spore-webhook.service': [
85
+ '[Unit]',
86
+ 'Description=spore-webhook: webhooks as messages to spores',
87
+ `${MARKER}=webhook`,
88
+ '',
89
+ '[Service]',
90
+ `ExecStart=${quoted(node)} ${quoted(join(root, 'bin', 'spore-webhook.js'))}`,
91
+ 'Restart=on-failure',
92
+ 'RestartPreventExitStatus=2',
93
+ 'KillMode=process',
94
+ '',
95
+ '[Install]',
96
+ 'WantedBy=default.target'
97
+ ]
98
+ })
99
+ },
100
+ api: {
101
+ what: 'the library\'s verbs over HTTP, for callers elsewhere: send, events, show, list, stop',
102
+ records: true,
103
+ primary: 'spore-api.service',
104
+ runs: 'spore-api.service',
105
+ check: ({ node, root }) => [node, [join(root, 'bin', 'spore-api.js'), '--check']],
106
+ next: () => 'give each caller its token and the socket or address api.json names',
107
+ units: ({ node, root }) => ({
108
+ 'spore-api.service': [
109
+ '[Unit]',
110
+ 'Description=spore-api: the library\'s verbs over HTTP',
111
+ `${MARKER}=api`,
112
+ '',
113
+ '[Service]',
114
+ `ExecStart=${quoted(node)} ${quoted(join(root, 'bin', 'spore-api.js'))}`,
115
+ 'Restart=on-failure',
116
+ 'RestartPreventExitStatus=2',
117
+ 'KillMode=process',
118
+ '',
119
+ '[Install]',
120
+ 'WantedBy=default.target'
121
+ ]
122
+ })
123
+ },
124
+ 'ssh-agent': {
125
+ what: 'holds the SSH keys spores may use, which they can sign with and never read',
126
+ primary: 'spore-ssh-agent.service',
127
+ runs: 'spore-ssh-agent.service',
128
+ check: ({ keys }) => ['/bin/sh', ['-c', sshKeysCheck(keys)]],
129
+ next: ({ uid }) => `spore plugin allow ssh socket=/run/user/${uid}/${SSH_AGENT_SOCKET}`,
130
+ units: ({ keys }) => ({
131
+ 'spore-ssh-agent.service': [
132
+ '[Unit]',
133
+ 'Description=spore ssh-agent: the SSH keys spores may use',
134
+ `${MARKER}=ssh-agent`,
135
+ '',
136
+ '[Service]',
137
+ `Environment=SSH_AUTH_SOCK=%t/${SSH_AGENT_SOCKET}`,
138
+ 'ExecStartPre=rm -f $SSH_AUTH_SOCK',
139
+ 'ExecStart=ssh-agent -D -a $SSH_AUTH_SOCK',
140
+ // systemd substitutes `$x` in a command line itself, so the shell's own are written `$$x`.
141
+ `ExecStartPost=sh -c 'until [ -S "$$SSH_AUTH_SOCK" ]; do sleep 0.1; done; for key in ${quoted(keys)}/*; do case "$$key" in *.pub) ;; *) ssh-add -q "$$key" ;; esac; done'`,
142
+ 'Restart=on-failure',
143
+ '',
144
+ '[Install]',
145
+ 'WantedBy=default.target'
146
+ ]
147
+ })
148
+ },
149
+ sluice: {
150
+ what: 'runs the host commands spores may ask for, as ~/.config/sluice/spore.rules allows',
151
+ primary: 'spore-sluice.service',
152
+ runs: 'spore-sluice.service',
153
+ check: () => ['/bin/sh', ['-c', sluiceCheck(sluiceBinary())]],
154
+ next: ({ uid }) => `spore plugin allow sluice socket=/run/user/${uid}/sluice/spore.sock`,
155
+ units: () => ({
156
+ 'spore-sluice.service': [
157
+ '[Unit]',
158
+ 'Description=spore sluice: the host commands spores may ask for',
159
+ `${MARKER}=sluice`,
160
+ '',
161
+ '[Service]',
162
+ 'ExecStartPre=/bin/mkdir -p %t/sluice',
163
+ `ExecStartPre=/bin/cp ${quoted(SLUICE_LIST)} %t/sluice/spore.md`,
164
+ `ExecStart=${quoted(sluiceBinary())} serve --rules ${quoted(SLUICE_RULES)} --socket %t/sluice/spore.sock`,
165
+ 'Restart=on-failure',
166
+ '',
167
+ '[Install]',
168
+ 'WantedBy=default.target'
169
+ ]
170
+ })
171
+ },
172
+ tick: {
173
+ what: 'fires every schedule that is due, each minute',
174
+ primary: 'spore-tick.timer',
175
+ runs: 'spore-tick.service',
176
+ check: null,
177
+ units: ({ node, root }) => ({
178
+ 'spore-tick.service': [
179
+ '[Unit]',
180
+ 'Description=spore tick: fires every schedule that is due',
181
+ `${MARKER}=tick`,
182
+ '',
183
+ '[Service]',
184
+ 'Type=oneshot',
185
+ `ExecStart=${quoted(node)} ${quoted(join(root, 'bin', 'spore-tick.js'))}`,
186
+ 'KillMode=process'
187
+ ],
188
+ 'spore-tick.timer': [
189
+ '[Unit]',
190
+ 'Description=spore tick, every minute',
191
+ `${MARKER}=tick`,
192
+ '',
193
+ '[Timer]',
194
+ 'OnCalendar=minutely',
195
+ 'AccuracySec=1s',
196
+ '',
197
+ '[Install]',
198
+ 'WantedBy=timers.target'
199
+ ]
200
+ })
201
+ }
202
+ })
203
+
204
+ /** A plugin's service, as the units spore writes for it: one Node program, started with the instance when it has them. */
205
+ function fromPlugin (found) {
206
+ const unit = found.instances ? `spore-${found.name}@.service` : `spore-${found.name}.service`
207
+ const named = found.instances ? (instance) => `spore-${found.name}@${instance}.service` : unit
208
+ const instance = found.instances ? ' %i' : ''
209
+ return {
210
+ what: found.what,
211
+ plugin: found.plugin,
212
+ package: found.package,
213
+ version: found.version,
214
+ instances: found.instances,
215
+ records: true,
216
+ primary: named,
217
+ runs: named,
218
+ check: found.check && (({ node, instance }) => [node, [found.program, ...(instance === null ? [] : [instance]), ...found.check]]),
219
+ units: ({ node }) => ({
220
+ [unit]: [
221
+ '[Unit]',
222
+ `Description=spore-${found.name}${instance}: ${found.what.replaceAll('%', '%%')}`,
223
+ `${MARKER}=${found.name}`,
224
+ '',
225
+ '[Service]',
226
+ `ExecStart=${quoted(node)} ${quoted(found.program)}${instance}`,
227
+ 'Restart=on-failure',
228
+ 'RestartPreventExitStatus=2',
229
+ 'KillMode=process',
230
+ '',
231
+ '[Install]',
232
+ 'WantedBy=default.target'
233
+ ]
234
+ })
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Spore's services and every installed plugin's. A name two of them claim goes to neither
240
+ * plugin, since which one was found first says nothing about which the operator meant.
241
+ */
242
+ function catalogOf (roots) {
243
+ const { services, problems } = pluginServices(roots)
244
+ const all = { ...SERVICES }
245
+ const claims = Map.groupBy(services, found => found.name)
246
+ for (const [name, claimed] of claims) {
247
+ for (const found of claimed) {
248
+ const others = claimed.filter(other => other !== found).map(other => `plugin ${other.plugin}`)
249
+ if (SERVICES[name] || others.length) {
250
+ problems.push({ plugin: found.plugin, package: found.package, problem: `offers a service ${name}, which ${SERVICES[name] ? 'spore ships' : `${others.join(' and ')} offers too`} — uninstall one of them` })
251
+ }
252
+ }
253
+ if (!SERVICES[name] && claimed.length === 1) all[name] = fromPlugin(claimed[0])
254
+ }
255
+ return { services: all, problems }
256
+ }
257
+
258
+ /** The unit files of a service, as they are written. */
259
+ export function renderUnits (name, { node = process.execPath, root = ROOT, keys = SSH_KEYS_DIR, roots = pluginRoots() } = {}) {
260
+ const { base, service } = parsed(name, catalogOf(roots).services, { instanceOptional: true, verb: 'define' })
261
+ return Object.fromEntries(Object.entries(service.units({ node, root, keys }))
262
+ .map(([file, lines]) => [file, `# Written by \`spore service define ${base}\`. Change it with that command, not by hand.\n${lines.join('\n')}\n`]))
263
+ }
264
+
265
+ function serviceOf (name, catalog) {
266
+ const service = catalog[name]
267
+ if (!service) {
268
+ throw new SporeError(`no service called "${name}"`, {
269
+ type: 'SERVICE_UNKNOWN',
270
+ detail: `spore and its installed plugins offer ${Object.keys(catalog).join(', ')}`
271
+ })
272
+ }
273
+ return service
274
+ }
275
+
276
+ const INSTANCE = /^[a-z0-9][a-z0-9._-]*$/i
277
+
278
+ /**
279
+ * `telegram@reviewer` is the service `telegram`, its instance `reviewer`. `verb` is the `spore
280
+ * service` subcommand it was named to, for the command a refusal suggests.
281
+ */
282
+ function parsed (name, catalog, { instanceOptional = false, verb } = {}) {
283
+ const at = name.indexOf('@')
284
+ const base = at < 0 ? name : name.slice(0, at)
285
+ const instance = at < 0 ? null : name.slice(at + 1)
286
+ const service = serviceOf(base, catalog)
287
+ if (!service.instances && instance !== null) {
288
+ throw new SporeError(`${base} runs once, not per ${instance}`, { type: 'SERVICE_UNKNOWN', detail: `spore service ${verb} ${base}` })
289
+ }
290
+ if (service.instances && instance === null && !instanceOptional) {
291
+ throw new SporeError(`${base} runs once per ${service.instances.called}: name one`, {
292
+ type: 'SERVICE_NEEDS_INSTANCE',
293
+ detail: `spore service ${verb} ${base}@<${service.instances.called}>, for the ${service.instances.called} in ${service.instances.dir}/<${service.instances.called}>${service.instances.ext} beside config.json`
294
+ })
295
+ }
296
+ if (instance !== null && !INSTANCE.test(instance)) {
297
+ throw new SporeError(`"${instance}" cannot be a ${service.instances.called}'s name`, { type: 'SERVICE_UNKNOWN', detail: 'letters, digits, ., - and _' })
298
+ }
299
+ return { base, instance, service }
300
+ }
301
+
302
+ const unitOf = (field, { service, instance }) => (typeof service[field] === 'function' ? service[field](instance) : service[field])
303
+
304
+ const systemRun = (command, args) => {
305
+ const ran = spawnSync(command, args, { encoding: 'utf8' })
306
+ if (ran.error) return { status: null, stdout: '', stderr: ran.error.message }
307
+ return { status: ran.status, stdout: ran.stdout, stderr: ran.stderr }
308
+ }
309
+
310
+ const procCmdline = (pid) => {
311
+ try {
312
+ return readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0').filter(Boolean)
313
+ } catch (err) {
314
+ if (err.code === 'ENOENT') return null
315
+ throw err
316
+ }
317
+ }
318
+
319
+ /**
320
+ * `run(command, args)` answers `{ status, stdout, stderr }`; it is injected so the verbs can
321
+ * be exercised without a user bus.
322
+ */
323
+ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf = procCmdline, node = process.execPath, root = ROOT, user = userInfo().username, uid = process.getuid(), keys = SSH_KEYS_DIR, stateDir = SERVICE_STATE_DIR, configDir = CONFIG_DIR, roots = pluginRoots() } = {}) {
324
+ const { services: catalog, problems } = catalogOf(roots)
325
+ const parse = (name, options) => parsed(name, catalog, options)
326
+ const systemctl = (...args) => {
327
+ const ran = run('systemctl', ['--user', ...args])
328
+ if (ran.status !== 0) {
329
+ throw new SporeError(`systemctl --user ${args.join(' ')} failed`, {
330
+ type: 'SERVICE_COMMAND_FAILED',
331
+ detail: (ran.stderr || ran.stdout || '').trim() || `exit ${ran.status}`
332
+ })
333
+ }
334
+ return ran.stdout
335
+ }
336
+
337
+ const requireSystemd = () => {
338
+ const ran = run('systemctl', ['--user', 'show-environment'])
339
+ if (ran.status !== 0) {
340
+ throw new SporeError('no systemd user session to run services in', {
341
+ type: 'SERVICE_NO_SYSTEMD',
342
+ detail: `spore service needs \`systemctl --user\` — ${(ran.stderr || '').trim() || `exit ${ran.status}`}`
343
+ })
344
+ }
345
+ }
346
+
347
+ const pathOf = (file) => join(unitDir, file)
348
+ const unitsOf = (service) => service.units({ node, root, keys })
349
+ const ours = (base, file) => {
350
+ const path = pathOf(file)
351
+ return existsSync(path) && readFileSync(path, 'utf8').split('\n').includes(`${MARKER}=${base}`)
352
+ }
353
+ const written = ({ base, service }) => Object.keys(unitsOf(service)).every(file => ours(base, file))
354
+
355
+ const instanceFile = ({ service, instance }) => join(configDir, service.instances.dir, `${instance}${service.instances.ext}`)
356
+ const instancesOf = (service) => {
357
+ const dir = join(configDir, service.instances.dir)
358
+ if (!existsSync(dir)) return []
359
+ return readdirSync(dir).filter(file => file.endsWith(service.instances.ext)).map(file => file.slice(0, -service.instances.ext.length)).sort()
360
+ }
361
+ const defined = (one) => written(one) && (one.instance === null || existsSync(instanceFile(one)))
362
+
363
+ const foreign = ({ base, service }) => Object.keys(unitsOf(service))
364
+ .find(file => existsSync(pathOf(file)) && !ours(base, file)) ?? null
365
+
366
+ const refuseForeign = (one, name) => {
367
+ const file = foreign(one)
368
+ if (file) {
369
+ throw new SporeError(`${pathOf(file)} was not written by spore`, {
370
+ type: 'SERVICE_NOT_OURS',
371
+ detail: `remove it — systemctl --user disable --now ${file}; rm ${pathOf(file)} — then spore service define ${name}`
372
+ })
373
+ }
374
+ }
375
+
376
+ const requireDefined = (one, name) => {
377
+ refuseForeign(one, name)
378
+ if (!defined(one)) {
379
+ throw new SporeError(`${name} is not defined`, {
380
+ type: 'SERVICE_NOT_DEFINED',
381
+ detail: one.instance !== null && !existsSync(instanceFile(one))
382
+ ? `there is no ${instanceFile(one)}`
383
+ : `spore service define ${name} writes its unit`
384
+ })
385
+ }
386
+ }
387
+
388
+ const execPaths = ({ service }) => {
389
+ const text = Object.keys(unitsOf(service)).map(file => readFileSync(pathOf(file), 'utf8')).find(unit => unit.includes('\nExecStart='))
390
+ const exec = text.split('\n').find(line => line.startsWith('ExecStart='))
391
+ return [...exec.matchAll(/"([^"]+)"/g)].map(found => found[1])
392
+ }
393
+
394
+ // The Node and the script a unit starts, read back from it: either gone means the unit was
395
+ // written for a checkout or an install that has since moved.
396
+ const stale = (one) => execPaths(one).filter(path => !existsSync(path))
397
+
398
+ // A process started before its unit was last written runs what the unit used to name.
399
+ const unitChanged = (one, pid) => {
400
+ const argv = pid && cmdlineOf(pid)
401
+ return Boolean(argv) && !execPaths(one).every(path => argv.includes(path))
402
+ }
403
+
404
+ const stateOf = (unit) => {
405
+ const fields = Object.fromEntries(systemctl('show', unit, '-p', 'ActiveState,SubState,UnitFileState,ActiveEnterTimestamp,MainPID,NRestarts')
406
+ .trim().split('\n').map(line => [line.slice(0, line.indexOf('=')), line.slice(line.indexOf('=') + 1)]))
407
+ return {
408
+ active: fields.ActiveState,
409
+ sub: fields.SubState,
410
+ enabled: fields.UnitFileState === 'enabled',
411
+ since: fields.ActiveEnterTimestamp || null,
412
+ pid: Number(fields.MainPID) || null,
413
+ restarts: Number(fields.NRestarts) || 0
414
+ }
415
+ }
416
+
417
+ // The version a running service recorded, when it is the process running now and not the
418
+ // one installed — of spore, or of the plugin that offers it. A service that recorded nothing,
419
+ // or a record left by an earlier process, says nothing either way.
420
+ const outdated = (name, { service }, pid) => {
421
+ const record = join(stateDir, `${name}.json`)
422
+ if (!service.records || !pid || !existsSync(record)) return null
423
+ const started = JSON.parse(readFileSync(record, 'utf8'))
424
+ const installed = service.plugin ? service.version : versionAt(root)
425
+ return started.pid === pid && started.version !== installed ? { from: service.package ?? 'spore', running: started.version, installed } : null
426
+ }
427
+
428
+ const row = (name) => {
429
+ const one = parse(name, { verb: 'show' })
430
+ const { service } = one
431
+ const other = foreign(one)
432
+ if (other) return { name, what: service.what, defined: false, foreign: pathOf(other) }
433
+ if (!defined(one)) return { name, what: service.what, defined: false }
434
+ const unit = unitOf('primary', one)
435
+ const state = stateOf(unit)
436
+ return { name, what: service.what, defined: true, unit, ...state, stale: stale(one), unitChanged: unitChanged(one, state.pid), outdated: outdated(name, one, state.pid) }
437
+ }
438
+
439
+ const rows = (base) => {
440
+ const service = serviceOf(base, catalog)
441
+ if (!service.instances) return [row(base)]
442
+ const names = instancesOf(service)
443
+ if (!names.length) {
444
+ return [{ name: base, what: service.what, defined: false, none: `no ${service.instances.called} yet — ${join(configDir, service.instances.dir)}/<${service.instances.called}>${service.instances.ext}, then spore service define ${base}@<${service.instances.called}>` }]
445
+ }
446
+ return names.map(instance => row(`${base}@${instance}`))
447
+ }
448
+
449
+ return {
450
+ list () {
451
+ requireSystemd()
452
+ return {
453
+ linger: existsSync(join('/var/lib/systemd/linger', user)),
454
+ services: Object.keys(catalog).flatMap(rows),
455
+ problems
456
+ }
457
+ },
458
+
459
+ show (name) {
460
+ requireSystemd()
461
+ const one = parse(name, { verb: 'show' })
462
+ const shown = row(name)
463
+ if (!shown.defined) return shown
464
+ const units = Object.keys(unitsOf(one.service)).map(pathOf)
465
+ const log = run('journalctl', ['--user', '-u', unitOf('runs', one), '-n', '10', '--no-pager', '-o', 'short-iso']).stdout.trim()
466
+ return { ...shown, units, log }
467
+ },
468
+
469
+ define (name) {
470
+ const one = parse(name, { verb: 'define' })
471
+ const { service, instance } = one
472
+ requireSystemd()
473
+ refuseForeign(one, name)
474
+ if (service.check) {
475
+ const [command, args] = service.check({ node, root, keys, instance })
476
+ const checked = run(command, args)
477
+ if (checked.status !== 0) {
478
+ throw new SporeError(`${name} would not start`, {
479
+ type: 'SERVICE_NOT_READY',
480
+ detail: (checked.stderr || checked.stdout || '').trim() || `exit ${checked.status}`
481
+ })
482
+ }
483
+ }
484
+ mkdirSync(unitDir, { recursive: true })
485
+ const units = []
486
+ for (const [file, text] of Object.entries(renderUnits(one.base, { node, root, keys, roots }))) {
487
+ writeFileSync(pathOf(file), text)
488
+ units.push(pathOf(file))
489
+ }
490
+ systemctl('daemon-reload')
491
+ return { name, units, next: service.next ? service.next({ uid }) : null }
492
+ },
493
+
494
+ act (verb, name) {
495
+ requireSystemd()
496
+ const one = parse(name, { verb })
497
+ requireDefined(one, name)
498
+ const unit = unitOf('primary', one)
499
+ systemctl(verb, unit)
500
+ return { name, unit, verb, ...stateOf(unit) }
501
+ },
502
+
503
+ /** Every service still running a spore older than the one installed, restarted. */
504
+ restartOutdated () {
505
+ requireSystemd()
506
+ return Object.keys(catalog).flatMap(rows)
507
+ .filter(each => each.outdated)
508
+ .map(each => ({ ...this.act('restart', each.name), was: each.outdated.running, now: each.outdated.installed }))
509
+ },
510
+
511
+ /**
512
+ * An instance is stopped and disabled, and its template stays for the others. The service
513
+ * itself, named without one, is every instance stopped and disabled and the template removed.
514
+ * Stopping one that is running takes `yes`.
515
+ */
516
+ remove (name, { yes = false } = {}) {
517
+ requireSystemd()
518
+ const one = parse(name, { instanceOptional: true, verb: 'rm' })
519
+ const { service, instance } = one
520
+ if (instance !== null) requireDefined(one, name)
521
+ else {
522
+ refuseForeign(one, name)
523
+ if (!written(one)) {
524
+ throw new SporeError(`${name} is not defined`, { type: 'SERVICE_NOT_DEFINED', detail: `spore service define ${name}${service.instances ? `@<${service.instances.called}>` : ''} writes its unit` })
525
+ }
526
+ }
527
+ const instances = instance !== null ? [instance] : service.instances ? instancesOf(service) : [null]
528
+ const running = instances.filter(each => !['inactive', 'failed'].includes(stateOf(unitOf('primary', { service, instance: each })).active))
529
+ if (running.length && !yes) {
530
+ const named = running.map(each => (each === null ? one.base : `${one.base}@${each}`))
531
+ throw new SporeError(`${named.join(', ')} ${named.length > 1 ? 'are' : 'is'} running`, {
532
+ type: 'SERVICE_RUNNING',
533
+ detail: `spore service rm ${name} --yes stops ${named.length > 1 ? 'them' : 'it'} and removes ${name}`
534
+ })
535
+ }
536
+ if (instance !== null) {
537
+ systemctl('disable', '--now', unitOf('primary', one))
538
+ return { name, units: [] }
539
+ }
540
+ for (const each of instances) systemctl('disable', '--now', unitOf('primary', { service, instance: each }))
541
+ const removed = Object.keys(unitsOf(service)).map(pathOf)
542
+ for (const path of removed) rmSync(path)
543
+ systemctl('daemon-reload')
544
+ return { name, units: removed }
545
+ },
546
+
547
+ /** The unit whose journal says what the service did. */
548
+ log (name) {
549
+ requireSystemd()
550
+ const one = parse(name, { verb: 'log' })
551
+ requireDefined(one, name)
552
+ return unitOf('runs', one)
553
+ },
554
+
555
+ /** The last `lines` journal lines of a service matching `grep`, a PCRE2 pattern. */
556
+ journal (name, { grep, lines }) {
557
+ const unit = this.log(name)
558
+ const ran = run('journalctl', ['--user', '-u', unit, '--grep', grep, '-n', String(lines), '--no-pager', '-o', 'short-iso'])
559
+ const printed = ran.stdout.trim()
560
+ if (printed === '-- No entries --') return ''
561
+ if (ran.status !== 0) {
562
+ throw new SporeError(`journalctl --user -u ${unit} failed`, { type: 'SERVICE_COMMAND_FAILED', detail: (ran.stderr || '').trim() || `exit ${ran.status}` })
563
+ }
564
+ return printed
565
+ }
566
+ }
567
+ }