@moondeck/station 1.0.4 → 1.0.6
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/lib/agent-dependencies.ts +246 -0
- package/lib/agent.ts +9 -1
- package/lib/cloud-credential-host.ts +31 -4
- package/lib/cloud-credential-leases.ts +35 -4
- package/lib/cloud-credential-runtime.ts +10 -3
- package/lib/container-runtime.ts +168 -31
- package/lib/machine-exec.ts +6 -2
- package/lib/machine-payload-image.ts +192 -0
- package/lib/machine-provider-aws.ts +429 -113
- package/lib/machine-provider.ts +65 -0
- package/lib/managed-runtime.ts +25 -0
- package/lib/orchestrator.ts +70 -1
- package/lib/runtime-archive.ts +47 -0
- package/lib/skills.ts +31 -9
- package/lib/standard-image-schedule.ts +53 -0
- package/lib/task-credential-cleanup.ts +62 -5
- package/lib/task-env-forwarder.ts +123 -17
- package/lib/task-environment/machine-task-up.ts +4 -0
- package/lib/task-environment/machine.ts +576 -23
- package/lib/task-environment/types.ts +28 -0
- package/lib/vnode-pressure.ts +31 -8
- package/package.json +1 -1
- package/scripts/agent/_common.sh +36 -29
- package/scripts/agent/_deps.sh +47 -0
- package/scripts/agent/check-deps.sh +59 -0
- package/src/cli.ts +1 -1
- package/src/event-outbox.ts +50 -1
- package/src/index.ts +138 -1
- package/src/main.ts +127 -15
- package/src/process-wake.ts +36 -0
- package/src/protocol.ts +120 -1
- package/src/task-note-publisher.ts +65 -0
|
@@ -15,14 +15,20 @@
|
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
import { execFile, spawn as nodeSpawn } from "node:child_process";
|
|
18
|
-
import { readFileSync, statSync, writeFileSync } from "node:fs";
|
|
18
|
+
import { readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
19
|
+
import { join } from "node:path";
|
|
19
20
|
import { promisify } from "node:util";
|
|
20
21
|
|
|
21
|
-
import
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
import {
|
|
23
|
+
MachineLaunchTokenSpentError,
|
|
24
|
+
type MachineInfo,
|
|
25
|
+
type MachineLaunchIntent,
|
|
26
|
+
type MachineLaunchIntentStore,
|
|
27
|
+
type MachineProvider,
|
|
24
28
|
} from "../machine-provider";
|
|
25
29
|
import { machineEnvironmentSshArgs } from "../machine-exec";
|
|
30
|
+
import { STATION_MACHINE_PAYLOAD_MARKER } from "../machine-payload-image";
|
|
31
|
+
import type { EnvironmentLossNotice } from "./types";
|
|
26
32
|
import { applyProjectEnvProfile } from "../runtime-authority";
|
|
27
33
|
import { rootAnchoredRequest } from "./anchor";
|
|
28
34
|
import {
|
|
@@ -120,6 +126,283 @@ export interface MachineTaskEnvironmentDeps {
|
|
|
120
126
|
readyTimeoutMs?: number;
|
|
121
127
|
}
|
|
122
128
|
|
|
129
|
+
/**
|
|
130
|
+
* F6: which launch of a task's machine is current, kept beside its SSH
|
|
131
|
+
* identity in the task control dir so it survives a Station restart. The
|
|
132
|
+
* generation feeds the backend's launch idempotency (MachineSpec), and is
|
|
133
|
+
* bumped only after the backend proves the current generation's machine
|
|
134
|
+
* terminated. `launched` records that this generation's launch succeeded, and
|
|
135
|
+
* `instanceId` which instance it made: a later launch answered by a DIFFERENT
|
|
136
|
+
* instance means the old one, and its disk, went away. The same instance
|
|
137
|
+
* means a retry found it again (a lagging describe), and nothing was lost.
|
|
138
|
+
*
|
|
139
|
+
* `pendingLossNotices` holds those proofs, one per lost machine, until the
|
|
140
|
+
* user has been told (reviews #w3qdsr, #4ndq0w): each is added when its loss
|
|
141
|
+
* is proven, carried across a crash before the relaunch and across failed
|
|
142
|
+
* starts after it, and removed (by its id) only once the cloud has its note.
|
|
143
|
+
* A queue, not one slot: every lost machine is its own fact with its own id,
|
|
144
|
+
* so a second loss can never be folded into, or hidden behind, the first.
|
|
145
|
+
*/
|
|
146
|
+
export interface MachineLaunchRecord {
|
|
147
|
+
generation: number;
|
|
148
|
+
launched: boolean;
|
|
149
|
+
instanceId?: string;
|
|
150
|
+
pendingLossNotices?: PendingLossNotice[];
|
|
151
|
+
/** F3: the subnet the latest launch attempt used, written BEFORE its
|
|
152
|
+
* run-instances; `attempting` means its outcome is not yet known. The
|
|
153
|
+
* next launch replays this subnet first (fileLaunchIntentStore). One
|
|
154
|
+
* record, so the generation and the subnet always move together; every
|
|
155
|
+
* write re-reads the file and keeps the fields it does not own. */
|
|
156
|
+
launchIntent?: MachineLaunchIntent;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export interface PendingLossNotice {
|
|
160
|
+
lostInstanceId: string | null;
|
|
161
|
+
/** The generation that replaced it: with the instance, the loss's id. */
|
|
162
|
+
generation: number;
|
|
163
|
+
/** Handed to a publisher at least once (review #2cp6r4). Set before the
|
|
164
|
+
* first publish and never cleared: the cloud may hold this id already, so
|
|
165
|
+
* the entry is immutable (never folded, grown or dropped) until its id is
|
|
166
|
+
* acknowledged, and every retry resends the identical id and text. */
|
|
167
|
+
attempted?: true;
|
|
168
|
+
/** A summary of several losses folded together when the queue overflowed
|
|
169
|
+
* (review #d0p42f). `lostInstanceId` and `generation` are the FIRST folded
|
|
170
|
+
* loss's, so the summary's id never changes as more fold in. */
|
|
171
|
+
folded?: { count: number; instanceIds: string[] };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* The most entries the queue keeps (review #d0p42f). Each one needs a real
|
|
176
|
+
* EC2 machine of this task proven terminated, whose note the cloud has not
|
|
177
|
+
* yet confirmed. Even a handful between two successful starts is far beyond
|
|
178
|
+
* what happens, so 16 never folds in practice and still bounds a broken
|
|
179
|
+
* delivery path. With at most MAX_FOLDED_INSTANCE_IDS ids in a summary, the
|
|
180
|
+
* whole record stays under 4 KiB.
|
|
181
|
+
*
|
|
182
|
+
* It is never exceeded (review #2cp6r4): the Station delivers one entry per
|
|
183
|
+
* task at a time, oldest first, and attempts the next only once the current
|
|
184
|
+
* one is acknowledged, so at most one entry is attempted at any time and at
|
|
185
|
+
* least 15 of 16 are always foldable.
|
|
186
|
+
*/
|
|
187
|
+
export const MAX_PENDING_LOSS_NOTICES = 16;
|
|
188
|
+
export const MAX_FOLDED_INSTANCE_IDS = 8;
|
|
189
|
+
|
|
190
|
+
function isPendingLossNotice(value: unknown): value is PendingLossNotice {
|
|
191
|
+
if (typeof value !== "object" || value === null) return false;
|
|
192
|
+
const notice = value as { lostInstanceId?: unknown; generation?: unknown; attempted?: unknown; folded?: unknown };
|
|
193
|
+
const folded = notice.folded as { count?: unknown; instanceIds?: unknown } | undefined;
|
|
194
|
+
return (
|
|
195
|
+
(notice.lostInstanceId === null || typeof notice.lostInstanceId === "string") &&
|
|
196
|
+
typeof notice.generation === "number" &&
|
|
197
|
+
Number.isSafeInteger(notice.generation) &&
|
|
198
|
+
(notice.attempted === undefined || notice.attempted === true) &&
|
|
199
|
+
(folded === undefined ||
|
|
200
|
+
(typeof folded === "object" &&
|
|
201
|
+
folded !== null &&
|
|
202
|
+
typeof folded.count === "number" &&
|
|
203
|
+
Number.isSafeInteger(folded.count) &&
|
|
204
|
+
folded.count >= 1 &&
|
|
205
|
+
Array.isArray(folded.instanceIds) &&
|
|
206
|
+
folded.instanceIds.length <= MAX_FOLDED_INSTANCE_IDS &&
|
|
207
|
+
folded.instanceIds.every((id) => typeof id === "string" && id.length <= 64)))
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** `into` (a summary, or a single loss that becomes one) with `next` folded in. */
|
|
212
|
+
function foldLossNotices(into: PendingLossNotice, next: PendingLossNotice): PendingLossNotice {
|
|
213
|
+
const idsOf = (notice: PendingLossNotice): string[] =>
|
|
214
|
+
notice.folded?.instanceIds ?? (notice.lostInstanceId === null ? [] : [notice.lostInstanceId]);
|
|
215
|
+
const countOf = (notice: PendingLossNotice): number => notice.folded?.count ?? 1;
|
|
216
|
+
return {
|
|
217
|
+
lostInstanceId: into.lostInstanceId,
|
|
218
|
+
generation: into.generation,
|
|
219
|
+
folded: {
|
|
220
|
+
count: countOf(into) + countOf(next),
|
|
221
|
+
instanceIds: [...idsOf(into), ...idsOf(next)].slice(0, MAX_FOLDED_INSTANCE_IDS),
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** The record's queue with `notice` added, unless one with its id is there. */
|
|
227
|
+
export function withLossNotice(current: MachineLaunchRecord, notice: PendingLossNotice): PendingLossNotice[] {
|
|
228
|
+
const existing = current.pendingLossNotices ?? [];
|
|
229
|
+
if (existing.some((pending) => lossNoticeId(pending) === lossNoticeId(notice))) return existing;
|
|
230
|
+
const queue = [...existing, notice];
|
|
231
|
+
// Reviews #d0p42f, #2cp6r4: at most MAX_PENDING_LOSS_NOTICES entries.
|
|
232
|
+
while (queue.length > MAX_PENDING_LOSS_NOTICES) {
|
|
233
|
+
// The two oldest entries never attempted fold into one. An attempted
|
|
234
|
+
// entry is never touched: the cloud may already hold its id. A summary
|
|
235
|
+
// never attempted may grow (the cloud never saw its id) and keeps it;
|
|
236
|
+
// two singles make a new summary, whose id is its own first loss's.
|
|
237
|
+
const first = queue.findIndex((pending) => pending.attempted !== true);
|
|
238
|
+
const second = first === -1 ? -1 : queue.findIndex((pending, index) => index > first && pending.attempted !== true);
|
|
239
|
+
if (second === -1) {
|
|
240
|
+
// Only reachable with two or more attempted entries, which one-at-a-time
|
|
241
|
+
// delivery never leaves: refuse rather than drop a proof or grow past
|
|
242
|
+
// the bound.
|
|
243
|
+
throw new Error(
|
|
244
|
+
`machine-loss notice queue invariant broken: ${String(queue.filter((pending) => pending.attempted === true).length)} attempted entries`,
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
const folded = foldLossNotices(queue[first]!, queue[second]!);
|
|
248
|
+
queue.splice(second, 1);
|
|
249
|
+
queue.splice(first, 1, folded);
|
|
250
|
+
}
|
|
251
|
+
return queue;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export function lossNoticeId(notice: PendingLossNotice): string {
|
|
255
|
+
const single = `${notice.lostInstanceId ?? "unknown-instance"}@generation-${notice.generation}`;
|
|
256
|
+
return notice.folded ? `folded:${single}` : single;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export const MACHINE_LAUNCH_RECORD = "machine-launch.json";
|
|
260
|
+
|
|
261
|
+
/** The task's launch record; a task from before F6 has none (generation 0,
|
|
262
|
+
* never recorded as launched). A record that does not parse is refused, not
|
|
263
|
+
* guessed at: a wrong generation could reuse a spent token or double-launch. */
|
|
264
|
+
export function readMachineLaunchRecord(controlDir: string): MachineLaunchRecord {
|
|
265
|
+
let raw: string;
|
|
266
|
+
try {
|
|
267
|
+
raw = readFileSync(join(controlDir, MACHINE_LAUNCH_RECORD), "utf8");
|
|
268
|
+
} catch (error) {
|
|
269
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return { generation: 0, launched: false };
|
|
270
|
+
throw error;
|
|
271
|
+
}
|
|
272
|
+
const parsed = JSON.parse(raw) as {
|
|
273
|
+
schemaVersion?: unknown;
|
|
274
|
+
generation?: unknown;
|
|
275
|
+
launched?: unknown;
|
|
276
|
+
instanceId?: unknown;
|
|
277
|
+
pendingLossNotices?: unknown;
|
|
278
|
+
launchIntent?: { subnetId?: unknown; state?: unknown } | null;
|
|
279
|
+
};
|
|
280
|
+
if (
|
|
281
|
+
parsed?.schemaVersion !== 1 ||
|
|
282
|
+
typeof parsed.generation !== "number" ||
|
|
283
|
+
!Number.isSafeInteger(parsed.generation) ||
|
|
284
|
+
parsed.generation < 0 ||
|
|
285
|
+
typeof parsed.launched !== "boolean" ||
|
|
286
|
+
(parsed.instanceId !== undefined && typeof parsed.instanceId !== "string") ||
|
|
287
|
+
(parsed.pendingLossNotices !== undefined &&
|
|
288
|
+
(!Array.isArray(parsed.pendingLossNotices) || !parsed.pendingLossNotices.every(isPendingLossNotice))) ||
|
|
289
|
+
(parsed.launchIntent !== undefined &&
|
|
290
|
+
(typeof parsed.launchIntent !== "object" ||
|
|
291
|
+
parsed.launchIntent === null ||
|
|
292
|
+
typeof parsed.launchIntent.subnetId !== "string" ||
|
|
293
|
+
// Refused, not guessed at: a wrong subnet could launch a second machine.
|
|
294
|
+
!/^subnet-[0-9a-f]{8,32}$/.test(parsed.launchIntent.subnetId) ||
|
|
295
|
+
(parsed.launchIntent.state !== "attempting" && parsed.launchIntent.state !== "launched")))
|
|
296
|
+
) {
|
|
297
|
+
throw new Error(`machine launch record in ${controlDir} is invalid`);
|
|
298
|
+
}
|
|
299
|
+
return {
|
|
300
|
+
generation: parsed.generation,
|
|
301
|
+
launched: parsed.launched,
|
|
302
|
+
...(typeof parsed.instanceId === "string" ? { instanceId: parsed.instanceId } : {}),
|
|
303
|
+
...(Array.isArray(parsed.pendingLossNotices) && parsed.pendingLossNotices.length > 0
|
|
304
|
+
? {
|
|
305
|
+
pendingLossNotices: (parsed.pendingLossNotices as PendingLossNotice[]).map((notice) => ({
|
|
306
|
+
lostInstanceId: notice.lostInstanceId,
|
|
307
|
+
generation: notice.generation,
|
|
308
|
+
...(notice.attempted === true ? { attempted: true as const } : {}),
|
|
309
|
+
...(notice.folded
|
|
310
|
+
? { folded: { count: notice.folded.count, instanceIds: [...notice.folded.instanceIds] } }
|
|
311
|
+
: {}),
|
|
312
|
+
})),
|
|
313
|
+
}
|
|
314
|
+
: {}),
|
|
315
|
+
...(parsed.launchIntent !== undefined
|
|
316
|
+
? {
|
|
317
|
+
launchIntent: {
|
|
318
|
+
subnetId: parsed.launchIntent.subnetId as string,
|
|
319
|
+
state: parsed.launchIntent.state as MachineLaunchIntent["state"],
|
|
320
|
+
},
|
|
321
|
+
}
|
|
322
|
+
: {}),
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** Read the record afresh, change it, write it: a writer never drops a field
|
|
327
|
+
* another one owns (the launch intent, the loss notice). */
|
|
328
|
+
export function updateMachineLaunchRecord(
|
|
329
|
+
controlDir: string,
|
|
330
|
+
change: (current: MachineLaunchRecord) => MachineLaunchRecord,
|
|
331
|
+
): void {
|
|
332
|
+
writeMachineLaunchRecord(controlDir, change(readMachineLaunchRecord(controlDir)));
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** F3's launch-intent store over the task's machine-launch.json. */
|
|
336
|
+
export function fileLaunchIntentStore(controlDir: string): MachineLaunchIntentStore {
|
|
337
|
+
return {
|
|
338
|
+
read: () => readMachineLaunchRecord(controlDir).launchIntent ?? null,
|
|
339
|
+
write: (intent) => updateMachineLaunchRecord(controlDir, (current) => ({ ...current, launchIntent: { ...intent } })),
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** The pending notice as the Station delivers it. Both steps touch only the
|
|
344
|
+
* notice they were handed (by id) and throw on a failed write. */
|
|
345
|
+
export function machineLossNotice(controlDir: string, pending: PendingLossNotice): EnvironmentLossNotice {
|
|
346
|
+
const id = lossNoticeId(pending);
|
|
347
|
+
// Each step re-reads the record and touches only this notice, by id.
|
|
348
|
+
const update = (change: (notice: PendingLossNotice) => PendingLossNotice | null): void =>
|
|
349
|
+
updateMachineLaunchRecord(controlDir, (current) => {
|
|
350
|
+
const queue: PendingLossNotice[] = [];
|
|
351
|
+
for (const notice of current.pendingLossNotices ?? []) {
|
|
352
|
+
if (lossNoticeId(notice) !== id) {
|
|
353
|
+
queue.push(notice);
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
const next = change(notice);
|
|
357
|
+
if (next !== null) queue.push(next);
|
|
358
|
+
}
|
|
359
|
+
const { pendingLossNotices: _old, ...rest } = current;
|
|
360
|
+
return queue.length > 0 ? { ...rest, pendingLossNotices: queue } : rest;
|
|
361
|
+
});
|
|
362
|
+
return {
|
|
363
|
+
id,
|
|
364
|
+
attempted: pending.attempted === true,
|
|
365
|
+
lostEnvironments: pending.folded?.count ?? 1,
|
|
366
|
+
markAttempted: () => {
|
|
367
|
+
// Persist the mark first and read what the entry carries from that same
|
|
368
|
+
// write: from here on it never changes, so the text sent now is the
|
|
369
|
+
// text every retry sends.
|
|
370
|
+
let count: number | null = null;
|
|
371
|
+
update((notice) => {
|
|
372
|
+
count = notice.folded?.count ?? 1;
|
|
373
|
+
return { ...notice, attempted: true };
|
|
374
|
+
});
|
|
375
|
+
return count;
|
|
376
|
+
},
|
|
377
|
+
acknowledge: () => update(() => null),
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
export function writeMachineLaunchRecord(controlDir: string, record: MachineLaunchRecord): void {
|
|
382
|
+
const path = join(controlDir, MACHINE_LAUNCH_RECORD);
|
|
383
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
384
|
+
writeFileSync(temporary, `${JSON.stringify({ schemaVersion: 1, ...record })}\n`, { mode: 0o600 });
|
|
385
|
+
renameSync(temporary, path);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** Best-effort: never blocks resuming a machine that exists. */
|
|
389
|
+
function noteMachineSeen(controlDir: string, taskId: string, instanceId: string | undefined): void {
|
|
390
|
+
try {
|
|
391
|
+
const record = readMachineLaunchRecord(controlDir);
|
|
392
|
+
if (!record.launched || (instanceId !== undefined && record.instanceId !== instanceId)) {
|
|
393
|
+
writeMachineLaunchRecord(controlDir, {
|
|
394
|
+
...record,
|
|
395
|
+
launched: true,
|
|
396
|
+
...(instanceId !== undefined ? { instanceId } : {}),
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
} catch (error) {
|
|
400
|
+
console.warn(
|
|
401
|
+
`[machine] task ${taskId}: could not update its launch record: ${error instanceof Error ? error.message : String(error)}`,
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
123
406
|
export function machineTaskEnvironmentLocator(
|
|
124
407
|
value: MachineTaskEnvironmentLocatorValue,
|
|
125
408
|
): TaskEnvironmentLocator {
|
|
@@ -217,6 +500,16 @@ class MachineTaskEnvironmentHandle implements TaskEnvironmentHandle {
|
|
|
217
500
|
MachineTaskEnvironmentDeps;
|
|
218
501
|
/** The machine's own /etc/environment, read once (see #anchoredBaseline). */
|
|
219
502
|
#machineWide: Promise<Record<string, string>> | null = null;
|
|
503
|
+
/** Station payload validation (plan §1 item 3), enforced IN the handle so
|
|
504
|
+
* that every path to this machine runs the same rule first: provision,
|
|
505
|
+
* recovery, and any reconstructed handle's exec/spawn/session/copy/file
|
|
506
|
+
* op/gateway tunnel (all dial through #target) plus route inspection. An
|
|
507
|
+
* AWS machine still tagged `pending` is probed for the marker before
|
|
508
|
+
* anything else reaches it. A pass is remembered PER PHYSICAL INSTANCE
|
|
509
|
+
* (the EC2 instance id): a replacement under the same logical id is a
|
|
510
|
+
* different machine and the rule applies to it afresh. */
|
|
511
|
+
#validatedInstance: string | null = null;
|
|
512
|
+
#payloadProbe: { instanceId: string; done: Promise<void> } | null = null;
|
|
220
513
|
|
|
221
514
|
constructor(
|
|
222
515
|
locator: TaskEnvironmentLocator,
|
|
@@ -242,7 +535,7 @@ class MachineTaskEnvironmentHandle implements TaskEnvironmentHandle {
|
|
|
242
535
|
/** Resolve the CURRENT dial target. Cloud machines change address across
|
|
243
536
|
* stop/start, so the locator never stores one — describe is the only
|
|
244
537
|
* source of truth, and a non-running machine has no target at all. */
|
|
245
|
-
async #target(): Promise<{
|
|
538
|
+
async #target(options: { validate?: boolean } = {}): Promise<{
|
|
246
539
|
address: string;
|
|
247
540
|
keyPath: string;
|
|
248
541
|
port?: number;
|
|
@@ -253,6 +546,17 @@ class MachineTaskEnvironmentHandle implements TaskEnvironmentHandle {
|
|
|
253
546
|
`machine ${this.#value.machineId} is not reachable (${info.state})`,
|
|
254
547
|
);
|
|
255
548
|
}
|
|
549
|
+
// Only readiness checks and the probe itself dial an unvalidated machine.
|
|
550
|
+
// The gate and the dial use the SAME describe answer, so the instance
|
|
551
|
+
// validated is the instance dialed.
|
|
552
|
+
if (options.validate !== false) await this.#gate(info);
|
|
553
|
+
return this.#dialTarget(info);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
#dialTarget(info: MachineInfo): { address: string; keyPath: string; port?: number } {
|
|
557
|
+
if (info.state !== "running" || info.address === null) {
|
|
558
|
+
throw new Error(`machine ${this.#value.machineId} is not reachable (${info.state})`);
|
|
559
|
+
}
|
|
256
560
|
return {
|
|
257
561
|
address: info.address,
|
|
258
562
|
keyPath: this.#value.privateKeyPath,
|
|
@@ -260,6 +564,146 @@ class MachineTaskEnvironmentHandle implements TaskEnvironmentHandle {
|
|
|
260
564
|
};
|
|
261
565
|
}
|
|
262
566
|
|
|
567
|
+
/** Validate before use. `validation` is what the caller knows (provision:
|
|
568
|
+
* what it launched or found); otherwise the machine's own tag is read. */
|
|
569
|
+
async ensurePayloadValidated(validation?: MachineInfo["payloadValidation"]): Promise<void> {
|
|
570
|
+
const info = await this.#describeOwn();
|
|
571
|
+
await this.#gate(validation === undefined ? info : { ...info, payloadValidation: validation });
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
async #gate(info: MachineInfo): Promise<void> {
|
|
575
|
+
if (this.#deps.machines.kind !== "aws") return;
|
|
576
|
+
const instanceId = info.instanceId ?? null;
|
|
577
|
+
// A different physical instance than the one validated: forget the pass
|
|
578
|
+
// and apply the rule to this one (pending → probe; ok/null → no probe).
|
|
579
|
+
if (this.#validatedInstance !== null && this.#validatedInstance !== instanceId) {
|
|
580
|
+
this.#validatedInstance = null;
|
|
581
|
+
}
|
|
582
|
+
if (info.payloadValidation !== "pending") return;
|
|
583
|
+
if (instanceId === null) {
|
|
584
|
+
throw new PayloadValidationError(
|
|
585
|
+
`machine ${this.#value.machineId} is pending payload validation but its instance id is unknown (left pending; the next attempt probes again)`,
|
|
586
|
+
true,
|
|
587
|
+
);
|
|
588
|
+
}
|
|
589
|
+
if (this.#validatedInstance === instanceId) return;
|
|
590
|
+
// Join an in-flight probe only when it is for THIS instance: one started
|
|
591
|
+
// for a replaced instance must never stand in for its successor.
|
|
592
|
+
let probe = this.#payloadProbe;
|
|
593
|
+
if (!probe || probe.instanceId !== instanceId) {
|
|
594
|
+
const started: { instanceId: string; done: Promise<void> } = {
|
|
595
|
+
instanceId,
|
|
596
|
+
done: this.#probePayloadMarker(info, instanceId).then(() => {
|
|
597
|
+
// Remember the instance that was PROBED, nothing else.
|
|
598
|
+
this.#validatedInstance = instanceId;
|
|
599
|
+
}),
|
|
600
|
+
};
|
|
601
|
+
started.done.catch(() => {
|
|
602
|
+
// A failed probe proves nothing: the next use probes again.
|
|
603
|
+
if (this.#payloadProbe === started) this.#payloadProbe = null;
|
|
604
|
+
});
|
|
605
|
+
this.#payloadProbe = started;
|
|
606
|
+
probe = started;
|
|
607
|
+
}
|
|
608
|
+
await probe.done;
|
|
609
|
+
// A replacement raced the probe: this caller's instance is no longer
|
|
610
|
+
// the one remembered, so the caller's answer is not validated.
|
|
611
|
+
if (this.#validatedInstance !== instanceId) {
|
|
612
|
+
throw new PayloadValidationError(
|
|
613
|
+
`machine ${this.#value.machineId} changed instance during payload validation (left pending; the next attempt probes again)`,
|
|
614
|
+
true,
|
|
615
|
+
);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** One ssh round trip that bypasses the payload gate (readiness, probe).
|
|
620
|
+
* `info` pins the dial to one describe answer (the probe's instance). */
|
|
621
|
+
async #ungatedSsh(argv: readonly [string, ...string[]], timeoutMs: number, info?: MachineInfo): Promise<{ exitCode: number | null; stderr: string }> {
|
|
622
|
+
const target = info ? this.#dialTarget(info) : await this.#target({ validate: false });
|
|
623
|
+
const result = await capturedCliExec(
|
|
624
|
+
this.#deps.spawn,
|
|
625
|
+
"ssh",
|
|
626
|
+
machineEnvironmentSshArgs(target, this.#maintenanceRequest({ argv }), "interactive"),
|
|
627
|
+
{ argv: [argv[0]], projectEnvProfile: "maintenance", timeoutMs, maxOutputBytes: 4 * 1024 },
|
|
628
|
+
);
|
|
629
|
+
return { exitCode: result.exitCode, stderr: Buffer.from(result.stderr).toString("utf8").trim() };
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
/** ssh readiness without the payload gate (provision's wait). */
|
|
633
|
+
async sshReady(): Promise<{ ready: boolean; detail: string }> {
|
|
634
|
+
try {
|
|
635
|
+
const probe = await this.#ungatedSsh(["/bin/true"], 10_000);
|
|
636
|
+
return { ready: probe.exitCode === 0, detail: probe.stderr || `probe exited ${probe.exitCode ?? "killed"}` };
|
|
637
|
+
} catch (error) {
|
|
638
|
+
return { ready: false, detail: error instanceof Error ? error.message : String(error) };
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/** Marker present: record `ok` (a failed write throws, retryable; the
|
|
643
|
+
* machine stays `pending`). Marker DEFINITELY missing (exit 1): terminate,
|
|
644
|
+
* then throw (fatal); a failed terminate leaves it `pending`, so every
|
|
645
|
+
* later use probes and terminates again and nothing reaches it. Anything
|
|
646
|
+
* else (ssh error, timeout): throw, retryable, machine alive and `pending`
|
|
647
|
+
* — a slow boot is not evidence of a wrong image. */
|
|
648
|
+
async #probePayloadMarker(info: MachineInfo, instanceId: string): Promise<void> {
|
|
649
|
+
const machineId = this.#value.machineId;
|
|
650
|
+
const machines = this.#deps.machines;
|
|
651
|
+
let probe: { exitCode: number | null; stderr: string };
|
|
652
|
+
try {
|
|
653
|
+
probe = await this.#ungatedSsh(
|
|
654
|
+
["/bin/sh", "-c", 'test -f "$1"', "payload-probe", STATION_MACHINE_PAYLOAD_MARKER],
|
|
655
|
+
30_000,
|
|
656
|
+
info,
|
|
657
|
+
);
|
|
658
|
+
} catch (error) {
|
|
659
|
+
throw new PayloadValidationError(
|
|
660
|
+
`payload marker probe on ${machineId} could not run (left pending; the next attempt probes again): ${
|
|
661
|
+
error instanceof Error ? error.message : String(error)
|
|
662
|
+
}`,
|
|
663
|
+
true,
|
|
664
|
+
);
|
|
665
|
+
}
|
|
666
|
+
if (probe.exitCode === 0) {
|
|
667
|
+
if (!machines.markPayloadValidated) {
|
|
668
|
+
throw new PayloadValidationError(`machine backend ${machines.kind} cannot record payload validation`, false);
|
|
669
|
+
}
|
|
670
|
+
try {
|
|
671
|
+
await machines.markPayloadValidated(machineId, instanceId);
|
|
672
|
+
} catch (error) {
|
|
673
|
+
throw new PayloadValidationError(
|
|
674
|
+
`${error instanceof Error ? error.message : String(error)} (left pending; the next attempt probes again)`,
|
|
675
|
+
true,
|
|
676
|
+
);
|
|
677
|
+
}
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
if (probe.exitCode === 1) {
|
|
681
|
+
try {
|
|
682
|
+
// Exactly the probed instance: never the logical id, which may
|
|
683
|
+
// already name a replacement that must not be touched.
|
|
684
|
+
if (!machines.terminateInstance) {
|
|
685
|
+
throw new Error(`machine backend ${machines.kind} cannot terminate one instance`);
|
|
686
|
+
}
|
|
687
|
+
await machines.terminateInstance(machineId, instanceId);
|
|
688
|
+
} catch (error) {
|
|
689
|
+
throw new PayloadValidationError(
|
|
690
|
+
`machine ${machineId} lacks the Station payload marker ${STATION_MACHINE_PAYLOAD_MARKER} and could not be terminated (left pending; the next attempt probes and terminates again): ${
|
|
691
|
+
error instanceof Error ? error.message : String(error)
|
|
692
|
+
}`,
|
|
693
|
+
false,
|
|
694
|
+
);
|
|
695
|
+
}
|
|
696
|
+
throw new PayloadValidationError(
|
|
697
|
+
`machine ${machineId} was launched from an image without the Station payload marker ${STATION_MACHINE_PAYLOAD_MARKER}; it was terminated. Set UAI_MACHINE_IMAGE to an approved Station AMI, or ask Moondeck to check this region's image`,
|
|
698
|
+
false,
|
|
699
|
+
);
|
|
700
|
+
}
|
|
701
|
+
throw new PayloadValidationError(
|
|
702
|
+
`payload marker probe on ${machineId} did not answer (exit ${probe.exitCode ?? "killed"}${probe.stderr ? `: ${probe.stderr}` : ""}); left pending, the next attempt probes again`,
|
|
703
|
+
true,
|
|
704
|
+
);
|
|
705
|
+
}
|
|
706
|
+
|
|
263
707
|
/** Describe with the ownership check every mutation rides on: a machine
|
|
264
708
|
* that does not carry OUR task label is a foreign occupant of the id and
|
|
265
709
|
* is treated as unknown — never dialed, never stopped, never terminated. */
|
|
@@ -621,6 +1065,12 @@ class MachineTaskEnvironmentHandle implements TaskEnvironmentHandle {
|
|
|
621
1065
|
> {
|
|
622
1066
|
const info = await this.#describeOwn();
|
|
623
1067
|
if (info.state === "running" && info.address !== null) {
|
|
1068
|
+
// The editor and previews dial the machine directly: same gate.
|
|
1069
|
+
try {
|
|
1070
|
+
await this.#gate(info);
|
|
1071
|
+
} catch (error) {
|
|
1072
|
+
return { kind: "unknown", detail: error instanceof Error ? error.message : String(error) };
|
|
1073
|
+
}
|
|
624
1074
|
return { kind: "running", ipv4Address: info.address };
|
|
625
1075
|
}
|
|
626
1076
|
if (info.state === "stopped" || info.state === "absent") {
|
|
@@ -752,6 +1202,21 @@ class MachineTaskEnvironmentHandle implements TaskEnvironmentHandle {
|
|
|
752
1202
|
if (!context.isCurrent()) {
|
|
753
1203
|
return { outcome: "deferred", detail: "runtime generation superseded" };
|
|
754
1204
|
}
|
|
1205
|
+
// A Station that died between launch and probe left the machine
|
|
1206
|
+
// `pending`: probe it before any consumer is prepared or admitted. A
|
|
1207
|
+
// retryable failure defers (the machine stays pending); a missing
|
|
1208
|
+
// marker terminated it, which throws like provision does.
|
|
1209
|
+
try {
|
|
1210
|
+
await this.#gate(info);
|
|
1211
|
+
} catch (error) {
|
|
1212
|
+
if (error instanceof PayloadValidationError && error.retryable) {
|
|
1213
|
+
return { outcome: "deferred", detail: error.message };
|
|
1214
|
+
}
|
|
1215
|
+
throw error;
|
|
1216
|
+
}
|
|
1217
|
+
if (!context.isCurrent()) {
|
|
1218
|
+
return { outcome: "deferred", detail: "runtime generation superseded" };
|
|
1219
|
+
}
|
|
755
1220
|
await context.prepareConsumers?.();
|
|
756
1221
|
context.allowConsumers?.();
|
|
757
1222
|
await context.ensureConsumersStarted?.();
|
|
@@ -764,7 +1229,7 @@ class MachineTaskEnvironmentHandle implements TaskEnvironmentHandle {
|
|
|
764
1229
|
|
|
765
1230
|
async #sshAnswers(): Promise<boolean> {
|
|
766
1231
|
try {
|
|
767
|
-
const target = await this.#target();
|
|
1232
|
+
const target = await this.#target({ validate: false });
|
|
768
1233
|
const result = await capturedCliExec(
|
|
769
1234
|
this.#deps.spawn,
|
|
770
1235
|
"ssh",
|
|
@@ -863,14 +1328,74 @@ export function createMachineTaskEnvironmentProvider(
|
|
|
863
1328
|
);
|
|
864
1329
|
}
|
|
865
1330
|
const reused = existing.state !== "absent";
|
|
1331
|
+
// Validation state lives ON the machine (set at launch), so a retry
|
|
1332
|
+
// or a restarted Station sees the same answer: an unconfirmed machine
|
|
1333
|
+
// is probed whether it is fresh or reused.
|
|
1334
|
+
let payloadValidation = existing.payloadValidation ?? null;
|
|
1335
|
+
const controlDir = deps.taskControlDir(taskId);
|
|
866
1336
|
if (existing.state === "absent") {
|
|
867
|
-
|
|
1337
|
+
// Read once for what this start knows of the task's last machine.
|
|
1338
|
+
// Every write below re-reads the record (updateMachineLaunchRecord)
|
|
1339
|
+
// and changes only its own fields: a delivery may acknowledge a
|
|
1340
|
+
// notice while this start awaits a launch, and a snapshot taken
|
|
1341
|
+
// before that await must never be written back (review #4ndq0w).
|
|
1342
|
+
const record = readMachineLaunchRecord(controlDir);
|
|
1343
|
+
let generation = record.generation;
|
|
1344
|
+
const launchSpec = {
|
|
868
1345
|
taskId,
|
|
869
1346
|
image: input.image,
|
|
870
1347
|
cpus: input.cpus,
|
|
871
1348
|
memoryMiB: input.memoryMiB,
|
|
872
1349
|
authorizedPublicKey: keys.publicKey,
|
|
873
1350
|
...(input.publishSsh ? { publishSsh: true } : {}),
|
|
1351
|
+
launchIntent: fileLaunchIntentStore(deps.taskControlDir(taskId)),
|
|
1352
|
+
};
|
|
1353
|
+
let launched: MachineInfo;
|
|
1354
|
+
try {
|
|
1355
|
+
launched = await deps.machines.launch({ ...launchSpec, launchGeneration: generation });
|
|
1356
|
+
} catch (error) {
|
|
1357
|
+
if (!(error instanceof MachineLaunchTokenSpentError)) throw error;
|
|
1358
|
+
// F6: the backend proved this generation's machine terminated, so
|
|
1359
|
+
// its token can only ever answer with that machine. Persist the
|
|
1360
|
+
// next generation BEFORE launching it: a crash mid-launch retries
|
|
1361
|
+
// with the new token, never the spent one, and never mints twice.
|
|
1362
|
+
generation += 1;
|
|
1363
|
+
const loss: PendingLossNotice = { lostInstanceId: error.instanceId, generation };
|
|
1364
|
+
const nextGeneration = generation;
|
|
1365
|
+
updateMachineLaunchRecord(controlDir, (current) => {
|
|
1366
|
+
// The lost instance is no longer the task's: drop its id, so a
|
|
1367
|
+
// retry after a crash cannot prove the same loss again.
|
|
1368
|
+
const { instanceId: _lost, ...rest } = current;
|
|
1369
|
+
return { ...rest, generation: nextGeneration, launched: false, pendingLossNotices: withLossNotice(current, loss) };
|
|
1370
|
+
});
|
|
1371
|
+
console.warn(
|
|
1372
|
+
`[machine] task ${taskId}: ${error.message}; launching generation ${generation} with a new launch token`,
|
|
1373
|
+
);
|
|
1374
|
+
launched = await deps.machines.launch({ ...launchSpec, launchGeneration: generation });
|
|
1375
|
+
}
|
|
1376
|
+
// Lost only on proof: the token was spent on a terminated instance
|
|
1377
|
+
// (above), or a launch this record knows answered with a different
|
|
1378
|
+
// instance than before.
|
|
1379
|
+
const replacedInstance =
|
|
1380
|
+
record.instanceId !== undefined &&
|
|
1381
|
+
launched.instanceId !== undefined &&
|
|
1382
|
+
launched.instanceId !== record.instanceId
|
|
1383
|
+
? record.instanceId
|
|
1384
|
+
: null;
|
|
1385
|
+
const launchedGeneration = generation;
|
|
1386
|
+
updateMachineLaunchRecord(controlDir, (current) => {
|
|
1387
|
+
const { instanceId: _previous, ...rest } = current;
|
|
1388
|
+
return {
|
|
1389
|
+
// The current record: the launch intent the launch just wrote,
|
|
1390
|
+
// and the notice queue as deliveries left it.
|
|
1391
|
+
...rest,
|
|
1392
|
+
generation: launchedGeneration,
|
|
1393
|
+
launched: true,
|
|
1394
|
+
...(launched.instanceId !== undefined ? { instanceId: launched.instanceId } : {}),
|
|
1395
|
+
...(replacedInstance !== null
|
|
1396
|
+
? { pendingLossNotices: withLossNotice(current, { lostInstanceId: replacedInstance, generation: launchedGeneration }) }
|
|
1397
|
+
: {}),
|
|
1398
|
+
};
|
|
874
1399
|
});
|
|
875
1400
|
if (launched.id !== machineId) {
|
|
876
1401
|
// The backend named the machine something other than what the
|
|
@@ -881,8 +1406,12 @@ export function createMachineTaskEnvironmentProvider(
|
|
|
881
1406
|
`machine backend named ${launched.id}, locator promised ${machineId}`,
|
|
882
1407
|
);
|
|
883
1408
|
}
|
|
884
|
-
|
|
885
|
-
|
|
1409
|
+
payloadValidation = launched.payloadValidation ?? null;
|
|
1410
|
+
} else {
|
|
1411
|
+
// A machine seen for this task (one a pre-F6 Station launched has no
|
|
1412
|
+
// record yet): once it is gone, a later Resume must say so.
|
|
1413
|
+
noteMachineSeen(controlDir, taskId, existing.instanceId);
|
|
1414
|
+
if (existing.state === "stopped") await deps.machines.start(machineId);
|
|
886
1415
|
}
|
|
887
1416
|
// running/pending: fall through to the ssh-readiness proof below.
|
|
888
1417
|
|
|
@@ -893,6 +1422,13 @@ export function createMachineTaskEnvironmentProvider(
|
|
|
893
1422
|
);
|
|
894
1423
|
await waitForSsh(handle, deps.readyTimeoutMs ?? 120_000);
|
|
895
1424
|
|
|
1425
|
+
// Before ANY workspace prep, clone or credential delivery: an AWS
|
|
1426
|
+
// machine launched from an auto-selected image must carry the Station
|
|
1427
|
+
// payload marker. `ok` / null (validated before, pre-1.0.5, or pinned)
|
|
1428
|
+
// is preserved and never terminated from here. (The handle enforces
|
|
1429
|
+
// the same rule on every later dial.)
|
|
1430
|
+
await handle.ensurePayloadValidated(payloadValidation);
|
|
1431
|
+
|
|
896
1432
|
// Workspace + optional in-env clone (ADR-121: the clone happens in the
|
|
897
1433
|
// task's world; the host never materializes task code).
|
|
898
1434
|
// As root: the workspace root is typically directly under a
|
|
@@ -936,7 +1472,23 @@ export function createMachineTaskEnvironmentProvider(
|
|
|
936
1472
|
);
|
|
937
1473
|
}
|
|
938
1474
|
}
|
|
939
|
-
|
|
1475
|
+
// Reported by every start until one succeeds, a retry that found the
|
|
1476
|
+
// replacement already running included.
|
|
1477
|
+
let pending: PendingLossNotice[] = [];
|
|
1478
|
+
try {
|
|
1479
|
+
pending = readMachineLaunchRecord(controlDir).pendingLossNotices ?? [];
|
|
1480
|
+
} catch {
|
|
1481
|
+
// An unreadable record was refused above for a launch; for a reused
|
|
1482
|
+
// machine it only costs the notice.
|
|
1483
|
+
}
|
|
1484
|
+
return {
|
|
1485
|
+
handle,
|
|
1486
|
+
result: handle.descriptor,
|
|
1487
|
+
reused,
|
|
1488
|
+
...(pending.length > 0
|
|
1489
|
+
? { replacedLostEnvironment: true, lossNotices: pending.map((notice) => machineLossNotice(controlDir, notice)) }
|
|
1490
|
+
: {}),
|
|
1491
|
+
};
|
|
940
1492
|
},
|
|
941
1493
|
|
|
942
1494
|
async reconstruct(
|
|
@@ -948,6 +1500,16 @@ export function createMachineTaskEnvironmentProvider(
|
|
|
948
1500
|
};
|
|
949
1501
|
}
|
|
950
1502
|
|
|
1503
|
+
/** A payload validation failure. `retryable`: the machine is alive and
|
|
1504
|
+
* still `pending`, and a later attempt probes again. Otherwise the image is
|
|
1505
|
+
* wrong (marker missing; terminated, or termination itself failed). */
|
|
1506
|
+
export class PayloadValidationError extends Error {
|
|
1507
|
+
override name = "PayloadValidationError";
|
|
1508
|
+
constructor(message: string, readonly retryable: boolean) {
|
|
1509
|
+
super(message);
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
|
|
951
1513
|
async function waitForSsh(
|
|
952
1514
|
handle: MachineTaskEnvironmentHandle,
|
|
953
1515
|
budgetMs: number,
|
|
@@ -955,19 +1517,10 @@ async function waitForSsh(
|
|
|
955
1517
|
const deadline = Date.now() + budgetMs;
|
|
956
1518
|
let lastDetail = "ssh never answered";
|
|
957
1519
|
while (Date.now() < deadline) {
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
timeoutMs: 10_000,
|
|
963
|
-
maxOutputBytes: 4 * 1024,
|
|
964
|
-
});
|
|
965
|
-
if (probe.exitCode === 0) return;
|
|
966
|
-
lastDetail = Buffer.from(probe.stderr).toString("utf8").trim() ||
|
|
967
|
-
`probe exited ${probe.exitCode ?? "killed"}`;
|
|
968
|
-
} catch (error) {
|
|
969
|
-
lastDetail = error instanceof Error ? error.message : String(error);
|
|
970
|
-
}
|
|
1520
|
+
// Readiness only: the payload gate runs after it, not inside it.
|
|
1521
|
+
const probe = await handle.sshReady();
|
|
1522
|
+
if (probe.ready) return;
|
|
1523
|
+
lastDetail = probe.detail;
|
|
971
1524
|
await new Promise<void>((resolve) => setTimeout(resolve, 2_000));
|
|
972
1525
|
}
|
|
973
1526
|
throw new Error(`machine never became reachable over ssh: ${lastDetail}`);
|