@braedonsaunders/appkit-desk 0.4.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/LICENSE +661 -0
- package/README.md +233 -0
- package/backend.d.ts +139 -0
- package/backend.d.ts.map +1 -0
- package/backend.js +583 -0
- package/backend.js.map +1 -0
- package/conformance.d.ts +19 -0
- package/conformance.d.ts.map +1 -0
- package/conformance.js +46 -0
- package/conformance.js.map +1 -0
- package/events.d.ts +190 -0
- package/events.d.ts.map +1 -0
- package/events.js +12 -0
- package/events.js.map +1 -0
- package/frames.d.ts +14 -0
- package/frames.d.ts.map +1 -0
- package/frames.js +24 -0
- package/frames.js.map +1 -0
- package/guest-agent.d.ts +129 -0
- package/guest-agent.d.ts.map +1 -0
- package/guest-agent.js +165 -0
- package/guest-agent.js.map +1 -0
- package/host.d.ts +325 -0
- package/host.d.ts.map +1 -0
- package/host.js +1038 -0
- package/host.js.map +1 -0
- package/index.d.ts +10 -0
- package/index.d.ts.map +1 -0
- package/index.js +10 -0
- package/index.js.map +1 -0
- package/package.json +41 -0
- package/plan.d.ts +117 -0
- package/plan.d.ts.map +1 -0
- package/plan.js +187 -0
- package/plan.js.map +1 -0
- package/portable-home.d.ts +79 -0
- package/portable-home.d.ts.map +1 -0
- package/portable-home.js +193 -0
- package/portable-home.js.map +1 -0
- package/protocol.d.ts +224 -0
- package/protocol.d.ts.map +1 -0
- package/protocol.js +498 -0
- package/protocol.js.map +1 -0
package/backend.js
ADDED
|
@@ -0,0 +1,583 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The backend port and its default Cloud Hypervisor implementation.
|
|
3
|
+
*
|
|
4
|
+
* `DeskBackend` is the seam that keeps the package testable without a
|
|
5
|
+
* hypervisor: the host asks a backend to boot a `DeskLaunchPlan` and gets a
|
|
6
|
+
* `DeskMachine` — a request/response channel to the in-guest agent plus an
|
|
7
|
+
* event subscription. CI and non-KVM developer machines inject an in-memory
|
|
8
|
+
* fake; production uses `cloudHypervisorBackend`, whose process-spawning glue
|
|
9
|
+
* is deliberately thin because everything that can be pure lives in the plan
|
|
10
|
+
* builder and the protocol module.
|
|
11
|
+
*/
|
|
12
|
+
import { spawn } from 'node:child_process';
|
|
13
|
+
import { randomUUID } from 'node:crypto';
|
|
14
|
+
import { createConnection } from 'node:net';
|
|
15
|
+
import { Buffer } from 'node:buffer';
|
|
16
|
+
import { DeskError } from './plan.js';
|
|
17
|
+
import { encodeFrame, FrameDecoder, GUEST_AGENT_VSOCK_PORT, parseHostBoundMessage, } from './protocol.js';
|
|
18
|
+
/**
|
|
19
|
+
* A request that was in flight when the guest connection dropped.
|
|
20
|
+
*
|
|
21
|
+
* Distinct from a plain `DeskError` because the caller's next move is
|
|
22
|
+
* different: this request may ALREADY HAVE RUN. The frame reached the guest,
|
|
23
|
+
* and whether the guest executed it before the channel went away is not
|
|
24
|
+
* knowable from the host. An `exec` may have sent mail; a `click` may have
|
|
25
|
+
* landed. So the transport refuses to guess — it names the ambiguity and lets
|
|
26
|
+
* the caller decide whether the operation is safe to repeat. Anything that
|
|
27
|
+
* rejects with a plain `DeskError` instead never reached the guest at all.
|
|
28
|
+
*/
|
|
29
|
+
export class DeskRequestFateUnknownError extends DeskError {
|
|
30
|
+
name = 'DeskRequestFateUnknownError';
|
|
31
|
+
}
|
|
32
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
|
|
33
|
+
const DEFAULT_CONNECT_TIMEOUT_MS = 20_000;
|
|
34
|
+
const DEFAULT_CONNECT_RETRY_DELAY_MS = 100;
|
|
35
|
+
const DEFAULT_HANDSHAKE_TIMEOUT_MS = 5_000;
|
|
36
|
+
const DEFAULT_RECONNECT_WINDOW_MS = 30_000;
|
|
37
|
+
const DEFAULT_RECONNECT_RETRY_DELAY_MS = 250;
|
|
38
|
+
/**
|
|
39
|
+
* How far the reconnect delay is allowed to double. A guest agent that systemd
|
|
40
|
+
* is restarting is not helped by being hammered four times a second for the
|
|
41
|
+
* whole window, and an unbounded doubling would spend most of the window
|
|
42
|
+
* asleep after two failures.
|
|
43
|
+
*/
|
|
44
|
+
const RECONNECT_BACKOFF_CEILING = 8;
|
|
45
|
+
const DEFAULT_KILL_GRACE_MS = 2_000;
|
|
46
|
+
const HANDSHAKE_LINE_LIMIT = 128;
|
|
47
|
+
export function createCloudHypervisorBackend(options = {}) {
|
|
48
|
+
const launcher = options.launcher ?? defaultLauncher;
|
|
49
|
+
const connect = options.connect ?? defaultConnect;
|
|
50
|
+
const platform = options.platform ?? process.platform;
|
|
51
|
+
const now = options.now ?? Date.now;
|
|
52
|
+
const idFactory = options.idFactory ?? randomUUID;
|
|
53
|
+
const requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
54
|
+
const connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
|
|
55
|
+
const connectRetryDelayMs = options.connectRetryDelayMs ?? DEFAULT_CONNECT_RETRY_DELAY_MS;
|
|
56
|
+
const handshakeTimeoutMs = options.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS;
|
|
57
|
+
const reconnectWindowMs = options.reconnectWindowMs ?? DEFAULT_RECONNECT_WINDOW_MS;
|
|
58
|
+
const reconnectRetryDelayMs = options.reconnectRetryDelayMs ?? DEFAULT_RECONNECT_RETRY_DELAY_MS;
|
|
59
|
+
const killGraceMs = options.killGraceMs ?? DEFAULT_KILL_GRACE_MS;
|
|
60
|
+
const guestAgentPort = options.guestAgentPort ?? GUEST_AGENT_VSOCK_PORT;
|
|
61
|
+
async function boot(plan) {
|
|
62
|
+
if (platform !== 'linux') {
|
|
63
|
+
throw new DeskError(`The AppKit desk requires Linux; received ${platform}.`);
|
|
64
|
+
}
|
|
65
|
+
if (plan.overlay.create) {
|
|
66
|
+
await runToCompletion(launcher(plan.overlay.create.command, plan.overlay.create.args, {
|
|
67
|
+
identity: plan.launcherIdentity,
|
|
68
|
+
}), `overlay creation for desk ${plan.deskId}`);
|
|
69
|
+
}
|
|
70
|
+
const child = launcher(plan.vmm.command, plan.vmm.args, { identity: plan.launcherIdentity });
|
|
71
|
+
const log = drainOutput(child);
|
|
72
|
+
const exit = watchExit(child);
|
|
73
|
+
let stream;
|
|
74
|
+
try {
|
|
75
|
+
stream = await connectWithRetry({
|
|
76
|
+
connect,
|
|
77
|
+
now,
|
|
78
|
+
socketPath: plan.vsock.socketPath,
|
|
79
|
+
port: guestAgentPort,
|
|
80
|
+
timeoutMs: connectTimeoutMs,
|
|
81
|
+
retryDelayMs: connectRetryDelayMs,
|
|
82
|
+
attemptTimeoutMs: handshakeTimeoutMs,
|
|
83
|
+
exited: exit,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
await terminate(child, exit, killGraceMs);
|
|
88
|
+
const said = log.tail();
|
|
89
|
+
const detail = said === '' ? '' : ` The VMM said: ${said}`;
|
|
90
|
+
throw error instanceof DeskError
|
|
91
|
+
? new DeskError(`${error.message}${detail}`)
|
|
92
|
+
: new DeskError(`Could not reach the guest agent for desk ${plan.deskId}: ${errorMessage(error)}${detail}`);
|
|
93
|
+
}
|
|
94
|
+
return createMachine({
|
|
95
|
+
deskId: plan.deskId,
|
|
96
|
+
child,
|
|
97
|
+
exit,
|
|
98
|
+
stream,
|
|
99
|
+
// The same path the first connection took, deliberately: a reconnect
|
|
100
|
+
// that skipped confirmGuest would adopt the very hollow handshake the
|
|
101
|
+
// boot path learned not to trust.
|
|
102
|
+
reconnect: (abandoned) => connectWithRetry({
|
|
103
|
+
connect,
|
|
104
|
+
now,
|
|
105
|
+
socketPath: plan.vsock.socketPath,
|
|
106
|
+
port: guestAgentPort,
|
|
107
|
+
timeoutMs: reconnectWindowMs,
|
|
108
|
+
retryDelayMs: reconnectRetryDelayMs,
|
|
109
|
+
maxRetryDelayMs: reconnectRetryDelayMs * RECONNECT_BACKOFF_CEILING,
|
|
110
|
+
attemptTimeoutMs: handshakeTimeoutMs,
|
|
111
|
+
exited: exit,
|
|
112
|
+
exitedMessage: `the VMM for desk ${plan.deskId} exited.`,
|
|
113
|
+
abandoned,
|
|
114
|
+
}),
|
|
115
|
+
reconnectWindowMs,
|
|
116
|
+
now,
|
|
117
|
+
idFactory,
|
|
118
|
+
requestTimeoutMs,
|
|
119
|
+
killGraceMs,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
return { boot };
|
|
123
|
+
}
|
|
124
|
+
/** The default backend: real Cloud Hypervisor over a real vsock socket. */
|
|
125
|
+
export const cloudHypervisorBackend = createCloudHypervisorBackend();
|
|
126
|
+
/**
|
|
127
|
+
* The machine, and the small state machine that keeps it connected.
|
|
128
|
+
*
|
|
129
|
+
* A vsock channel is not a fact the host learns once at boot — the transport
|
|
130
|
+
* can lie about being connected, and it can go away mid-lease for reasons that
|
|
131
|
+
* have nothing to do with the desk being unusable: the guest agent restarts,
|
|
132
|
+
* the socat bridge drops, a transient vsock error, the guest wedges for a
|
|
133
|
+
* moment. Treating any of those as terminal stranded the desk for the rest of
|
|
134
|
+
* its lease with a perfectly healthy guest behind it, answering every call
|
|
135
|
+
* with "no longer connected". So a live connection is something this machine
|
|
136
|
+
* RE-ESTABLISHES:
|
|
137
|
+
*
|
|
138
|
+
* live ──unexpected drop──▶ reconnecting ──confirmed guest──▶ live
|
|
139
|
+
* │ │
|
|
140
|
+
* │ └──window exhausted / VMM exited──▶ closed
|
|
141
|
+
* └──shutdown(), VMM already exited, protocol violation───────────▶ closed
|
|
142
|
+
*
|
|
143
|
+
* `closed` is terminal. Nothing reconnects out of it, which is what makes
|
|
144
|
+
* `shutdown()` and a dead VMM final rather than the start of a retry loop.
|
|
145
|
+
*/
|
|
146
|
+
function createMachine(options) {
|
|
147
|
+
const { deskId, child, exit, now, idFactory, requestTimeoutMs, killGraceMs, reconnectWindowMs } = options;
|
|
148
|
+
const pending = new Map();
|
|
149
|
+
// Listeners live on the machine rather than on the socket, so a reconnect
|
|
150
|
+
// re-points the data path at the new stream and every subscriber keeps
|
|
151
|
+
// working without re-registering.
|
|
152
|
+
const listeners = new Set();
|
|
153
|
+
const watchers = new Set();
|
|
154
|
+
let stream = options.stream;
|
|
155
|
+
let state = 'live';
|
|
156
|
+
let reconnects = 0;
|
|
157
|
+
let reconnecting = null;
|
|
158
|
+
function failAll(error) {
|
|
159
|
+
for (const entry of pending.values()) {
|
|
160
|
+
clearTimeout(entry.timer);
|
|
161
|
+
entry.reject(error);
|
|
162
|
+
}
|
|
163
|
+
pending.clear();
|
|
164
|
+
}
|
|
165
|
+
function announce(change) {
|
|
166
|
+
for (const watcher of [...watchers])
|
|
167
|
+
watcher(change);
|
|
168
|
+
}
|
|
169
|
+
function close(error, intentional) {
|
|
170
|
+
if (state === 'closed')
|
|
171
|
+
return;
|
|
172
|
+
state = 'closed';
|
|
173
|
+
failAll(error);
|
|
174
|
+
stream.destroy();
|
|
175
|
+
// A desk the consumer asked to stop is not news; one that stopped on its
|
|
176
|
+
// own is the thing an operator needs to be told about.
|
|
177
|
+
if (!intentional)
|
|
178
|
+
announce({ state: 'lost', deskId, reason: error.message });
|
|
179
|
+
}
|
|
180
|
+
function attach(next) {
|
|
181
|
+
stream = next;
|
|
182
|
+
// Each connection decodes with its OWN decoder: a frame the drop cut in
|
|
183
|
+
// half must never be completed by the first bytes of its replacement.
|
|
184
|
+
const decoder = new FrameDecoder();
|
|
185
|
+
const current = () => stream === next && state !== 'closed';
|
|
186
|
+
const onData = (chunk) => {
|
|
187
|
+
if (!current())
|
|
188
|
+
return;
|
|
189
|
+
let values;
|
|
190
|
+
try {
|
|
191
|
+
values = decoder.push(chunk);
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
close(new DeskError(`Guest agent protocol violation on desk ${deskId}: ${errorMessage(error)}`), false);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
for (const value of values) {
|
|
198
|
+
let message;
|
|
199
|
+
try {
|
|
200
|
+
message = parseHostBoundMessage(value);
|
|
201
|
+
}
|
|
202
|
+
catch (error) {
|
|
203
|
+
close(new DeskError(`Guest agent sent a malformed message on desk ${deskId}: ${errorMessage(error)}`), false);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
if ('id' in message) {
|
|
207
|
+
const entry = pending.get(message.id);
|
|
208
|
+
if (!entry)
|
|
209
|
+
continue;
|
|
210
|
+
pending.delete(message.id);
|
|
211
|
+
clearTimeout(entry.timer);
|
|
212
|
+
if (message.ok)
|
|
213
|
+
entry.resolve(message.result);
|
|
214
|
+
else
|
|
215
|
+
entry.reject(new DeskError(`Guest agent error on desk ${deskId}: ${message.error}`));
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
for (const listener of [...listeners])
|
|
219
|
+
listener(message);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
next.on('data', onData);
|
|
224
|
+
next.once('close', () => {
|
|
225
|
+
drop(next, `the guest agent connection closed on desk ${deskId}`);
|
|
226
|
+
});
|
|
227
|
+
next.once('error', (error) => {
|
|
228
|
+
drop(next, `the guest agent connection failed on desk ${deskId}: ${error.message}`);
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
function drop(from, reason) {
|
|
232
|
+
if (state !== 'live' || from !== stream)
|
|
233
|
+
return;
|
|
234
|
+
from.destroy();
|
|
235
|
+
if (exit.done) {
|
|
236
|
+
// A dead VMM is not a connection problem. There is no guest to get back
|
|
237
|
+
// to, and retrying against it forever only delays the fresh boot the
|
|
238
|
+
// desk actually needs.
|
|
239
|
+
close(new DeskError(`Desk ${deskId} is no longer connected: the VMM exited (${reason}).`), false);
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
state = 'reconnecting';
|
|
243
|
+
const lostAt = now();
|
|
244
|
+
// In-flight requests CANNOT be silently retried. Each of their frames
|
|
245
|
+
// already reached the guest, and whether the guest ran it before the
|
|
246
|
+
// channel went away is not knowable from here: an `exec` may have sent
|
|
247
|
+
// mail, a `click` may have landed. Replaying a side-effecting operation to
|
|
248
|
+
// paper over a blip is the wrong kind of resilience, so every one of them
|
|
249
|
+
// is told its fate is unknown and the caller decides.
|
|
250
|
+
failAll(new DeskRequestFateUnknownError(`Desk ${deskId} lost its guest agent connection while this request was in flight `
|
|
251
|
+
+ `(${reason}); the guest may or may not have run it.`));
|
|
252
|
+
reconnecting = restore(reason, lostAt);
|
|
253
|
+
}
|
|
254
|
+
/** Always resolves: callers await it to learn the outcome, not to be thrown at. */
|
|
255
|
+
async function restore(reason, lostAt) {
|
|
256
|
+
let next;
|
|
257
|
+
try {
|
|
258
|
+
next = await options.reconnect(() => state !== 'reconnecting');
|
|
259
|
+
}
|
|
260
|
+
catch (error) {
|
|
261
|
+
close(new DeskError(`Desk ${deskId} lost its guest agent connection and could not get it back: ${errorMessage(error)}`), false);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
if (state !== 'reconnecting') {
|
|
265
|
+
// shutdown() won the race while the replacement socket was coming up.
|
|
266
|
+
next.destroy();
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
attach(next);
|
|
270
|
+
state = 'live';
|
|
271
|
+
reconnects += 1;
|
|
272
|
+
announce({ state: 'reconnected', deskId, reason, downtimeMs: now() - lostAt, reconnects });
|
|
273
|
+
}
|
|
274
|
+
attach(options.stream);
|
|
275
|
+
return {
|
|
276
|
+
deskId,
|
|
277
|
+
async request(command, requestOptions = {}) {
|
|
278
|
+
// A call that lands mid-reconnect waits for it rather than failing on
|
|
279
|
+
// the spot: the guest is usually back within seconds, and telling a
|
|
280
|
+
// caller a desk is gone when it is about to be fine is the bug this
|
|
281
|
+
// machine exists to end. The wait is bounded by the same window the
|
|
282
|
+
// reconnect itself is.
|
|
283
|
+
const waitUntil = now() + reconnectWindowMs;
|
|
284
|
+
while (state === 'reconnecting') {
|
|
285
|
+
const attempt = reconnecting;
|
|
286
|
+
if (!attempt || now() >= waitUntil)
|
|
287
|
+
break;
|
|
288
|
+
await attempt;
|
|
289
|
+
}
|
|
290
|
+
if (state !== 'live') {
|
|
291
|
+
// This one never left the host, so — unlike a request that was in
|
|
292
|
+
// flight when the channel dropped — repeating it is safe.
|
|
293
|
+
throw new DeskError(`Desk ${deskId} is no longer connected.`);
|
|
294
|
+
}
|
|
295
|
+
const id = idFactory();
|
|
296
|
+
const timeoutMs = requestOptions.timeoutMs ?? requestTimeoutMs;
|
|
297
|
+
const target = stream;
|
|
298
|
+
return await new Promise((resolvePromise, rejectPromise) => {
|
|
299
|
+
const timer = setTimeout(() => {
|
|
300
|
+
pending.delete(id);
|
|
301
|
+
rejectPromise(new DeskError(`Guest request ${command.op} timed out on desk ${deskId}.`));
|
|
302
|
+
}, timeoutMs);
|
|
303
|
+
timer.unref();
|
|
304
|
+
pending.set(id, { resolve: resolvePromise, reject: rejectPromise, timer });
|
|
305
|
+
target.write(encodeFrame({ ...command, id }));
|
|
306
|
+
});
|
|
307
|
+
},
|
|
308
|
+
subscribe(listener) {
|
|
309
|
+
listeners.add(listener);
|
|
310
|
+
return () => {
|
|
311
|
+
listeners.delete(listener);
|
|
312
|
+
};
|
|
313
|
+
},
|
|
314
|
+
onConnectionChange(listener) {
|
|
315
|
+
watchers.add(listener);
|
|
316
|
+
return () => {
|
|
317
|
+
watchers.delete(listener);
|
|
318
|
+
};
|
|
319
|
+
},
|
|
320
|
+
async shutdown() {
|
|
321
|
+
// Terminal by construction: `closed` is the state the reconnect loop
|
|
322
|
+
// checks, so an explicit shutdown can never be followed by a reconnect.
|
|
323
|
+
close(new DeskError(`Desk ${deskId} is shutting down.`), true);
|
|
324
|
+
await terminate(child, exit, killGraceMs);
|
|
325
|
+
},
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Read the VMM's stdout and stderr, and keep only the last few kilobytes.
|
|
330
|
+
*
|
|
331
|
+
* This is not for logging — it is load-bearing. The child is spawned with
|
|
332
|
+
* both streams as PIPES, and a pipe nobody reads fills after about 64KB, at
|
|
333
|
+
* which point the VMM BLOCKS on its next write. Cloud Hypervisor logs while
|
|
334
|
+
* it runs, so an unread pipe freezes the guest partway through boot: the
|
|
335
|
+
* process is alive, the disk is untouched, and the guest agent never reaches
|
|
336
|
+
* vsock. Every symptom points at the image and none of them are its fault.
|
|
337
|
+
*
|
|
338
|
+
* Draining costs nothing and buys the tail of what the VMM said, which is the
|
|
339
|
+
* difference between "the VMM exited" and knowing why.
|
|
340
|
+
*/
|
|
341
|
+
function drainOutput(child, limit = 8 * 1024) {
|
|
342
|
+
let buffered = '';
|
|
343
|
+
const absorb = (chunk) => {
|
|
344
|
+
buffered += String(chunk);
|
|
345
|
+
if (buffered.length > limit)
|
|
346
|
+
buffered = buffered.slice(buffered.length - limit);
|
|
347
|
+
};
|
|
348
|
+
child.stdout?.on('data', absorb);
|
|
349
|
+
child.stderr?.on('data', absorb);
|
|
350
|
+
// A pipe that errors must not take the process down with it.
|
|
351
|
+
child.stdout?.on('error', () => undefined);
|
|
352
|
+
child.stderr?.on('error', () => undefined);
|
|
353
|
+
return { tail: () => buffered.trim() };
|
|
354
|
+
}
|
|
355
|
+
function watchExit(child) {
|
|
356
|
+
const watcher = { done: false, promise: Promise.resolve() };
|
|
357
|
+
watcher.promise = new Promise((resolvePromise) => {
|
|
358
|
+
const settle = () => {
|
|
359
|
+
watcher.done = true;
|
|
360
|
+
resolvePromise();
|
|
361
|
+
};
|
|
362
|
+
child.once('exit', settle);
|
|
363
|
+
child.once('error', settle);
|
|
364
|
+
});
|
|
365
|
+
return watcher;
|
|
366
|
+
}
|
|
367
|
+
async function terminate(child, exit, killGraceMs) {
|
|
368
|
+
if (exit.done)
|
|
369
|
+
return;
|
|
370
|
+
child.kill('SIGTERM');
|
|
371
|
+
const forceKill = setTimeout(() => {
|
|
372
|
+
if (!exit.done)
|
|
373
|
+
child.kill('SIGKILL');
|
|
374
|
+
}, killGraceMs);
|
|
375
|
+
forceKill.unref();
|
|
376
|
+
await exit.promise;
|
|
377
|
+
clearTimeout(forceKill);
|
|
378
|
+
}
|
|
379
|
+
function runToCompletion(child, label) {
|
|
380
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
381
|
+
let stderr = '';
|
|
382
|
+
child.stderr?.on('data', (chunk) => {
|
|
383
|
+
stderr += String(chunk);
|
|
384
|
+
});
|
|
385
|
+
child.once('error', (error) => {
|
|
386
|
+
rejectPromise(new DeskError(`${label} failed to start: ${error.message}`));
|
|
387
|
+
});
|
|
388
|
+
child.once('exit', (code, signal) => {
|
|
389
|
+
if (code === 0) {
|
|
390
|
+
resolvePromise();
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
const detail = stderr.trim();
|
|
394
|
+
rejectPromise(new DeskError(`${label} exited with code ${code ?? 'unknown'}`
|
|
395
|
+
+ `${signal ? ` (${signal})` : ''}${detail ? `: ${detail}` : '.'}`));
|
|
396
|
+
});
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Cloud Hypervisor exposes guest vsock ports through a host Unix socket with
|
|
401
|
+
* a line-oriented preamble: the client writes `CONNECT <port>\n` and the VMM
|
|
402
|
+
* answers `OK <assigned>\n` before the byte stream becomes the guest
|
|
403
|
+
* connection. The VMM creates the socket during boot, so connection attempts
|
|
404
|
+
* retry until the deadline.
|
|
405
|
+
*
|
|
406
|
+
* The same loop serves the first connection and every later reconnect, so a
|
|
407
|
+
* reconnect gets `confirmGuest` too — a mid-lease reconnect that trusted the
|
|
408
|
+
* banner would re-adopt exactly the hollow stream the boot path learned not to.
|
|
409
|
+
*/
|
|
410
|
+
async function connectWithRetry(options) {
|
|
411
|
+
const deadline = options.now() + options.timeoutMs;
|
|
412
|
+
let lastFailure = 'the guest agent never answered';
|
|
413
|
+
let retryDelayMs = options.retryDelayMs;
|
|
414
|
+
while (options.now() <= deadline) {
|
|
415
|
+
if (options.exited.done) {
|
|
416
|
+
throw new DeskError(options.exitedMessage ?? 'The VMM exited before the guest agent came up.');
|
|
417
|
+
}
|
|
418
|
+
if (options.abandoned?.() === true) {
|
|
419
|
+
throw new DeskError('the connection attempt was abandoned.');
|
|
420
|
+
}
|
|
421
|
+
try {
|
|
422
|
+
const stream = await attemptHandshake(options.connect, options.socketPath, options.port, options.attemptTimeoutMs);
|
|
423
|
+
try {
|
|
424
|
+
await confirmGuest(stream, options.attemptTimeoutMs);
|
|
425
|
+
}
|
|
426
|
+
catch (error) {
|
|
427
|
+
stream.destroy();
|
|
428
|
+
throw error;
|
|
429
|
+
}
|
|
430
|
+
return stream;
|
|
431
|
+
}
|
|
432
|
+
catch (error) {
|
|
433
|
+
lastFailure = errorMessage(error);
|
|
434
|
+
}
|
|
435
|
+
await delay(retryDelayMs);
|
|
436
|
+
if (options.maxRetryDelayMs !== undefined) {
|
|
437
|
+
retryDelayMs = Math.min(retryDelayMs * 2, options.maxRetryDelayMs);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
throw new DeskError(`Timed out connecting to the guest agent at ${options.socketPath}: ${lastFailure}`);
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* One handshake attempt, which MUST settle.
|
|
444
|
+
*
|
|
445
|
+
* Cloud Hypervisor accepts a connection on the vsock socket whether or not
|
|
446
|
+
* anything in the guest is listening on the port, and when nothing is it may
|
|
447
|
+
* answer nothing at all: no reply, no error, no close. Without a deadline of
|
|
448
|
+
* its own this promise then never settles — and because the caller awaits it
|
|
449
|
+
* inside the retry loop, the loop stops iterating, the overall deadline is
|
|
450
|
+
* never re-checked, and the boot hangs forever rather than failing. That is
|
|
451
|
+
* indistinguishable from a wedged host and it is why every attempt is bounded
|
|
452
|
+
* here as well as in aggregate.
|
|
453
|
+
*/
|
|
454
|
+
/**
|
|
455
|
+
* Prove a guest is behind the handshake by asking it something.
|
|
456
|
+
*
|
|
457
|
+
* Cloud Hypervisor answers `CONNECT <port>` with `OK` whether or not anything
|
|
458
|
+
* in the guest is listening on that port, and only closes the socket a moment
|
|
459
|
+
* later when it finds nobody there. A caller that trusts the banner therefore
|
|
460
|
+
* "connects" to a guest that is still booting, gets a closed stream seconds
|
|
461
|
+
* later, and — because a closed machine is not retried — leaves the desk dead
|
|
462
|
+
* for as long as it is leased, with a healthy guest sitting behind it. So the
|
|
463
|
+
* handshake is not the test; a reply is.
|
|
464
|
+
*/
|
|
465
|
+
async function confirmGuest(stream, timeoutMs) {
|
|
466
|
+
const decoder = new FrameDecoder();
|
|
467
|
+
await new Promise((resolvePromise, rejectPromise) => {
|
|
468
|
+
let settled = false;
|
|
469
|
+
const finish = (error) => {
|
|
470
|
+
if (settled)
|
|
471
|
+
return;
|
|
472
|
+
settled = true;
|
|
473
|
+
clearTimeout(timer);
|
|
474
|
+
stream.off('data', onData);
|
|
475
|
+
stream.off('close', onClose);
|
|
476
|
+
stream.off('error', finish);
|
|
477
|
+
if (error)
|
|
478
|
+
rejectPromise(error);
|
|
479
|
+
else
|
|
480
|
+
resolvePromise();
|
|
481
|
+
};
|
|
482
|
+
const timer = setTimeout(() => finish(new DeskError('the guest agent did not answer the first request.')), timeoutMs);
|
|
483
|
+
timer.unref?.();
|
|
484
|
+
const onClose = () => finish(new DeskError('the connection closed before the guest agent answered.'));
|
|
485
|
+
const onData = (chunk) => {
|
|
486
|
+
let values;
|
|
487
|
+
try {
|
|
488
|
+
values = decoder.push(chunk);
|
|
489
|
+
}
|
|
490
|
+
catch (error) {
|
|
491
|
+
finish(error instanceof Error ? error : new Error(String(error)));
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
for (const value of values) {
|
|
495
|
+
// Anything at all proves a guest is there; the reply is parsed for
|
|
496
|
+
// real by the machine once it owns the stream.
|
|
497
|
+
if (value && typeof value === 'object') {
|
|
498
|
+
finish();
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
};
|
|
503
|
+
stream.on('data', onData);
|
|
504
|
+
stream.once('close', onClose);
|
|
505
|
+
stream.once('error', finish);
|
|
506
|
+
stream.write(encodeFrame({ id: 'hello', op: 'ping' }));
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
function attemptHandshake(connect, socketPath, port, attemptTimeoutMs) {
|
|
510
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
511
|
+
let stream;
|
|
512
|
+
try {
|
|
513
|
+
stream = connect(socketPath);
|
|
514
|
+
}
|
|
515
|
+
catch (error) {
|
|
516
|
+
rejectPromise(error instanceof Error ? error : new Error(String(error)));
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
let banner = '';
|
|
520
|
+
let settled = false;
|
|
521
|
+
const timer = setTimeout(() => {
|
|
522
|
+
fail(new DeskError('vsock handshake went unanswered.'));
|
|
523
|
+
}, attemptTimeoutMs);
|
|
524
|
+
// An unref'd timer must not hold the process open on its own.
|
|
525
|
+
timer.unref?.();
|
|
526
|
+
const fail = (error) => {
|
|
527
|
+
if (settled)
|
|
528
|
+
return;
|
|
529
|
+
settled = true;
|
|
530
|
+
clearTimeout(timer);
|
|
531
|
+
stream.destroy();
|
|
532
|
+
rejectPromise(error);
|
|
533
|
+
};
|
|
534
|
+
const onData = (chunk) => {
|
|
535
|
+
banner += chunk.toString('latin1');
|
|
536
|
+
const newline = banner.indexOf('\n');
|
|
537
|
+
if (newline === -1) {
|
|
538
|
+
if (banner.length > HANDSHAKE_LINE_LIMIT) {
|
|
539
|
+
fail(new DeskError('vsock handshake reply exceeded the line limit.'));
|
|
540
|
+
}
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
const line = banner.slice(0, newline);
|
|
544
|
+
const rest = banner.slice(newline + 1);
|
|
545
|
+
stream.off('data', onData);
|
|
546
|
+
stream.off('error', fail);
|
|
547
|
+
if (!line.startsWith('OK ')) {
|
|
548
|
+
fail(new DeskError(`vsock handshake was refused: ${line}`));
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
settled = true;
|
|
552
|
+
clearTimeout(timer);
|
|
553
|
+
if (rest.length > 0)
|
|
554
|
+
stream.unshift(Buffer.from(rest, 'latin1'));
|
|
555
|
+
resolvePromise(stream);
|
|
556
|
+
};
|
|
557
|
+
stream.on('data', onData);
|
|
558
|
+
stream.once('error', fail);
|
|
559
|
+
// A close before the banner is a refusal, not a hang.
|
|
560
|
+
stream.once('close', () => fail(new DeskError('vsock handshake closed before a reply.')));
|
|
561
|
+
stream.write(`CONNECT ${port}\n`);
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
function defaultLauncher(command, args, options) {
|
|
565
|
+
return spawn(command, [...args], {
|
|
566
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
567
|
+
uid: options.identity?.uid,
|
|
568
|
+
gid: options.identity?.gid,
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
function defaultConnect(socketPath) {
|
|
572
|
+
return createConnection(socketPath);
|
|
573
|
+
}
|
|
574
|
+
function delay(ms) {
|
|
575
|
+
return new Promise((resolvePromise) => {
|
|
576
|
+
const timer = setTimeout(resolvePromise, ms);
|
|
577
|
+
timer.unref();
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
function errorMessage(error) {
|
|
581
|
+
return error instanceof Error ? error.message : String(error);
|
|
582
|
+
}
|
|
583
|
+
//# sourceMappingURL=backend.js.map
|