@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
|
@@ -24,20 +24,36 @@ import { spawn } from "node:child_process";
|
|
|
24
24
|
import type { DockerResult } from "./docker-exec";
|
|
25
25
|
import { createHash } from "node:crypto";
|
|
26
26
|
|
|
27
|
-
import
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
27
|
+
import {
|
|
28
|
+
MachineLaunchTokenSpentError,
|
|
29
|
+
type MachineInfo,
|
|
30
|
+
type MachineLaunchIntent,
|
|
31
|
+
type MachineLaunchIntentStore,
|
|
32
|
+
type MachineProvider,
|
|
33
|
+
type MachineSpec,
|
|
34
|
+
type MachineState,
|
|
32
35
|
} from "./machine-provider";
|
|
36
|
+
import {
|
|
37
|
+
noApprovedImageMessage,
|
|
38
|
+
PAYLOAD_AMI_OWNER,
|
|
39
|
+
payloadImageFilters,
|
|
40
|
+
PRODUCTION_PAYLOAD_SELECTOR,
|
|
41
|
+
selectStationPayloadImage,
|
|
42
|
+
STALE_MAX_MS,
|
|
43
|
+
type PayloadImageSelector,
|
|
44
|
+
} from "./machine-payload-image";
|
|
33
45
|
|
|
34
46
|
export const AWS_MACHINE_TAG = "com.uai.machine";
|
|
47
|
+
/** Station payload validation state, carried ON the instance so it survives
|
|
48
|
+
* retries, Station restarts and moves with the machine. `pending` is set
|
|
49
|
+
* atomically in run-instances for an auto-selected image; `ok` once the
|
|
50
|
+
* payload marker was confirmed over ssh (task-environment/machine.ts). */
|
|
51
|
+
export const PAYLOAD_VALIDATION_TAG = "com.uai.payload-validation";
|
|
35
52
|
|
|
36
|
-
/** ADR-125 BYO-AWS:
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
export
|
|
40
|
-
export const PAYLOAD_AMI_NAME_PREFIX = "uai-machine-payload";
|
|
53
|
+
/** ADR-125 BYO-AWS: a host with no UAI_MACHINE_IMAGE resolves the newest
|
|
54
|
+
* APPROVED Station payload in its region; the gate is
|
|
55
|
+
* PRODUCTION_PAYLOAD_SELECTOR (machine-payload-image.ts). */
|
|
56
|
+
export { PAYLOAD_AMI_OWNER };
|
|
41
57
|
/** Regions the payload AMI is published to (build-ami.sh bakes in the first
|
|
42
58
|
* and copies to the rest). A BYO-AWS runner elsewhere would find no image
|
|
43
59
|
* and fail every launch, so setup refuses other regions up front (owner,
|
|
@@ -66,12 +82,12 @@ export interface AwsMachineConfig {
|
|
|
66
82
|
|
|
67
83
|
const DEFAULT_DISK_GIB = 50;
|
|
68
84
|
|
|
69
|
-
type Runner = (args: string[]) => Promise<DockerResult>;
|
|
85
|
+
type Runner = (args: string[], options?: { env?: Record<string, string> }) => Promise<DockerResult>;
|
|
70
86
|
|
|
71
87
|
const DEFAULT_TIMEOUT_MS = 60_000;
|
|
72
88
|
|
|
73
89
|
function defaultRunner(region: string): Runner {
|
|
74
|
-
return (args) =>
|
|
90
|
+
return (args, options = {}) =>
|
|
75
91
|
new Promise<DockerResult>((resolve) => {
|
|
76
92
|
let stdout = "";
|
|
77
93
|
let stderr = "";
|
|
@@ -79,7 +95,10 @@ function defaultRunner(region: string): Runner {
|
|
|
79
95
|
const child = spawn(
|
|
80
96
|
"aws",
|
|
81
97
|
["--region", region, "--output", "json", ...args],
|
|
82
|
-
{
|
|
98
|
+
{
|
|
99
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
100
|
+
...(options.env ? { env: { ...process.env, ...options.env } } : {}),
|
|
101
|
+
},
|
|
83
102
|
);
|
|
84
103
|
const settle = (status: number | null): void => {
|
|
85
104
|
if (settled) return;
|
|
@@ -220,8 +239,84 @@ type LiveInstance = {
|
|
|
220
239
|
state: string;
|
|
221
240
|
privateIp: string | null;
|
|
222
241
|
taskLabel: string | null;
|
|
242
|
+
payloadValidation: "pending" | "ok" | null;
|
|
223
243
|
};
|
|
224
244
|
|
|
245
|
+
interface LaunchSubnet {
|
|
246
|
+
id: string;
|
|
247
|
+
/** Its availability zone, when describe-subnets named it. */
|
|
248
|
+
az: string | null;
|
|
249
|
+
/** UAI_AWS_SUBNET_ID: never replaced by another subnet. */
|
|
250
|
+
pinned: boolean;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function azLabel(subnet: LaunchSubnet): string {
|
|
254
|
+
return subnet.az ?? subnet.id;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* EC2 error codes that reject a launch in THIS availability zone or subnet
|
|
259
|
+
* and provably launched nothing, so another AZ is safe to try (F3):
|
|
260
|
+
*
|
|
261
|
+
* - InsufficientInstanceCapacity: AWS has no On-Demand capacity for the type
|
|
262
|
+
* in the requested AZ; AWS's own advice is to try another AZ
|
|
263
|
+
* (docs.aws.amazon.com/AWSEC2/latest/UserGuide/troubleshooting-launch.html).
|
|
264
|
+
* - Unsupported, only in its instance-type/AZ form (AZ_UNSUPPORTED): the type
|
|
265
|
+
* is not offered in the requested AZ ("Please retry your request by ...
|
|
266
|
+
* choosing <other AZs>", same page). Any other Unsupported stops.
|
|
267
|
+
* - InsufficientFreeAddressesInSubnet: the subnet has no free private
|
|
268
|
+
* address (EC2 API error codes reference); another default subnet has its
|
|
269
|
+
* own range.
|
|
270
|
+
*
|
|
271
|
+
* Each launch asks for exactly one instance (--count 1, so MinCount 1), and
|
|
272
|
+
* RunInstances launches nothing when it cannot launch MinCount
|
|
273
|
+
* (RunInstances API reference). With AWS_MAX_ATTEMPTS=1 every answer is one
|
|
274
|
+
* request. So a definite rejection is no instance.
|
|
275
|
+
* Everything else (no exit status, RequestLimitExceeded, InternalError,
|
|
276
|
+
* Unavailable, an unrecognised code or message) is ambiguous and stops.
|
|
277
|
+
*/
|
|
278
|
+
/** The AZ-specific `Unsupported` answer, as EC2 words it: "Your requested
|
|
279
|
+
* instance type (m7g.xlarge) is not supported in your requested
|
|
280
|
+
* Availability Zone (us-west-2d)." */
|
|
281
|
+
const AZ_UNSUPPORTED = /instance type \([^)]+\) is not supported in your requested Availability Zone \([^)]+\)/;
|
|
282
|
+
|
|
283
|
+
const AZ_REJECTION_CODES = new Set([
|
|
284
|
+
"InsufficientInstanceCapacity",
|
|
285
|
+
"Unsupported",
|
|
286
|
+
"InsufficientFreeAddressesInSubnet",
|
|
287
|
+
]);
|
|
288
|
+
|
|
289
|
+
function definiteCapacityRejection(res: DockerResult): { code: string; message: string } | null {
|
|
290
|
+
if (res.status === null || res.status === 0) return null;
|
|
291
|
+
const match = /An error occurred \(([A-Za-z]+)\) when calling the RunInstances operation(?: \(reached max retries: (\d+)\))?: ([^\n]*)/.exec(res.stderr);
|
|
292
|
+
if (!match || !AZ_REJECTION_CODES.has(match[1]!)) return null;
|
|
293
|
+
// `Unsupported` covers many unsupported requests; only the instance-type
|
|
294
|
+
// and AZ one is about this AZ (review #mta79m).
|
|
295
|
+
if (match[1] === "Unsupported" && !AZ_UNSUPPORTED.test(match[3]!)) return null;
|
|
296
|
+
// Only a single answered request is a clean rejection. With
|
|
297
|
+
// AWS_MAX_ATTEMPTS=1, botocore's standard retry mode still marks a
|
|
298
|
+
// retryable error as max-attempts-reached on the first attempt
|
|
299
|
+
// (botocore/retries/standard.py, MaxAttemptsChecker sets
|
|
300
|
+
// MaxAttemptsReached), and ClientError then appends "(reached max
|
|
301
|
+
// retries: <RetryAttempts>)" (botocore/exceptions.py, _get_retry_info):
|
|
302
|
+
// 0 there is one attempt. A positive count means earlier attempts whose
|
|
303
|
+
// outcome is unknown: stop.
|
|
304
|
+
if (match[2] !== undefined && Number(match[2]) !== 0) return null;
|
|
305
|
+
return { code: match[1]!, message: match[3]!.trim() };
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** The one instance id a run-instances answer names; null otherwise. */
|
|
309
|
+
function runInstancesInstanceId(stdout: string): string | null {
|
|
310
|
+
try {
|
|
311
|
+
const instances = (JSON.parse(stdout) as { Instances?: unknown }).Instances;
|
|
312
|
+
if (!Array.isArray(instances) || instances.length !== 1) return null;
|
|
313
|
+
const id = (instances[0] as { InstanceId?: unknown } | null)?.InstanceId;
|
|
314
|
+
return typeof id === "string" && /^i-[0-9a-f]{8,32}$/.test(id) ? id : null;
|
|
315
|
+
} catch {
|
|
316
|
+
return null;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
225
320
|
/** Strict reservations parse. Any malformed instance voids the answer. */
|
|
226
321
|
function parseReservations(stdout: string): LiveInstance[] | null {
|
|
227
322
|
let parsed: unknown;
|
|
@@ -249,6 +344,7 @@ function parseReservations(stdout: string): LiveInstance[] | null {
|
|
|
249
344
|
const state = record.State?.Name;
|
|
250
345
|
if (typeof state !== "string") return null;
|
|
251
346
|
let taskLabel: string | null = null;
|
|
347
|
+
let payloadValidation: "pending" | "ok" | null = null;
|
|
252
348
|
if (record.Tags !== undefined) {
|
|
253
349
|
if (!Array.isArray(record.Tags)) return null;
|
|
254
350
|
for (const tag of record.Tags) {
|
|
@@ -256,6 +352,11 @@ function parseReservations(stdout: string): LiveInstance[] | null {
|
|
|
256
352
|
if (typeof tag.Value !== "string") return null;
|
|
257
353
|
taskLabel = tag.Value;
|
|
258
354
|
}
|
|
355
|
+
if (tag?.Key === PAYLOAD_VALIDATION_TAG) {
|
|
356
|
+
if (typeof tag.Value !== "string") return null;
|
|
357
|
+
// Anything but `ok` is still unvalidated: fail closed (probe).
|
|
358
|
+
payloadValidation = tag.Value === "ok" ? "ok" : "pending";
|
|
359
|
+
}
|
|
259
360
|
}
|
|
260
361
|
}
|
|
261
362
|
instances.push({
|
|
@@ -272,6 +373,7 @@ function parseReservations(stdout: string): LiveInstance[] | null {
|
|
|
272
373
|
? record.PrivateIpAddress
|
|
273
374
|
: null,
|
|
274
375
|
taskLabel,
|
|
376
|
+
payloadValidation,
|
|
275
377
|
});
|
|
276
378
|
}
|
|
277
379
|
}
|
|
@@ -323,19 +425,25 @@ async function hostEgressIp(): Promise<string> {
|
|
|
323
425
|
);
|
|
324
426
|
}
|
|
325
427
|
|
|
326
|
-
/** How long a resolved payload AMI is trusted before the newest
|
|
428
|
+
/** How long a resolved payload AMI is trusted before the newest approved
|
|
327
429
|
* image is looked up again. Long enough that a burst of launches shares one
|
|
328
|
-
* describe-images; short enough that a
|
|
329
|
-
* RUNNING host
|
|
330
|
-
* (before 0.9.106 the answer was kept for the process lifetime). */
|
|
430
|
+
* describe-images; short enough that a promotion or demotion reaches every
|
|
431
|
+
* RUNNING host on its next task without a restart. */
|
|
331
432
|
export const PAYLOAD_AMI_TTL_MS = 5 * 60_000;
|
|
332
433
|
|
|
333
434
|
export function createAwsMachineProvider(
|
|
334
435
|
config: AwsMachineConfig,
|
|
335
436
|
runner: Runner = defaultRunner(config.region),
|
|
336
|
-
deps: {
|
|
437
|
+
deps: {
|
|
438
|
+
now?: () => number;
|
|
439
|
+
/** ONLY the non-packaged canary driver passes one. Production
|
|
440
|
+
* construction (task-environment/index.ts) never does, and no env var or
|
|
441
|
+
* config reads one. */
|
|
442
|
+
selector?: PayloadImageSelector;
|
|
443
|
+
} = {},
|
|
337
444
|
): MachineProvider {
|
|
338
445
|
const now = deps.now ?? (() => Date.now());
|
|
446
|
+
const selector = deps.selector ?? PRODUCTION_PAYLOAD_SELECTOR;
|
|
339
447
|
const taskIdOf = (machineId: string): string => {
|
|
340
448
|
if (!machineId.startsWith("uai-machine-")) {
|
|
341
449
|
throw new Error(`not a uai machine id: ${machineId}`);
|
|
@@ -385,66 +493,106 @@ export function createAwsMachineProvider(
|
|
|
385
493
|
// orchestrator can never reach.
|
|
386
494
|
// -------------------------------------------------------------------------
|
|
387
495
|
|
|
388
|
-
|
|
496
|
+
// The last SUCCESSFUL lookup's answer. Only a successful lookup sets
|
|
497
|
+
// lastOkAt; a failed one never advances it.
|
|
498
|
+
let payloadMemo: {
|
|
499
|
+
id: string;
|
|
500
|
+
name: string;
|
|
501
|
+
lastOkAt: number;
|
|
502
|
+
deprecationTime: number | null;
|
|
503
|
+
} | null = null;
|
|
504
|
+
/** Guards applied before EVERY cached return (the TTL fast path and the
|
|
505
|
+
* failed-lookup fallback alike): at most STALE_MAX_MS after the last
|
|
506
|
+
* successful lookup, and never at or past the image's deprecation time. */
|
|
507
|
+
const memoReturnable = (at: number): boolean =>
|
|
508
|
+
payloadMemo !== null &&
|
|
509
|
+
at < payloadMemo.lastOkAt + STALE_MAX_MS &&
|
|
510
|
+
(payloadMemo.deprecationTime === null || at < payloadMemo.deprecationTime);
|
|
511
|
+
|
|
389
512
|
async function resolveImage(specImage: string): Promise<string> {
|
|
513
|
+
// An explicit AMI (UAI_MACHINE_IMAGE=ami-…) bypasses the lookup.
|
|
390
514
|
if (specImage.startsWith("ami-")) return specImage;
|
|
391
|
-
|
|
392
|
-
|
|
515
|
+
const started = now();
|
|
516
|
+
if (payloadMemo && started - payloadMemo.lastOkAt < PAYLOAD_AMI_TTL_MS && memoReturnable(started)) {
|
|
517
|
+
return payloadMemo.id;
|
|
393
518
|
}
|
|
394
519
|
const res = await runner([
|
|
395
520
|
"ec2",
|
|
396
521
|
"describe-images",
|
|
397
522
|
"--owners",
|
|
398
|
-
|
|
523
|
+
selector.owner,
|
|
399
524
|
"--filters",
|
|
400
|
-
|
|
401
|
-
"Name=state,Values=available",
|
|
525
|
+
...payloadImageFilters(selector),
|
|
402
526
|
"--query",
|
|
403
|
-
"
|
|
527
|
+
"Images[].{ImageId: ImageId, Name: Name, CreationDate: CreationDate, OwnerId: OwnerId, " +
|
|
528
|
+
"Architecture: Architecture, State: State, Public: Public, DeprecationTime: DeprecationTime, Tags: Tags}",
|
|
404
529
|
]);
|
|
405
|
-
let
|
|
530
|
+
let images: unknown = null;
|
|
406
531
|
if (res.status === 0) {
|
|
407
532
|
try {
|
|
408
|
-
|
|
533
|
+
images = JSON.parse(res.stdout);
|
|
409
534
|
} catch {
|
|
410
|
-
|
|
535
|
+
images = null;
|
|
411
536
|
}
|
|
412
537
|
}
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
//
|
|
416
|
-
|
|
538
|
+
const at = now();
|
|
539
|
+
if (!Array.isArray(images)) {
|
|
540
|
+
// A failed lookup proves nothing: keep launching the last approved
|
|
541
|
+
// image only while its guards hold, otherwise fail closed.
|
|
542
|
+
if (payloadMemo && memoReturnable(at)) {
|
|
543
|
+
console.warn(
|
|
544
|
+
`[machine-aws] payload image lookup failed in ${config.region}; keeping ${payloadMemo.id} ` +
|
|
545
|
+
`(last confirmed ${Math.round((at - payloadMemo.lastOkAt) / 1000)}s ago)`,
|
|
546
|
+
);
|
|
547
|
+
return payloadMemo.id;
|
|
548
|
+
}
|
|
417
549
|
throw new Error(
|
|
418
|
-
`
|
|
419
|
-
|
|
550
|
+
`could not look up the Moondeck Station machine image in ${config.region}: ${
|
|
551
|
+
res.stderr.trim() || `exit ${res.status ?? "killed"}`
|
|
552
|
+
} — set UAI_MACHINE_IMAGE to an AMI id to launch without the lookup`,
|
|
420
553
|
);
|
|
421
554
|
}
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
//
|
|
425
|
-
|
|
555
|
+
const { selected, rejected } = selectStationPayloadImage(images, selector, at);
|
|
556
|
+
if (!selected) {
|
|
557
|
+
// A successful empty answer is authoritative: forget the cached image.
|
|
558
|
+
payloadMemo = null;
|
|
559
|
+
if (rejected.length > 0) {
|
|
560
|
+
console.warn(
|
|
561
|
+
`[machine-aws] payload images rejected in ${config.region}: ${rejected
|
|
562
|
+
.map((r) => `${r.id} (${r.reason})`)
|
|
563
|
+
.join(", ")}`,
|
|
564
|
+
);
|
|
565
|
+
}
|
|
566
|
+
throw new Error(noApprovedImageMessage(selector, config.region));
|
|
567
|
+
}
|
|
568
|
+
if (payloadMemo?.id !== selected.id) {
|
|
569
|
+
// The journal line that tells an operator which payload a task got.
|
|
426
570
|
console.log(
|
|
427
|
-
`[machine-aws] payload image for ${config.region}: ${
|
|
428
|
-
(
|
|
571
|
+
`[machine-aws] payload image for ${config.region}: ${selected.id} (${selected.name})` +
|
|
572
|
+
(payloadMemo ? ` (was ${payloadMemo.id})` : ""),
|
|
429
573
|
);
|
|
430
574
|
}
|
|
431
|
-
|
|
432
|
-
return
|
|
575
|
+
payloadMemo = { ...selected, lastOkAt: at };
|
|
576
|
+
return selected.id;
|
|
433
577
|
}
|
|
434
578
|
|
|
435
|
-
let
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
579
|
+
let resolvedSubnets: LaunchSubnet[] | null = null;
|
|
580
|
+
/** Where a launch may go, in order. An explicit UAI_AWS_SUBNET_ID is the
|
|
581
|
+
* only candidate and is never overridden. Otherwise every default-VPC
|
|
582
|
+
* subnet (one per AZ, sorted by AZ), the public ones only when any is
|
|
583
|
+
* public: the Station dials the machine's public address. */
|
|
584
|
+
async function resolveSubnets(): Promise<LaunchSubnet[]> {
|
|
585
|
+
if (config.subnetId) return [{ id: config.subnetId, az: null, pinned: true }];
|
|
586
|
+
if (resolvedSubnets) return resolvedSubnets;
|
|
439
587
|
const res = await runner([
|
|
440
588
|
"ec2",
|
|
441
589
|
"describe-subnets",
|
|
442
590
|
"--filters",
|
|
443
591
|
"Name=default-for-az,Values=true",
|
|
444
592
|
"--query",
|
|
445
|
-
"sort_by(Subnets, &AvailabilityZone)[].{id: SubnetId, public: MapPublicIpOnLaunch, vpc: VpcId}",
|
|
593
|
+
"sort_by(Subnets, &AvailabilityZone)[].{id: SubnetId, public: MapPublicIpOnLaunch, vpc: VpcId, az: AvailabilityZone}",
|
|
446
594
|
]);
|
|
447
|
-
let subnets: Array<{ id?: unknown; public?: unknown }> = [];
|
|
595
|
+
let subnets: Array<{ id?: unknown; public?: unknown; az?: unknown }> = [];
|
|
448
596
|
if (res.status === 0) {
|
|
449
597
|
try {
|
|
450
598
|
const parsed = JSON.parse(res.stdout);
|
|
@@ -453,19 +601,32 @@ export function createAwsMachineProvider(
|
|
|
453
601
|
subnets = [];
|
|
454
602
|
}
|
|
455
603
|
}
|
|
456
|
-
const
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
if (
|
|
604
|
+
const named = subnets.filter((s): s is { id: string; public?: unknown; az?: unknown } => typeof s.id === "string");
|
|
605
|
+
const publicOnes = named.filter((s) => s.public === true);
|
|
606
|
+
const eligible = publicOnes.length > 0 ? publicOnes : named;
|
|
607
|
+
if (eligible.length === 0) {
|
|
460
608
|
throw new Error(
|
|
461
609
|
`no default-VPC subnet found in ${config.region} — set ` +
|
|
462
610
|
"UAI_AWS_SUBNET_ID to a public subnet",
|
|
463
611
|
);
|
|
464
612
|
}
|
|
465
|
-
|
|
466
|
-
|
|
613
|
+
resolvedSubnets = eligible.map((s) => ({
|
|
614
|
+
id: s.id,
|
|
615
|
+
az: typeof s.az === "string" ? s.az : null,
|
|
616
|
+
pinned: false,
|
|
617
|
+
}));
|
|
618
|
+
return resolvedSubnets;
|
|
467
619
|
}
|
|
468
620
|
|
|
621
|
+
/** Launch intents for callers that bring no durable store (tests, the
|
|
622
|
+
* smoke scripts): per task, in-process only. */
|
|
623
|
+
const memoryIntents = new Map<string, MachineLaunchIntent>();
|
|
624
|
+
const intentStoreFor = (spec: MachineSpec): MachineLaunchIntentStore =>
|
|
625
|
+
spec.launchIntent ?? {
|
|
626
|
+
read: () => memoryIntents.get(spec.taskId) ?? null,
|
|
627
|
+
write: (intent) => void memoryIntents.set(spec.taskId, intent),
|
|
628
|
+
};
|
|
629
|
+
|
|
469
630
|
let resolvedSecurityGroup: string | null = null;
|
|
470
631
|
async function resolveSecurityGroup(subnetId: string): Promise<string> {
|
|
471
632
|
if (config.securityGroupId) return config.securityGroupId;
|
|
@@ -647,6 +808,8 @@ export function createAwsMachineProvider(
|
|
|
647
808
|
return {
|
|
648
809
|
id: machineId,
|
|
649
810
|
taskLabel: instance.taskLabel,
|
|
811
|
+
payloadValidation: instance.payloadValidation,
|
|
812
|
+
instanceId: instance.instanceId,
|
|
650
813
|
state,
|
|
651
814
|
// Still stopping: its processes run until the instance is stopped.
|
|
652
815
|
...(instance.state === "stopping" ? { frozen: true as const } : {}),
|
|
@@ -674,71 +837,162 @@ export function createAwsMachineProvider(
|
|
|
674
837
|
// volume while the root stays small — so resolve it per image.
|
|
675
838
|
const diskGiB = config.diskGiB ?? DEFAULT_DISK_GIB;
|
|
676
839
|
// ADR-125 BYO-AWS: explicit config wins; otherwise resolve the newest
|
|
677
|
-
//
|
|
840
|
+
// approved payload AMI and the default-VPC network per process.
|
|
841
|
+
// Only an auto-selected image is subject to the payload-marker probe.
|
|
842
|
+
const autoSelected = !spec.image.startsWith("ami-");
|
|
678
843
|
const image = await resolveImage(spec.image);
|
|
679
|
-
const
|
|
680
|
-
|
|
844
|
+
const subnets = await resolveSubnets();
|
|
845
|
+
// Default-VPC subnets share the default VPC, so one group serves all.
|
|
846
|
+
const securityGroupId = await resolveSecurityGroup(subnets[0]!.id);
|
|
681
847
|
const rootDevice = await rootDeviceName(image);
|
|
682
|
-
//
|
|
683
|
-
|
|
684
|
-
|
|
848
|
+
// F3 (review #mta79m): the persisted intent's subnet goes first, an
|
|
849
|
+
// attempt whose outcome is unknown included. Its token replays: a
|
|
850
|
+
// machine it made comes back (no second one in another AZ, whatever the
|
|
851
|
+
// tag query shows), and only a definite rejection there moves on. A
|
|
852
|
+
// launched intent also makes the AZ that worked the task's first choice.
|
|
853
|
+
const intents = intentStoreFor(spec);
|
|
854
|
+
const intent = intents.read();
|
|
855
|
+
const remembered: LaunchSubnet | null =
|
|
856
|
+
intent === null || subnets[0]!.pinned
|
|
857
|
+
? null
|
|
858
|
+
: subnets.find((s) => s.id === intent.subnetId) ?? { id: intent.subnetId, az: null, pinned: false };
|
|
859
|
+
const order = remembered === null
|
|
860
|
+
? subnets
|
|
861
|
+
: [remembered, ...subnets.filter((s) => s.id !== remembered.id)];
|
|
862
|
+
// F3: one attempt per subnet, moving on ONLY after a definite
|
|
863
|
+
// per-AZ rejection that launched nothing. Each subnet's token differs
|
|
864
|
+
// (the subnet is in the fingerprint), and is the same on every retry of
|
|
865
|
+
// that subnet, so a later attempt there replays rather than doubles.
|
|
866
|
+
const rejected: Array<{ subnet: LaunchSubnet; code: string; message: string }> = [];
|
|
867
|
+
let launchedIn: LaunchSubnet | null = null;
|
|
868
|
+
for (const subnet of order) {
|
|
869
|
+
const subnetId = subnet.id;
|
|
870
|
+
// a live machine.
|
|
871
|
+
const launchFingerprint = createHash("sha256")
|
|
872
|
+
.update(
|
|
873
|
+
JSON.stringify([
|
|
874
|
+
image,
|
|
875
|
+
type,
|
|
876
|
+
spec.authorizedPublicKey ?? null,
|
|
877
|
+
subnetId,
|
|
878
|
+
securityGroupId,
|
|
879
|
+
config.iamInstanceProfileArn ?? null,
|
|
880
|
+
diskGiB,
|
|
881
|
+
// The tag spec depends on the validation mode (an auto-selected
|
|
882
|
+
// image gets the `pending` tag, a pinned one none), so the mode
|
|
883
|
+
// is part of the token: the same AMI pinned and auto-selected
|
|
884
|
+
// must never share one (IdempotentParameterMismatch). The "v1"
|
|
885
|
+
// also keeps the tokens of 1.0.4 and earlier from meeting the new tag spec.
|
|
886
|
+
// describe-first above still prevents a double launch.
|
|
887
|
+
["payload-validation-v1", autoSelected ? "pending" : null],
|
|
888
|
+
// F6: the task's Nth machine after N-1 proven terminations,
|
|
889
|
+
// appended only when N > 0, so generation 0 keeps exactly the
|
|
890
|
+
// 1.0.5 token (payload-validation-v1 included).
|
|
891
|
+
...((spec.launchGeneration ?? 0) > 0
|
|
892
|
+
? [["launch-generation", spec.launchGeneration]]
|
|
893
|
+
: []),
|
|
894
|
+
]),
|
|
895
|
+
)
|
|
896
|
+
.digest("hex")
|
|
897
|
+
.slice(0, 16);
|
|
898
|
+
const args = [
|
|
899
|
+
"ec2",
|
|
900
|
+
"run-instances",
|
|
901
|
+
"--image-id",
|
|
902
|
+
image,
|
|
903
|
+
"--instance-type",
|
|
904
|
+
type,
|
|
905
|
+
"--count",
|
|
906
|
+
"1",
|
|
907
|
+
// Idempotency across crashed/retried provisions: the same token can
|
|
908
|
+
// never mint a second instance.
|
|
909
|
+
"--client-token",
|
|
910
|
+
`${machineId}-${launchFingerprint}`.slice(0, 64),
|
|
911
|
+
"--tag-specifications",
|
|
912
|
+
`ResourceType=instance,Tags=[{Key=${AWS_MACHINE_TAG},Value=${spec.taskId}},{Key=Name,Value=${machineId}}${
|
|
913
|
+
autoSelected ? `,{Key=${PAYLOAD_VALIDATION_TAG},Value=pending}` : ""
|
|
914
|
+
}]`,
|
|
915
|
+
"--block-device-mappings",
|
|
685
916
|
JSON.stringify([
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
]),
|
|
694
|
-
)
|
|
695
|
-
.digest("hex")
|
|
696
|
-
.slice(0, 16);
|
|
697
|
-
const args = [
|
|
698
|
-
"ec2",
|
|
699
|
-
"run-instances",
|
|
700
|
-
"--image-id",
|
|
701
|
-
image,
|
|
702
|
-
"--instance-type",
|
|
703
|
-
type,
|
|
704
|
-
"--count",
|
|
705
|
-
"1",
|
|
706
|
-
// Idempotency across crashed/retried provisions: the same token can
|
|
707
|
-
// never mint a second instance.
|
|
708
|
-
"--client-token",
|
|
709
|
-
`${machineId}-${launchFingerprint}`.slice(0, 64),
|
|
710
|
-
"--tag-specifications",
|
|
711
|
-
`ResourceType=instance,Tags=[{Key=${AWS_MACHINE_TAG},Value=${spec.taskId}},{Key=Name,Value=${machineId}}]`,
|
|
712
|
-
"--block-device-mappings",
|
|
713
|
-
JSON.stringify([
|
|
714
|
-
{
|
|
715
|
-
DeviceName: rootDevice,
|
|
716
|
-
Ebs: {
|
|
717
|
-
VolumeSize: diskGiB,
|
|
718
|
-
VolumeType: "gp3",
|
|
719
|
-
DeleteOnTermination: true,
|
|
917
|
+
{
|
|
918
|
+
DeviceName: rootDevice,
|
|
919
|
+
Ebs: {
|
|
920
|
+
VolumeSize: diskGiB,
|
|
921
|
+
VolumeType: "gp3",
|
|
922
|
+
DeleteOnTermination: true,
|
|
923
|
+
},
|
|
720
924
|
},
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
925
|
+
]),
|
|
926
|
+
...(spec.authorizedPublicKey
|
|
927
|
+
? ["--user-data", awsUserData(spec.authorizedPublicKey)]
|
|
928
|
+
: []),
|
|
929
|
+
"--subnet-id",
|
|
930
|
+
subnetId,
|
|
931
|
+
"--security-group-ids",
|
|
932
|
+
securityGroupId,
|
|
933
|
+
...(config.iamInstanceProfileArn
|
|
934
|
+
? ["--iam-instance-profile", `Arn=${config.iamInstanceProfileArn}`]
|
|
935
|
+
: []),
|
|
936
|
+
];
|
|
937
|
+
// Durable BEFORE the request: a crash or an unknown answer from here
|
|
938
|
+
// on leaves this subnet to be replayed first. A failed write launches
|
|
939
|
+
// nothing.
|
|
940
|
+
intents.write({ subnetId, state: "attempting" });
|
|
941
|
+
// One attempt per answer (review #mta79m): the CLI's own retries
|
|
942
|
+
// could hide an earlier attempt's unknown outcome behind a final
|
|
943
|
+
// capacity error. AWS_MAX_ATTEMPTS counts the initial call, so 1
|
|
944
|
+
// disables retries; the environment overrides the config file
|
|
945
|
+
// (AWS CLI "AWS CLI retries" and environment-variable docs).
|
|
946
|
+
const res = await runner(args, { env: { AWS_MAX_ATTEMPTS: "1" } });
|
|
947
|
+
if (res.status === 0) {
|
|
948
|
+
// F6 (test 6.3): a repeated client token is answered with the
|
|
949
|
+
// instance it first launched, even once that instance is terminated
|
|
950
|
+
// (its root volume deleted with it). The tag query below never lists
|
|
951
|
+
// a terminated instance, so look the answered instance up by id: only
|
|
952
|
+
// a definite terminated / shutting-down answer is proof the token is
|
|
953
|
+
// spent. A brand-new id that is not yet visible proves nothing.
|
|
954
|
+
const answeredId = runInstancesInstanceId(res.stdout);
|
|
955
|
+
if (answeredId !== null) {
|
|
956
|
+
const byId = await runner([
|
|
957
|
+
"ec2",
|
|
958
|
+
"describe-instances",
|
|
959
|
+
"--instance-ids",
|
|
960
|
+
answeredId,
|
|
961
|
+
]);
|
|
962
|
+
const answered = byId.status === 0 ? parseReservations(byId.stdout) : null;
|
|
963
|
+
const gone = answered?.length === 1 &&
|
|
964
|
+
answered[0]!.instanceId === answeredId &&
|
|
965
|
+
(answered[0]!.state === "terminated" || answered[0]!.state === "shutting-down");
|
|
966
|
+
if (gone) {
|
|
967
|
+
throw new MachineLaunchTokenSpentError(machineId, answeredId, answered[0]!.state);
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
launchedIn = subnet;
|
|
971
|
+
break;
|
|
972
|
+
}
|
|
973
|
+
const rejection = subnet.pinned ? null : definiteCapacityRejection(res);
|
|
974
|
+
if (rejection === null) {
|
|
975
|
+
// Ambiguous (a timeout, throttling, a 5xx, anything unrecognised) or
|
|
976
|
+
// a pinned subnet: no other AZ, since this attempt may have launched.
|
|
977
|
+
throw new Error(
|
|
978
|
+
`machine launch failed for ${machineId}${
|
|
979
|
+
rejected.length > 0 ? ` (after no capacity in ${rejected.map((r) => azLabel(r.subnet)).join(", ")})` : ""
|
|
980
|
+
}: ${res.stderr.trim() || `exit ${res.status ?? "killed"}`}`,
|
|
981
|
+
);
|
|
982
|
+
}
|
|
983
|
+
rejected.push({ subnet, ...rejection });
|
|
984
|
+
console.warn(
|
|
985
|
+
`[machine-aws] ${machineId}: ${rejection.code} in ${azLabel(subnet)}; trying the next availability zone`,
|
|
986
|
+
);
|
|
987
|
+
}
|
|
988
|
+
if (launchedIn === null) {
|
|
736
989
|
throw new Error(
|
|
737
|
-
`machine launch failed for ${machineId}: ${
|
|
738
|
-
|
|
739
|
-
|
|
990
|
+
`machine launch failed for ${machineId}: no ${type} capacity in ${config.region} ` +
|
|
991
|
+
`(${rejected.map((r) => `${azLabel(r.subnet)}: ${r.code}`).join("; ")}). ` +
|
|
992
|
+
"Try again later, choose another instance type, or launch the host in another region.",
|
|
740
993
|
);
|
|
741
994
|
}
|
|
995
|
+
intents.write({ subnetId: launchedIn.id, state: "launched" });
|
|
742
996
|
// DescribeInstances TAG FILTERS are eventually consistent: the query
|
|
743
997
|
// can miss an instance RunInstances just created (live 2026-08-28 —
|
|
744
998
|
// the machine was running the whole time while launch reported
|
|
@@ -760,7 +1014,67 @@ export function createAwsMachineProvider(
|
|
|
760
1014
|
})`,
|
|
761
1015
|
);
|
|
762
1016
|
}
|
|
763
|
-
|
|
1017
|
+
// What was launched decides the probe, not a possibly stale describe.
|
|
1018
|
+
return { ...info, payloadValidation: autoSelected ? "pending" : null };
|
|
1019
|
+
},
|
|
1020
|
+
|
|
1021
|
+
async terminateInstance(machineId: string, instanceId: string): Promise<void> {
|
|
1022
|
+
if (!/^i-[0-9a-f]+$/.test(instanceId)) {
|
|
1023
|
+
throw new Error(`machine ${machineId}: refusing to terminate bad instance id ${instanceId}`);
|
|
1024
|
+
}
|
|
1025
|
+
const res = await runner(["ec2", "terminate-instances", "--instance-ids", instanceId]);
|
|
1026
|
+
if (res.status !== 0) {
|
|
1027
|
+
throw new Error(
|
|
1028
|
+
`machine terminate failed for ${machineId} (${instanceId}): ${
|
|
1029
|
+
res.stderr.trim() || `exit ${res.status ?? "killed"}`
|
|
1030
|
+
}`,
|
|
1031
|
+
);
|
|
1032
|
+
}
|
|
1033
|
+
// Proven by THIS instance id, never by the tag (which may now name a
|
|
1034
|
+
// replacement): shutting-down/terminated, or EC2's exact not-found.
|
|
1035
|
+
const deadline = Date.now() + 120_000;
|
|
1036
|
+
for (;;) {
|
|
1037
|
+
const raw = await runner([
|
|
1038
|
+
"ec2",
|
|
1039
|
+
"describe-instances",
|
|
1040
|
+
"--instance-ids",
|
|
1041
|
+
instanceId,
|
|
1042
|
+
"--query",
|
|
1043
|
+
"Reservations[].Instances[].State.Name",
|
|
1044
|
+
"--output",
|
|
1045
|
+
"text",
|
|
1046
|
+
]);
|
|
1047
|
+
const state = raw.status === 0 ? raw.stdout.trim() : "";
|
|
1048
|
+
if (state === "shutting-down" || state === "terminated") return;
|
|
1049
|
+
if (raw.status !== 0 && /InvalidInstanceID\.NotFound/.test(raw.stderr)) return;
|
|
1050
|
+
if (Date.now() >= deadline) {
|
|
1051
|
+
throw new Error(`instance ${instanceId} of ${machineId} could not be proven terminated (${state || "unknown"})`);
|
|
1052
|
+
}
|
|
1053
|
+
await new Promise<void>((resolve) => setTimeout(resolve, 5_000));
|
|
1054
|
+
}
|
|
1055
|
+
},
|
|
1056
|
+
|
|
1057
|
+
async markPayloadValidated(machineId: string, instanceId: string): Promise<void> {
|
|
1058
|
+
if (!/^i-[0-9a-f]+$/.test(instanceId)) {
|
|
1059
|
+
throw new Error(`could not record payload validation on ${machineId}: bad instance id ${instanceId}`);
|
|
1060
|
+
}
|
|
1061
|
+
// The probed instance itself — never re-resolved by tag, so a
|
|
1062
|
+
// replacement under the same logical id can never inherit `ok`.
|
|
1063
|
+
const res = await runner([
|
|
1064
|
+
"ec2",
|
|
1065
|
+
"create-tags",
|
|
1066
|
+
"--resources",
|
|
1067
|
+
instanceId,
|
|
1068
|
+
"--tags",
|
|
1069
|
+
`Key=${PAYLOAD_VALIDATION_TAG},Value=ok`,
|
|
1070
|
+
]);
|
|
1071
|
+
if (res.status !== 0) {
|
|
1072
|
+
throw new Error(
|
|
1073
|
+
`could not record payload validation on ${machineId}: ${
|
|
1074
|
+
res.stderr.trim() || `exit ${res.status ?? "killed"}`
|
|
1075
|
+
}`,
|
|
1076
|
+
);
|
|
1077
|
+
}
|
|
764
1078
|
},
|
|
765
1079
|
|
|
766
1080
|
async stop(machineId: string): Promise<void> {
|
|
@@ -900,6 +1214,8 @@ export function createAwsMachineProvider(
|
|
|
900
1214
|
? awsMachineName(instance.taskLabel)
|
|
901
1215
|
: instance.instanceId,
|
|
902
1216
|
taskLabel: instance.taskLabel,
|
|
1217
|
+
payloadValidation: instance.payloadValidation,
|
|
1218
|
+
instanceId: instance.instanceId,
|
|
903
1219
|
state,
|
|
904
1220
|
...(instance.state === "stopping" ? { frozen: true as const } : {}),
|
|
905
1221
|
address: state === "running" ? instance.privateIp : null,
|