@crvouga/homelab 0.23.11 → 0.23.12

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.
@@ -50,6 +50,16 @@ def reserved(root, budget):
50
50
  return total
51
51
 
52
52
 
53
+ def grant(policy, budget, reserve, headroom, reservations):
54
+ # A shell's maximum is an upper bound, not its minimum working set. Keep
55
+ # small inspection/recovery commands usable without overcommitting memory.
56
+ mib = 1024 * 1024
57
+ minimum = min(budget, policy.get('minimumMemoryMiB', 256) * mib)
58
+ granted = min(budget, max(0, headroom - reservations - reserve))
59
+ granted = granted // mib * mib
60
+ return granted if granted >= minimum else 0
61
+
62
+
53
63
  def main():
54
64
  policy = json.loads(Path(__file__).with_name('agent-tool-policy.json').read_text())
55
65
  runtime = Path(os.environ['XDG_RUNTIME_DIR'])
@@ -67,9 +77,15 @@ def main():
67
77
  # section. Kernel hard caps enforce every granted reservation afterwards.
68
78
  with (runtime / 'homelab-tool-admission.lock').open('a') as lock:
69
79
  fcntl.flock(lock, fcntl.LOCK_EX)
70
- if available(root, Path('/proc')) - reserved(root, budget) < budget + reserve:
80
+ requested = budget
81
+ budget = grant(policy, requested, reserve, available(root, Path('/proc')),
82
+ reserved(root, requested))
83
+ if budget == 0:
71
84
  sys.stderr.write('AGENT_TOOL_REFUSED: insufficient unreserved memory for a bounded shell job. Finish other jobs or move work to another worker, then retry.\n')
72
85
  return 75
86
+ if budget < requested:
87
+ sys.stderr.write('AGENT_TOOL_BUDGET: reduced memory cap to ' +
88
+ str(budget // (1024 * 1024)) + ' MiB; reduce build workers or retry later if this job exceeds it.\n')
73
89
  unit = 'homelab-tool-' + uuid.uuid4().hex + '.scope'
74
90
  env = dict(os.environ)
75
91
  env.pop('BASH_ENV', None)
@@ -23,7 +23,7 @@
23
23
  "docker-compose-v2": "2.40.3+ds1-0ubuntu1~24.04.1",
24
24
  "docker-buildx": "0.30.1-0ubuntu1~24.04.1",
25
25
  "build-essential": "12.10ubuntu1",
26
- "ca-certificates": "20260816ubuntu0.24.04.2",
26
+ "ca-certificates": "20261130ubuntu0.24.04.1",
27
27
  "curl": "8.5.0-2ubuntu10.16",
28
28
  "git": "1:2.43.0-1ubuntu7.4",
29
29
  "python3": "3.12.3-0ubuntu2.1",
@@ -66,7 +66,7 @@
66
66
  }
67
67
  }
68
68
  ],
69
- "snapshot": "20261129T000000Z",
69
+ "snapshot": "20261201T000000Z",
70
70
  "packages": {
71
71
  "sudo": "1.9.17p2-1ubuntu3.2",
72
72
  "openssh-server": "1:10.2p1-2ubuntu3.8",
@@ -75,7 +75,7 @@
75
75
  "docker-compose-v2": "2.40.3+ds1-0ubuntu1",
76
76
  "docker-buildx": "0.30.1-0ubuntu1",
77
77
  "build-essential": "12.12ubuntu2.26.04.2",
78
- "ca-certificates": "20260816ubuntu0.26.04.2",
78
+ "ca-certificates": "20261130ubuntu0.26.04.1",
79
79
  "curl": "8.18.0-1ubuntu2.8",
80
80
  "git": "1:2.53.0-1ubuntu1.1",
81
81
  "python3": "3.14.3-0ubuntu2",
@@ -277,6 +277,7 @@
277
277
  "diskGcFetchMaxMiB": 256,
278
278
  "agentTool": {
279
279
  "memoryMiB": 4096,
280
+ "minimumMemoryMiB": 256,
280
281
  "reserveMiB": 2048,
281
282
  "swapMiB": 512,
282
283
  "providerReserveMiB": 1024
@@ -19,14 +19,31 @@ import { configureShellPath } from './shell-path';
19
19
  import { installNativeAws } from './native-aws';
20
20
  import { installNativeT3 } from './native-t3';
21
21
 
22
- function run(args: string[]): void {
23
- const result = spawnSync(args[0]!, args.slice(1), {
24
- cwd: workspaceRoot,
25
- stdio: 'inherit',
26
- });
27
- if (result.error) throw result.error;
28
- if (result.status !== 0)
29
- throw new Error(`${args.join(' ')} failed (${result.status})`);
22
+ /** Pauses before each further try of a download: a registry or release host
23
+ * that answered with an error a moment ago usually answers the next call. */
24
+ const RETRY_PAUSES_SECONDS = [5, 20];
25
+
26
+ /**
27
+ * Runs a command. One that fetches from the network is given `pauses`, the
28
+ * seconds to wait before each further try, so a single failed download does
29
+ * not fail the whole toolchain; the last failure is the one reported.
30
+ */
31
+ export function run(args: string[], pauses: readonly number[] = []): void {
32
+ for (let attempt = 0; ; attempt++) {
33
+ const result = spawnSync(args[0]!, args.slice(1), {
34
+ cwd: workspaceRoot,
35
+ stdio: 'inherit',
36
+ });
37
+ if (result.error) throw result.error;
38
+ if (result.status === 0) return;
39
+ const pause = pauses[attempt];
40
+ if (pause === undefined)
41
+ throw new Error(`${args.join(' ')} failed (${result.status})`);
42
+ console.error(
43
+ `${args[0]} failed (${result.status}); trying again in ${pause}s.`
44
+ );
45
+ spawnSync('sleep', [String(pause)]);
46
+ }
30
47
  }
31
48
 
32
49
  export async function syncTools(
@@ -44,7 +61,7 @@ export async function syncTools(
44
61
  const selected = worker
45
62
  ? Object.keys(workerToolset(config.tools, config.vars, selection))
46
63
  : [];
47
- run(['mise', 'install', '--locked', ...selected]);
64
+ run(['mise', 'install', '--locked', ...selected], RETRY_PAUSES_SECONDS);
48
65
  observe('aws');
49
66
  if (!worker) await installNativeAws();
50
67
  observe('t3');
@@ -77,15 +94,18 @@ if (import.meta.main) {
77
94
  if (!process.argv.includes('--tools-only')) {
78
95
  phase = 'dependencies';
79
96
  report(phase, 'running');
80
- run([
81
- 'mise',
82
- 'exec',
83
- '--locked',
84
- '--',
85
- 'bun',
86
- 'install',
87
- '--frozen-lockfile',
88
- ]);
97
+ run(
98
+ [
99
+ 'mise',
100
+ 'exec',
101
+ '--locked',
102
+ '--',
103
+ 'bun',
104
+ 'install',
105
+ '--frozen-lockfile',
106
+ ],
107
+ RETRY_PAUSES_SECONDS
108
+ );
89
109
  }
90
110
  report(phase, 'passed');
91
111
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crvouga/homelab",
3
- "version": "0.23.11",
3
+ "version": "0.23.12",
4
4
  "description": "Keeps a set of development machines in sync: one manager and many workers",
5
5
  "license": "MIT",
6
6
  "repository": "github:crvouga/homelab",
@@ -74,5 +74,5 @@
74
74
  "engines": {
75
75
  "node": ">=22"
76
76
  },
77
- "gitHead": "9be01ec43800a7b1ab2a4e0de570807c8ceefcc1"
77
+ "gitHead": "1d754c76bc9281a6df4a4db8f257687e2b390b6e"
78
78
  }
@@ -1,3 +1,4 @@
1
+ import { sshArgs } from '../ssh';
1
2
  import { sshConnectivity } from '../ssh-health';
2
3
  import { managerCustomizations } from '../state/t3-customizations';
3
4
  import { managerClientSettings } from '../state/t3-client-settings';
@@ -421,6 +422,7 @@ function deployWithMonitoring(
421
422
  definition: canonical,
422
423
  verifyConnectivity: (target) => sshConnectivity(target, run),
423
424
  playbook: packagePlaybook(run),
425
+ accountHome: (target) => accountHome(target, run),
424
426
  converge,
425
427
  control: () =>
426
428
  (control ??= fleetTailnetControl(canonical.tailnet, secret)),
@@ -434,6 +436,19 @@ function deployWithMonitoring(
434
436
  };
435
437
  }
436
438
 
439
+ /** The account's home on a worker, as its SSH alias reports it. */
440
+ async function accountHome(
441
+ node: FleetNode,
442
+ run: Runner
443
+ ): Promise<string | null> {
444
+ const result = await run([...sshArgs(node), 'printf "%s" "$HOME"'], {
445
+ timeoutMs: 20_000,
446
+ });
447
+ return result.ok && /^\/[A-Za-z0-9._/-]{1,4000}$/.test(result.stdout)
448
+ ? result.stdout
449
+ : null;
450
+ }
451
+
437
452
  /** One converge of a worker: privilege, Vault, the bootstrap, then what is
438
453
  * verified from the manager and the worker's monitoring.
439
454
  */
@@ -1,5 +1,9 @@
1
1
  import { sshArgs } from '../ssh';
2
- import { playbookAddress } from '../worker-reboot';
2
+ import {
3
+ MANAGED_WORKSPACE,
4
+ playbookAddress,
5
+ workerHome,
6
+ } from '../worker-reboot';
3
7
  import type { FleetDefinition } from '../definition';
4
8
  import {
5
9
  TailnetControlError,
@@ -31,6 +35,10 @@ export interface WorkerDeployment {
31
35
  verifyConnectivity?: (node: FleetNode) => Promise<Check[]>;
32
36
  /** Applies a playbook of the package from the manager. */
33
37
  playbook: PackagePlaybook;
38
+ /** The account's home on the worker, asked over its SSH alias; null when
39
+ * it is not answered. Needed only for a roster entry whose workspace does
40
+ * not name the account home. */
41
+ accountHome?: (node: FleetNode) => Promise<string | null>;
34
42
  /** One converge of the worker; `tailnetKey` is handed to its bootstrap. */
35
43
  converge: (
36
44
  node: FleetNode,
@@ -66,6 +74,11 @@ export async function deployWorker(
66
74
  before.push(...(await keyExpiry(node, deployment)));
67
75
  let target = node;
68
76
  let result = await deployment.converge(target, revision, key);
77
+ // The worker's own home, for the playbooks the manager applies, when the
78
+ // roster workspace does not carry it.
79
+ let managed: Promise<FleetNode> | undefined;
80
+ const playbookNode = (): Promise<FleetNode> =>
81
+ (managed ??= managedWorkspace(target, deployment));
69
82
  const account = await rootOnly(node, result, deployment);
70
83
  if (account) {
71
84
  before.push(account.check);
@@ -77,7 +90,7 @@ export async function deployWorker(
77
90
  const maintenance: Check[] = [];
78
91
  if (deployment.maintenanceReboot && tailscaleUpgradePending(result.checks)) {
79
92
  const upgrade = await upgradeTailscale(
80
- target,
93
+ await playbookNode(),
81
94
  revision,
82
95
  deployment.playbook
83
96
  );
@@ -88,7 +101,7 @@ export async function deployWorker(
88
101
  const reason = rebootReason(node.id, result.checks, deployment);
89
102
  if (reason) {
90
103
  const reboot = await rebootWorker(
91
- target,
104
+ await playbookNode(),
92
105
  {
93
106
  revision,
94
107
  reason,
@@ -108,13 +121,26 @@ export async function deployWorker(
108
121
  (c) => c.id.startsWith('bootstrap:') && c.status === 'fail'
109
122
  )
110
123
  ) {
111
- result.checks.push(await nativeSsh(target, deployment));
124
+ result.checks.push(await nativeSsh(await playbookNode(), deployment));
112
125
  result.checks.push(...(await connectivity(target, deployment)));
113
126
  }
114
127
  result.checks.unshift(...before, ...maintenance);
115
128
  return result;
116
129
  }
117
130
 
131
+ /** The roster entry a playbook is applied to: its own workspace when that is
132
+ * under the account home, else the managed workspace under the home the
133
+ * worker reports for the same SSH alias the converge reached it by.
134
+ */
135
+ async function managedWorkspace(
136
+ node: FleetNode,
137
+ deployment: WorkerDeployment
138
+ ): Promise<FleetNode> {
139
+ if (workerHome(node) || !deployment.accountHome) return node;
140
+ const home = await deployment.accountHome(node);
141
+ return home ? { ...node, workspace: `${home}${MANAGED_WORKSPACE}` } : node;
142
+ }
143
+
118
144
  /** Why this worker is rebooted now, if it is. A worker that converged
119
145
  * before is never rebooted for its first converge; only an explicit
120
146
  * maintenance run reboots it.
package/src/runner.ts CHANGED
@@ -16,6 +16,58 @@ function terminate(child: ChildProcess): void {
16
16
  } catch {}
17
17
  }
18
18
 
19
+ const pause = (ms: number): Promise<void> =>
20
+ new Promise((done) => setTimeout(done, ms));
21
+
22
+ /** Whether any process of the group still exists, whoever owns it. */
23
+ function groupExists(group: number): boolean {
24
+ try {
25
+ process.kill(-group, 0);
26
+ return true;
27
+ } catch (error) {
28
+ // A group whose members this user may not signal still exists.
29
+ return (error as NodeJS.ErrnoException).code === 'EPERM';
30
+ }
31
+ }
32
+
33
+ /** Ends what a stopped command left in its process group. A process a
34
+ * privileged helper started for it (an Ansible module run through sudo) is
35
+ * not the user's to signal, so it outlives the SIGKILL, keeps the operation
36
+ * lock it inherited and blocks the next converge. It is signalled through
37
+ * sudo, which never asks for a password here and is left alone without it.
38
+ */
39
+ async function reap(
40
+ group: number | undefined,
41
+ privileged: (group: number) => Promise<void> = signalThroughSudo
42
+ ): Promise<void> {
43
+ if (process.platform === 'win32' || !group) return;
44
+ for (let waited = 0; waited < 500; waited += 25) {
45
+ if (!groupExists(group)) return;
46
+ await pause(25);
47
+ }
48
+ await privileged(group);
49
+ for (let waited = 0; waited < 1000 && groupExists(group); waited += 25)
50
+ await pause(25);
51
+ }
52
+
53
+ function signalThroughSudo(group: number): Promise<void> {
54
+ return new Promise((done) => {
55
+ const kill = spawn('sudo', ['-n', 'kill', '-KILL', '--', `-${group}`], {
56
+ stdio: 'ignore',
57
+ });
58
+ const timer = setTimeout(() => {
59
+ kill.kill('SIGKILL');
60
+ done();
61
+ }, 5000);
62
+ const end = (): void => {
63
+ clearTimeout(timer);
64
+ done();
65
+ };
66
+ kill.on('error', end);
67
+ kill.on('close', end);
68
+ });
69
+ }
70
+
19
71
  export function runCommand(
20
72
  command: string[],
21
73
  options: CommandOptions = {}
@@ -47,16 +99,20 @@ export function runCommand(
47
99
  child.stderr.destroy();
48
100
  resolve({ ok, stdout, stderr, reason });
49
101
  };
102
+ let stopping = false;
50
103
  const abort = (cause: CommandResult['reason']): void => {
104
+ if (stopping) return;
105
+ stopping = true;
51
106
  reason = cause;
52
107
  terminate(child);
53
- finish(false);
108
+ // The result waits until nothing of the command is left running.
109
+ void reap(child.pid).then(() => finish(false));
54
110
  };
55
111
  const timer = setTimeout(() => {
56
112
  abort('timeout');
57
113
  }, options.timeoutMs ?? 15_000);
58
114
  const capture = (stream: 'stdout' | 'stderr', chunk: string): void => {
59
- if (finished) return;
115
+ if (finished || stopping) return;
60
116
  bytes += Buffer.byteLength(chunk);
61
117
  if (bytes > MAX_OUTPUT_BYTES) {
62
118
  abort('overflow');
@@ -77,6 +133,7 @@ export function runCommand(
77
133
  abort('missing');
78
134
  });
79
135
  child.on('close', (code) => {
136
+ if (stopping) return;
80
137
  finish(code === 0 && reason === 'exit');
81
138
  });
82
139
  child.stdin.end(options.input);
@@ -59,14 +59,22 @@ export function updatesPending(checks: Check[]): boolean {
59
59
  return rebootNeeded(checks);
60
60
  }
61
61
 
62
+ /** Where a worker keeps what converge manages, under the account home. */
63
+ export const MANAGED_WORKSPACE = '/.local/share/personal/fleet';
64
+
62
65
  /** The home of the account a roster entry converges, from its workspace. */
63
66
  export function workerHome(node: FleetNode): string | null {
64
- const suffix = '/.local/share/personal/fleet';
65
- return node.workspace.endsWith(suffix)
66
- ? node.workspace.slice(0, -suffix.length) || null
67
+ return node.workspace.endsWith(MANAGED_WORKSPACE)
68
+ ? node.workspace.slice(0, -MANAGED_WORKSPACE.length) || null
67
69
  : null;
68
70
  }
69
71
 
72
+ /** Said when no account home is known for a worker: the roster entry names a
73
+ * workspace elsewhere and the worker did not report its home.
74
+ */
75
+ export const HOME_UNKNOWN =
76
+ 'The worker did not report its account home and the roster workspace is not under it, so the playbook was not applied. Check that the SSH alias logs in, or set the roster workspace to <home>/.local/share/personal/fleet, then rerun converge.';
77
+
70
78
  /** How a playbook the manager applies reaches a worker: `user@alias` only
71
79
  * for a worker whose account this run created; a worker reached from
72
80
  * declared data logs in as its declared account. Null without an account
@@ -108,8 +116,7 @@ export async function rebootWorker(
108
116
  status: 'fail',
109
117
  summary: 'WORKER_REBOOT_FAILED',
110
118
  remedy: {
111
- action:
112
- 'The roster names no workspace under the account home, so the worker was not rebooted. Rerun converge once it is enrolled.',
119
+ action: `${HOME_UNKNOWN} The worker was not rebooted.`,
113
120
  },
114
121
  };
115
122
  const result = await playbook(
@@ -1,6 +1,6 @@
1
1
  import type { PackagePlaybook } from './platform/ansible';
2
2
  import type { Check, FleetNode } from './types';
3
- import { playbookAddress } from './worker-reboot';
3
+ import { HOME_UNKNOWN, playbookAddress } from './worker-reboot';
4
4
 
5
5
  /** The worker's converge stopped because its Tailscale is older than the
6
6
  * pin, which a converge never upgrades (ansible/ubuntu/tailscale.yml).
@@ -33,10 +33,7 @@ export async function upgradeTailscale(
33
33
  playbook: PackagePlaybook
34
34
  ): Promise<Check> {
35
35
  const address = playbookAddress(node);
36
- if (!address)
37
- return FAILED(
38
- 'The roster names no workspace under the account home, so Tailscale was not upgraded. Rerun converge --maintenance-reboot once the worker is enrolled.'
39
- );
36
+ if (!address) return FAILED(`${HOME_UNKNOWN} Tailscale was not upgraded.`);
40
37
  const result = await playbook(
41
38
  'ubuntu/tailscale-upgrade.yml',
42
39
  { ...address, revision },