@serfab/cadre-host 0.9.0 → 0.11.0
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/dist/auth/index.d.ts +2 -0
- package/dist/auth/index.js +1 -0
- package/dist/auth/index.js.map +1 -1
- package/dist/auth/self-label.d.ts +36 -0
- package/dist/auth/self-label.js +57 -0
- package/dist/auth/self-label.js.map +1 -0
- package/dist/auth/trust-circle.d.ts +32 -5
- package/dist/auth/trust-circle.js +31 -11
- package/dist/auth/trust-circle.js.map +1 -1
- package/dist/bin/host.js +41 -5
- package/dist/bin/host.js.map +1 -1
- package/dist/donation/__tests__/fake-orchestrator.d.ts +103 -0
- package/dist/donation/__tests__/fake-orchestrator.js +180 -0
- package/dist/donation/__tests__/fake-orchestrator.js.map +1 -0
- package/dist/donation/donation-service.d.ts +237 -12
- package/dist/donation/donation-service.js +491 -34
- package/dist/donation/donation-service.js.map +1 -1
- package/dist/donation/donation-store.d.ts +7 -0
- package/dist/donation/donation-store.js +7 -0
- package/dist/donation/donation-store.js.map +1 -1
- package/dist/donation/donation-supervisor.d.ts +167 -0
- package/dist/donation/donation-supervisor.js +341 -0
- package/dist/donation/donation-supervisor.js.map +1 -0
- package/dist/donation/index.d.ts +4 -2
- package/dist/donation/index.js +2 -1
- package/dist/donation/index.js.map +1 -1
- package/dist/donation/types.d.ts +26 -0
- package/dist/donation/types.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/orchestrator/host-process-orchestrator.d.ts +109 -5
- package/dist/orchestrator/host-process-orchestrator.js +341 -98
- package/dist/orchestrator/host-process-orchestrator.js.map +1 -1
- package/dist/orchestrator/node-identity.d.ts +26 -0
- package/dist/orchestrator/node-identity.js +36 -0
- package/dist/orchestrator/node-identity.js.map +1 -0
- package/dist/orchestrator/port-allocator.d.ts +14 -0
- package/dist/orchestrator/port-allocator.js +45 -0
- package/dist/orchestrator/port-allocator.js.map +1 -1
- package/dist/owner/owner-node-client.d.ts +20 -5
- package/dist/owner/owner-node-client.js +21 -4
- package/dist/owner/owner-node-client.js.map +1 -1
- package/dist/server/error-handler.d.ts +7 -1
- package/dist/server/error-handler.js +23 -1
- package/dist/server/error-handler.js.map +1 -1
- package/dist/server/events/types.d.ts +3 -0
- package/dist/server/index.d.ts +7 -0
- package/dist/server/index.js +9 -3
- package/dist/server/index.js.map +1 -1
- package/dist/server/routes/grants.js +22 -3
- package/dist/server/routes/grants.js.map +1 -1
- package/dist/server/routes/strands.d.ts +20 -0
- package/dist/server/routes/strands.js +38 -0
- package/dist/server/routes/strands.js.map +1 -0
- package/dist/server/static.js +38 -38
- package/dist/strands/index.d.ts +7 -0
- package/dist/strands/index.js +6 -0
- package/dist/strands/index.js.map +1 -0
- package/dist/strands/strand-service.d.ts +50 -0
- package/dist/strands/strand-service.js +103 -0
- package/dist/strands/strand-service.js.map +1 -0
- package/dist/strands/types.d.ts +93 -0
- package/dist/strands/types.js +23 -0
- package/dist/strands/types.js.map +1 -0
- package/dist/ui/assets/index-BVoqLjyX.css +1 -0
- package/dist/ui/assets/index-C-iks41M.js +17 -0
- package/dist/ui/assets/index-C-iks41M.js.map +1 -0
- package/dist/ui/index.html +14 -14
- package/dist/update/release-key.d.ts +1 -1
- package/dist/update/release-key.js +1 -1
- package/package.json +5 -5
- package/service/cadre-host.service.tmpl +16 -16
- package/service/com.serfab.cadre-host.plist.tmpl +35 -35
- package/service/install-service.ps1 +98 -98
- package/service/uninstall-service.ps1 +19 -19
- package/src/__tests__/build-targets.test.ts +26 -0
- package/src/__tests__/cli-invite.smoke.test.ts +192 -192
- package/src/__tests__/cli-nat.smoke.test.ts +212 -212
- package/src/__tests__/cli.smoke.test.ts +46 -46
- package/src/__tests__/global-setup.ts +51 -0
- package/src/__tests__/host-owner.smoke.test.ts +123 -123
- package/src/__tests__/orchestrator-env-scrub.test.ts +140 -0
- package/src/__tests__/orchestrator-node-identity.test.ts +204 -0
- package/src/__tests__/orchestrator-owner.test.ts +198 -198
- package/src/__tests__/orchestrator-pin-keys.test.ts +153 -153
- package/src/__tests__/orchestrator-push.test.ts +145 -145
- package/src/__tests__/orchestrator.test.ts +951 -570
- package/src/auth/__tests__/duration.test.ts +28 -28
- package/src/auth/__tests__/self-label.test.ts +85 -0
- package/src/auth/__tests__/trust-circle-integration.test.ts +152 -147
- package/src/auth/__tests__/trust-circle-store.test.ts +115 -115
- package/src/auth/__tests__/trust-circle.test.ts +445 -401
- package/src/auth/duration.ts +33 -33
- package/src/auth/index.ts +21 -19
- package/src/auth/self-label.ts +74 -0
- package/src/auth/trust-circle-store.ts +155 -155
- package/src/auth/trust-circle.ts +45 -13
- package/src/auth/types.ts +99 -99
- package/src/bin/host.ts +1299 -1258
- package/src/donation/__tests__/donation-service.test.ts +1068 -290
- package/src/donation/__tests__/donation-supervisor.test.ts +510 -0
- package/src/donation/__tests__/fake-orchestrator.test.ts +168 -0
- package/src/donation/__tests__/fake-orchestrator.ts +225 -0
- package/src/donation/__tests__/grant-service.test.ts +213 -213
- package/src/donation/__tests__/grant-store.test.ts +113 -113
- package/src/donation/donation-service.ts +962 -392
- package/src/donation/donation-store.ts +171 -164
- package/src/donation/donation-supervisor.ts +388 -0
- package/src/donation/grant-service.ts +200 -200
- package/src/donation/grant-store.ts +152 -152
- package/src/donation/index.ts +64 -49
- package/src/donation/types.ts +243 -220
- package/src/index.ts +14 -0
- package/src/installer/__tests__/identity.test.ts +34 -34
- package/src/installer/__tests__/paths.test.ts +47 -47
- package/src/installer/__tests__/service-host.test.ts +62 -62
- package/src/installer/__tests__/wizard.test.ts +64 -64
- package/src/installer/identity.ts +49 -49
- package/src/installer/paths.ts +109 -109
- package/src/installer/platform.ts +27 -27
- package/src/installer/service-host/index.ts +21 -21
- package/src/installer/service-host/template.ts +21 -21
- package/src/installer/wizard.ts +103 -103
- package/src/nat/__tests__/address-resolver.test.ts +82 -82
- package/src/nat/__tests__/ddns-duckdns.test.ts +83 -83
- package/src/nat/__tests__/ddns-updater.test.ts +253 -253
- package/src/nat/__tests__/external-ip.test.ts +124 -124
- package/src/nat/__tests__/nat-service.test.ts +497 -497
- package/src/nat/__tests__/nat-store.test.ts +93 -93
- package/src/nat/__tests__/port-mapper.test.ts +191 -191
- package/src/nat/__tests__/reachability.test.ts +24 -24
- package/src/nat/__tests__/secrets.test.ts +178 -178
- package/src/nat/address-resolver.ts +51 -51
- package/src/nat/ddns/duckdns.ts +76 -76
- package/src/nat/ddns/index.ts +55 -55
- package/src/nat/ddns/updater.ts +243 -243
- package/src/nat/external-ip.ts +154 -154
- package/src/nat/index.ts +71 -71
- package/src/nat/nat-service.ts +501 -501
- package/src/nat/nat-store.ts +154 -154
- package/src/nat/port-mapper.ts +329 -329
- package/src/nat/reachability.ts +34 -34
- package/src/nat/secrets/file-store.ts +130 -130
- package/src/nat/secrets/index.ts +112 -112
- package/src/nat/secrets/keytar-store.ts +67 -67
- package/src/nat/types.ts +159 -159
- package/src/orchestrator/__tests__/node-identity.test.ts +62 -0
- package/src/orchestrator/host-process-orchestrator.ts +1133 -894
- package/src/orchestrator/index.ts +10 -10
- package/src/orchestrator/log-rotator.ts +53 -53
- package/src/orchestrator/node-identity.ts +40 -0
- package/src/orchestrator/pid-liveness.ts +24 -24
- package/src/orchestrator/port-allocator.ts +91 -43
- package/src/orchestrator/state-store.ts +90 -90
- package/src/orchestrator/types.ts +141 -141
- package/src/owner/__tests__/owner-node-client.test.ts +194 -194
- package/src/owner/index.ts +12 -12
- package/src/owner/owner-node-client.ts +259 -233
- package/src/push/__tests__/push.test.ts +90 -90
- package/src/push/index.ts +146 -146
- package/src/server/__tests__/bus.test.ts +38 -38
- package/src/server/__tests__/error-handler.test.ts +118 -118
- package/src/server/__tests__/grants-admin-route.test.ts +73 -73
- package/src/server/__tests__/grants-route.test.ts +263 -189
- package/src/server/__tests__/nodes-route.test.ts +259 -259
- package/src/server/__tests__/origin-guard.test.ts +72 -72
- package/src/server/__tests__/publishers.test.ts +216 -216
- package/src/server/__tests__/server.smoke.test.ts +253 -253
- package/src/server/__tests__/settings-route.test.ts +194 -194
- package/src/server/__tests__/sse-route.test.ts +119 -119
- package/src/server/__tests__/static.test.ts +145 -145
- package/src/server/__tests__/status-route.test.ts +134 -134
- package/src/server/__tests__/strands-route.test.ts +233 -0
- package/src/server/error-handler.ts +178 -155
- package/src/server/events/bus.ts +42 -42
- package/src/server/events/sse-route.ts +81 -81
- package/src/server/events/types.ts +23 -22
- package/src/server/index.ts +267 -254
- package/src/server/origin-guard.ts +84 -84
- package/src/server/routes/grants-admin.ts +41 -41
- package/src/server/routes/grants.ts +210 -186
- package/src/server/routes/nat.ts +63 -63
- package/src/server/routes/nodes.ts +170 -170
- package/src/server/routes/settings.ts +123 -123
- package/src/server/routes/status.ts +118 -118
- package/src/server/routes/strands.ts +54 -0
- package/src/server/routes/trust-circle.ts +49 -49
- package/src/server/routes/update.ts +43 -43
- package/src/server/server.ts +122 -122
- package/src/server/settings-store.ts +37 -37
- package/src/server/static.ts +207 -207
- package/src/strands/__tests__/strand-service.test.ts +165 -0
- package/src/strands/index.ts +14 -0
- package/src/strands/strand-service.ts +135 -0
- package/src/strands/types.ts +102 -0
- package/src/update/__tests__/apply.test.ts +158 -158
- package/src/update/__tests__/manifest.test.ts +128 -128
- package/src/update/__tests__/release-key.test.ts +42 -42
- package/src/update/__tests__/sign.test.ts +78 -78
- package/src/update/__tests__/store.test.ts +81 -81
- package/src/update/__tests__/update-service.integration.test.ts +256 -256
- package/src/update/__tests__/version.test.ts +31 -31
- package/src/update/apply.ts +190 -190
- package/src/update/index.ts +341 -341
- package/src/update/release-key.ts +71 -71
- package/src/update/sign.ts +74 -74
- package/src/update/store.ts +101 -101
- package/src/update/types.ts +109 -109
- package/src/update/version.ts +80 -80
- package/dist/ui/assets/index-BlMXQPSw.js +0 -14
- package/dist/ui/assets/index-BlMXQPSw.js.map +0 -1
- package/dist/ui/assets/index-BwU5mJGF.css +0 -1
|
@@ -2,11 +2,12 @@ import { spawn } from 'node:child_process';
|
|
|
2
2
|
import { createRequire } from 'node:module';
|
|
3
3
|
import { randomBytes } from 'node:crypto';
|
|
4
4
|
import { existsSync, readFileSync, rmSync, writeFileSync, mkdirSync, statSync, openSync, readSync, closeSync, } from 'node:fs';
|
|
5
|
-
import { join, resolve as resolvePath } from 'node:path';
|
|
5
|
+
import { join, resolve as resolvePath, sep } from 'node:path';
|
|
6
6
|
import debug from 'debug';
|
|
7
7
|
import pidusage from 'pidusage';
|
|
8
8
|
import { defaultLogPath, rotateOnDisk } from './log-rotator.js';
|
|
9
|
-
import {
|
|
9
|
+
import { ensureNodeIdentity } from './node-identity.js';
|
|
10
|
+
import { allocateNodePorts, PortAllocator } from './port-allocator.js';
|
|
10
11
|
import { StateStore } from './state-store.js';
|
|
11
12
|
import { isPidAlive } from './pid-liveness.js';
|
|
12
13
|
import { decodeDockerId, encodeDockerId, } from './types.js';
|
|
@@ -21,6 +22,26 @@ const DEFAULTS = {
|
|
|
21
22
|
const STARTUP_TOKEN_FILE = '.startup-token';
|
|
22
23
|
const CONFIG_FILE = 'cadre.json';
|
|
23
24
|
const LIVENESS_POLL_MS = 100;
|
|
25
|
+
const CADRE_ENV_PREFIX = 'CADRE_';
|
|
26
|
+
/**
|
|
27
|
+
* Manager's own `process.env` with every `CADRE_*` key removed. A child node
|
|
28
|
+
* takes its whole configuration from the config file this orchestrator writes
|
|
29
|
+
* plus the vars set explicitly below, and `@serfab/cadre-cli` treats inherited
|
|
30
|
+
* `CADRE_*` vars as overrides that BEAT that config file — so inheriting them
|
|
31
|
+
* would let a var set on the manager (e.g. CADRE_PARTY_ID) silently
|
|
32
|
+
* reconfigure every spawned child. Scrubbing the whole prefix rather than a
|
|
33
|
+
* list of known keys means a new cli env var can't reintroduce the leak by
|
|
34
|
+
* being forgotten here. Non-CADRE vars (PATH, DEBUG, proxy/TLS settings, etc.)
|
|
35
|
+
* still pass through untouched.
|
|
36
|
+
*/
|
|
37
|
+
function scrubbedParentEnv() {
|
|
38
|
+
const env = { ...process.env };
|
|
39
|
+
for (const key of Object.keys(env)) {
|
|
40
|
+
if (key.startsWith(CADRE_ENV_PREFIX))
|
|
41
|
+
delete env[key];
|
|
42
|
+
}
|
|
43
|
+
return env;
|
|
44
|
+
}
|
|
24
45
|
/** Fixed friendly id for the admin's owner node. */
|
|
25
46
|
export const OWNER_CONTAINER_ID = 'owner';
|
|
26
47
|
/**
|
|
@@ -96,13 +117,7 @@ export class HostProcessOrchestrator {
|
|
|
96
117
|
};
|
|
97
118
|
this.handles.set(handle.dockerId, handle);
|
|
98
119
|
// Always reserve ports — even for dead handles, until the caller cleans them up
|
|
99
|
-
this.
|
|
100
|
-
this.portAllocator.markUsed(persisted.ports.metrics);
|
|
101
|
-
this.portAllocator.markUsed(persisted.ports.p2p);
|
|
102
|
-
// `admin` is absent on handles persisted before this build.
|
|
103
|
-
if (typeof persisted.ports.admin === 'number') {
|
|
104
|
-
this.portAllocator.markUsed(persisted.ports.admin);
|
|
105
|
-
}
|
|
120
|
+
this.reservePorts(persisted.ports);
|
|
106
121
|
}
|
|
107
122
|
log('init: re-attached %d handles', state.handles.length);
|
|
108
123
|
}
|
|
@@ -148,49 +163,156 @@ export class HostProcessOrchestrator {
|
|
|
148
163
|
this.stateListeners.add(listener);
|
|
149
164
|
return () => { this.stateListeners.delete(listener); };
|
|
150
165
|
}
|
|
151
|
-
/**
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
166
|
+
/**
|
|
167
|
+
* Spawn a generic managed node — the donated-node path (the requester's cadre,
|
|
168
|
+
* pinned to the *requester's* owner key). The node is given its own protobuf
|
|
169
|
+
* identity key inside its workdir (`ensureNodeIdentity`, reused across
|
|
170
|
+
* re-spawns of the same containerId), which is what makes its peer id stable
|
|
171
|
+
* across restarts AND what makes its node-local stores durable: `cadre-cli
|
|
172
|
+
* start` opens the file-backed bootstrap-peer and trusted-owner stores only
|
|
173
|
+
* when a protobuf identity key file is configured, and puts them beside it.
|
|
174
|
+
* Terminating the loan (`removeContainer`) deletes the workdir, so the key and
|
|
175
|
+
* both stores go with it.
|
|
176
|
+
*/
|
|
177
|
+
async createContainer(request) {
|
|
178
|
+
const workdir = this.workdirFor(request.containerId);
|
|
179
|
+
// Sampled BEFORE `ensureNodeIdentity`, which brings the directory into
|
|
180
|
+
// existence as a side effect of writing the key. Only a spawn that found
|
|
181
|
+
// nothing here may delete anything on its way out — a re-spawn is REUSING
|
|
182
|
+
// the identity key and node-local stores this directory holds, and they are
|
|
183
|
+
// the whole reason the node comes back as the same peer. `false` is
|
|
184
|
+
// therefore the safe default: a directory that exists for any reason
|
|
185
|
+
// (respawn, an earlier failed provision, an operator's file) is never
|
|
186
|
+
// touched by the unwind below.
|
|
187
|
+
const isNewWorkdir = !existsSync(workdir);
|
|
188
|
+
let dropped = [];
|
|
189
|
+
let ports;
|
|
190
|
+
try {
|
|
191
|
+
// Identity BEFORE any port is reserved: it is the one step here that can
|
|
192
|
+
// fail on its own (an unreadable or undecodable identity.key throws rather
|
|
193
|
+
// than silently re-keying), and everything past the allocation is either
|
|
194
|
+
// infallible or releases the ports itself. Allocating first would leak four
|
|
195
|
+
// ports from a bounded range on every failed provision attempt.
|
|
196
|
+
const identity = await ensureNodeIdentity(workdir);
|
|
197
|
+
log('container %s identity peerId=%s', request.containerId, identity.peerId);
|
|
198
|
+
// A node started with pinned owner keys belongs to a FOREIGN cadre (the
|
|
199
|
+
// node-donation flow: it trusts the requester's owner key, not the host's).
|
|
200
|
+
// The host's FCM/APNs credentials are minted for the host owner's own app
|
|
201
|
+
// and are meaningless to a foreign cadre — so donated nodes get NO push
|
|
202
|
+
// block. (Per-grantee push creds would be a future ticket; none in v1.)
|
|
203
|
+
const foreignParty = (request.pinnedOwnerKeys?.length ?? 0) > 0;
|
|
204
|
+
// Only storage-profile nodes participate in strands and thus fan out push
|
|
205
|
+
// wakes — a transaction-only node need not carry credentials. Resolved
|
|
206
|
+
// BEFORE the drop below: it is the last `await` on this path, which is what
|
|
207
|
+
// keeps the drop → launch window synchronous (see restoreDroppedHandles).
|
|
208
|
+
const push = request.profile === 'storage' && !foreignParty ? await this.resolvePush() : undefined;
|
|
209
|
+
// Pinned owner key(s) reach the child via CADRE_OWNER_KEYS (comma-separated);
|
|
210
|
+
// `cadre-cli start` unions it into its cold-start pinnedKeyTrustPolicy so the
|
|
211
|
+
// node will accept the foreign-authority-signed seed presented via POST /seed.
|
|
212
|
+
const extraEnv = request.pinnedOwnerKeys?.length
|
|
213
|
+
? { CADRE_OWNER_KEYS: request.pinnedOwnerKeys.join(',') }
|
|
214
|
+
: undefined;
|
|
215
|
+
// Nothing from here to the launch is `await`ed — which is what keeps
|
|
216
|
+
// `restoreDroppedHandles`'s documented precondition true even though the
|
|
217
|
+
// `try` now opens further up. Do not add an `await` past this line.
|
|
218
|
+
dropped = this.dropStaleHandle(request.containerId);
|
|
219
|
+
// NOTE: the p2p port is re-allocated per spawn, so a re-spawned donated
|
|
220
|
+
// node keeps its peer id but may announce a different port. Recoverable —
|
|
221
|
+
// it dials out to its retained bootstrap peers and republishes its own
|
|
222
|
+
// CadrePeer row once connected. If that reconnect ever proves too slow,
|
|
223
|
+
// pin the p2p port per containerId (see donated-node-respawn-core).
|
|
224
|
+
ports = allocateNodePorts(this.portAllocator);
|
|
225
|
+
return this.launchChild({
|
|
226
|
+
containerId: request.containerId,
|
|
227
|
+
partyId: request.partyId,
|
|
228
|
+
profile: request.profile,
|
|
229
|
+
ports,
|
|
230
|
+
owner: false,
|
|
231
|
+
buildConfig: () => this.buildChildConfig(request, workdir, push),
|
|
232
|
+
extraArgs: ['--identity-protobuf', identity.path],
|
|
233
|
+
...(extraEnv ? { extraEnv } : {}),
|
|
234
|
+
...(request.resources?.memoryLimit ? { memoryLimit: request.resources.memoryLimit } : {}),
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
catch (err) {
|
|
238
|
+
// Release BEFORE restoring: a re-spawn allocates the very ports the drop
|
|
239
|
+
// just freed, so restoring first and releasing second would hand the
|
|
240
|
+
// restored handle's own ports straight back to the allocator.
|
|
241
|
+
if (ports)
|
|
242
|
+
this.releasePorts(ports);
|
|
243
|
+
// A no-op for the failures that happen before the drop (`dropped` is
|
|
244
|
+
// still empty).
|
|
245
|
+
this.restoreDroppedHandles(dropped);
|
|
246
|
+
// Safe because a throw out of `launchChild` means NO child is running:
|
|
247
|
+
// its throw surface ends where the child is spawned and its handle stored
|
|
248
|
+
// (everything past that line is best-effort), and the `if (!child.pid)`
|
|
249
|
+
// throw is on the no-process side too. So nothing is ever holding the
|
|
250
|
+
// directory this deletes.
|
|
251
|
+
if (isNewWorkdir)
|
|
252
|
+
this.discardWorkdir(workdir);
|
|
253
|
+
throw err;
|
|
158
254
|
}
|
|
159
|
-
return dead;
|
|
160
255
|
}
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
//
|
|
173
|
-
|
|
174
|
-
//
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
//
|
|
178
|
-
//
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
256
|
+
/**
|
|
257
|
+
* Remove the working directory a spawn created for `containerId` when no
|
|
258
|
+
* handle owns it — the cleanup of last resort for a donation record that
|
|
259
|
+
* never got a `dockerId` (the host died between `ensureNodeIdentity` and the
|
|
260
|
+
* handle write, so `createContainer`'s own unwind never ran). Returns whether
|
|
261
|
+
* anything was removed.
|
|
262
|
+
*
|
|
263
|
+
* Synchronous, mirroring {@link resolveDockerId}: nothing on this path needs
|
|
264
|
+
* to await.
|
|
265
|
+
*/
|
|
266
|
+
reclaimWorkdir(containerId) {
|
|
267
|
+
// The admin's own node is never reclaimed by this route: its workdir is a
|
|
268
|
+
// single fixed path reused by every restart and it holds the host's own
|
|
269
|
+
// control-DB storage.
|
|
270
|
+
if (containerId === OWNER_CONTAINER_ID)
|
|
271
|
+
return false;
|
|
272
|
+
// A live handle owns that directory, and `removeContainer` — which stops
|
|
273
|
+
// the child first — is the only thing allowed to delete it.
|
|
274
|
+
if (this.resolveDockerId(containerId))
|
|
275
|
+
return false;
|
|
276
|
+
const workdir = this.workdirFor(containerId);
|
|
277
|
+
// Defence, not a live case: donation ids are `grn_<base64url>` and so can
|
|
278
|
+
// hold neither a path separator nor a dot. A caller that ever passes
|
|
279
|
+
// something else must not be able to walk out of `rootDir`.
|
|
280
|
+
if (!workdir.startsWith(this.rootDir + sep)) {
|
|
281
|
+
log('refusing to reclaim workdir outside rootDir: %s', workdir);
|
|
282
|
+
return false;
|
|
283
|
+
}
|
|
284
|
+
// Must be a DIRECTORY, not merely something that exists: `rootDir` also
|
|
285
|
+
// holds `state.json` (this orchestrator's own persisted handles), and
|
|
286
|
+
// `discardWorkdir`'s `rmSync` deletes files as happily as trees. Same
|
|
287
|
+
// defence class as the escape check above — no real containerId names a
|
|
288
|
+
// file — but the blast radius if one ever did is the whole handle map.
|
|
289
|
+
if (!statSync(workdir, { throwIfNoEntry: false })?.isDirectory())
|
|
290
|
+
return false;
|
|
291
|
+
this.discardWorkdir(workdir);
|
|
292
|
+
return true;
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Best-effort removal of a workdir no handle owns. Logs, never throws: every
|
|
296
|
+
* caller is either unwinding a failure it must report instead of this one, or
|
|
297
|
+
* tearing a container down along a path where a surviving directory is a
|
|
298
|
+
* nuisance rather than a fault.
|
|
299
|
+
*
|
|
300
|
+
* `retries` sizes the wait for the OS to release a cwd handle — Windows drops
|
|
301
|
+
* it asynchronously after a child exits. `createContainer`'s unwind needs none
|
|
302
|
+
* of that (its throw surface ends before any child is spawned), but
|
|
303
|
+
* `reclaimWorkdir` can still meet an orphan process the previous host left
|
|
304
|
+
* running with this directory as its cwd, so it is not a *guaranteed*
|
|
305
|
+
* no-process path either — it simply logs and leaves the directory when the
|
|
306
|
+
* removal fails.
|
|
307
|
+
*/
|
|
308
|
+
discardWorkdir(workdir, retries = { maxRetries: 5, retryDelay: 100 }) {
|
|
309
|
+
try {
|
|
310
|
+
rmSync(workdir, { recursive: true, force: true, ...retries });
|
|
311
|
+
log('discarded workdir %s', workdir);
|
|
312
|
+
}
|
|
313
|
+
catch (err) {
|
|
314
|
+
log('failed to discard workdir %s: %o', workdir, err);
|
|
315
|
+
}
|
|
194
316
|
}
|
|
195
317
|
/**
|
|
196
318
|
* Resolve the push credentials to inject into the node about to spawn. Called
|
|
@@ -237,38 +359,46 @@ export class HostProcessOrchestrator {
|
|
|
237
359
|
this.persist();
|
|
238
360
|
return toNodeInfo(existing);
|
|
239
361
|
}
|
|
240
|
-
if (existing) {
|
|
241
|
-
// Drop the stale handle and release its ports — but DO NOT delete the
|
|
242
|
-
// workdir: the owner node's control-DB storage lives there and must
|
|
243
|
-
// survive a restart. launchChild reuses the same workdir.
|
|
244
|
-
this.releasePorts(existing.ports);
|
|
245
|
-
this.handles.delete(existing.dockerId);
|
|
246
|
-
}
|
|
247
362
|
const profile = config.profile ?? 'storage';
|
|
248
363
|
// Re-resolve push credentials from the secret store on every (re-)spawn so a
|
|
249
364
|
// restart picks up rotated keys and nothing raw is replayed from state.json.
|
|
365
|
+
// Resolved BEFORE the drop below so the drop → launch window stays
|
|
366
|
+
// synchronous (see restoreDroppedHandles).
|
|
250
367
|
const push = await this.resolvePush();
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
368
|
+
// NOTE: the short-circuit above matches via `findOwnerHandle` (owner flag OR
|
|
369
|
+
// containerId), this drop only by containerId. Equivalent today — every
|
|
370
|
+
// owner handle is launched with OWNER_CONTAINER_ID. If an owner spawn ever
|
|
371
|
+
// takes a different containerId, the two would disagree and the handle the
|
|
372
|
+
// short-circuit found would survive here, leaking it and its ports.
|
|
373
|
+
const dropped = this.dropStaleHandle(OWNER_CONTAINER_ID);
|
|
374
|
+
let ports;
|
|
375
|
+
try {
|
|
376
|
+
// The owner node must listen on the configured libp2p port so the NAT
|
|
377
|
+
// mapping (external → internal) lands on it — hence the p2p override.
|
|
378
|
+
ports = allocateNodePorts(this.portAllocator, { p2p: config.libp2pPort });
|
|
379
|
+
const result = this.launchChild({
|
|
380
|
+
containerId: OWNER_CONTAINER_ID,
|
|
381
|
+
partyId: config.partyId,
|
|
382
|
+
profile,
|
|
383
|
+
ports,
|
|
384
|
+
owner: true,
|
|
385
|
+
buildConfig: (workdir) => this.buildOwnerChildConfig(config, profile, workdir, push),
|
|
386
|
+
extraArgs: ['--owner', '--admin-port', String(ports.admin), '--identity-protobuf', config.identityPath],
|
|
387
|
+
});
|
|
388
|
+
const handle = this.handles.get(result.dockerId);
|
|
389
|
+
return toNodeInfo(handle);
|
|
390
|
+
}
|
|
391
|
+
catch (err) {
|
|
392
|
+
// Release before restoring — see the same note in createContainer.
|
|
393
|
+
if (ports)
|
|
394
|
+
this.releasePorts(ports);
|
|
395
|
+
this.restoreDroppedHandles(dropped);
|
|
396
|
+
// Deliberately NOT `discardWorkdir` — the asymmetry with createContainer
|
|
397
|
+
// is the point. `<rootDir>/owner` is a single fixed path reused by every
|
|
398
|
+
// restart and holds the host's own control-DB storage, so it neither
|
|
399
|
+
// grows without bound nor is safe to delete on a failed spawn.
|
|
400
|
+
throw err;
|
|
401
|
+
}
|
|
272
402
|
}
|
|
273
403
|
/** Endpoint + bearer for the owner node's admin channel, if spawned. */
|
|
274
404
|
getOwnerAdminEndpoint() {
|
|
@@ -314,12 +444,22 @@ export class HostProcessOrchestrator {
|
|
|
314
444
|
}
|
|
315
445
|
/**
|
|
316
446
|
* Core spawn mechanics shared by `createContainer` and `ensureOwnerNode`.
|
|
317
|
-
*
|
|
318
|
-
*
|
|
447
|
+
*
|
|
448
|
+
* The caller has already allocated `ports` and **owns their lifetime**: this
|
|
449
|
+
* method never releases them, so every caller must release on any throw out
|
|
450
|
+
* of here (it has to unwind its handle drop on the same path anyway — see
|
|
451
|
+
* `restoreDroppedHandles`).
|
|
452
|
+
*
|
|
453
|
+
* That contract holds because this method throws only *before* the child is
|
|
454
|
+
* spawned and its handle stored — everything after that point is
|
|
455
|
+
* best-effort. Anything new added at the tail must keep it that way.
|
|
456
|
+
*
|
|
457
|
+
* Entirely synchronous, which is what makes that unwind sound. Do not add an
|
|
458
|
+
* `await` here.
|
|
319
459
|
*/
|
|
320
460
|
launchChild(opts) {
|
|
321
461
|
const { containerId, ports } = opts;
|
|
322
|
-
const workdir =
|
|
462
|
+
const workdir = this.workdirFor(containerId);
|
|
323
463
|
mkdirSync(workdir, { recursive: true });
|
|
324
464
|
mkdirSync(join(workdir, 'storage'), { recursive: true });
|
|
325
465
|
const token = randomBytes(16).toString('hex');
|
|
@@ -343,15 +483,23 @@ export class HostProcessOrchestrator {
|
|
|
343
483
|
const heapBytes = parseMemoryLimit(memoryLimit);
|
|
344
484
|
const heapMB = heapBytes !== undefined ? Math.max(64, Math.floor(heapBytes / (1024 * 1024))) : undefined;
|
|
345
485
|
const env = {
|
|
346
|
-
|
|
347
|
-
//
|
|
348
|
-
//
|
|
486
|
+
// Scrubbed, not raw process.env: every CADRE_* config-override key is
|
|
487
|
+
// stripped so a var set on the manager can't silently reconfigure every
|
|
488
|
+
// child (see scrubbedParentEnv). Caller-supplied extras come next — the
|
|
489
|
+
// fixed per-child vars below always win so extraEnv can never clobber
|
|
490
|
+
// the seed/startup tokens or port wiring.
|
|
491
|
+
...scrubbedParentEnv(),
|
|
349
492
|
...opts.extraEnv,
|
|
350
493
|
CADRE_STARTUP_TOKEN: token,
|
|
351
494
|
CADRE_HEALTH_PORT: String(ports.health),
|
|
352
495
|
CADRE_METRICS_PORT: String(ports.metrics),
|
|
353
496
|
CADRE_LISTEN_ADDRS: `/ip4/0.0.0.0/tcp/${ports.p2p}`,
|
|
354
497
|
CADRE_SEED_TOKEN: seedToken,
|
|
498
|
+
// Pin each child's node-local state (trusted-owner anchor, retained
|
|
499
|
+
// cold-start dial targets) to its OWN workdir. This is the same value the
|
|
500
|
+
// cli would derive by default (the config file lives here too), but stated
|
|
501
|
+
// explicitly rather than relying on the scrub above (belt and suspenders).
|
|
502
|
+
CADRE_NODE_STATE_DIR: workdir,
|
|
355
503
|
};
|
|
356
504
|
if (heapMB !== undefined) {
|
|
357
505
|
env.NODE_OPTIONS = `${process.env.NODE_OPTIONS ?? ''} --max-old-space-size=${heapMB}`.trim();
|
|
@@ -384,17 +532,16 @@ export class HostProcessOrchestrator {
|
|
|
384
532
|
});
|
|
385
533
|
}
|
|
386
534
|
catch (err) {
|
|
387
|
-
// Synchronous spawn failure —
|
|
388
|
-
//
|
|
535
|
+
// Synchronous spawn failure — close the fd before propagating. This is
|
|
536
|
+
// the ONLY fd-leak guard on this path: nothing between the `openSync`
|
|
537
|
+
// above and the `spawn` can throw, so no other catch is needed. Keep it
|
|
538
|
+
// that way, or add one. (The ports are the caller's to release.)
|
|
389
539
|
closeSync(logFd);
|
|
390
|
-
this.releasePorts(ports);
|
|
391
540
|
throw err;
|
|
392
541
|
}
|
|
393
542
|
// Always release the parent's copy of the fd — the child has its own.
|
|
394
543
|
closeSync(logFd);
|
|
395
544
|
if (!child.pid) {
|
|
396
|
-
// Spawn returned without a pid — release reservations and report.
|
|
397
|
-
this.releasePorts(ports);
|
|
398
545
|
throw new Error(`Failed to spawn child for container ${containerId}`);
|
|
399
546
|
}
|
|
400
547
|
child.unref();
|
|
@@ -421,7 +568,20 @@ export class HostProcessOrchestrator {
|
|
|
421
568
|
}
|
|
422
569
|
});
|
|
423
570
|
this.handles.set(dockerId, handle);
|
|
424
|
-
this
|
|
571
|
+
// Past this line the launch has SUCCEEDED: the child is running and this
|
|
572
|
+
// handle owns its ports. So the state mirror is best-effort — a throw here
|
|
573
|
+
// would reach the caller's unwind, which would release ports the live child
|
|
574
|
+
// is bound to and restore the handle this spawn just replaced, leaving two
|
|
575
|
+
// handles for one container and one of them holding unreserved ports. A
|
|
576
|
+
// lost write self-heals: the next persist() (any stop/remove/spawn)
|
|
577
|
+
// rewrites the whole map. Until then a manager restart would fail to
|
|
578
|
+
// re-attach this child, hence the log.
|
|
579
|
+
try {
|
|
580
|
+
this.persist();
|
|
581
|
+
}
|
|
582
|
+
catch (err) {
|
|
583
|
+
log('failed to persist state after launching container %s: %o', containerId, err);
|
|
584
|
+
}
|
|
425
585
|
this.emitStateChange(handle);
|
|
426
586
|
log('created container %s -> pid %d ports=%j', containerId, child.pid, handle.ports);
|
|
427
587
|
return {
|
|
@@ -434,6 +594,79 @@ export class HostProcessOrchestrator {
|
|
|
434
594
|
p2pPort: ports.p2p,
|
|
435
595
|
};
|
|
436
596
|
}
|
|
597
|
+
/**
|
|
598
|
+
* Drop any handle left over from a previous spawn of the same `containerId`
|
|
599
|
+
* and release its ports. Handles are keyed by the per-spawn `dockerId`, so
|
|
600
|
+
* without this a re-spawn (donated-node respawn) would strand the prior
|
|
601
|
+
* handle in the map forever, leaking four ports from a bounded range each
|
|
602
|
+
* time. Mirrors the same cleanup in `ensureOwnerNode`.
|
|
603
|
+
*
|
|
604
|
+
* DO NOT delete the workdir: the identity key and node-local stores
|
|
605
|
+
* (trusted-owner anchor, retained cold-start dial targets) live there and are
|
|
606
|
+
* the whole reason a respawn comes back as the same node. `launchChild`
|
|
607
|
+
* reuses the same workdir.
|
|
608
|
+
*
|
|
609
|
+
* NOTE: releasing the ports hands them straight back to the allocator, so a
|
|
610
|
+
* re-spawn while the *previous* child is still listening can bind-clash. Every
|
|
611
|
+
* caller today re-spawns only a container it has established is not running
|
|
612
|
+
* (`DonationService.respawn`, `ensureOwnerNode`). If a caller ever needs to
|
|
613
|
+
* replace a live child, stop it first — or hold the ports until its exit.
|
|
614
|
+
*
|
|
615
|
+
* **The drop is reversible.** It happens before the launch can fail, so the
|
|
616
|
+
* dropped handles are returned and every caller restores them via
|
|
617
|
+
* {@link restoreDroppedHandles} when the launch throws — otherwise the caller
|
|
618
|
+
* would be left holding a dockerId this orchestrator no longer knows, and the
|
|
619
|
+
* node's workdir could never be reclaimed. On a *successful* spawn the drop
|
|
620
|
+
* stands: `DonationService.abandonRespawn` depends on the old handle being
|
|
621
|
+
* gone by then.
|
|
622
|
+
*/
|
|
623
|
+
dropStaleHandle(containerId) {
|
|
624
|
+
const dropped = [];
|
|
625
|
+
for (const h of this.handles.values()) {
|
|
626
|
+
if (h.containerId !== containerId)
|
|
627
|
+
continue;
|
|
628
|
+
log('dropping stale handle %s for container %s', h.dockerId, containerId);
|
|
629
|
+
this.releasePorts(h.ports);
|
|
630
|
+
this.handles.delete(h.dockerId);
|
|
631
|
+
dropped.push(h);
|
|
632
|
+
}
|
|
633
|
+
return dropped;
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Inverse of {@link dropStaleHandle}, for a spawn that then failed: put each
|
|
637
|
+
* handle back in the map and re-reserve its four ports, leaving host state
|
|
638
|
+
* exactly as the failed attempt found it.
|
|
639
|
+
*
|
|
640
|
+
* **Precondition: the drop → launch window is synchronous.** Restoring is
|
|
641
|
+
* sound only because nothing can have taken those ports or run cleanup
|
|
642
|
+
* against the handle in between — `launchChild` contains no `await` and both
|
|
643
|
+
* callers resolve push credentials *before* their drop. `launchChild`'s half
|
|
644
|
+
* is enforced: its declared return type is not a Promise, so adding an
|
|
645
|
+
* `await` there is a compile error. The callers' half is not — an `await`
|
|
646
|
+
* slipped between a drop and its launch silently breaks this.
|
|
647
|
+
*
|
|
648
|
+
* No `persist()` here: `state.json` is rewritten only by `launchChild` and
|
|
649
|
+
* only *after* the new handle is stored, so throughout the failure window the
|
|
650
|
+
* on-disk state still lists the dropped handle — this restore realigns memory
|
|
651
|
+
* to disk rather than diverging from it.
|
|
652
|
+
*
|
|
653
|
+
* NOTE: a restored handle keeps `alive: true` even if its child exited while
|
|
654
|
+
* it was out of the map (`launchChild`'s exit listener looks the handle up by
|
|
655
|
+
* dockerId and finds nothing). Only reachable by re-spawning a container
|
|
656
|
+
* whose child is still live, which `dropStaleHandle`'s note above already
|
|
657
|
+
* forbids.
|
|
658
|
+
*/
|
|
659
|
+
restoreDroppedHandles(dropped) {
|
|
660
|
+
for (const h of dropped) {
|
|
661
|
+
log('restoring dropped handle %s for container %s after failed launch', h.dockerId, h.containerId);
|
|
662
|
+
this.handles.set(h.dockerId, h);
|
|
663
|
+
this.reservePorts(h.ports);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
/** A managed node's own directory under `rootDir` — config, log, storage, identity. */
|
|
667
|
+
workdirFor(containerId) {
|
|
668
|
+
return join(this.rootDir, containerId);
|
|
669
|
+
}
|
|
437
670
|
/** Locate the owner node's handle, if one has been spawned. */
|
|
438
671
|
findOwnerHandle() {
|
|
439
672
|
for (const h of this.handles.values()) {
|
|
@@ -442,6 +675,20 @@ export class HostProcessOrchestrator {
|
|
|
442
675
|
}
|
|
443
676
|
return undefined;
|
|
444
677
|
}
|
|
678
|
+
/**
|
|
679
|
+
* Inverse of {@link releasePorts} — hold a handle's whole port set against
|
|
680
|
+
* the allocator. Used both to rehydrate on `init` and to undo a drop whose
|
|
681
|
+
* launch then failed.
|
|
682
|
+
*/
|
|
683
|
+
reservePorts(ports) {
|
|
684
|
+
this.portAllocator.markUsed(ports.health);
|
|
685
|
+
this.portAllocator.markUsed(ports.metrics);
|
|
686
|
+
this.portAllocator.markUsed(ports.p2p);
|
|
687
|
+
// `admin` is absent on handles persisted before this build; markUsed would
|
|
688
|
+
// otherwise put `undefined` in the used-set.
|
|
689
|
+
if (typeof ports.admin === 'number')
|
|
690
|
+
this.portAllocator.markUsed(ports.admin);
|
|
691
|
+
}
|
|
445
692
|
releasePorts(ports) {
|
|
446
693
|
this.portAllocator.release(ports.health);
|
|
447
694
|
this.portAllocator.release(ports.metrics);
|
|
@@ -506,14 +753,10 @@ export class HostProcessOrchestrator {
|
|
|
506
753
|
await this.stopContainer(dockerId);
|
|
507
754
|
}
|
|
508
755
|
this.releasePorts(handle.ports);
|
|
509
|
-
//
|
|
510
|
-
//
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
}
|
|
514
|
-
catch (err) {
|
|
515
|
-
log('failed to remove workdir %s: %o', handle.workdir, err);
|
|
516
|
-
}
|
|
756
|
+
// Longer retries than the other callers': this is the one path that has
|
|
757
|
+
// just killed a child which held this directory as its cwd, and on Windows
|
|
758
|
+
// the OS releases that handle asynchronously.
|
|
759
|
+
this.discardWorkdir(handle.workdir, { maxRetries: 20, retryDelay: 200 });
|
|
517
760
|
this.handles.delete(dockerId);
|
|
518
761
|
this.persist();
|
|
519
762
|
}
|