@bakers-build/addon-daemon 0.0.0-stage → 0.19.1-next.7
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.
- package/LICENSE +21 -0
- package/README.md +4 -2
- package/dist/src/deps-node.d.ts +7 -0
- package/dist/src/deps-node.js +53 -0
- package/dist/src/index.d.ts +8 -0
- package/dist/src/index.js +55 -0
- package/dist/src/install.d.ts +41 -0
- package/dist/src/install.js +124 -0
- package/dist/src/preset.d.ts +5 -0
- package/dist/src/preset.js +16 -0
- package/dist/src/run.d.ts +22 -0
- package/dist/src/run.js +207 -0
- package/dist/src/select.d.ts +10 -0
- package/dist/src/select.js +8 -0
- package/dist/src/tool-definitions.d.ts +2 -0
- package/dist/src/tool-definitions.js +13 -0
- package/dist/src/tools.d.ts +4 -0
- package/dist/src/tools.js +17 -0
- package/dist/src/units.d.ts +7 -0
- package/dist/src/units.js +62 -0
- package/options.schema.json +6 -0
- package/package.json +30 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 keytec GmbH
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @bakers-build/addon-daemon
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
bakers.build daemon command plugin: a background service that starts the conductors flagged autostart.
|
|
4
|
+
|
|
5
|
+
Part of the bakers.build CLI. Install the meta package `@bakers-build/bakers` to get the `bakers` CLI with all addons. Source: https://github.com/bakers-build/bakers-build (bakers-cli/).
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type BbCommandHost } from '@bakers-build/core';
|
|
2
|
+
import type { DaemonDeps } from './install.js';
|
|
3
|
+
import type { RunDeps } from './run.js';
|
|
4
|
+
/** The real machine: service managers, this process's env and the machine connection. */
|
|
5
|
+
export declare function nodeDaemonDeps(host?: BbCommandHost): DaemonDeps;
|
|
6
|
+
/** The real loop: this process, its timers and signals, and detached conductors. */
|
|
7
|
+
export declare function nodeRunDeps(host?: BbCommandHost): RunDeps;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { promisify } from 'node:util';
|
|
4
|
+
import { classify, daemonStatePath, machineRemote, readDaemonState, spawnDetachedConductor, } from '@bakers-build/conductor';
|
|
5
|
+
import { readCliVersion, readMachineContext, } from '@bakers-build/core';
|
|
6
|
+
/** The real machine: service managers, this process's env and the machine connection. */
|
|
7
|
+
export function nodeDaemonDeps(host) {
|
|
8
|
+
return {
|
|
9
|
+
platform: process.platform,
|
|
10
|
+
exec: async (file, args) => {
|
|
11
|
+
await promisify(execFile)(file, args);
|
|
12
|
+
},
|
|
13
|
+
home: homedir(),
|
|
14
|
+
env: process.env,
|
|
15
|
+
uid: process.getuid?.() ?? 0,
|
|
16
|
+
// The running bakers entry script; it carries its own shebang.
|
|
17
|
+
bakersBin: process.argv[1] ?? 'bakers',
|
|
18
|
+
statePath: daemonStatePath(),
|
|
19
|
+
daemonState: () => readDaemonState(),
|
|
20
|
+
conductors: async () => (await machineRemote(host)).listConductors('me'),
|
|
21
|
+
hostKey: async () => {
|
|
22
|
+
const id = (await readMachineContext()).machine_id;
|
|
23
|
+
if (!id)
|
|
24
|
+
throw new Error('this machine has no machine id, so its conductors cannot be told apart; run: bakers config init --scope machine');
|
|
25
|
+
return id;
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/** The real loop: this process, its timers and signals, and detached conductors. */
|
|
30
|
+
export function nodeRunDeps(host) {
|
|
31
|
+
const d = nodeDaemonDeps(host);
|
|
32
|
+
return {
|
|
33
|
+
statePath: d.statePath,
|
|
34
|
+
remote: () => machineRemote(host),
|
|
35
|
+
hostKey: d.hostKey,
|
|
36
|
+
spawn: spawnDetachedConductor,
|
|
37
|
+
running: (row, hostKey) => classify(row, hostKey) !== 'offline',
|
|
38
|
+
readVersion: () => readCliVersion(),
|
|
39
|
+
now: Date.now,
|
|
40
|
+
setTimer: (fn, ms) => {
|
|
41
|
+
const t = setTimeout(fn, ms);
|
|
42
|
+
return () => clearTimeout(t);
|
|
43
|
+
},
|
|
44
|
+
onSignal: (signal, fn) => {
|
|
45
|
+
process.on(signal, fn);
|
|
46
|
+
},
|
|
47
|
+
exit: (code) => process.exit(code),
|
|
48
|
+
log: (msg) => console.log(msg),
|
|
49
|
+
pid: process.pid,
|
|
50
|
+
execPath: process.execPath,
|
|
51
|
+
env: process.env,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { BbCommandPlugin } from '@bakers-build/core';
|
|
2
|
+
import type { Command } from 'commander';
|
|
3
|
+
import { type DaemonDeps } from './install.js';
|
|
4
|
+
import { type RunDeps } from './run.js';
|
|
5
|
+
/** `bakers daemon install|uninstall|status|run`. */
|
|
6
|
+
export declare function registerDaemon(program: Command, deps: () => DaemonDeps, runDeps: () => RunDeps): void;
|
|
7
|
+
declare const daemonCommandPlugin: BbCommandPlugin;
|
|
8
|
+
export default daemonCommandPlugin;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { nodeDaemonDeps, nodeRunDeps } from './deps-node.js';
|
|
2
|
+
import { install, status, uninstall, } from './install.js';
|
|
3
|
+
import { run } from './run.js';
|
|
4
|
+
const describe = 'install, remove or inspect the background service that starts autostart conductors';
|
|
5
|
+
function print(s) {
|
|
6
|
+
console.log(`installed: ${s.installed ? 'yes' : 'no'} (${s.unit})`);
|
|
7
|
+
console.log(`running: ${s.running ? 'yes' : 'no'}`);
|
|
8
|
+
if (s.error)
|
|
9
|
+
console.log(`conductors: unknown (${s.error})`);
|
|
10
|
+
else if (s.conductors.length === 0)
|
|
11
|
+
console.log('conductors: none with autostart on this machine');
|
|
12
|
+
else
|
|
13
|
+
for (const c of s.conductors)
|
|
14
|
+
console.log(`${c.label}\t${c.project}\t${c.workspace_root}\t${c.id}`);
|
|
15
|
+
if (s.hint)
|
|
16
|
+
console.log(s.hint);
|
|
17
|
+
}
|
|
18
|
+
/** `bakers daemon install|uninstall|status|run`. */
|
|
19
|
+
export function registerDaemon(program, deps, runDeps) {
|
|
20
|
+
const daemon = program.command('daemon').description(describe);
|
|
21
|
+
const action = (fn) => async () => {
|
|
22
|
+
try {
|
|
23
|
+
print(await fn(deps()));
|
|
24
|
+
}
|
|
25
|
+
catch (err) {
|
|
26
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
27
|
+
process.exitCode = 1;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
daemon
|
|
31
|
+
.command('install')
|
|
32
|
+
.description('install and start the daemon as a user service')
|
|
33
|
+
.action(action(install));
|
|
34
|
+
daemon
|
|
35
|
+
.command('uninstall')
|
|
36
|
+
.description('stop and remove the daemon; conductors keep running')
|
|
37
|
+
.action(action(uninstall));
|
|
38
|
+
daemon
|
|
39
|
+
.command('status')
|
|
40
|
+
.description('whether the daemon is installed and running, and what it starts')
|
|
41
|
+
.action(action((d) => status(d)));
|
|
42
|
+
daemon
|
|
43
|
+
.command('run')
|
|
44
|
+
.description("the service itself: start this machine's autostart conductors and keep them running")
|
|
45
|
+
.action(() => run(runDeps()));
|
|
46
|
+
}
|
|
47
|
+
const daemonCommandPlugin = {
|
|
48
|
+
kind: 'command',
|
|
49
|
+
name: 'daemon',
|
|
50
|
+
describe,
|
|
51
|
+
register(program, host) {
|
|
52
|
+
registerDaemon(program, () => nodeDaemonDeps(host), () => nodeRunDeps(host));
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
export default daemonCommandPlugin;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { ConductorStatus } from '@bakers-build/conductor/contract';
|
|
2
|
+
export type DaemonDeps = {
|
|
3
|
+
platform: NodeJS.Platform;
|
|
4
|
+
/** Runs a service-manager command; rejects when it fails. */
|
|
5
|
+
exec: (file: string, args: string[]) => Promise<void>;
|
|
6
|
+
/** The user's home, where the unit file goes. */
|
|
7
|
+
home: string;
|
|
8
|
+
/** The installing shell's environment. */
|
|
9
|
+
env: NodeJS.ProcessEnv;
|
|
10
|
+
uid: number;
|
|
11
|
+
/** The `bakers` entry the unit runs. */
|
|
12
|
+
bakersBin: string;
|
|
13
|
+
statePath: string;
|
|
14
|
+
daemonState: () => 'none' | 'installed' | 'running';
|
|
15
|
+
/** The signed-in user's conductors; rejects with a fix hint when the
|
|
16
|
+
* machine connection or its login is missing. */
|
|
17
|
+
conductors: () => Promise<ConductorStatus[]>;
|
|
18
|
+
/** This machine's host key. */
|
|
19
|
+
hostKey: () => Promise<string>;
|
|
20
|
+
};
|
|
21
|
+
export type DaemonStatus = {
|
|
22
|
+
installed: boolean;
|
|
23
|
+
running: boolean;
|
|
24
|
+
unit: string;
|
|
25
|
+
/** This machine's conductors with `autostart` on. */
|
|
26
|
+
conductors: {
|
|
27
|
+
id: string;
|
|
28
|
+
label: string;
|
|
29
|
+
project: string;
|
|
30
|
+
workspace_root: string;
|
|
31
|
+
}[];
|
|
32
|
+
error?: string;
|
|
33
|
+
hint?: string;
|
|
34
|
+
};
|
|
35
|
+
/** Scoped to one run, conductor or process: never baked into the unit or passed to a child. */
|
|
36
|
+
export declare const RUN_SCOPED: string[];
|
|
37
|
+
export declare function writeState(path: string, patch: Record<string, unknown>): void;
|
|
38
|
+
export declare function status(d: DaemonDeps, rows?: ConductorStatus[]): Promise<DaemonStatus>;
|
|
39
|
+
export declare function install(d: DaemonDeps): Promise<DaemonStatus>;
|
|
40
|
+
/** Stops and removes only the daemon; the conductors it started keep running. */
|
|
41
|
+
export declare function uninstall(d: DaemonDeps): Promise<DaemonStatus>;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// Install, remove and inspect the user-level service that runs `bakers daemon
|
|
2
|
+
// run`. Every side effect but the files under `home` and `statePath` is
|
|
3
|
+
// injected, so tests run on any OS without systemd or launchd.
|
|
4
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
|
|
5
|
+
import { dirname, join } from 'node:path';
|
|
6
|
+
import { selectToStart } from './select.js';
|
|
7
|
+
import { launchdPlist, systemdUnit } from './units.js';
|
|
8
|
+
const SYSTEMD_UNIT = 'bakers-daemon.service';
|
|
9
|
+
const LAUNCHD_LABEL = 'build.bakers.daemon';
|
|
10
|
+
function unitPath(d) {
|
|
11
|
+
if (d.platform === 'linux')
|
|
12
|
+
return join(d.home, '.config', 'systemd', 'user', SYSTEMD_UNIT);
|
|
13
|
+
if (d.platform === 'darwin')
|
|
14
|
+
return join(d.home, 'Library', 'LaunchAgents', `${LAUNCHD_LABEL}.plist`);
|
|
15
|
+
throw new Error(`the bakers daemon runs on Linux (systemd) and macOS (launchd) only, not ${d.platform}`);
|
|
16
|
+
}
|
|
17
|
+
/** Scoped to one run, conductor or process: never baked into the unit or passed to a child. */
|
|
18
|
+
export const RUN_SCOPED = [
|
|
19
|
+
'BAKERS_CONDUCTOR',
|
|
20
|
+
'BAKERS_CONDUCTOR_CONFIG',
|
|
21
|
+
'BAKERS_CONDUCTOR_LOG',
|
|
22
|
+
'BAKERS_CONDUCTOR_TOKEN',
|
|
23
|
+
'BAKERS_CONDUCTOR_URL',
|
|
24
|
+
'BAKERS_RESTART_SINCE',
|
|
25
|
+
'BAKERS_RUN_UUID',
|
|
26
|
+
'BAKERS_SUPERVISED',
|
|
27
|
+
];
|
|
28
|
+
/** PATH, HOME, TMPDIR and the machine-wide BAKERS_* variables of the installing shell. */
|
|
29
|
+
function unitEnv(env) {
|
|
30
|
+
return Object.fromEntries(Object.entries(env).filter((e) => e[1] !== undefined &&
|
|
31
|
+
(['PATH', 'HOME', 'TMPDIR'].includes(e[0]) ||
|
|
32
|
+
(e[0].startsWith('BAKERS_') && !RUN_SCOPED.includes(e[0])))));
|
|
33
|
+
}
|
|
34
|
+
export function writeState(path, patch) {
|
|
35
|
+
let prev = {};
|
|
36
|
+
try {
|
|
37
|
+
prev = JSON.parse(readFileSync(path, 'utf8'));
|
|
38
|
+
}
|
|
39
|
+
catch { }
|
|
40
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
41
|
+
// A reader never sees a half-written file.
|
|
42
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
43
|
+
writeFileSync(tmp, `${JSON.stringify({ ...prev, ...patch })}\n`);
|
|
44
|
+
renameSync(tmp, path);
|
|
45
|
+
}
|
|
46
|
+
export async function status(d, rows) {
|
|
47
|
+
const unit = unitPath(d);
|
|
48
|
+
let error;
|
|
49
|
+
let hostKey = '';
|
|
50
|
+
try {
|
|
51
|
+
rows ??= await d.conductors();
|
|
52
|
+
hostKey = await d.hostKey();
|
|
53
|
+
}
|
|
54
|
+
catch (err) {
|
|
55
|
+
error = err instanceof Error ? err.message : String(err);
|
|
56
|
+
rows = [];
|
|
57
|
+
}
|
|
58
|
+
const managed = selectToStart(rows ?? [], {
|
|
59
|
+
hostKey,
|
|
60
|
+
firstPass: true,
|
|
61
|
+
exists: () => true,
|
|
62
|
+
running: () => false,
|
|
63
|
+
stopped: () => false,
|
|
64
|
+
});
|
|
65
|
+
return {
|
|
66
|
+
installed: existsSync(unit),
|
|
67
|
+
running: d.daemonState() === 'running',
|
|
68
|
+
unit,
|
|
69
|
+
conductors: managed.map((r) => ({
|
|
70
|
+
id: r.id,
|
|
71
|
+
label: r.label,
|
|
72
|
+
project: r.project,
|
|
73
|
+
workspace_root: r.workspaceRoot,
|
|
74
|
+
})),
|
|
75
|
+
...(error ? { error } : {}),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
export async function install(d) {
|
|
79
|
+
const unit = unitPath(d);
|
|
80
|
+
// Refuses before writing anything: the daemon cannot list conductors without it.
|
|
81
|
+
const rows = await d.conductors();
|
|
82
|
+
await d.hostKey();
|
|
83
|
+
const opts = { bakersBin: d.bakersBin, env: unitEnv(d.env), home: d.home };
|
|
84
|
+
mkdirSync(dirname(unit), { recursive: true });
|
|
85
|
+
writeFileSync(unit, d.platform === 'linux' ? systemdUnit(opts) : launchdPlist(opts), { mode: 0o600 });
|
|
86
|
+
// The mode above applies to a new file only; a reinstall keeps the old one.
|
|
87
|
+
chmodSync(unit, 0o600);
|
|
88
|
+
// Before the service starts, so the daemon's own pid write is not overwritten.
|
|
89
|
+
writeState(d.statePath, {
|
|
90
|
+
installed: true,
|
|
91
|
+
pid: null,
|
|
92
|
+
last_exit: null,
|
|
93
|
+
bakers: d.bakersBin,
|
|
94
|
+
});
|
|
95
|
+
if (d.platform === 'linux') {
|
|
96
|
+
await d.exec('systemctl', ['--user', 'daemon-reload']);
|
|
97
|
+
await d.exec('systemctl', ['--user', 'enable', SYSTEMD_UNIT]);
|
|
98
|
+
// restart, not --now: an already running daemon must load the new unit.
|
|
99
|
+
await d.exec('systemctl', ['--user', 'restart', SYSTEMD_UNIT]);
|
|
100
|
+
return {
|
|
101
|
+
...(await status(d, rows)),
|
|
102
|
+
hint: 'to keep it running without an open login session, run: loginctl enable-linger $USER',
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
// A loaded agent would make bootstrap fail; not loaded is fine.
|
|
106
|
+
await d
|
|
107
|
+
.exec('launchctl', ['bootout', `gui/${d.uid}/${LAUNCHD_LABEL}`])
|
|
108
|
+
.catch(() => { });
|
|
109
|
+
await d.exec('launchctl', ['bootstrap', `gui/${d.uid}`, unit]);
|
|
110
|
+
return status(d, rows);
|
|
111
|
+
}
|
|
112
|
+
/** Stops and removes only the daemon; the conductors it started keep running. */
|
|
113
|
+
export async function uninstall(d) {
|
|
114
|
+
const unit = unitPath(d);
|
|
115
|
+
if (existsSync(unit)) {
|
|
116
|
+
if (d.platform === 'linux')
|
|
117
|
+
await d.exec('systemctl', ['--user', 'disable', '--now', SYSTEMD_UNIT]);
|
|
118
|
+
else
|
|
119
|
+
await d.exec('launchctl', ['bootout', `gui/${d.uid}/${LAUNCHD_LABEL}`]);
|
|
120
|
+
rmSync(unit);
|
|
121
|
+
}
|
|
122
|
+
writeState(d.statePath, { installed: false });
|
|
123
|
+
return status(d);
|
|
124
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { DAEMON_TOOL_DEFINITIONS } from './tool-definitions.js';
|
|
2
|
+
export const commands = (acc) => [
|
|
3
|
+
...acc,
|
|
4
|
+
{
|
|
5
|
+
name: 'daemon',
|
|
6
|
+
plugin: '@bakers-build/addon-daemon',
|
|
7
|
+
describe: 'install, remove or inspect the background service that starts autostart conductors',
|
|
8
|
+
},
|
|
9
|
+
];
|
|
10
|
+
export const scopes = ['machine'];
|
|
11
|
+
// Served by this machine's conductors to every run.
|
|
12
|
+
export const tools = {
|
|
13
|
+
contract: 1,
|
|
14
|
+
tools: DAEMON_TOOL_DEFINITIONS,
|
|
15
|
+
handlers: (options) => import('./tools.js').then((m) => m.toolsFor(options)),
|
|
16
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { BbRemote, ConductorStatus, DetachedChild, DetachedSpawnRequest } from '@bakers-build/conductor';
|
|
2
|
+
export type RunDeps = {
|
|
3
|
+
statePath: string;
|
|
4
|
+
/** Rejects with a fix hint when the machine connection or its login is missing. */
|
|
5
|
+
remote: () => Promise<Pick<BbRemote, 'listConductors'>>;
|
|
6
|
+
hostKey: () => Promise<string>;
|
|
7
|
+
spawn: (req: DetachedSpawnRequest) => Promise<DetachedChild>;
|
|
8
|
+
/** Whether the conductor's process is alive, as `bakers conductor ls` sees it. */
|
|
9
|
+
running: (row: ConductorStatus, hostKey: string) => boolean;
|
|
10
|
+
readVersion: () => string;
|
|
11
|
+
now: () => number;
|
|
12
|
+
/** Calls `fn` after `ms`; returns its cancel. */
|
|
13
|
+
setTimer: (fn: () => void, ms: number) => () => void;
|
|
14
|
+
onSignal: (signal: 'SIGTERM' | 'SIGINT', fn: () => void) => void;
|
|
15
|
+
exit: (code: number) => void;
|
|
16
|
+
log: (msg: string) => void;
|
|
17
|
+
pid: number;
|
|
18
|
+
execPath: string;
|
|
19
|
+
env: NodeJS.ProcessEnv;
|
|
20
|
+
};
|
|
21
|
+
/** Resolves after the first pass; the timers drive the rest. */
|
|
22
|
+
export declare function run(d: RunDeps): Promise<void>;
|
package/dist/src/run.js
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
// The loop behind `bakers daemon run`: one selection pass every 30 s and at
|
|
2
|
+
// once when a child exits; it starts this machine's autostart conductors.
|
|
3
|
+
// Every side effect but the state file and the markers is injected.
|
|
4
|
+
import { existsSync, readFileSync, rmSync } from 'node:fs';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { configHomeOf, stopMarkerOf, UNKNOWN_VERSION, } from '@bakers-build/core';
|
|
7
|
+
import { RUN_SCOPED, writeState } from './install.js';
|
|
8
|
+
import { nextDelay, selectToStart } from './select.js';
|
|
9
|
+
const TICK = 30_000;
|
|
10
|
+
/** A child that ran this long starts its backoff over. */
|
|
11
|
+
const STABLE = 600_000;
|
|
12
|
+
/** The exit code of a conductor that asks to be restarted. */
|
|
13
|
+
const RESTART = 75;
|
|
14
|
+
function readState(path) {
|
|
15
|
+
try {
|
|
16
|
+
return JSON.parse(readFileSync(path, 'utf8')) ?? {};
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return {};
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const marker = (row) => stopMarkerOf(row.workspaceRoot, row.conductorName);
|
|
23
|
+
const message = (err) => err instanceof Error ? err.message : String(err);
|
|
24
|
+
/** Resolves after the first pass; the timers drive the rest. */
|
|
25
|
+
export async function run(d) {
|
|
26
|
+
const last = readState(d.statePath).last_exit;
|
|
27
|
+
// After boot, login, install or a shutdown; a crash or update keeps the markers.
|
|
28
|
+
let firstPass = last === 'shutdown' || last == null;
|
|
29
|
+
let remote;
|
|
30
|
+
let hostKey;
|
|
31
|
+
try {
|
|
32
|
+
remote = await d.remote();
|
|
33
|
+
hostKey = await d.hostKey();
|
|
34
|
+
}
|
|
35
|
+
catch (err) {
|
|
36
|
+
d.log(`bakers daemon: ${message(err)}`);
|
|
37
|
+
writeState(d.statePath, { pid: null });
|
|
38
|
+
d.exit(1);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
// Until a signal records a shutdown, a crash must read as one that keeps the markers.
|
|
42
|
+
writeState(d.statePath, { pid: d.pid, last_exit: 'restart' });
|
|
43
|
+
const startVersion = d.readVersion();
|
|
44
|
+
let lastVersion;
|
|
45
|
+
/** Conductor id → pid of the live child this daemon started. */
|
|
46
|
+
const children = new Map();
|
|
47
|
+
/** Conductor id → pid of its last child that exited; its row may still show it alive. */
|
|
48
|
+
const exited = new Map();
|
|
49
|
+
const backoff = new Map();
|
|
50
|
+
let serverAttempts = 0;
|
|
51
|
+
let cancel = () => { };
|
|
52
|
+
let done = false;
|
|
53
|
+
let busy = false;
|
|
54
|
+
let again = false;
|
|
55
|
+
const finish = (lastExit, code) => {
|
|
56
|
+
done = true;
|
|
57
|
+
cancel();
|
|
58
|
+
// The children keep running: they are detached and outlive the daemon.
|
|
59
|
+
writeState(d.statePath, { pid: null, last_exit: lastExit });
|
|
60
|
+
d.exit(code);
|
|
61
|
+
};
|
|
62
|
+
for (const signal of ['SIGTERM', 'SIGINT'])
|
|
63
|
+
d.onSignal(signal, () => {
|
|
64
|
+
d.log(`bakers daemon: stopping on ${signal}`);
|
|
65
|
+
finish('shutdown', 0);
|
|
66
|
+
});
|
|
67
|
+
const schedule = (ms) => {
|
|
68
|
+
cancel();
|
|
69
|
+
cancel = d.setTimer(() => void pass(), ms);
|
|
70
|
+
};
|
|
71
|
+
const failed = (id, uptime) => {
|
|
72
|
+
const attempts = uptime >= STABLE ? 0 : (backoff.get(id)?.attempts ?? 0);
|
|
73
|
+
backoff.set(id, {
|
|
74
|
+
attempts: attempts + 1,
|
|
75
|
+
notBefore: d.now() + nextDelay(attempts),
|
|
76
|
+
});
|
|
77
|
+
};
|
|
78
|
+
const start = async (row) => {
|
|
79
|
+
const name = row.conductorName;
|
|
80
|
+
try {
|
|
81
|
+
// Read again on every spawn: a reinstall may point at a new binary.
|
|
82
|
+
const bakers = readState(d.statePath).bakers;
|
|
83
|
+
if (typeof bakers !== 'string')
|
|
84
|
+
throw new Error(`no bakers path in ${d.statePath}; run: bakers daemon install`);
|
|
85
|
+
const child = await d.spawn({
|
|
86
|
+
// The argv of a detached `bakers conductor start`.
|
|
87
|
+
argv: [
|
|
88
|
+
d.execPath,
|
|
89
|
+
bakers,
|
|
90
|
+
...(name && name !== 'conductor' ? ['--conductor', name] : []),
|
|
91
|
+
'conductor',
|
|
92
|
+
'start',
|
|
93
|
+
'--foreground',
|
|
94
|
+
'--no-update-check',
|
|
95
|
+
],
|
|
96
|
+
cwd: row.workspaceRoot,
|
|
97
|
+
// The argv alone selects the conductor; the daemon's own run variables do not leak.
|
|
98
|
+
env: {
|
|
99
|
+
...Object.fromEntries(Object.entries(d.env).filter(([k]) => !RUN_SCOPED.includes(k))),
|
|
100
|
+
BAKERS_CONDUCTOR_LOG: 'file',
|
|
101
|
+
BAKERS_SUPERVISED: '1',
|
|
102
|
+
},
|
|
103
|
+
logPath: join(configHomeOf(row.workspaceRoot), 'log.txt'),
|
|
104
|
+
});
|
|
105
|
+
const startedAt = d.now();
|
|
106
|
+
children.set(row.id, child.pid);
|
|
107
|
+
d.log(`bakers daemon: started ${row.label} (${row.id}), pid ${child.pid}`);
|
|
108
|
+
void child.exited.then((code) => {
|
|
109
|
+
children.delete(row.id);
|
|
110
|
+
exited.set(row.id, child.pid);
|
|
111
|
+
if (done)
|
|
112
|
+
return;
|
|
113
|
+
d.log(`bakers daemon: ${row.label} (${row.id}) exited with ${code}`);
|
|
114
|
+
// A requested restart is respawned at once.
|
|
115
|
+
if (code === RESTART)
|
|
116
|
+
backoff.delete(row.id);
|
|
117
|
+
else
|
|
118
|
+
failed(row.id, d.now() - startedAt);
|
|
119
|
+
void pass();
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
catch (err) {
|
|
123
|
+
d.log(`bakers daemon: could not start ${row.label}: ${message(err)}`);
|
|
124
|
+
failed(row.id, 0);
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
const selectAndStart = async () => {
|
|
128
|
+
const version = d.readVersion();
|
|
129
|
+
const previous = lastVersion;
|
|
130
|
+
lastVersion = version;
|
|
131
|
+
// A half-written install reads differently on the next pass, as in the conductor.
|
|
132
|
+
if (version !== UNKNOWN_VERSION &&
|
|
133
|
+
version !== startVersion &&
|
|
134
|
+
version === previous) {
|
|
135
|
+
d.log(`bakers daemon: CLI version changed ${startVersion} → ${version}`);
|
|
136
|
+
finish('restart', 1);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
let rows;
|
|
140
|
+
try {
|
|
141
|
+
// shortcut: one page of 200 conductors, page further when remote-drupal exposes a next page
|
|
142
|
+
rows = await remote.listConductors('me');
|
|
143
|
+
serverAttempts = 0;
|
|
144
|
+
}
|
|
145
|
+
catch (err) {
|
|
146
|
+
const ms = nextDelay(serverAttempts++);
|
|
147
|
+
d.log(`bakers daemon: ${message(err)}; retrying in ${ms / 1000} s`);
|
|
148
|
+
schedule(ms);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
if (done)
|
|
152
|
+
return;
|
|
153
|
+
const toStart = selectToStart(rows, {
|
|
154
|
+
hostKey,
|
|
155
|
+
firstPass,
|
|
156
|
+
exists: existsSync,
|
|
157
|
+
// A live child counts too: its row may not show it yet.
|
|
158
|
+
// shortcut: a daemon restart between spawn and the child's first heartbeat can start a duplicate, add an exclusive lock in .bakers when that shows up
|
|
159
|
+
running: (r) => children.has(r.id) ||
|
|
160
|
+
(!(exited.has(r.id) && r.lastPid === exited.get(r.id)) &&
|
|
161
|
+
d.running(r, hostKey)),
|
|
162
|
+
stopped: (r) => existsSync(marker(r)),
|
|
163
|
+
});
|
|
164
|
+
const clear = firstPass;
|
|
165
|
+
firstPass = false;
|
|
166
|
+
for (const row of toStart) {
|
|
167
|
+
if (done)
|
|
168
|
+
return;
|
|
169
|
+
if ((backoff.get(row.id)?.notBefore ?? 0) > d.now())
|
|
170
|
+
continue;
|
|
171
|
+
if (clear)
|
|
172
|
+
rmSync(marker(row), { force: true });
|
|
173
|
+
await start(row);
|
|
174
|
+
}
|
|
175
|
+
if (done)
|
|
176
|
+
return;
|
|
177
|
+
const waits = [...backoff.values()]
|
|
178
|
+
.map((b) => b.notBefore - d.now())
|
|
179
|
+
.filter((ms) => ms > 0);
|
|
180
|
+
schedule(Math.min(TICK, ...waits));
|
|
181
|
+
};
|
|
182
|
+
// Passes never overlap: one asked for during a pass runs right after it.
|
|
183
|
+
const pass = async () => {
|
|
184
|
+
if (done)
|
|
185
|
+
return;
|
|
186
|
+
if (busy) {
|
|
187
|
+
again = true;
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
busy = true;
|
|
191
|
+
try {
|
|
192
|
+
await selectAndStart();
|
|
193
|
+
}
|
|
194
|
+
catch (err) {
|
|
195
|
+
d.log(`bakers daemon: pass failed: ${message(err)}`);
|
|
196
|
+
schedule(TICK);
|
|
197
|
+
}
|
|
198
|
+
finally {
|
|
199
|
+
busy = false;
|
|
200
|
+
}
|
|
201
|
+
if (again) {
|
|
202
|
+
again = false;
|
|
203
|
+
return pass();
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
await pass();
|
|
207
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ConductorStatus } from '@bakers-build/conductor/contract';
|
|
2
|
+
export type SelectOpts = {
|
|
3
|
+
hostKey: string;
|
|
4
|
+
firstPass: boolean;
|
|
5
|
+
exists: (path: string) => boolean;
|
|
6
|
+
running: (row: ConductorStatus) => boolean;
|
|
7
|
+
stopped: (row: ConductorStatus) => boolean;
|
|
8
|
+
};
|
|
9
|
+
export declare function selectToStart(rows: ConductorStatus[], o: SelectOpts): ConductorStatus[];
|
|
10
|
+
export declare const nextDelay: (attempts: number) => number;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export function selectToStart(rows, o) {
|
|
2
|
+
return rows.filter((r) => r.hostKey === o.hostKey &&
|
|
3
|
+
r.autostart &&
|
|
4
|
+
o.exists(r.workspaceRoot) &&
|
|
5
|
+
!o.running(r) &&
|
|
6
|
+
(o.firstPass || !o.stopped(r)));
|
|
7
|
+
}
|
|
8
|
+
export const nextDelay = (attempts) => Math.min(60000, 1000 * 2 ** attempts);
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// The daemon tools' definitions, apart from their handlers so the preset
|
|
2
|
+
// stays import-light (the handlers load lazily).
|
|
3
|
+
export const DAEMON_TOOL_DEFINITIONS = {
|
|
4
|
+
daemon_install: {
|
|
5
|
+
description: "Install and start this machine's bakers daemon, the user service that starts the conductors flagged autostart; returns the daemon status as JSON.",
|
|
6
|
+
},
|
|
7
|
+
daemon_uninstall: {
|
|
8
|
+
description: "Stop and remove this machine's bakers daemon; running conductors keep running. Returns the daemon status as JSON.",
|
|
9
|
+
},
|
|
10
|
+
daemon_status: {
|
|
11
|
+
description: "This machine's bakers daemon as JSON: installed, running, and the conductors it manages (autostart on).",
|
|
12
|
+
},
|
|
13
|
+
};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { ToolHandler } from '@bakers-build/conductor/contract';
|
|
2
|
+
import { type DaemonDeps } from './install.js';
|
|
3
|
+
export declare function daemonTools(deps: () => DaemonDeps): Record<string, ToolHandler>;
|
|
4
|
+
export declare function toolsFor(_options?: unknown): Record<string, ToolHandler>;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// The daemon tools, served by this machine's conductors; `bakers daemon`
|
|
2
|
+
// calls the same functions.
|
|
3
|
+
import { nodeDaemonDeps } from './deps-node.js';
|
|
4
|
+
import { install, status, uninstall } from './install.js';
|
|
5
|
+
export function daemonTools(deps) {
|
|
6
|
+
const json = async (run) => ({
|
|
7
|
+
text: JSON.stringify(await run(deps())),
|
|
8
|
+
});
|
|
9
|
+
return {
|
|
10
|
+
daemon_install: () => json(install),
|
|
11
|
+
daemon_uninstall: () => json(uninstall),
|
|
12
|
+
daemon_status: () => json((d) => status(d)),
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
export function toolsFor(_options) {
|
|
16
|
+
return daemonTools(() => nodeDaemonDeps());
|
|
17
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
const systemdQuote = (v) => `"${v.replace(/[\\"]/g, '\\$&').replace(/\n/g, '\\n').replace(/%/g, '%%')}"`;
|
|
2
|
+
export function systemdUnit(o) {
|
|
3
|
+
const env = Object.entries(o.env).map(([k, v]) => `Environment=${systemdQuote(`${k}=${v}`)}`);
|
|
4
|
+
return [
|
|
5
|
+
'[Unit]',
|
|
6
|
+
'Description=bakers.build daemon: starts autostart conductors',
|
|
7
|
+
'',
|
|
8
|
+
'[Service]',
|
|
9
|
+
// systemd expands $VAR in ExecStart only; $$ is the literal dollar.
|
|
10
|
+
`ExecStart=${systemdQuote(o.bakersBin.replace(/\$/g, '$$$$'))} daemon run`,
|
|
11
|
+
'Restart=always',
|
|
12
|
+
// Without a delay a fast exit loop hits the start limit and the unit stays failed.
|
|
13
|
+
'RestartSec=10',
|
|
14
|
+
'KillMode=process',
|
|
15
|
+
...env,
|
|
16
|
+
'',
|
|
17
|
+
'[Install]',
|
|
18
|
+
'WantedBy=default.target',
|
|
19
|
+
'',
|
|
20
|
+
].join('\n');
|
|
21
|
+
}
|
|
22
|
+
const xml = (v) => v
|
|
23
|
+
.replace(/&/g, '&')
|
|
24
|
+
.replace(/</g, '<')
|
|
25
|
+
.replace(/>/g, '>')
|
|
26
|
+
.replace(/"/g, '"')
|
|
27
|
+
.replace(/'/g, ''');
|
|
28
|
+
export function launchdPlist(o) {
|
|
29
|
+
const log = xml(`${o.home}/Library/Logs/bakers-daemon.log`);
|
|
30
|
+
const env = Object.entries(o.env)
|
|
31
|
+
.map(([k, v]) => ` <key>${xml(k)}</key>\n <string>${xml(v)}</string>`)
|
|
32
|
+
.join('\n');
|
|
33
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
34
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
35
|
+
<plist version="1.0">
|
|
36
|
+
<dict>
|
|
37
|
+
<key>Label</key>
|
|
38
|
+
<string>build.bakers.daemon</string>
|
|
39
|
+
<key>ProgramArguments</key>
|
|
40
|
+
<array>
|
|
41
|
+
<string>${xml(o.bakersBin)}</string>
|
|
42
|
+
<string>daemon</string>
|
|
43
|
+
<string>run</string>
|
|
44
|
+
</array>
|
|
45
|
+
<key>RunAtLoad</key>
|
|
46
|
+
<true/>
|
|
47
|
+
<key>KeepAlive</key>
|
|
48
|
+
<true/>
|
|
49
|
+
<key>AbandonProcessGroup</key>
|
|
50
|
+
<true/>
|
|
51
|
+
<key>StandardOutPath</key>
|
|
52
|
+
<string>${log}</string>
|
|
53
|
+
<key>StandardErrorPath</key>
|
|
54
|
+
<string>${log}</string>
|
|
55
|
+
<key>EnvironmentVariables</key>
|
|
56
|
+
<dict>
|
|
57
|
+
${env}
|
|
58
|
+
</dict>
|
|
59
|
+
</dict>
|
|
60
|
+
</plist>
|
|
61
|
+
`;
|
|
62
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bakers-build/addon-daemon",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.19.1-next.7",
|
|
4
|
+
"description": "bakers.build daemon command plugin: a background service that starts the conductors flagged autostart.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./dist/src/index.js",
|
|
9
|
+
"./preset": "./dist/src/preset.js"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist/src",
|
|
13
|
+
"options.schema.json"
|
|
14
|
+
],
|
|
15
|
+
"publishConfig": {
|
|
16
|
+
"access": "public"
|
|
17
|
+
},
|
|
18
|
+
"homepage": "https://bakers.build",
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://github.com/bakers-build/bakers-build.git",
|
|
22
|
+
"directory": "bakers-cli/addons/daemon"
|
|
23
|
+
},
|
|
24
|
+
"peerDependencies": {
|
|
25
|
+
"@bakers-build/conductor": "^0.19.1-next.7",
|
|
26
|
+
"@bakers-build/core": "^0.19.1-next.7"
|
|
27
|
+
},
|
|
28
|
+
"bakersBuild": {
|
|
29
|
+
"commit": "fcf15c6f0cb6e8317fdc683ac1638e0b84ed861c",
|
|
30
|
+
"channel": "next"
|
|
31
|
+
}
|
|
32
|
+
}
|