@runuai/host 0.9.68 → 0.9.70

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.
@@ -0,0 +1,437 @@
1
+ /**
2
+ * ADR-121: the `aws` MachineProvider — task machines as EC2 instances.
3
+ *
4
+ * Shell-out to the `aws` CLI with strict JSON parsing, matching every other
5
+ * backend integration (docker, container, ssh): no SDK dependency rides the
6
+ * OTA channel, and tests inject the runner.
7
+ *
8
+ * Identity model: EC2 invents instance ids, but the environment layer's
9
+ * locator-first invariant needs a DERIVED id. The machine id is therefore
10
+ * the logical `uai-machine-<taskId>`; the provider resolves it internally
11
+ * through the `com.uai.machine` tag on every call, and `--client-token`
12
+ * makes launch idempotent so a crashed provision retried cannot mint a
13
+ * second instance. Two live instances carrying one machine's tag is a
14
+ * confusing answer and maps to `unknown` — never to either instance.
15
+ *
16
+ * Absence: a SUCCESSFUL tag query with zero non-terminated matches proves
17
+ * absence (the filter asked AWS directly and AWS answered "none");
18
+ * `terminated` counts as absent — the id is unreachable and its disk is
19
+ * gone. A failed query proves nothing.
20
+ */
21
+
22
+ import { spawn } from "node:child_process";
23
+
24
+ import type { DockerResult } from "./docker-exec";
25
+ import type {
26
+ MachineInfo,
27
+ MachineProvider,
28
+ MachineSpec,
29
+ MachineState,
30
+ } from "./machine-provider";
31
+
32
+ export const AWS_MACHINE_TAG = "com.uai.machine";
33
+
34
+ export interface AwsMachineConfig {
35
+ region: string;
36
+ /** AMI id used when the spec's image is not already an ami-*. */
37
+ subnetId?: string;
38
+ securityGroupId?: string;
39
+ iamInstanceProfileArn?: string;
40
+ /** Override the size ladder; the default picks the smallest Graviton
41
+ * type satisfying both cpu and memory. */
42
+ instanceType?: (spec: MachineSpec) => string;
43
+ }
44
+
45
+ type Runner = (args: string[]) => Promise<DockerResult>;
46
+
47
+ const DEFAULT_TIMEOUT_MS = 60_000;
48
+
49
+ function defaultRunner(region: string): Runner {
50
+ return (args) =>
51
+ new Promise<DockerResult>((resolve) => {
52
+ let stdout = "";
53
+ let stderr = "";
54
+ let settled = false;
55
+ const child = spawn(
56
+ "aws",
57
+ ["--region", region, "--output", "json", ...args],
58
+ { stdio: ["ignore", "pipe", "pipe"] },
59
+ );
60
+ const settle = (status: number | null): void => {
61
+ if (settled) return;
62
+ settled = true;
63
+ clearTimeout(timer);
64
+ resolve({ status, stdout, stderr });
65
+ };
66
+ const timer = setTimeout(() => {
67
+ child.kill("SIGKILL");
68
+ const grace = setTimeout(() => settle(null), 2_000);
69
+ grace.unref?.();
70
+ }, DEFAULT_TIMEOUT_MS);
71
+ timer.unref?.();
72
+ child.stdout.setEncoding("utf8");
73
+ child.stderr.setEncoding("utf8");
74
+ child.stdout.on("data", (chunk: string) => (stdout += chunk));
75
+ child.stderr.on("data", (chunk: string) => (stderr += chunk));
76
+ child.once("error", () => settle(null));
77
+ child.once("close", (code) => settle(code));
78
+ });
79
+ }
80
+
81
+ export function awsMachineName(taskId: string): string {
82
+ return `uai-machine-${taskId.toLowerCase()}`;
83
+ }
84
+
85
+ /** Smallest Graviton type satisfying both dimensions. */
86
+ export function defaultInstanceType(spec: MachineSpec): string {
87
+ const ladder: Array<[string, number, number]> = [
88
+ ["m7g.medium", 1, 4096],
89
+ ["m7g.large", 2, 8192],
90
+ ["m7g.xlarge", 4, 16384],
91
+ ["m7g.2xlarge", 8, 32768],
92
+ ["m7g.4xlarge", 16, 65536],
93
+ ];
94
+ for (const [type, cpus, memoryMiB] of ladder) {
95
+ if (spec.cpus <= cpus && spec.memoryMiB <= memoryMiB) return type;
96
+ }
97
+ return "m7g.4xlarge";
98
+ }
99
+
100
+ /** cloud-init: install the orchestrator key for node (and root for the
101
+ * provisioning path), creating the node user when the AMI lacks it. */
102
+ export function awsUserData(authorizedPublicKey: string): string {
103
+ const script = [
104
+ "#!/bin/sh",
105
+ "set -e",
106
+ "id node >/dev/null 2>&1 || useradd -m -u 1000 -s /bin/bash node",
107
+ "for account in node root; do",
108
+ ' home=$(getent passwd "$account" | cut -d: -f6)',
109
+ ' mkdir -p "$home/.ssh"',
110
+ ` printf '%s\\n' '${authorizedPublicKey.replace(/'/g, "")}' > "$home/.ssh/authorized_keys"`,
111
+ ' chown -R "$account" "$home/.ssh"',
112
+ ' chmod 700 "$home/.ssh"',
113
+ ' chmod 600 "$home/.ssh/authorized_keys"',
114
+ "done",
115
+ "",
116
+ ].join("\n");
117
+ return Buffer.from(script, "utf8").toString("base64");
118
+ }
119
+
120
+ type LiveInstance = {
121
+ instanceId: string;
122
+ state: string;
123
+ privateIp: string | null;
124
+ taskLabel: string | null;
125
+ };
126
+
127
+ /** Strict reservations parse. Any malformed instance voids the answer. */
128
+ function parseReservations(stdout: string): LiveInstance[] | null {
129
+ let parsed: unknown;
130
+ try {
131
+ parsed = JSON.parse(stdout);
132
+ } catch {
133
+ return null;
134
+ }
135
+ const reservations = (parsed as { Reservations?: unknown }).Reservations;
136
+ if (!Array.isArray(reservations)) return null;
137
+ const instances: LiveInstance[] = [];
138
+ for (const reservation of reservations) {
139
+ const list = (reservation as { Instances?: unknown }).Instances;
140
+ if (!Array.isArray(list)) return null;
141
+ for (const instance of list) {
142
+ if (typeof instance !== "object" || instance === null) return null;
143
+ const record = instance as {
144
+ InstanceId?: unknown;
145
+ State?: { Name?: unknown };
146
+ PrivateIpAddress?: unknown;
147
+ Tags?: Array<{ Key?: unknown; Value?: unknown }>;
148
+ };
149
+ if (typeof record.InstanceId !== "string") return null;
150
+ const state = record.State?.Name;
151
+ if (typeof state !== "string") return null;
152
+ let taskLabel: string | null = null;
153
+ if (record.Tags !== undefined) {
154
+ if (!Array.isArray(record.Tags)) return null;
155
+ for (const tag of record.Tags) {
156
+ if (tag?.Key === AWS_MACHINE_TAG) {
157
+ if (typeof tag.Value !== "string") return null;
158
+ taskLabel = tag.Value;
159
+ }
160
+ }
161
+ }
162
+ instances.push({
163
+ instanceId: record.InstanceId,
164
+ state,
165
+ privateIp:
166
+ typeof record.PrivateIpAddress === "string"
167
+ ? record.PrivateIpAddress
168
+ : null,
169
+ taskLabel,
170
+ });
171
+ }
172
+ }
173
+ return instances;
174
+ }
175
+
176
+ function stateFromAws(state: string): MachineState {
177
+ switch (state) {
178
+ case "running":
179
+ return "running";
180
+ case "pending":
181
+ return "pending";
182
+ case "stopping":
183
+ case "stopped":
184
+ return "stopped";
185
+ case "shutting-down":
186
+ case "terminated":
187
+ return "absent";
188
+ default:
189
+ return "unknown";
190
+ }
191
+ }
192
+
193
+ function unknown(id: string, detail: string): MachineInfo {
194
+ return { id, taskLabel: null, state: "unknown", address: null, detail };
195
+ }
196
+
197
+ export function createAwsMachineProvider(
198
+ config: AwsMachineConfig,
199
+ runner: Runner = defaultRunner(config.region),
200
+ ): MachineProvider {
201
+ const taskIdOf = (machineId: string): string => {
202
+ if (!machineId.startsWith("uai-machine-")) {
203
+ throw new Error(`not a uai machine id: ${machineId}`);
204
+ }
205
+ return machineId.slice("uai-machine-".length);
206
+ };
207
+
208
+ /** Resolve the logical machine id to its live instances via the tag. */
209
+ async function resolveLive(
210
+ machineId: string,
211
+ ): Promise<{ instances: LiveInstance[] } | { failure: string }> {
212
+ const res = await runner([
213
+ "ec2",
214
+ "describe-instances",
215
+ "--filters",
216
+ `Name=tag:${AWS_MACHINE_TAG},Values=${taskIdOf(machineId)}`,
217
+ "Name=instance-state-name,Values=pending,running,stopping,stopped",
218
+ ]);
219
+ if (res.status !== 0) {
220
+ return {
221
+ failure: res.stderr.trim() || `describe exited ${res.status ?? "killed"}`,
222
+ };
223
+ }
224
+ const instances = parseReservations(res.stdout);
225
+ if (instances === null) {
226
+ return { failure: "describe answered with a confusing shape" };
227
+ }
228
+ return { instances };
229
+ }
230
+
231
+ async function describe(machineId: string): Promise<MachineInfo> {
232
+ let resolved: Awaited<ReturnType<typeof resolveLive>>;
233
+ try {
234
+ resolved = await resolveLive(machineId);
235
+ } catch (error) {
236
+ return unknown(
237
+ machineId,
238
+ error instanceof Error ? error.message : String(error),
239
+ );
240
+ }
241
+ if ("failure" in resolved) return unknown(machineId, resolved.failure);
242
+ if (resolved.instances.length === 0) {
243
+ // A successful tag query answering "none live" IS the absence proof.
244
+ return { id: machineId, taskLabel: null, state: "absent", address: null };
245
+ }
246
+ if (resolved.instances.length > 1) {
247
+ return unknown(
248
+ machineId,
249
+ `multiple live instances carry this machine's tag`,
250
+ );
251
+ }
252
+ const instance = resolved.instances[0]!;
253
+ const state = stateFromAws(instance.state);
254
+ return {
255
+ id: machineId,
256
+ taskLabel: instance.taskLabel,
257
+ state,
258
+ address: state === "running" ? instance.privateIp : null,
259
+ };
260
+ }
261
+
262
+ return {
263
+ kind: "aws",
264
+
265
+ async launch(spec: MachineSpec): Promise<MachineInfo> {
266
+ const machineId = awsMachineName(spec.taskId);
267
+ const type = (config.instanceType ?? defaultInstanceType)(spec);
268
+ const args = [
269
+ "ec2",
270
+ "run-instances",
271
+ "--image-id",
272
+ spec.image,
273
+ "--instance-type",
274
+ type,
275
+ "--count",
276
+ "1",
277
+ // Idempotency across crashed/retried provisions: the same token can
278
+ // never mint a second instance.
279
+ "--client-token",
280
+ machineId,
281
+ "--tag-specifications",
282
+ `ResourceType=instance,Tags=[{Key=${AWS_MACHINE_TAG},Value=${spec.taskId}},{Key=Name,Value=${machineId}}]`,
283
+ ...(spec.authorizedPublicKey
284
+ ? ["--user-data", awsUserData(spec.authorizedPublicKey)]
285
+ : []),
286
+ ...(config.subnetId ? ["--subnet-id", config.subnetId] : []),
287
+ ...(config.securityGroupId
288
+ ? ["--security-group-ids", config.securityGroupId]
289
+ : []),
290
+ ...(config.iamInstanceProfileArn
291
+ ? ["--iam-instance-profile", `Arn=${config.iamInstanceProfileArn}`]
292
+ : []),
293
+ ];
294
+ const res = await runner(args);
295
+ if (res.status !== 0) {
296
+ throw new Error(
297
+ `machine launch failed for ${machineId}: ${
298
+ res.stderr.trim() || `exit ${res.status ?? "killed"}`
299
+ }`,
300
+ );
301
+ }
302
+ const info = await describe(machineId);
303
+ if (info.state === "absent" || info.state === "unknown") {
304
+ throw new Error(
305
+ `machine ${machineId} launched but could not be described (${info.state}${
306
+ info.detail ? `: ${info.detail}` : ""
307
+ })`,
308
+ );
309
+ }
310
+ return info;
311
+ },
312
+
313
+ async stop(machineId: string): Promise<void> {
314
+ const instance = await requireSingleLive(machineId);
315
+ const res = await runner([
316
+ "ec2",
317
+ "stop-instances",
318
+ "--instance-ids",
319
+ instance.instanceId,
320
+ ]);
321
+ if (res.status !== 0) {
322
+ throw new Error(
323
+ `machine stop failed for ${machineId}: ${
324
+ res.stderr.trim() || `exit ${res.status ?? "killed"}`
325
+ }`,
326
+ );
327
+ }
328
+ },
329
+
330
+ async start(machineId: string): Promise<MachineInfo> {
331
+ const instance = await requireSingleLive(machineId);
332
+ const res = await runner([
333
+ "ec2",
334
+ "start-instances",
335
+ "--instance-ids",
336
+ instance.instanceId,
337
+ ]);
338
+ if (res.status !== 0) {
339
+ throw new Error(
340
+ `machine start failed for ${machineId}: ${
341
+ res.stderr.trim() || `exit ${res.status ?? "killed"}`
342
+ }`,
343
+ );
344
+ }
345
+ return describe(machineId);
346
+ },
347
+
348
+ async terminate(machineId: string): Promise<void> {
349
+ const resolved = await resolveLive(machineId);
350
+ if ("failure" in resolved) {
351
+ throw new Error(
352
+ `machine ${machineId} could not be resolved for terminate: ${resolved.failure}`,
353
+ );
354
+ }
355
+ // Terminate EVERY live instance carrying the tag: a duplicate from a
356
+ // pathological double-launch must not survive its sibling's teardown.
357
+ for (const instance of resolved.instances) {
358
+ const res = await runner([
359
+ "ec2",
360
+ "terminate-instances",
361
+ "--instance-ids",
362
+ instance.instanceId,
363
+ ]);
364
+ if (res.status !== 0) {
365
+ throw new Error(
366
+ `machine terminate failed for ${machineId} (${instance.instanceId}): ${
367
+ res.stderr.trim() || `exit ${res.status ?? "killed"}`
368
+ }`,
369
+ );
370
+ }
371
+ }
372
+ // Absence is not best-effort: poll until the tag query answers "none
373
+ // live" (shutting-down/terminated fall out of the live filter).
374
+ const deadline = Date.now() + 120_000;
375
+ for (;;) {
376
+ const after = await describe(machineId);
377
+ if (after.state === "absent") return;
378
+ if (Date.now() >= deadline) {
379
+ throw new Error(
380
+ `machine ${machineId} could not be proven absent after terminate (${after.state}${
381
+ after.detail ? `: ${after.detail}` : ""
382
+ })`,
383
+ );
384
+ }
385
+ await new Promise<void>((resolve) => setTimeout(resolve, 5_000));
386
+ }
387
+ },
388
+
389
+ describe,
390
+
391
+ async list(): Promise<MachineInfo[]> {
392
+ const res = await runner([
393
+ "ec2",
394
+ "describe-instances",
395
+ "--filters",
396
+ `Name=tag-key,Values=${AWS_MACHINE_TAG}`,
397
+ "Name=instance-state-name,Values=pending,running,stopping,stopped",
398
+ ]);
399
+ if (res.status !== 0) {
400
+ throw new Error(
401
+ `machine listing failed: ${
402
+ res.stderr.trim() || `exit ${res.status ?? "killed"}`
403
+ }`,
404
+ );
405
+ }
406
+ const instances = parseReservations(res.stdout);
407
+ if (instances === null) {
408
+ throw new Error("machine inventory was unparseable");
409
+ }
410
+ return instances.map((instance) => {
411
+ const state = stateFromAws(instance.state);
412
+ return {
413
+ id:
414
+ instance.taskLabel !== null
415
+ ? awsMachineName(instance.taskLabel)
416
+ : instance.instanceId,
417
+ taskLabel: instance.taskLabel,
418
+ state,
419
+ address: state === "running" ? instance.privateIp : null,
420
+ };
421
+ });
422
+ },
423
+ };
424
+
425
+ async function requireSingleLive(machineId: string): Promise<LiveInstance> {
426
+ const resolved = await resolveLive(machineId);
427
+ if ("failure" in resolved) {
428
+ throw new Error(`machine ${machineId} could not be resolved: ${resolved.failure}`);
429
+ }
430
+ if (resolved.instances.length !== 1) {
431
+ throw new Error(
432
+ `machine ${machineId} resolution expected one live instance, found ${resolved.instances.length}`,
433
+ );
434
+ }
435
+ return resolved.instances[0]!;
436
+ }
437
+ }