@parcha/agentrun-computer 0.1.0-beta.35 → 0.1.0-beta.37
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/NOTICE +2 -0
- package/README.md +423 -323
- package/box/Dockerfile +3 -1
- package/box/agentrun-archil +59 -7
- package/box/build-agent37.mjs +177 -0
- package/box/build-daytona.py +20 -4
- package/dist/agent37.d.ts +165 -0
- package/dist/agent37.js +759 -0
- package/dist/attach.d.ts +146 -0
- package/dist/attach.js +469 -0
- package/dist/browser.d.ts +61 -10
- package/dist/browser.js +125 -3
- package/dist/browserbase.d.ts +46 -23
- package/dist/browserbase.js +162 -17
- package/dist/chrome.d.ts +3 -4
- package/dist/chrome.js +6 -11
- package/dist/client.d.ts +33 -1
- package/dist/client.js +53 -0
- package/dist/computerd-linux-amd64 +0 -0
- package/dist/computerd-linux-arm64 +0 -0
- package/dist/conformance/agent37.d.ts +96 -0
- package/dist/conformance/agent37.js +154 -0
- package/dist/conformance/cases/apps.d.ts +5 -0
- package/dist/conformance/cases/apps.js +160 -73
- package/dist/conformance/cases/health.js +14 -0
- package/dist/conformance/cases/index.js +2 -0
- package/dist/conformance/cases/provider.js +27 -1
- package/dist/conformance/cases/screen.d.ts +3 -0
- package/dist/conformance/cases/screen.js +18 -0
- package/dist/conformance/cases/settings.d.ts +29 -23
- package/dist/conformance/cases/settings.js +76 -58
- package/dist/conformance/cases/touch.js +19 -17
- package/dist/conformance/cases/ui.d.ts +2 -0
- package/dist/conformance/cases/ui.js +475 -0
- package/dist/conformance/cli.d.ts +9 -0
- package/dist/conformance/cli.js +28 -3
- package/dist/conformance/daytona.d.ts +4 -0
- package/dist/conformance/daytona.js +5 -0
- package/dist/conformance/e2b.d.ts +6 -0
- package/dist/conformance/e2b.js +9 -2
- package/dist/conformance/fixture.d.ts +1 -1
- package/dist/conformance/fixture.js +25 -1
- package/dist/conformance/modal.d.ts +17 -13
- package/dist/conformance/modal.js +18 -9
- package/dist/conformance/orgo.d.ts +3 -3
- package/dist/conformance/orgo.js +6 -8
- package/dist/conformance/phone-harness.d.ts +6 -2
- package/dist/conformance/phone-harness.js +21 -4
- package/dist/conformance/report.js +1 -1
- package/dist/conformance/runner.js +23 -4
- package/dist/conformance/sweep.d.ts +50 -0
- package/dist/conformance/sweep.js +187 -0
- package/dist/conformance/types.d.ts +11 -3
- package/dist/conformance/ui-fixture.d.ts +56 -0
- package/dist/conformance/ui-fixture.js +43 -0
- package/dist/create-requests.d.ts +51 -0
- package/dist/create-requests.js +121 -0
- package/dist/daytona.d.ts +15 -5
- package/dist/daytona.js +58 -38
- package/dist/descriptor.d.ts +29 -2
- package/dist/descriptor.js +13 -0
- package/dist/descriptors/agent37.d.ts +41 -0
- package/dist/descriptors/agent37.js +28 -0
- package/dist/descriptors/browserbase.d.ts +1 -0
- package/dist/descriptors/browserbase.js +2 -0
- package/dist/descriptors/daytona.d.ts +23 -2
- package/dist/descriptors/daytona.js +34 -2
- package/dist/descriptors/index.d.ts +66 -3
- package/dist/descriptors/index.js +5 -3
- package/dist/descriptors/kernel.d.ts +1 -0
- package/dist/descriptors/kernel.js +2 -0
- package/dist/descriptors/modal.d.ts +4 -0
- package/dist/descriptors/modal.js +11 -1
- package/dist/descriptors/orgo.d.ts +13 -1
- package/dist/descriptors/orgo.js +9 -3
- package/dist/descriptors/phone-harness.d.ts +6 -1
- package/dist/descriptors/phone-harness.js +5 -2
- package/dist/docker/egress.d.ts +4 -3
- package/dist/docker/egress.js +7 -6
- package/dist/docker.d.ts +7 -4
- package/dist/docker.js +278 -34
- package/dist/e2b.d.ts +9 -165
- package/dist/e2b.js +282 -1342
- package/dist/fake-ui-driver.d.ts +97 -0
- package/dist/fake-ui-driver.js +717 -0
- package/dist/host.d.ts +182 -0
- package/dist/host.js +1 -0
- package/dist/hosted/process.d.ts +67 -0
- package/dist/hosted/process.js +228 -0
- package/dist/hosted/provider.d.ts +146 -0
- package/dist/hosted/provider.js +1364 -0
- package/dist/hosted/scripts.d.ts +76 -0
- package/dist/{child.js → hosted/scripts.js} +93 -12
- package/dist/index.d.ts +11 -7
- package/dist/index.js +10 -7
- package/dist/janitor.d.ts +5 -4
- package/dist/janitor.js +1 -1
- package/dist/kernel.d.ts +17 -27
- package/dist/kernel.js +94 -18
- package/dist/kinds.d.ts +17 -5
- package/dist/kinds.js +20 -4
- package/dist/labels.d.ts +10 -2
- package/dist/labels.js +30 -7
- package/dist/local-chrome.d.ts +5 -5
- package/dist/local-chrome.js +10 -5
- package/dist/modal.d.ts +23 -181
- package/dist/modal.js +273 -1232
- package/dist/mount-archil.d.ts +25 -3
- package/dist/mount-archil.js +39 -8
- package/dist/orgo-channel.d.ts +3 -2
- package/dist/orgo-channel.js +5 -2
- package/dist/orgo-desktop.d.ts +23 -9
- package/dist/orgo-desktop.js +328 -66
- package/dist/orgo-names.d.ts +129 -3
- package/dist/orgo-names.js +211 -8
- package/dist/orgo-workspaces.d.ts +47 -0
- package/dist/orgo-workspaces.js +94 -0
- package/dist/orgo.d.ts +27 -10
- package/dist/orgo.js +411 -81
- package/dist/phone-harness.d.ts +31 -21
- package/dist/phone-harness.js +510 -681
- package/dist/png.d.ts +4 -0
- package/dist/png.js +27 -0
- package/dist/protocol.d.ts +338 -30
- package/dist/protocol.js +96 -3
- package/dist/provider.d.ts +97 -7
- package/dist/provider.js +24 -3
- package/dist/result.d.ts +1 -1
- package/dist/surface/api.d.ts +248 -0
- package/dist/surface/api.js +1 -0
- package/dist/surface/core.d.ts +42 -0
- package/dist/surface/core.js +393 -0
- package/dist/surface/index.d.ts +5 -0
- package/dist/surface/index.js +3 -0
- package/dist/surface/outline.d.ts +8 -0
- package/dist/surface/outline.js +50 -0
- package/dist/surface/script.d.ts +10 -0
- package/dist/surface/script.js +92 -0
- package/dist/ui-engine.d.ts +114 -0
- package/dist/ui-engine.js +798 -0
- package/package.json +17 -1
- package/dist/child.d.ts +0 -42
- package/dist/conformance/e2b-diagnose.d.ts +0 -16
- package/dist/conformance/e2b-diagnose.js +0 -61
- package/dist/conformance/e2b-sweep.d.ts +0 -18
- package/dist/conformance/e2b-sweep.js +0 -132
- package/dist/conformance/modal-sweep.d.ts +0 -22
- package/dist/conformance/modal-sweep.js +0 -213
|
@@ -0,0 +1,1364 @@
|
|
|
1
|
+
// The shared machine-host adapter: hostedProvider(host, options) is a whole ComputerProvider over a vendor's
|
|
2
|
+
// MachineHost (../host.ts). The vendor answers create, get, list, delete and exec about its own machines; everything a
|
|
3
|
+
// computer is beyond that is here, once, for every vendor: the spec's check, the computer's name from its create's
|
|
4
|
+
// request id (one create per request: a retry finds the first), the daemon's upload, install and sha256 read-back,
|
|
5
|
+
// the Archil mount, init's start (detached, or the machine's main process on a pid1 host), the stdio bridge, the
|
|
6
|
+
// read-back inside the computer (the daemon's credentials and network, the display, the network-none probe), the wait
|
|
7
|
+
// for the listing, list and attach, the network (fixed at create), the deadline and extend, delete-then-wait-gone, the
|
|
8
|
+
// sweep of a create whose answer never came, and the words of every refusal.
|
|
9
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
10
|
+
import { readFileSync } from "node:fs";
|
|
11
|
+
import { resolve } from "node:path";
|
|
12
|
+
import { fileURLToPath } from "node:url";
|
|
13
|
+
import { CreateRequests, endedWords, otherSpecWords, readBackDiffer } from "../create-requests.js";
|
|
14
|
+
import { DESKTOP_GROUPS, desktopOf, startDisplay } from "../desktop.js";
|
|
15
|
+
import { COMPUTER_LABEL, DAEMON_IN_COMPUTER, DEADLINE_LABEL, helloDrift, probeNetworkDrift, probeNotes, probeReportOf, WORK } from "../drift.js";
|
|
16
|
+
import { OWN_NETWORK_ONLY, readOwnNetwork, TOOL_USER } from "../isolation.js";
|
|
17
|
+
import { releaseOlder } from "../janitor.js";
|
|
18
|
+
import { RUN_LABEL } from "../labels.js";
|
|
19
|
+
import { checkMount, readBackOf } from "../mount.js";
|
|
20
|
+
import { ARCHIL_MOUNT_LABEL, ARCHIL_TOOL_UID, archilEgressOf, archilLabels, archilMount, archilRefusals, archilRelease, claimEpoch, mountDrift, readArchilMount, recordedArchil as recordedArchilOf, recordedMount, syncingClient, } from "../mount-archil.js";
|
|
21
|
+
import { checkGpu, checkTenure, runLifetimeMs, } from "../provider.js";
|
|
22
|
+
import { ok } from "../result.js";
|
|
23
|
+
import { daemonWatch } from "../screen-watch.js";
|
|
24
|
+
import { countTested } from "../test-connection.js";
|
|
25
|
+
import { waitUntil } from "../wait.js";
|
|
26
|
+
import { bounded, CALL_SLACK_MS, failOf, hostCall, openBridge, pause, race, rootOf, runToExit, seconds, uploadThroughExec, words } from "./process.js";
|
|
27
|
+
import { ARCHIL_GATE, daemonDrift, hostedCommands, installerOf } from "./scripts.js";
|
|
28
|
+
const VERSION = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
|
|
29
|
+
export const NAME_LABEL = `${COMPUTER_LABEL}.name`;
|
|
30
|
+
/** The image create was asked for: a vendor may report another name for it (a template's id). */
|
|
31
|
+
export const IMAGE_LABEL = `${COMPUTER_LABEL}.image`;
|
|
32
|
+
/** The most extend may move the deadline to: create's time plus the cap, by this machine's clock, as init was given. */
|
|
33
|
+
export const MAX_LABEL = `${COMPUTER_LABEL}.max-deadline`;
|
|
34
|
+
const NAME = /^computer-[0-9a-f]{12}$/;
|
|
35
|
+
const MACHINE_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/;
|
|
36
|
+
const USER = /^(\d+):(\d+)$/;
|
|
37
|
+
/** A spec's user, where the host takes one: a uid, or uid:gid, in numbers (a uid alone is its own gid). */
|
|
38
|
+
const SPEC_USER = /^(\d+)(?::(\d+))?$/;
|
|
39
|
+
const MAX_ID = 4_294_967_294;
|
|
40
|
+
const DEFAULTS = {
|
|
41
|
+
requestMs: 30_000,
|
|
42
|
+
createMs: 120_000,
|
|
43
|
+
uploadMs: 120_000,
|
|
44
|
+
execMs: 60_000,
|
|
45
|
+
helloMs: 30_000,
|
|
46
|
+
probeMs: 30_000,
|
|
47
|
+
listMs: 60_000,
|
|
48
|
+
goneMs: 120_000,
|
|
49
|
+
pollMs: 1_000,
|
|
50
|
+
listedMs: 15_000,
|
|
51
|
+
listedStableMs: 1_000,
|
|
52
|
+
mountMs: 120_000,
|
|
53
|
+
};
|
|
54
|
+
/** The user an Archil computer's tools run as: the image's agentrun-tool, with no sudo and no capability. */
|
|
55
|
+
const ARCHIL_USER = `${ARCHIL_TOOL_UID}:${ARCHIL_TOOL_UID}`;
|
|
56
|
+
const RELEASE_POLL_MAX_MS = 5_000;
|
|
57
|
+
const LISTED_POLL_MS = 150;
|
|
58
|
+
const LISTED_ROUNDS = 2;
|
|
59
|
+
const LISTED_POLL_MAX_MS = 1_000;
|
|
60
|
+
const LISTEN_RETRY_MS = 250;
|
|
61
|
+
const START_POLL_MS = 500;
|
|
62
|
+
/** The longest a Node timer or AbortSignal.timeout holds. */
|
|
63
|
+
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
64
|
+
/** The longest timeout the adapter takes: the race of a call bounded by it must still fit a Node timer. */
|
|
65
|
+
const MAX_TIMEOUT_MS = MAX_TIMER_MS - CALL_SLACK_MS;
|
|
66
|
+
const STAGING = "/tmp/agentrun-computerd-";
|
|
67
|
+
/**
|
|
68
|
+
* Public anycast resolvers, by address: TCP to 443, and DNS over UDP to 53, the classic path out where TCP is dropped,
|
|
69
|
+
* over IPv4 and IPv6.
|
|
70
|
+
*/
|
|
71
|
+
const DEFAULT_PROBE_TARGETS = ["1.1.1.1:443", "8.8.8.8:443", "[2606:4700:4700::1111]:443", "1.1.1.1:53/udp", "[2606:4700:4700::1111]:53/udp"];
|
|
72
|
+
/** A probe target: host:port, over TCP, or host:port/udp, a DNS query over UDP. */
|
|
73
|
+
const TARGET = /^(?:\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9.-]+):[0-9]{1,5}(?:\/udp)?$/;
|
|
74
|
+
const SPEC_FIELDS = new Set(["image", "lifetimeMs", "network", "labels", "mount", "gpu", "owner"]);
|
|
75
|
+
const isWhole = (value) => typeof value === "number" && Number.isSafeInteger(value);
|
|
76
|
+
const show = (value) => (value === undefined ? "nothing" : JSON.stringify(value));
|
|
77
|
+
const policyWords = (policy) => (typeof policy === "string" ? policy : "other" in policy ? policy.other : JSON.stringify(policy));
|
|
78
|
+
const alive = (state) => state === "running" || state === "stopped" || state === "starting";
|
|
79
|
+
/** An ISO time a label holds, or undefined when it is missing or not the ISO time create writes. */
|
|
80
|
+
function isoOf(written) {
|
|
81
|
+
const at = written === undefined ? Number.NaN : Date.parse(written);
|
|
82
|
+
return Number.isNaN(at) || new Date(at).toISOString() !== written ? undefined : new Date(at);
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* When a machine ends: the deadline create wrote; or, once an extend moved the vendor's own timer past where create set
|
|
86
|
+
* it (the vendor keeps no label change), that end, up to the most the computer may live, which is what init was given.
|
|
87
|
+
*/
|
|
88
|
+
export function deadlineOf(machine) {
|
|
89
|
+
const written = isoOf(machine.labels[DEADLINE_LABEL]);
|
|
90
|
+
if (written === undefined)
|
|
91
|
+
return undefined;
|
|
92
|
+
const end = machine.endsAt instanceof Date ? machine.endsAt.getTime() : Number.NaN;
|
|
93
|
+
if (machine.timerMoved !== true || Number.isNaN(end))
|
|
94
|
+
return written;
|
|
95
|
+
const most = isoOf(machine.labels[MAX_LABEL]);
|
|
96
|
+
return new Date(most === undefined ? end : Math.min(end, most.getTime()));
|
|
97
|
+
}
|
|
98
|
+
/** Only a machine this adapter made counts: its label, a name of its making, and the name asked for when one is. */
|
|
99
|
+
export const ours = (labels, name) => labels?.[COMPUTER_LABEL] === "1" && NAME.test(labels[NAME_LABEL] ?? "") && (name === undefined || labels[NAME_LABEL] === name);
|
|
100
|
+
/** The Archil mount a computer's agentrun.mount label records, or undefined when it has none. */
|
|
101
|
+
function recordedArchil(labels) {
|
|
102
|
+
if (labels?.[ARCHIL_MOUNT_LABEL] === undefined)
|
|
103
|
+
return undefined;
|
|
104
|
+
const mount = recordedMount(labels);
|
|
105
|
+
return recordedArchilOf(labels, mount === undefined ? { other: `the label ${ARCHIL_MOUNT_LABEL} records a mount this provider never makes` } : { mount });
|
|
106
|
+
}
|
|
107
|
+
function filterProblem(labels) {
|
|
108
|
+
if (typeof labels !== "object" || labels === null || Array.isArray(labels))
|
|
109
|
+
return "labels must map names to strings";
|
|
110
|
+
for (const [key, value] of Object.entries(labels)) {
|
|
111
|
+
if (typeof value !== "string")
|
|
112
|
+
return `the label ${key} must be a string`;
|
|
113
|
+
if (key === "" || key.includes("\0") || value.includes("\0"))
|
|
114
|
+
return `the label ${JSON.stringify(key)} must be a non-empty name with no NUL byte`;
|
|
115
|
+
}
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
/** A spec's user as uid:gid in numbers, or undefined when it is not one. */
|
|
119
|
+
function specUserOf(value) {
|
|
120
|
+
const found = typeof value === "string" ? SPEC_USER.exec(value) : null;
|
|
121
|
+
if (found === null)
|
|
122
|
+
return undefined;
|
|
123
|
+
const [uid, gid] = [Number(found[1]), Number(found[2] ?? found[1])];
|
|
124
|
+
return uid <= MAX_ID && gid <= MAX_ID ? `${uid}:${gid}` : undefined;
|
|
125
|
+
}
|
|
126
|
+
/** The caller's labels of a machine: every one but the adapter's own namespace and the Archil mount's. */
|
|
127
|
+
const callerLabels = (labels) => Object.fromEntries(Object.entries(labels).filter(([key]) => key !== COMPUTER_LABEL && !key.startsWith(`${COMPUTER_LABEL}.`) && key !== ARCHIL_MOUNT_LABEL));
|
|
128
|
+
/** hostedProvider's provider: a ComputerProvider whose vendor is host. */
|
|
129
|
+
export class HostedProvider {
|
|
130
|
+
id;
|
|
131
|
+
version = VERSION;
|
|
132
|
+
/** The vendor's machines, for the live sweep (conformance/sweep.ts); nothing else reaches past the provider to them. */
|
|
133
|
+
host;
|
|
134
|
+
extend;
|
|
135
|
+
#label;
|
|
136
|
+
#fail;
|
|
137
|
+
#daemonPath;
|
|
138
|
+
#kind;
|
|
139
|
+
#desktop;
|
|
140
|
+
#maxLifetimeMs;
|
|
141
|
+
#uid;
|
|
142
|
+
#gid;
|
|
143
|
+
#timeouts;
|
|
144
|
+
#probeTargets;
|
|
145
|
+
#onNote;
|
|
146
|
+
#archilEgress;
|
|
147
|
+
/** Each create in flight, and the names of the computers this provider ended (create-requests.ts). In memory alone:
|
|
148
|
+
* past it, and past this process, the vendor's listing is what holds. */
|
|
149
|
+
#requests = new CreateRequests();
|
|
150
|
+
/** Each computer's last extend, by machine id, while one runs: the next waits for it. */
|
|
151
|
+
#extending = new Map();
|
|
152
|
+
constructor(host, options) {
|
|
153
|
+
const { label, kind = "linux", desktop = {}, maxLifetimeMs = host.facts.maxLifetimeMs, daemonPath = fileURLToPath(new URL(`../computerd-linux-${host.facts.arch}`, import.meta.url)), daemonUser = TOOL_USER, timeouts = {}, probeTargets = DEFAULT_PROBE_TARGETS, onNote, archilEgress, } = options;
|
|
154
|
+
this.id = host.id;
|
|
155
|
+
this.host = host;
|
|
156
|
+
this.#label = label;
|
|
157
|
+
this.#fail = failOf(host);
|
|
158
|
+
this.#onNote = onNote;
|
|
159
|
+
this.#archilEgress = archilEgress === undefined || archilEgress === "" ? undefined : archilEgressOf(archilEgress);
|
|
160
|
+
if (kind !== "desktop" && kind !== "linux")
|
|
161
|
+
throw new Error(`kind is desktop or linux, not ${String(kind)}`);
|
|
162
|
+
if (!isWhole(maxLifetimeMs) || maxLifetimeMs <= 0 || maxLifetimeMs > host.facts.maxLifetimeMs) {
|
|
163
|
+
throw new Error(`maxLifetimeMs must be a whole number of ms above 0 and at most ${host.facts.maxLifetimeMs} ms, the longest ${label} keeps a computer`);
|
|
164
|
+
}
|
|
165
|
+
const user = USER.exec(daemonUser);
|
|
166
|
+
if (user === null || Number(user[1]) > MAX_ID || Number(user[2]) > MAX_ID)
|
|
167
|
+
throw new Error(`the daemon user ${daemonUser} must be uid:gid in numbers, such as 1000:1000`);
|
|
168
|
+
// The numbers, not the text: "00" is root as much as "0" is.
|
|
169
|
+
if (Number(user[1]) === 0 || Number(user[2]) === 0)
|
|
170
|
+
throw new Error(`the daemon user ${daemonUser} is root or in root's group; ${a(label)} computer's daemon runs as neither`);
|
|
171
|
+
const merged = { ...DEFAULTS, ...timeouts };
|
|
172
|
+
// AbortSignal.timeout and Node's timers take whole ms up to 2^31 - 1 (a fraction throws, a longer one fires at
|
|
173
|
+
// once), and a call's race adds CALL_SLACK_MS to its bound: refused here, before any machine exists. The listing's
|
|
174
|
+
// stability window alone may be 0: two consecutive polls, with no time between them asked for.
|
|
175
|
+
for (const [key, value] of Object.entries(merged)) {
|
|
176
|
+
const zero = key === "listedStableMs";
|
|
177
|
+
if (!isWhole(value) || value < (zero ? 0 : 1) || value > MAX_TIMEOUT_MS)
|
|
178
|
+
throw new Error(`timeouts.${key} must be a whole number of ms ${zero ? "0 or more" : "above 0"} and at most ${MAX_TIMEOUT_MS}, not ${value}`);
|
|
179
|
+
}
|
|
180
|
+
if (!Array.isArray(probeTargets) || probeTargets.length === 0 || probeTargets.some((target) => typeof target !== "string" || !TARGET.test(target))) {
|
|
181
|
+
throw new Error("probeTargets must name at least one address for the probe, each host:port or host:port/udp");
|
|
182
|
+
}
|
|
183
|
+
this.#daemonPath = resolve(daemonPath);
|
|
184
|
+
this.#kind = kind;
|
|
185
|
+
this.#desktop = kind === "desktop" ? desktopOf(desktop) : undefined;
|
|
186
|
+
this.#maxLifetimeMs = maxLifetimeMs;
|
|
187
|
+
[this.#uid, this.#gid] = [String(Number(user[1])), String(Number(user[2]))];
|
|
188
|
+
this.#timeouts = merged;
|
|
189
|
+
this.#probeTargets = [...probeTargets];
|
|
190
|
+
// Extend only where the deadline can follow it: the vendor's timer moved, or the janitor's label.
|
|
191
|
+
const { lifetime } = host.facts;
|
|
192
|
+
if ((lifetime === "vendor" && host.setTimer) || (lifetime === "janitor" && host.setLabels))
|
|
193
|
+
this.extend = (ref, ttlMs, context) => this.#extendSerial(ref, ttlMs, context?.signal);
|
|
194
|
+
}
|
|
195
|
+
/** The computer's facts, from the host's and the adapter's options alone. */
|
|
196
|
+
capabilities() {
|
|
197
|
+
const { facts } = this.host;
|
|
198
|
+
return {
|
|
199
|
+
kind: this.#kind,
|
|
200
|
+
lifetime: facts.lifetime,
|
|
201
|
+
network: [...facts.network],
|
|
202
|
+
networkReadBack: facts.networkReadBack,
|
|
203
|
+
isolation: facts.isolation,
|
|
204
|
+
os: "linux",
|
|
205
|
+
daemon: facts.daemon,
|
|
206
|
+
groups: ["exec", "files", "processes", ...(this.#desktop ? DESKTOP_GROUPS : [])],
|
|
207
|
+
maxLifetimeMs: this.#maxLifetimeMs,
|
|
208
|
+
release: [...facts.release],
|
|
209
|
+
...(facts.stopDeletes === undefined ? {} : { stopDeletes: facts.stopDeletes }),
|
|
210
|
+
...(facts.mounts === undefined ? {} : { mount: [...facts.mounts] }),
|
|
211
|
+
vendorAgentPorts: [...facts.vendorAgentPorts],
|
|
212
|
+
...(facts.gpu === undefined ? {} : { gpu: structuredClone(facts.gpu) }),
|
|
213
|
+
...(facts.user === undefined ? {} : { user: [...facts.user] }),
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
check(spec) {
|
|
217
|
+
const refusals = [];
|
|
218
|
+
const refuse = (field, message) => refusals.push({ field, message });
|
|
219
|
+
const given = (typeof spec === "object" && spec !== null ? spec : {});
|
|
220
|
+
const { image, network, labels, mount } = given;
|
|
221
|
+
const capabilities = this.capabilities();
|
|
222
|
+
const label = this.#label;
|
|
223
|
+
refusals.push(...checkMount(mount, capabilities.mount ?? []), ...archilRefusals(given));
|
|
224
|
+
const daemonUser = `${this.#uid}:${this.#gid}`;
|
|
225
|
+
const archil = mount?.kind === "archil";
|
|
226
|
+
const asked = this.#takesUser() ? given.user : undefined;
|
|
227
|
+
if (asked !== undefined) {
|
|
228
|
+
const user = specUserOf(asked);
|
|
229
|
+
if (user === undefined)
|
|
230
|
+
refuse("user", "user must be a uid or uid:gid in numbers, such as 1000:1000; a name is refused, since the image may not have it");
|
|
231
|
+
else if (user.startsWith("0:") && !(this.host.facts.user ?? []).includes("root")) {
|
|
232
|
+
refuse("user", `${a(label)} computer does not run as root: each connection is the vendor's exec of the daemon's stdio bridge, as the vendor's root, outside the daemon, and a root computer user, though init leaves it no capability, owns the directories above the daemon, so it could replace what that exec runs; ask for another uid, such as 1000:1000`);
|
|
233
|
+
}
|
|
234
|
+
else if (archil && user !== ARCHIL_USER) {
|
|
235
|
+
refuse("user", `a computer with an Archil mount runs its tools as agentrun-tool, ${ARCHIL_USER}, the user its image makes with no way to root; leave user unset or ask for ${ARCHIL_USER}`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
else if (archil && daemonUser !== ARCHIL_USER) {
|
|
239
|
+
refuse("mount", `a computer with an Archil mount runs its tools as agentrun-tool, ${ARCHIL_USER}, the user its image makes with no way to root; this provider's daemon user is ${daemonUser}: make it with daemonUser ${ARCHIL_USER}`);
|
|
240
|
+
}
|
|
241
|
+
if (typeof image !== "string" || image === "" || image.includes("\0"))
|
|
242
|
+
refuse("image", `an image is required: the name of ${a(label)} image`);
|
|
243
|
+
refusals.push(...checkTenure(given, capabilities, label));
|
|
244
|
+
if (network === "open" || (typeof network === "object" && network !== null && "allow" in network))
|
|
245
|
+
refuse("network", OWN_NETWORK_ONLY);
|
|
246
|
+
else if (network !== "none")
|
|
247
|
+
refuse("network", 'network is required: "none"');
|
|
248
|
+
if (labels !== undefined) {
|
|
249
|
+
const entries = typeof labels === "object" && labels !== null && !Array.isArray(labels) ? Object.entries(labels) : undefined;
|
|
250
|
+
const bad = entries === undefined ? "labels must map names to strings" : (entries.map(([key, value]) => labelProblem(key, value, this.host.facts.labelRules?.key)).find(Boolean) ?? this.#labelCount(entries.length, mount));
|
|
251
|
+
if (bad)
|
|
252
|
+
refuse("labels", bad);
|
|
253
|
+
}
|
|
254
|
+
refusals.push(...checkGpu(given.gpu, capabilities, mount));
|
|
255
|
+
const taken = new Set(this.host.facts.specFields ?? []);
|
|
256
|
+
for (const [field, value] of Object.entries(given)) {
|
|
257
|
+
if (SPEC_FIELDS.has(field) || taken.has(field) || value === undefined)
|
|
258
|
+
continue;
|
|
259
|
+
if (field === "cpus" || field === "memoryMb" || field === "pids")
|
|
260
|
+
refuse(field, `${a(label)} computer has the size of its image: name an image of the size you need, not ${field}`);
|
|
261
|
+
else if (field === "user")
|
|
262
|
+
refuse(field, `${a(label)} computer's daemon runs as the provider's daemon user (${daemonUser}), never as one a spec names`);
|
|
263
|
+
else if (field === "workdir")
|
|
264
|
+
refuse(field, `${a(label)} computer works in ${WORK}, its home; a spec cannot name another`);
|
|
265
|
+
else
|
|
266
|
+
refuse(field, `${a(label)} computer does not support ${field}`);
|
|
267
|
+
}
|
|
268
|
+
if (this.host.check)
|
|
269
|
+
refusals.push(...this.host.check(spec));
|
|
270
|
+
return refusals;
|
|
271
|
+
}
|
|
272
|
+
/** Whether the host takes a spec's user (facts.specFields): then a computer's daemon runs as the one a spec names. */
|
|
273
|
+
#takesUser() {
|
|
274
|
+
return (this.host.facts.specFields ?? []).includes("user");
|
|
275
|
+
}
|
|
276
|
+
/** Who one create's daemon runs as, uid:gid: the spec's user where the host takes one, else the provider's daemon user. */
|
|
277
|
+
#userOf(spec) {
|
|
278
|
+
return (this.#takesUser() ? specUserOf(spec.user) : undefined) ?? `${this.#uid}:${this.#gid}`;
|
|
279
|
+
}
|
|
280
|
+
/** Why a spec's labels, with the adapter's own, are more than the vendor takes; undefined when they fit. */
|
|
281
|
+
#labelCount(count, mount) {
|
|
282
|
+
const max = this.host.facts.labelRules?.max;
|
|
283
|
+
if (max === undefined)
|
|
284
|
+
return undefined;
|
|
285
|
+
const own = 5 + (mount?.kind === "archil" ? Object.keys(archilLabels({ kind: "archil", disk: "d", region: "r", folder: "f", token: "t" })).length : 0);
|
|
286
|
+
return count + own > max ? `${a(this.#label)} computer takes ${max} labels, ${own} of them the provider's own: ${count} is ${count + own - max} too many` : undefined;
|
|
287
|
+
}
|
|
288
|
+
/** A host call bounded by ms, the caller's signal when given. */
|
|
289
|
+
#call(what, run, ms, signal) {
|
|
290
|
+
return hostCall(this.host, what, run, ms, signal);
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Makes a computer, once per request: context.requestId names it (computerNameFor), and a create of a request already made
|
|
294
|
+
* finds that computer instead of making another. One still starting is waited for (within createMs); one up is
|
|
295
|
+
* returned once its labels and daemon read back as attach reads them, else refused as exists; one that ended (or
|
|
296
|
+
* that this provider gave up on) is refused as exists, in words. A second create of a request still in flight waits
|
|
297
|
+
* for the first and answers what it does.
|
|
298
|
+
*/
|
|
299
|
+
async create(spec, context) {
|
|
300
|
+
const refusals = this.check(spec);
|
|
301
|
+
return this.#requests.create(spec, context, {
|
|
302
|
+
refuse: (code, message) => this.#fail(code, message),
|
|
303
|
+
...(refusals.length > 0 ? { refused: refusals.map(({ field, message }) => `${field}: ${message}`).join("; ") } : {}),
|
|
304
|
+
// The checks #again makes of a computer listed already, made here of the spec in flight: what it gives is shared
|
|
305
|
+
// only with a create that asks the same.
|
|
306
|
+
userOf: (asked) => this.#userOf(asked),
|
|
307
|
+
make: (name) => this.#createOnce(spec, name, context.signal),
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
/** A request's computer given up on or deleted: its request is refused from now on. */
|
|
311
|
+
#end(name) {
|
|
312
|
+
this.#requests.end(name);
|
|
313
|
+
}
|
|
314
|
+
/** How spec's labels differ from labels, a computer's of this request (seen: "read back", or "in flight"), in words. */
|
|
315
|
+
#labelDiffer(spec, name, labels, seen) {
|
|
316
|
+
const asked = this.#labelsOf(spec, name, labels[DEADLINE_LABEL] ?? "", labels[MAX_LABEL] ?? "");
|
|
317
|
+
const differ = Object.entries(asked)
|
|
318
|
+
.filter(([key, value]) => key !== DEADLINE_LABEL && key !== MAX_LABEL && labels[key] !== value)
|
|
319
|
+
.map(([key, value]) => `label ${key}: asked ${show(value)}, ${seen} ${show(labels[key])}`);
|
|
320
|
+
const extra = Object.keys(callerLabels(labels)).filter((key) => !Object.hasOwn(asked, key));
|
|
321
|
+
if (extra.length > 0)
|
|
322
|
+
differ.push(`labels ${extra.join(", ")}: ${seen}, never asked for`);
|
|
323
|
+
return differ;
|
|
324
|
+
}
|
|
325
|
+
async #createOnce(spec, name, signal) {
|
|
326
|
+
const { listMs } = this.#timeouts;
|
|
327
|
+
const listed = await this.#call("the listing by the request's name", (ctx) => this.host.list({ [COMPUTER_LABEL]: "1", [NAME_LABEL]: name }, ctx), listMs, signal);
|
|
328
|
+
if (!listed.ok)
|
|
329
|
+
return listed;
|
|
330
|
+
const found = listed.value.filter((machine) => ours(machine.labels, name));
|
|
331
|
+
if (found.length > 1)
|
|
332
|
+
return this.#fail("exists", `${found.length} machines carry the name ${name} (${found.map((m) => m.id).join(", ")}): create with a new request id`);
|
|
333
|
+
if (found.length === 1)
|
|
334
|
+
return this.#again(spec, name, found[0], signal);
|
|
335
|
+
const launched = await this.#launch(spec, name, signal);
|
|
336
|
+
if (!launched.ok)
|
|
337
|
+
return launched;
|
|
338
|
+
const { ref, made } = launched.value;
|
|
339
|
+
// From here the machine exists: every step takes the caller's signal, and a failure or an abort deletes it.
|
|
340
|
+
// Another provider instance's create of this request may have made one too (#converge): the oldest is kept.
|
|
341
|
+
const first = await this.#converge(name, ref.id, signal);
|
|
342
|
+
if (first.ok && first.value !== undefined && first.value.id !== ref.id)
|
|
343
|
+
return this.#again(spec, name, first.value, signal);
|
|
344
|
+
const prepared = await this.#prepare(spec, ref, made, signal);
|
|
345
|
+
if (signal?.aborted)
|
|
346
|
+
return this.#abandon(ref, { code: "aborted", message: "create was aborted" }, signal);
|
|
347
|
+
if (!prepared.ok) {
|
|
348
|
+
// A create of this request on another instance, whose machine is older, deletes this one under it: answer that one.
|
|
349
|
+
const kept = await this.#converge(name, ref.id, signal);
|
|
350
|
+
if (kept.ok && kept.value !== undefined && kept.value.id !== ref.id) {
|
|
351
|
+
await this.#kill(ref.id);
|
|
352
|
+
return this.#again(spec, name, kept.value, signal);
|
|
353
|
+
}
|
|
354
|
+
return this.#abandon(ref, prepared.error, signal);
|
|
355
|
+
}
|
|
356
|
+
// The last read of the name, once this machine is listed: one made by another instance and listed only now is
|
|
357
|
+
// settled here, the oldest kept and every other deleted.
|
|
358
|
+
const last = await this.#converge(name, ref.id, signal);
|
|
359
|
+
if (!last.ok)
|
|
360
|
+
return this.#abandon(ref, last.error, signal, true);
|
|
361
|
+
if (last.value !== undefined && last.value.id !== ref.id)
|
|
362
|
+
return this.#again(spec, name, last.value, signal);
|
|
363
|
+
return ok(prepared.value.length > 0 ? { ...ref, notes: prepared.value } : ref);
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* The one machine a request keeps. Two creates of one request on two provider instances can both find no machine by
|
|
367
|
+
* the name and both make one: #requests holds within one instance alone, and a vendor's name or label need not be
|
|
368
|
+
* unique. So after the vendor's answer the name's listing is read, with mine (read by get when not yet listed): where
|
|
369
|
+
* more than one machine holds the name, the oldest (createdAt, or the lowest id where any has none) is kept, and every
|
|
370
|
+
* other is deleted and read back gone, its Archil folder let go first. Every instance picks the same one from the
|
|
371
|
+
* same listing. Its value is the machine kept, or undefined when mine holds the name alone (or nothing is listed yet).
|
|
372
|
+
*/
|
|
373
|
+
async #converge(name, mine, signal) {
|
|
374
|
+
const listed = await this.#call("the listing by the request's name", (ctx) => this.host.list({ [COMPUTER_LABEL]: "1", [NAME_LABEL]: name }, ctx), this.#timeouts.listMs, signal);
|
|
375
|
+
if (!listed.ok)
|
|
376
|
+
return listed;
|
|
377
|
+
const holders = listed.value.filter((machine) => ours(machine.labels, name) && alive(machine.state));
|
|
378
|
+
if (!holders.some((machine) => machine.id !== mine))
|
|
379
|
+
return ok(undefined);
|
|
380
|
+
if (!holders.some((machine) => machine.id === mine)) {
|
|
381
|
+
const read = await this.#get(mine, signal);
|
|
382
|
+
if (read.ok && read.value !== undefined && alive(read.value.state))
|
|
383
|
+
holders.push(read.value);
|
|
384
|
+
}
|
|
385
|
+
const [kept, ...others] = holders.sort(oldestFirst(holders));
|
|
386
|
+
for (const other of others) {
|
|
387
|
+
const gone = await this.#discard(other, signal);
|
|
388
|
+
if (!gone.ok)
|
|
389
|
+
return this.#fail(gone.error.code, `${holders.length} machines carry the name ${name}: ${kept?.id}, the oldest, is kept, and ${other.id} could not be deleted (${gone.error.message})`);
|
|
390
|
+
}
|
|
391
|
+
return ok(kept);
|
|
392
|
+
}
|
|
393
|
+
/** A machine create does not keep, deleted and read back gone; a running Archil computer lets go of its folder first. */
|
|
394
|
+
async #discard(machine, signal) {
|
|
395
|
+
const ref = { id: machine.id, name: machine.labels[NAME_LABEL] };
|
|
396
|
+
if (recordedArchil(machine.labels) !== undefined && machine.state === "running") {
|
|
397
|
+
const letGo = await this.#letGo(ref, signal);
|
|
398
|
+
if (!letGo.ok)
|
|
399
|
+
this.#onNote?.({ computer: ref.name, note: `${machine.id}, a second machine of one request, was deleted, and ${letGo.error.message}` });
|
|
400
|
+
}
|
|
401
|
+
const killed = await this.#kill(machine.id);
|
|
402
|
+
return killed.ok ? this.#settle(ref, signal) : killed;
|
|
403
|
+
}
|
|
404
|
+
/** A create of a request whose computer is listed already: the same create, the computer as it is; see create. */
|
|
405
|
+
async #again(spec, name, first, signal) {
|
|
406
|
+
const until = Date.now() + this.#timeouts.createMs;
|
|
407
|
+
let machine = first;
|
|
408
|
+
let last;
|
|
409
|
+
for (;;) {
|
|
410
|
+
if (machine === undefined || !alive(machine.state) || machine.state === "stopped")
|
|
411
|
+
return this.#fail("exists", endedWords(name));
|
|
412
|
+
const deadline = deadlineOf(machine);
|
|
413
|
+
if (deadline !== undefined && deadline.getTime() <= Date.now())
|
|
414
|
+
return this.#fail("exists", endedWords(name));
|
|
415
|
+
if (machine.state === "running") {
|
|
416
|
+
const differ = this.#labelDiffer(spec, name, machine.labels, "read back");
|
|
417
|
+
if (differ.length > 0)
|
|
418
|
+
return this.#fail("exists", otherSpecWords(name, "was made", differ));
|
|
419
|
+
const attached = await this.#attached(machine, signal);
|
|
420
|
+
// The image and an Archil mount are in the labels; the user, the network, and a size where the vendor takes
|
|
421
|
+
// one in a spec and reads it back, are read back. A vendor that reads no size back (Modal) cannot show a drift.
|
|
422
|
+
const sizes = ["cpus", "memoryMb"].filter((field) => this.host.facts.specFields?.includes(field) && attached.ok && attached.value.spec[field] !== undefined);
|
|
423
|
+
const drift = attached.ok ? readBackDiffer({ ...spec, user: this.#userOf(spec) }, attached.value.spec, ["user", "network", ...sizes]) : [];
|
|
424
|
+
if (drift.length > 0)
|
|
425
|
+
return this.#fail("exists", otherSpecWords(name, "was made", drift));
|
|
426
|
+
if (attached.ok)
|
|
427
|
+
return ok({ id: attached.value.id, name: attached.value.name, ...(attached.value.notes ? { notes: attached.value.notes } : {}) });
|
|
428
|
+
if (attached.error.code === "aborted")
|
|
429
|
+
return attached;
|
|
430
|
+
// Its daemon is not up yet, or not yet as declared (a desktop whose display the first create is still
|
|
431
|
+
// starting): the first create is still making it. A refusal that holds past createMs is exists.
|
|
432
|
+
last = attached.error;
|
|
433
|
+
}
|
|
434
|
+
if (Date.now() + this.#startPollMs() >= until) {
|
|
435
|
+
const within = seconds(this.#timeouts.createMs);
|
|
436
|
+
if (last?.code === "refused")
|
|
437
|
+
return this.#fail("exists", `${name} was made for this request, and after ${within} still ${last.message}`);
|
|
438
|
+
return this.#fail("timeout", `${name}, made for this request, was not up within ${within}${last ? `: ${last.message}` : ""}`);
|
|
439
|
+
}
|
|
440
|
+
await pause(this.#startPollMs(), signal);
|
|
441
|
+
if (signal?.aborted)
|
|
442
|
+
return this.#fail("aborted", `create was aborted while ${name}, made for this request, came up`);
|
|
443
|
+
const read = await this.#get(first.id, signal);
|
|
444
|
+
if (!read.ok)
|
|
445
|
+
return read;
|
|
446
|
+
machine = read.value;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
/** The labels create gives a computer: the caller's, the adapter's own, and an Archil mount's (never its token). */
|
|
450
|
+
#labelsOf(spec, name, deadline, maxDeadline) {
|
|
451
|
+
return {
|
|
452
|
+
...spec.labels,
|
|
453
|
+
[COMPUTER_LABEL]: "1",
|
|
454
|
+
[NAME_LABEL]: name,
|
|
455
|
+
[DEADLINE_LABEL]: deadline,
|
|
456
|
+
[IMAGE_LABEL]: spec.image,
|
|
457
|
+
[MAX_LABEL]: maxDeadline,
|
|
458
|
+
...(spec.mount?.kind === "archil" ? archilLabels(spec.mount) : {}),
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
/** Everything create does up to the vendor's answer: the daemon read, the machine made, by its request. */
|
|
462
|
+
async #launch(spec, name, signal) {
|
|
463
|
+
let daemon;
|
|
464
|
+
try {
|
|
465
|
+
daemon = readFileSync(this.#daemonPath);
|
|
466
|
+
}
|
|
467
|
+
catch {
|
|
468
|
+
return this.#fail("not_found", `no daemon binary at ${this.#daemonPath}: run npm run build:daemon -w @parcha/agentrun-computer`);
|
|
469
|
+
}
|
|
470
|
+
const sha256 = createHash("sha256").update(daemon).digest("hex");
|
|
471
|
+
if (signal?.aborted)
|
|
472
|
+
return this.#fail("aborted", `create was aborted before ${this.#label} was called`);
|
|
473
|
+
const now = Date.now();
|
|
474
|
+
const lifetimeMs = runLifetimeMs(spec);
|
|
475
|
+
const deadline = new Date(now + lifetimeMs).toISOString();
|
|
476
|
+
const maxDeadline = new Date(now + this.#maxLifetimeMs).toISOString();
|
|
477
|
+
const labels = this.#labelsOf(spec, name, deadline, maxDeadline);
|
|
478
|
+
const archil = spec.mount?.kind === "archil";
|
|
479
|
+
const user = this.#userOf(spec);
|
|
480
|
+
const commands = hostedCommands({
|
|
481
|
+
staging: `${STAGING}${randomBytes(8).toString("hex")}`,
|
|
482
|
+
deadline,
|
|
483
|
+
user,
|
|
484
|
+
display: this.#desktop?.display ?? "",
|
|
485
|
+
maxDeadline,
|
|
486
|
+
atomic: this.host.facts.daemon === "pid1",
|
|
487
|
+
sha256,
|
|
488
|
+
// This create's own: the entrypoint starts the daemon whose marker holds it, never one the image had.
|
|
489
|
+
nonce: randomBytes(16).toString("hex"),
|
|
490
|
+
waitS: Math.ceil((this.#timeouts.createMs + this.#timeouts.uploadMs + this.#timeouts.execMs + (archil ? this.#timeouts.mountMs * 3 : 0)) / 1000),
|
|
491
|
+
...(archil && this.host.facts.daemon === "pid1" ? { gate: ARCHIL_GATE } : {}),
|
|
492
|
+
});
|
|
493
|
+
const taken = new Set(this.host.facts.specFields ?? []);
|
|
494
|
+
const request = {
|
|
495
|
+
name,
|
|
496
|
+
image: spec.image,
|
|
497
|
+
labels,
|
|
498
|
+
...(this.host.facts.lifetime === "vendor" ? { lifetimeMs } : {}),
|
|
499
|
+
// An Archil computer's root reaches Archil, so its vendor network is open: its tools' none is init's own, read
|
|
500
|
+
// back by the probe from inside, as the tool user, like every network none here.
|
|
501
|
+
network: archil ? "open" : "none",
|
|
502
|
+
...(this.host.facts.daemon === "pid1" ? { command: commands.entrypoint } : {}),
|
|
503
|
+
...(spec.gpu === undefined ? {} : { gpu: spec.gpu }),
|
|
504
|
+
...(taken.has("cpus") && spec.cpus !== undefined ? { cpus: spec.cpus } : {}),
|
|
505
|
+
...(taken.has("memoryMb") && spec.memoryMb !== undefined ? { memoryMb: spec.memoryMb } : {}),
|
|
506
|
+
...(taken.has("workdir") && spec.workdir !== undefined ? { workdir: spec.workdir } : {}),
|
|
507
|
+
...(taken.has("user") && spec.user !== undefined ? { user } : {}),
|
|
508
|
+
};
|
|
509
|
+
const runtime = this.host.facts.runtime?.(request);
|
|
510
|
+
const { createMs } = this.#timeouts;
|
|
511
|
+
// Never cancelled, only raced: an aborted call could leave a machine made whose id never came back.
|
|
512
|
+
let creating;
|
|
513
|
+
try {
|
|
514
|
+
creating = Promise.resolve(this.host.create(request, { timeoutMs: createMs }));
|
|
515
|
+
}
|
|
516
|
+
catch (error) {
|
|
517
|
+
return this.#fail(this.host.errorCode(error), `${this.#label}'s create failed: ${words(error)}`);
|
|
518
|
+
}
|
|
519
|
+
const raced = await race(this.host, creating, `${this.#label}'s create`, createMs + CALL_SLACK_MS, signal);
|
|
520
|
+
const created = raced.ok ? raced.value : raced;
|
|
521
|
+
if (!created.ok) {
|
|
522
|
+
const { code, message } = created.error;
|
|
523
|
+
if (code === "aborted" || code === "timeout") {
|
|
524
|
+
// One that lands is deleted by its id; one whose answer never comes, by its name.
|
|
525
|
+
this.#end(name);
|
|
526
|
+
creating.then(async (made) => void (made.ok ? await this.#kill(made.value.id) : await this.#deleteNamed(name)), async () => void (await this.#deleteNamed(name)));
|
|
527
|
+
return this.#fail(code, `${message}; a machine it makes after this is deleted as it lands, and ${this.#label} ends it by ${deadline} either way`);
|
|
528
|
+
}
|
|
529
|
+
// A create the vendor refused made nothing. One that failed otherwise may have: it goes by its name.
|
|
530
|
+
if (["invalid", "denied", "limit", "not_found", "refused", "unauthorized", "exists"].includes(code))
|
|
531
|
+
return created;
|
|
532
|
+
this.#end(name);
|
|
533
|
+
const swept = await this.#deleteNamed(name);
|
|
534
|
+
return this.#fail(code, `${this.#label} did not create the machine: ${message}${swept}`);
|
|
535
|
+
}
|
|
536
|
+
this.#requests.made(name);
|
|
537
|
+
return ok({ ref: { id: created.value.id, name }, made: { deadline, maxDeadline, labels, daemon, sha256, commands, user, ...(runtime === undefined ? {} : { runtime }) } });
|
|
538
|
+
}
|
|
539
|
+
/** Deletes a machine create gives up on, then waits, under the caller's signal, until the vendor reads it gone. */
|
|
540
|
+
async #abandon(ref, error, signal, mounted = false) {
|
|
541
|
+
this.#end(ref.name);
|
|
542
|
+
// A computer create made whole (its Archil folder mounted) lets go of the folder first, as release does.
|
|
543
|
+
if (mounted) {
|
|
544
|
+
const read = await this.#get(ref.id);
|
|
545
|
+
if (read.ok && read.value !== undefined && recordedArchil(read.value.labels) !== undefined && read.value.state === "running")
|
|
546
|
+
await this.#letGo(ref, signal);
|
|
547
|
+
}
|
|
548
|
+
const killed = await this.#kill(ref.id);
|
|
549
|
+
const gone = killed.ok ? await this.#settle(ref, signal) : killed;
|
|
550
|
+
const after = gone.ok
|
|
551
|
+
? "was deleted"
|
|
552
|
+
: killed.ok && gone.error.code === "aborted"
|
|
553
|
+
? `was deleted, and the wait for it to go was aborted; ${this.#label} ends it at its deadline if the delete did not take`
|
|
554
|
+
: `could not be deleted (${gone.error.message}); it ends at its deadline`;
|
|
555
|
+
return this.#fail(error.code, `the computer ${ref.name} ${after}: ${error.message}`);
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Every machine carrying a name create gave, deleted and read back gone: for a create whose answer never came. The
|
|
559
|
+
* listing shows a new machine a moment after the vendor makes it, so it is read for the name until one shows or
|
|
560
|
+
* listedMs passes. Best effort, in words.
|
|
561
|
+
*/
|
|
562
|
+
async #deleteNamed(name) {
|
|
563
|
+
const { listedMs, pollMs, listMs } = this.#timeouts;
|
|
564
|
+
const until = Date.now() + listedMs;
|
|
565
|
+
let found;
|
|
566
|
+
for (;;) {
|
|
567
|
+
const listed = await this.#call("the listing by name", (ctx) => this.host.list({ [COMPUTER_LABEL]: "1", [NAME_LABEL]: name }, ctx), listMs);
|
|
568
|
+
if (!listed.ok)
|
|
569
|
+
return `; a machine named ${name} may be left (${listed.error.message}), which ends at its deadline`;
|
|
570
|
+
found = listed.value.filter((machine) => ours(machine.labels, name));
|
|
571
|
+
if (found.length > 0 || Date.now() >= until)
|
|
572
|
+
break;
|
|
573
|
+
await pause(Math.min(LISTED_POLL_MS, pollMs));
|
|
574
|
+
}
|
|
575
|
+
if (found.length === 0)
|
|
576
|
+
return `; no machine named ${name} was listed within ${seconds(listedMs)}, and any it made ends at its deadline`;
|
|
577
|
+
const said = [];
|
|
578
|
+
for (const machine of found) {
|
|
579
|
+
const killed = await this.#kill(machine.id);
|
|
580
|
+
const gone = killed.ok ? await this.#settle({ id: machine.id, name }) : killed;
|
|
581
|
+
said.push(gone.ok ? `${machine.id} was deleted and read back gone` : `${machine.id} may be left (${gone.error.message}), which ends at its deadline`);
|
|
582
|
+
}
|
|
583
|
+
return `; the machine named ${name} it made: ${said.join("; ")}`;
|
|
584
|
+
}
|
|
585
|
+
/** The host's delete, never signalled: a delete that cleans up after an abort must outlive it. Not found is done. */
|
|
586
|
+
async #kill(id) {
|
|
587
|
+
const killed = await this.#call(`the delete of ${id}`, (ctx) => this.host.delete(id, ctx), this.#timeouts.requestMs);
|
|
588
|
+
return killed.ok || killed.error.code === "not_found" ? ok(undefined) : killed;
|
|
589
|
+
}
|
|
590
|
+
/** The pause between two reads of a machine that is starting: the next read comes after it, within createMs. */
|
|
591
|
+
#startPollMs() {
|
|
592
|
+
return Math.min(START_POLL_MS, this.#timeouts.pollMs * 10);
|
|
593
|
+
}
|
|
594
|
+
/** The host's get, bounded by requestMs. */
|
|
595
|
+
#get(id, signal) {
|
|
596
|
+
return this.#call(`the read of ${id}`, (ctx) => this.host.get(id, ctx), this.#timeouts.requestMs, signal);
|
|
597
|
+
}
|
|
598
|
+
/** The machine running, read while it starts (within createMs); gone or failed is refused in words. */
|
|
599
|
+
async #running(ref, signal) {
|
|
600
|
+
const until = Date.now() + this.#timeouts.createMs;
|
|
601
|
+
for (;;) {
|
|
602
|
+
const read = await this.#get(ref.id, signal);
|
|
603
|
+
if (!read.ok)
|
|
604
|
+
return read;
|
|
605
|
+
const machine = read.value;
|
|
606
|
+
if (machine === undefined)
|
|
607
|
+
return this.#fail("gone", `${ref.name} was gone before it ran`);
|
|
608
|
+
if (machine.state === "failed")
|
|
609
|
+
return this.#fail("vendor", `${this.#label} could not start ${ref.name}${machine.why ? `: ${machine.why}` : ""}`);
|
|
610
|
+
if (machine.state !== "starting")
|
|
611
|
+
return ok(machine);
|
|
612
|
+
if (Date.now() + this.#startPollMs() >= until)
|
|
613
|
+
return this.#fail("timeout", `${ref.name} did not start within ${seconds(this.#timeouts.createMs)}`);
|
|
614
|
+
await pause(this.#startPollMs(), signal);
|
|
615
|
+
if (signal?.aborted)
|
|
616
|
+
return this.#fail("aborted", "create was aborted while the machine started");
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
/** Every way a machine, as the vendor reads it back, differs from what create asked for. Pure: no call. */
|
|
620
|
+
#machineDrift(spec, machine, labels) {
|
|
621
|
+
const found = [...(machine.drift ?? [])];
|
|
622
|
+
for (const [key, value] of Object.entries(labels))
|
|
623
|
+
if (machine.labels[key] !== value)
|
|
624
|
+
found.push(`label ${key}: declared ${show(value)}, read back ${show(machine.labels[key])}`);
|
|
625
|
+
if (this.host.facts.networkReadBack) {
|
|
626
|
+
// An Archil computer's vendor network is open, for root to reach Archil; its tools' none is read from inside.
|
|
627
|
+
const archil = spec.mount?.kind === "archil";
|
|
628
|
+
const vendor = archil ? "open" : spec.network;
|
|
629
|
+
const network = machine.network ?? { other: `${this.#label} read no network back` };
|
|
630
|
+
if (network !== vendor)
|
|
631
|
+
found.push(`network: declared ${policyWords(vendor)}${archil ? ` (${this.#label}'s, for root to reach Archil)` : ""}, read back ${policyWords(network)}`);
|
|
632
|
+
}
|
|
633
|
+
if (machine.state !== "running")
|
|
634
|
+
found.push(`state: declared "running", read back ${show(machine.state)}`);
|
|
635
|
+
// No extend has run on a machine create just made: a timer that reads moved ends it later than its spec.
|
|
636
|
+
if (machine.timerMoved === true)
|
|
637
|
+
found.push(`timer: declared the spec's lifetime, read back an end of ${machine.endsAt instanceof Date ? machine.endsAt.toISOString() : "nothing"}, later than create set it`);
|
|
638
|
+
return found;
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* Everything between the vendor's answer and a computer that passed the read-back, whose value is what the read-back
|
|
642
|
+
* recorded that does not refuse it (notes).
|
|
643
|
+
*/
|
|
644
|
+
async #prepare(spec, ref, { labels, daemon, sha256, commands, user, runtime }, signal) {
|
|
645
|
+
const { uploadMs, execMs, requestMs } = this.#timeouts;
|
|
646
|
+
const running = await this.#running(ref, signal);
|
|
647
|
+
if (!running.ok)
|
|
648
|
+
return running;
|
|
649
|
+
if (this.host.prepare) {
|
|
650
|
+
const prepare = this.host.prepare.bind(this.host);
|
|
651
|
+
const prepared = await this.#call(`${this.#label}'s settings of ${ref.name}`, (ctx) => prepare(ref.id, ctx), requestMs, signal);
|
|
652
|
+
if (!prepared.ok)
|
|
653
|
+
return prepared;
|
|
654
|
+
}
|
|
655
|
+
const drift = this.#machineDrift(spec, running.value, labels);
|
|
656
|
+
if (drift.length > 0)
|
|
657
|
+
return this.#fail("refused", `it did not match its spec: ${drift.join("; ")}`);
|
|
658
|
+
const staging = commands.install[4];
|
|
659
|
+
const bytes = new Uint8Array(daemon.buffer, daemon.byteOffset, daemon.byteLength);
|
|
660
|
+
const upload = this.host.upload?.bind(this.host);
|
|
661
|
+
const uploaded = upload
|
|
662
|
+
? await this.#call(`the daemon's upload into ${ref.name}`, (ctx) => upload(ref.id, staging, bytes, ctx), uploadMs, signal)
|
|
663
|
+
: await uploadThroughExec(this.host, ref.id, staging, bytes, uploadMs, signal);
|
|
664
|
+
if (!uploaded.ok)
|
|
665
|
+
return this.#fail(uploaded.error.code, `the daemon's upload was refused: ${uploaded.error.message}`);
|
|
666
|
+
const install = await runToExit(this.host, ref.id, commands.install, { ms: execMs, ...(signal ? { signal } : {}), what: `the daemon's install in ${ref.name}` });
|
|
667
|
+
if (!install.ok)
|
|
668
|
+
return install;
|
|
669
|
+
const printed = `${install.value.stdout} ${install.value.stderr}`.trim();
|
|
670
|
+
if (install.value.exitCode !== 0)
|
|
671
|
+
return this.#fail("refused", `installing the daemon failed (exit ${install.value.exitCode}): ${printed.slice(0, 500)}`);
|
|
672
|
+
const read = /^sha256 ([0-9a-f]{64})$/m.exec(install.value.stdout)?.[1];
|
|
673
|
+
if (read !== sha256)
|
|
674
|
+
return this.#fail("refused", `it did not match its spec: daemon: uploaded sha256 ${sha256}, the installed binary reads back ${show(read)}`);
|
|
675
|
+
// Who installed it, for the create's notes: root, or the image's user through passwordless sudo.
|
|
676
|
+
const installer = installerOf(install.value.stdout);
|
|
677
|
+
// The run's folder, after the daemon is in place (serve runs it) and before init starts: no tool program runs before
|
|
678
|
+
// it is mounted. A folder mounted for a computer create then gives up on is let go before the delete, never signalled.
|
|
679
|
+
const started = async () => {
|
|
680
|
+
const done = await this.#start(spec, ref, commands, { user, ...(runtime === undefined ? {} : { runtime }) }, signal);
|
|
681
|
+
return done.ok && installer !== undefined ? ok([installer, ...done.value]) : done;
|
|
682
|
+
};
|
|
683
|
+
if (spec.mount?.kind !== "archil")
|
|
684
|
+
return started();
|
|
685
|
+
const root = rootOf(this.host, ref.id, ref.name);
|
|
686
|
+
const mounted = await this.#mountArchil(root, ref, { mount: spec.mount, run: spec.labels?.[RUN_LABEL], epoch: claimEpoch(spec.labels) }, signal);
|
|
687
|
+
if (!mounted.ok)
|
|
688
|
+
return mounted;
|
|
689
|
+
if (this.host.facts.daemon === "pid1") {
|
|
690
|
+
// The entrypoint waits for this gate as well as the daemon: init starts once the folder is there.
|
|
691
|
+
const gated = await root.run(["sh", "-c", 'touch "$1"', "sh", ARCHIL_GATE], { timeoutMs: execMs, ...(signal ? { signal } : {}) });
|
|
692
|
+
if (!gated.ok || gated.value.exitCode !== 0) {
|
|
693
|
+
await archilRelease({ root, client: undefined, timeoutMs: this.#timeouts.mountMs });
|
|
694
|
+
return gated.ok ? this.#fail("refused", `the Archil gate was not made (exit ${gated.value.exitCode}): ${gated.value.output.trim().slice(0, 300)}`) : gated;
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
const done = await started();
|
|
698
|
+
if (!done.ok || signal?.aborted)
|
|
699
|
+
await archilRelease({ root, client: undefined, timeoutMs: this.#timeouts.mountMs });
|
|
700
|
+
return done;
|
|
701
|
+
}
|
|
702
|
+
/** The rest of #prepare from the daemon's install on: init started, its first connection checked, the listing waited for. */
|
|
703
|
+
async #start(spec, ref, commands, want, signal) {
|
|
704
|
+
if (this.host.facts.daemon === "child") {
|
|
705
|
+
const init = await runToExit(this.host, ref.id, commands.start, { ms: this.#timeouts.execMs, ...(signal ? { signal } : {}), what: `starting the daemon in ${ref.name}` });
|
|
706
|
+
if (!init.ok)
|
|
707
|
+
return init;
|
|
708
|
+
if (init.value.exitCode !== 0)
|
|
709
|
+
return this.#fail("refused", `starting the daemon failed (exit ${init.value.exitCode}): ${`${init.value.stdout} ${init.value.stderr}`.trim().slice(0, 500)}`);
|
|
710
|
+
}
|
|
711
|
+
const opened = await this.#openWhenListening(ref, signal);
|
|
712
|
+
if (!opened.ok) {
|
|
713
|
+
if (opened.error.code === "aborted")
|
|
714
|
+
return opened;
|
|
715
|
+
const why = await this.#initWords(ref);
|
|
716
|
+
return this.#fail(opened.error.code, `the daemon did not answer: ${opened.error.message}${why ? `; init wrote: ${why}` : ""}`);
|
|
717
|
+
}
|
|
718
|
+
let notes;
|
|
719
|
+
try {
|
|
720
|
+
const archil = spec.mount?.kind === "archil" ? { mount: { kind: "archil", disk: spec.mount.disk, region: spec.mount.region, folder: spec.mount.folder }, epoch: claimEpoch(spec.labels) } : undefined;
|
|
721
|
+
const expected = archil === undefined ? undefined : { ...archil, expected: readBackOf({ ...archil.mount, token: "" }, archil.epoch) };
|
|
722
|
+
const inside = await this.#checkInside(opened.value, ref.name, spec.network, true, want, signal, expected);
|
|
723
|
+
if (!inside.ok)
|
|
724
|
+
return inside;
|
|
725
|
+
notes = inside.value;
|
|
726
|
+
}
|
|
727
|
+
finally {
|
|
728
|
+
await opened.value.close();
|
|
729
|
+
}
|
|
730
|
+
const listed = await this.#waitListed(ref, signal);
|
|
731
|
+
return listed.ok ? ok(notes) : listed;
|
|
732
|
+
}
|
|
733
|
+
/** What init wrote to its log (child) or the vendor's words of the machine (pid1): the end of it, or nothing. */
|
|
734
|
+
async #initWords(ref) {
|
|
735
|
+
const { requestMs } = this.#timeouts;
|
|
736
|
+
// A pid1 machine's init is its main process, with no log of start's: the vendor's words of the machine stand for it.
|
|
737
|
+
if (this.host.facts.daemon === "child") {
|
|
738
|
+
const log = await runToExit(this.host, ref.id, hostedCommands().log, { ms: requestMs, what: `reading init's log in ${ref.name}` });
|
|
739
|
+
if (log.ok)
|
|
740
|
+
return log.value.stdout.trim().slice(-500);
|
|
741
|
+
}
|
|
742
|
+
const read = await this.#get(ref.id);
|
|
743
|
+
return read.ok && read.value?.why ? read.value.why.slice(-500) : "";
|
|
744
|
+
}
|
|
745
|
+
/**
|
|
746
|
+
* Inside the computer: for a desktop just made, the X server started through the daemon and hello declaring the
|
|
747
|
+
* display; then the daemon's own report (hello, credentials, home, binary) and, for network none, the probe, which
|
|
748
|
+
* refuses on an answer and records a silent accept in the notes it returns; and, for an Archil computer, the mount
|
|
749
|
+
* read back from inside, held to the one expected. want.user is the uid:gid the daemon runs as (undefined: read back,
|
|
750
|
+
* never root), want.runtime the kernel the probe must report. Its value says what was read back of the mount (mount)
|
|
751
|
+
* and, through the probe, the user the computer's programs run as (user).
|
|
752
|
+
*/
|
|
753
|
+
async #checkInside(connection, name, network, starting, want, signal, archil) {
|
|
754
|
+
let current = connection;
|
|
755
|
+
if (starting && this.#desktop) {
|
|
756
|
+
const shown = await startDisplay(connection.client, this.#desktop, { version: VERSION, vendor: this.id, signal });
|
|
757
|
+
if (!shown.ok)
|
|
758
|
+
return shown;
|
|
759
|
+
const hello = await connection.client.call("hello", { client: `@parcha/agentrun-computer ${VERSION}` }, { signal: bounded(this.#timeouts.helloMs, signal) });
|
|
760
|
+
if (!hello.ok)
|
|
761
|
+
return hello.error.code === "aborted" && !signal?.aborted ? this.#fail("timeout", `the daemon in ${name} did not answer hello within ${seconds(this.#timeouts.helloMs)}`) : hello;
|
|
762
|
+
current = { ...connection, hello: hello.value };
|
|
763
|
+
}
|
|
764
|
+
const found = await daemonDrift(current, this.#daemonExpected(want.user), this.#timeouts.helloMs, signal);
|
|
765
|
+
if (!found.ok)
|
|
766
|
+
return found;
|
|
767
|
+
const drift = [...found.value];
|
|
768
|
+
const notes = [];
|
|
769
|
+
let user;
|
|
770
|
+
if (network === "none") {
|
|
771
|
+
const probe = await this.#probe(current, name, signal);
|
|
772
|
+
if (!probe.ok)
|
|
773
|
+
return probe;
|
|
774
|
+
user = `${probe.value.uid}:${probe.value.gid}`;
|
|
775
|
+
drift.push(...probeNetworkDrift(probe.value));
|
|
776
|
+
if (want.runtime !== undefined)
|
|
777
|
+
drift.push(...runtimeDrift(want.runtime, probe.value.kernel));
|
|
778
|
+
notes.push(...probeNotes(probe.value, network));
|
|
779
|
+
}
|
|
780
|
+
// Which way init fenced its programs, as hello read it back: said once a way other than the plain one was taken.
|
|
781
|
+
if (starting && current.hello.fence === "userns-netns") {
|
|
782
|
+
notes.push(`fence: userns-netns: init made its programs' network namespace inside a user namespace of its own, as root on ${want.runtime ?? "this machine"} may not make one itself`);
|
|
783
|
+
}
|
|
784
|
+
const said = user === undefined ? {} : { user };
|
|
785
|
+
if (archil === undefined)
|
|
786
|
+
return drift.length === 0 ? { ...ok(notes), ...said } : this.#fail("refused", `it did not match its spec: ${drift.join("; ")}`);
|
|
787
|
+
const mount = await readArchilMount(current.client, archil, { name, timeoutMs: this.#timeouts.helloMs, ...(signal ? { signal } : {}) });
|
|
788
|
+
if (!mount.ok)
|
|
789
|
+
return mount;
|
|
790
|
+
drift.push(...mountDrift(archil.expected, mount.value));
|
|
791
|
+
const read = mount.value === undefined ? {} : { mount: mount.value };
|
|
792
|
+
return drift.length === 0 ? { ...ok(notes), ...read, ...said } : this.#fail("refused", `it did not match its spec: ${drift.join("; ")}`);
|
|
793
|
+
}
|
|
794
|
+
/** The shared Archil steps (archilMount) through root, with the takeover of this provider's lower epochs. */
|
|
795
|
+
#mountArchil(root, computer, { mount, run, epoch }, signal) {
|
|
796
|
+
return archilMount({
|
|
797
|
+
root,
|
|
798
|
+
mount,
|
|
799
|
+
self: computer,
|
|
800
|
+
releaseOlder: () => releaseOlder(this, run, epoch, signal ? { signal } : {}),
|
|
801
|
+
timeoutMs: this.#timeouts.mountMs,
|
|
802
|
+
...(this.#archilEgress ? { egress: this.#archilEgress } : {}),
|
|
803
|
+
...(signal ? { signal } : {}),
|
|
804
|
+
});
|
|
805
|
+
}
|
|
806
|
+
/** What the daemon must report: the user given (uid:gid), or, with none, any one user that is not root. */
|
|
807
|
+
#daemonExpected(user) {
|
|
808
|
+
const { kind, groups } = this.capabilities();
|
|
809
|
+
const [uid, gid] = user === undefined ? [] : user.split(":");
|
|
810
|
+
return { version: VERSION, ...(uid === undefined || gid === undefined ? {} : { uid, gid }), arch: this.host.facts.arch, kind, groups };
|
|
811
|
+
}
|
|
812
|
+
/** One stdio bridge into the machine, after hello, unchecked. */
|
|
813
|
+
#open(ref, signal, helloMs = this.#timeouts.helloMs) {
|
|
814
|
+
return openBridge(this.host, ref.id, { argv: hostedCommands().stdio, name: ref.name, version: VERSION, requestMs: this.#timeouts.requestMs, helloMs, ...(signal ? { signal } : {}) });
|
|
815
|
+
}
|
|
816
|
+
/** #open, tried again while the bridge finds no daemon listening, until hello or helloMs in all. */
|
|
817
|
+
async #openWhenListening(ref, signal) {
|
|
818
|
+
const until = Date.now() + this.#timeouts.helloMs;
|
|
819
|
+
for (;;) {
|
|
820
|
+
const opened = await this.#open(ref, signal, Math.max(1, until - Date.now()));
|
|
821
|
+
if (opened.ok || !opened.notListening || signal?.aborted || Date.now() + LISTEN_RETRY_MS >= until)
|
|
822
|
+
return opened;
|
|
823
|
+
await pause(LISTEN_RETRY_MS, signal);
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
/** `computerd probe` through the daemon, so it runs as the computer's own user. */
|
|
827
|
+
async #probe(connection, name, signal) {
|
|
828
|
+
const { probeMs } = this.#timeouts;
|
|
829
|
+
const argv = [DAEMON_IN_COMPUTER, "probe", ...this.#probeTargets.flatMap((target) => ["--connect", target])];
|
|
830
|
+
const ran = await connection.client.call("exec.run", { argv, timeoutMs: probeMs }, { signal: bounded(probeMs + CALL_SLACK_MS, signal) });
|
|
831
|
+
if (!ran.ok) {
|
|
832
|
+
if (signal?.aborted)
|
|
833
|
+
return this.#fail("aborted", `the probe in ${name} was aborted`);
|
|
834
|
+
if (ran.error.code === "aborted")
|
|
835
|
+
return this.#fail("timeout", `the probe in ${name} did not answer within ${seconds(probeMs)}`);
|
|
836
|
+
return this.#fail(ran.error.code, `the probe in ${name} failed: ${ran.error.message}`);
|
|
837
|
+
}
|
|
838
|
+
const { exitCode, stdout, stderr, timedOut } = ran.value;
|
|
839
|
+
if (timedOut)
|
|
840
|
+
return this.#fail("timeout", `the probe in ${name} did not end within ${seconds(probeMs)}`);
|
|
841
|
+
if (exitCode !== 0)
|
|
842
|
+
return this.#fail("refused", `the probe in ${name} exited with ${exitCode}: ${Buffer.from(stderr, "base64").toString("utf8").trim().slice(0, 300)}`);
|
|
843
|
+
const report = probeReportOf(stdout);
|
|
844
|
+
return "not" in report ? this.#fail("refused", `the probe in ${name} ${report.not}`) : ok(report);
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* Create waits until the listing shows the new computer on two consecutive polls at least listedStableMs apart (and on
|
|
848
|
+
* every poll between), so list() shows it once create returns: a listing that showed it once and then not starts over.
|
|
849
|
+
*/
|
|
850
|
+
async #waitListed(ref, signal) {
|
|
851
|
+
const { listedMs, listMs, pollMs, listedStableMs } = this.#timeouts;
|
|
852
|
+
const until = Date.now() + listedMs;
|
|
853
|
+
let since;
|
|
854
|
+
for (let hits = 0;;) {
|
|
855
|
+
const listed = await this.#call("the listing by name", (ctx) => this.host.list({ [COMPUTER_LABEL]: "1", [NAME_LABEL]: ref.name }, ctx), listMs, signal);
|
|
856
|
+
if (!listed.ok)
|
|
857
|
+
return listed;
|
|
858
|
+
if (listed.value.some((machine) => machine.id === ref.id)) {
|
|
859
|
+
hits += 1;
|
|
860
|
+
since ??= Date.now();
|
|
861
|
+
}
|
|
862
|
+
else
|
|
863
|
+
[hits, since] = [0, undefined];
|
|
864
|
+
if (hits >= LISTED_ROUNDS && since !== undefined && Date.now() - since >= listedStableMs)
|
|
865
|
+
return ok(undefined);
|
|
866
|
+
if (Date.now() >= until)
|
|
867
|
+
return this.#fail("timeout", `the computer was not listed within ${seconds(listedMs)} of its creation`);
|
|
868
|
+
await pause(Math.min(LISTED_POLL_MS, LISTED_POLL_MAX_MS, pollMs), signal);
|
|
869
|
+
if (signal?.aborted)
|
|
870
|
+
return this.#fail("aborted", "create was aborted while it waited for the listing");
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
/** This provider's machine for ref, as the vendor reads it, or why not. */
|
|
874
|
+
async #own(ref, signal) {
|
|
875
|
+
const found = await this.#get(ref.id, signal);
|
|
876
|
+
if (!found.ok)
|
|
877
|
+
return found.error.code === "not_found" ? this.#fail("not_found", `no ${this.#label} computer is ${ref.name} (${ref.id})`) : found;
|
|
878
|
+
if (found.value === undefined)
|
|
879
|
+
return this.#fail("not_found", `no ${this.#label} computer is ${ref.name} (${ref.id})`);
|
|
880
|
+
if (!ours(found.value.labels, ref.name))
|
|
881
|
+
return this.#fail("not_found", `no ${this.#label} computer named ${ref.name} has the id ${ref.id}`);
|
|
882
|
+
return ok(found.value);
|
|
883
|
+
}
|
|
884
|
+
/** Why ref is not a computer's ref of this provider, or undefined. */
|
|
885
|
+
#refProblem(ref) {
|
|
886
|
+
if (typeof ref?.name !== "string" || !NAME.test(ref.name))
|
|
887
|
+
return `${String(ref?.name)} is not the name of ${a(this.#label)} computer (computer-<12 hex digits>)`;
|
|
888
|
+
if (typeof ref.id !== "string" || !MACHINE_ID.test(ref.id))
|
|
889
|
+
return `${String(ref.id)} is not ${a(this.#label)} machine id`;
|
|
890
|
+
return undefined;
|
|
891
|
+
}
|
|
892
|
+
/** The live view: screen.watch on a connection of the watch's own (daemonWatch); a linux computer has no screen. */
|
|
893
|
+
watch(ref, handlers, options) {
|
|
894
|
+
return daemonWatch(this, ref, handlers, options);
|
|
895
|
+
}
|
|
896
|
+
async connect(ref) {
|
|
897
|
+
const problem = this.#refProblem(ref);
|
|
898
|
+
if (problem)
|
|
899
|
+
return this.#fail("invalid", problem);
|
|
900
|
+
const found = await this.#own(ref);
|
|
901
|
+
if (!found.ok)
|
|
902
|
+
return found;
|
|
903
|
+
if (found.value.state !== "running")
|
|
904
|
+
return this.#fail("refused", `${ref.name} is ${found.value.state}, not running: its daemon does not run`);
|
|
905
|
+
const opened = await this.#open(ref);
|
|
906
|
+
if (!opened.ok)
|
|
907
|
+
return opened;
|
|
908
|
+
const { kind, groups } = this.capabilities();
|
|
909
|
+
const drifted = helloDrift(opened.value.hello, { version: VERSION, kind, groups, arch: this.host.facts.arch, fence: true });
|
|
910
|
+
// An Archil computer's client syncs the run's folder after every call that may change it, before it answers.
|
|
911
|
+
if (drifted.length === 0)
|
|
912
|
+
return recordedArchil(found.value.labels) === undefined ? opened : ok({ ...opened.value, client: syncingClient(opened.value.client) });
|
|
913
|
+
await opened.value.close();
|
|
914
|
+
return this.#fail("refused", `the daemon in ${ref.name} does not match this provider: ${drifted.join("; ")}`);
|
|
915
|
+
}
|
|
916
|
+
async attach(ref, { signal } = {}) {
|
|
917
|
+
const given = (typeof ref === "object" && ref !== null ? ref : {});
|
|
918
|
+
if ((given.id === undefined) === (given.labels === undefined))
|
|
919
|
+
return this.#fail("invalid", "attach takes { id } or { labels }, one of them");
|
|
920
|
+
if (given.id !== undefined) {
|
|
921
|
+
const id = given.id;
|
|
922
|
+
if (typeof id !== "string" || !MACHINE_ID.test(id))
|
|
923
|
+
return this.#fail("invalid", `${String(id)} is not ${a(this.#label)} machine id`);
|
|
924
|
+
const found = await this.#get(id, signal);
|
|
925
|
+
if (!found.ok)
|
|
926
|
+
return found.error.code === "not_found" ? this.#fail("not_found", `no ${this.#label} computer has the id ${id}`) : found;
|
|
927
|
+
if (found.value === undefined || !ours(found.value.labels))
|
|
928
|
+
return this.#fail("not_found", `no ${this.#label} computer has the id ${id}`);
|
|
929
|
+
return this.#attached(found.value, signal);
|
|
930
|
+
}
|
|
931
|
+
const problem = filterProblem(given.labels);
|
|
932
|
+
if (problem)
|
|
933
|
+
return this.#fail("invalid", problem);
|
|
934
|
+
const labels = given.labels;
|
|
935
|
+
if (Object.keys(labels).length === 0)
|
|
936
|
+
return this.#fail("invalid", "attach by labels needs at least one label");
|
|
937
|
+
const listed = await this.list(labels, { ...(signal ? { signal } : {}) });
|
|
938
|
+
if (!listed.ok)
|
|
939
|
+
return listed;
|
|
940
|
+
const text = JSON.stringify(labels);
|
|
941
|
+
if (listed.value.length === 0)
|
|
942
|
+
return this.#fail("not_found", `no ${this.#label} computer has the labels ${text}`);
|
|
943
|
+
if (listed.value.length > 1)
|
|
944
|
+
return this.#fail("invalid", `${listed.value.length} computers match the labels ${text}: ${listed.value.map((info) => info.ref.name).join(", ")}`);
|
|
945
|
+
const found = await this.#own(listed.value[0].ref, signal);
|
|
946
|
+
if (!found.ok)
|
|
947
|
+
return found;
|
|
948
|
+
return this.#attached(found.value, signal);
|
|
949
|
+
}
|
|
950
|
+
/**
|
|
951
|
+
* The read-back of a computer attach did not make: its spec read back from the vendor and held to what check()
|
|
952
|
+
* allows, and, when it runs, its daemon, as at create. One that drifted is refused and left as it is.
|
|
953
|
+
*/
|
|
954
|
+
async #attached(machine, signal) {
|
|
955
|
+
const name = machine.labels[NAME_LABEL];
|
|
956
|
+
const ref = { id: machine.id, name };
|
|
957
|
+
const found = [];
|
|
958
|
+
const deadline = deadlineOf(machine);
|
|
959
|
+
if (deadline === undefined)
|
|
960
|
+
found.push(`deadline: the label ${DEADLINE_LABEL} reads ${show(machine.labels[DEADLINE_LABEL])}, not the ISO time create writes`);
|
|
961
|
+
const archil = recordedArchil(machine.labels);
|
|
962
|
+
const network = this.#toolsNetwork(machine);
|
|
963
|
+
if (typeof network === "object")
|
|
964
|
+
found.push(`network: ${policyWords(network)}, which this provider never makes`);
|
|
965
|
+
const resolved = machine.image?.resolved;
|
|
966
|
+
const image = machine.labels[IMAGE_LABEL] ?? resolved ?? "";
|
|
967
|
+
// The size the vendor reads back is held to check() where the vendor takes it in a spec, and reported either way.
|
|
968
|
+
const taken = new Set(this.host.facts.specFields ?? []);
|
|
969
|
+
const cpus = machine.size?.cpus;
|
|
970
|
+
const memoryMb = machine.size?.memoryMb;
|
|
971
|
+
const sized = { ...(taken.has("cpus") && cpus !== undefined ? { cpus } : {}), ...(taken.has("memoryMb") && memoryMb !== undefined ? { memoryMb } : {}) };
|
|
972
|
+
const spec = { image, lifetimeMs: 1, network: typeof network === "object" ? "open" : network, labels: callerLabels(machine.labels), ...sized };
|
|
973
|
+
found.push(...this.check(spec).map(({ field, message }) => `${field}: ${message}, read back from the computer`));
|
|
974
|
+
// The vendor's own create options read back, as create holds them (#machineDrift).
|
|
975
|
+
found.push(...(machine.drift ?? []));
|
|
976
|
+
let kind;
|
|
977
|
+
let notes = [];
|
|
978
|
+
let mount;
|
|
979
|
+
let user;
|
|
980
|
+
if (machine.state === "running") {
|
|
981
|
+
const opened = await this.#open(ref, signal);
|
|
982
|
+
if (!opened.ok)
|
|
983
|
+
return opened;
|
|
984
|
+
try {
|
|
985
|
+
// A host that takes a spec's user made this computer's daemon run as the one its spec named: read back, never root
|
|
986
|
+
// (an Archil computer's is the tool user); every other runs as the provider's daemon user.
|
|
987
|
+
const want = this.#takesUser() ? (archil === undefined ? {} : { user: ARCHIL_USER }) : { user: `${this.#uid}:${this.#gid}` };
|
|
988
|
+
const inside = await this.#checkInside(opened.value, name, network, false, want, signal, archil);
|
|
989
|
+
if (!inside.ok && inside.error.code !== "refused")
|
|
990
|
+
return inside;
|
|
991
|
+
if (!inside.ok)
|
|
992
|
+
found.push(inside.error.message.replace(/^it did not match its spec: /, ""));
|
|
993
|
+
else {
|
|
994
|
+
notes = inside.value;
|
|
995
|
+
mount = inside.mount;
|
|
996
|
+
user = inside.user;
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
finally {
|
|
1000
|
+
await opened.value.close();
|
|
1001
|
+
}
|
|
1002
|
+
kind = opened.value.hello.kind;
|
|
1003
|
+
}
|
|
1004
|
+
else if (archil !== undefined)
|
|
1005
|
+
found.push(`mount: ${name} is ${machine.state}, so its mount cannot be read back from inside`);
|
|
1006
|
+
if (found.length > 0)
|
|
1007
|
+
return this.#fail("refused", `the computer ${name} does not match this provider, so attach refuses it and it is left as it is: ${found.join("; ")}`);
|
|
1008
|
+
return ok({
|
|
1009
|
+
...ref,
|
|
1010
|
+
spec: {
|
|
1011
|
+
image,
|
|
1012
|
+
...(resolved !== undefined && resolved !== image ? { snapshot: resolved } : {}),
|
|
1013
|
+
user: (this.#takesUser() ? user : undefined) ?? `${this.#uid}:${this.#gid}`,
|
|
1014
|
+
network: spec.network,
|
|
1015
|
+
...(cpus === undefined ? {} : { cpus }),
|
|
1016
|
+
...(memoryMb === undefined ? {} : { memoryMb }),
|
|
1017
|
+
workdir: WORK,
|
|
1018
|
+
...(deadline === undefined ? {} : { deadline }),
|
|
1019
|
+
...(kind === undefined ? {} : { kind }),
|
|
1020
|
+
...(mount === undefined ? {} : { mount }),
|
|
1021
|
+
...(machine.gpu === undefined ? {} : { gpu: machine.gpu }),
|
|
1022
|
+
},
|
|
1023
|
+
...(notes.length > 0 ? { notes } : {}),
|
|
1024
|
+
});
|
|
1025
|
+
}
|
|
1026
|
+
/**
|
|
1027
|
+
* Settings' test: the host's own, or one list by the adapter's label, counted, which makes nothing; a refused key is
|
|
1028
|
+
* unauthorized, a vendor not reached unreachable, the message never carrying a key.
|
|
1029
|
+
*/
|
|
1030
|
+
async testConnection({ signal } = {}) {
|
|
1031
|
+
const { requestMs, listMs } = this.#timeouts;
|
|
1032
|
+
const tested = this.host.testConnection?.bind(this.host);
|
|
1033
|
+
if (tested)
|
|
1034
|
+
return countTestedAs(this.#label, await this.#call(`${this.#label}'s test`, (ctx) => tested(ctx), requestMs, signal));
|
|
1035
|
+
const listed = await this.#call("the listing", (ctx) => this.host.list({ [COMPUTER_LABEL]: "1" }, ctx), listMs, signal);
|
|
1036
|
+
return countTested(this.#label, listed.ok ? ok({ count: listed.value.filter((machine) => ours(machine.labels)).length }) : listed);
|
|
1037
|
+
}
|
|
1038
|
+
/**
|
|
1039
|
+
* Every computer this provider made that carries all of these labels, running or stopped, each one's network read
|
|
1040
|
+
* back. One deadline, listMs from the call, bounds every page and every read-back.
|
|
1041
|
+
*/
|
|
1042
|
+
async list(labels, { signal } = {}) {
|
|
1043
|
+
const problem = filterProblem(labels);
|
|
1044
|
+
if (problem)
|
|
1045
|
+
return this.#fail("invalid", problem);
|
|
1046
|
+
const { listMs } = this.#timeouts;
|
|
1047
|
+
const listed = await this.#call("the listing", (ctx) => this.host.list({ ...labels, [COMPUTER_LABEL]: "1" }, ctx), listMs, signal);
|
|
1048
|
+
if (!listed.ok)
|
|
1049
|
+
return listed.error.code === "timeout" ? this.#fail("timeout", `list did not finish within ${seconds(listMs)}: ${listed.error.message}`) : listed;
|
|
1050
|
+
const infos = [];
|
|
1051
|
+
for (const machine of listed.value) {
|
|
1052
|
+
if (!ours(machine.labels) || !Object.entries(labels).every(([key, value]) => machine.labels[key] === value))
|
|
1053
|
+
continue;
|
|
1054
|
+
if (machine.state !== "running" && machine.state !== "stopped")
|
|
1055
|
+
continue;
|
|
1056
|
+
// list runs nothing in a computer: an Archil computer's mount is the one its label records, under its epoch label.
|
|
1057
|
+
const archil = recordedArchil(machine.labels);
|
|
1058
|
+
infos.push({
|
|
1059
|
+
ref: { id: machine.id, name: machine.labels[NAME_LABEL] },
|
|
1060
|
+
labels: { ...machine.labels },
|
|
1061
|
+
deadline: deadlineOf(machine),
|
|
1062
|
+
state: machine.state,
|
|
1063
|
+
network: this.#toolsNetwork(machine),
|
|
1064
|
+
...(archil === undefined ? {} : { mount: archil.expected }),
|
|
1065
|
+
});
|
|
1066
|
+
}
|
|
1067
|
+
return ok(infos);
|
|
1068
|
+
}
|
|
1069
|
+
/** The vendor reads the policy back (or the probe stands for it). A change is refused: the network is fixed at create. */
|
|
1070
|
+
async network(ref, policy, { signal } = {}) {
|
|
1071
|
+
const problem = this.#refProblem(ref);
|
|
1072
|
+
if (problem)
|
|
1073
|
+
return this.#fail("invalid", problem);
|
|
1074
|
+
const fixed = `${a(this.#label)} computer's network is fixed at create: create a new computer`;
|
|
1075
|
+
if (policy !== undefined && policy !== "none") {
|
|
1076
|
+
const wider = policy === "open" || (typeof policy === "object" && policy !== null && "allow" in policy);
|
|
1077
|
+
return this.#fail("refused", wider ? `${OWN_NETWORK_ONLY}; ${fixed}` : `${fixed}; a network is "none"`);
|
|
1078
|
+
}
|
|
1079
|
+
const found = await this.#own(ref, signal);
|
|
1080
|
+
if (!found.ok)
|
|
1081
|
+
return found;
|
|
1082
|
+
let read = this.#toolsNetwork(found.value);
|
|
1083
|
+
// Its tools' none is read from inside, as the tool user, where the vendor's network is root's (an Archil computer's)
|
|
1084
|
+
// or the vendor reads none back: the daemon's own network namespace's live interfaces are lo alone, none can be
|
|
1085
|
+
// raised (computerd probe), and no probe target answers.
|
|
1086
|
+
const inside = (recordedArchil(found.value.labels) !== undefined || !this.host.facts.networkReadBack) && found.value.state === "running";
|
|
1087
|
+
if (read === "none" && inside) {
|
|
1088
|
+
const opened = await this.#open(ref, signal);
|
|
1089
|
+
if (!opened.ok)
|
|
1090
|
+
return opened;
|
|
1091
|
+
try {
|
|
1092
|
+
const drift = await readOwnNetwork(opened.value.client, this.#timeouts.helloMs, bounded(this.#timeouts.helloMs, signal));
|
|
1093
|
+
if (!drift.ok)
|
|
1094
|
+
return this.#fail(drift.error.code, `${ref.name}: ${drift.error.message}`);
|
|
1095
|
+
if (drift.value.length > 0)
|
|
1096
|
+
read = { other: drift.value.join("; ") };
|
|
1097
|
+
const probe = await this.#probe(opened.value, ref.name, signal);
|
|
1098
|
+
if (!probe.ok)
|
|
1099
|
+
return probe;
|
|
1100
|
+
if (probe.value.reached.length > 0)
|
|
1101
|
+
read = { other: `its tools' network was created none, yet from inside an answer came back from ${probe.value.reached.join(", ")}` };
|
|
1102
|
+
}
|
|
1103
|
+
finally {
|
|
1104
|
+
await opened.value.close();
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
if (policy === undefined || policy === read)
|
|
1108
|
+
return ok(read);
|
|
1109
|
+
return this.#fail("refused", `${fixed}: ${ref.name} reads back network ${policyWords(read)}, not ${policy}`);
|
|
1110
|
+
}
|
|
1111
|
+
/**
|
|
1112
|
+
* The tools' network as the vendor's policy shows it: the vendor's own (none where it reads none back), except for an
|
|
1113
|
+
* Archil computer, whose open vendor network is root's, to reach Archil: its tools' network is init's own, none.
|
|
1114
|
+
*/
|
|
1115
|
+
#toolsNetwork(machine) {
|
|
1116
|
+
const vendor = this.host.facts.networkReadBack ? (machine.network ?? { other: `${this.#label} read no network back` }) : "none";
|
|
1117
|
+
if (recordedArchil(machine.labels) === undefined)
|
|
1118
|
+
return vendor;
|
|
1119
|
+
if (vendor === "open" || !this.host.facts.networkReadBack)
|
|
1120
|
+
return "none";
|
|
1121
|
+
return { other: `an Archil computer whose ${this.#label} network reads ${policyWords(vendor)}, not the open one create makes for root to reach Archil` };
|
|
1122
|
+
}
|
|
1123
|
+
/** One extend of a computer at a time, each reading the deadline the one before it left. */
|
|
1124
|
+
async #extendSerial(ref, ttlMs, signal) {
|
|
1125
|
+
const problem = this.#refProblem(ref);
|
|
1126
|
+
if (problem)
|
|
1127
|
+
return this.#fail("invalid", problem);
|
|
1128
|
+
if (!isWhole(ttlMs) || ttlMs <= 0)
|
|
1129
|
+
return this.#fail("invalid", "extend takes ttlMs, a whole number of milliseconds above 0");
|
|
1130
|
+
const before = this.#extending.get(ref.id) ?? Promise.resolve();
|
|
1131
|
+
const mine = before.then(() => this.#extend(ref, ttlMs, signal));
|
|
1132
|
+
const done = mine.then(() => { }, () => { });
|
|
1133
|
+
this.#extending.set(ref.id, done);
|
|
1134
|
+
try {
|
|
1135
|
+
return await mine;
|
|
1136
|
+
}
|
|
1137
|
+
finally {
|
|
1138
|
+
if (this.#extending.get(ref.id) === done)
|
|
1139
|
+
this.#extending.delete(ref.id);
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
/**
|
|
1143
|
+
* Moves the deadline to now + ttlMs, refusing one earlier than it is (before any vendor call), never past create's time plus the cap (init's maximum):
|
|
1144
|
+
* the vendor's timer (setTimer, then read back) or the janitor's label (setLabels) first, then init's own deadline, to
|
|
1145
|
+
* the end the vendor reads back. The deadline returned is the one init took.
|
|
1146
|
+
*/
|
|
1147
|
+
async #extend(ref, ttlMs, signal) {
|
|
1148
|
+
const found = await this.#own(ref, signal);
|
|
1149
|
+
if (!found.ok)
|
|
1150
|
+
return found;
|
|
1151
|
+
const machine = found.value;
|
|
1152
|
+
if (machine.state !== "running")
|
|
1153
|
+
return this.#fail("refused", `${ref.name} is ${machine.state}, not running`);
|
|
1154
|
+
const most = isoOf(machine.labels[MAX_LABEL]);
|
|
1155
|
+
if (most === undefined)
|
|
1156
|
+
return this.#fail("refused", `${ref.name}'s label ${MAX_LABEL} reads ${show(machine.labels[MAX_LABEL])}, so the most it may live is unknown`);
|
|
1157
|
+
const current = deadlineOf(machine) ?? machine.endsAt;
|
|
1158
|
+
const now = Date.now();
|
|
1159
|
+
const target = now + ttlMs;
|
|
1160
|
+
if (target > most.getTime()) {
|
|
1161
|
+
return this.#fail("limit", `${new Date(target).toISOString()} is past ${most.toISOString()}, the most this computer may live: create's time plus this provider's ${seconds(this.#maxLifetimeMs)} cap`);
|
|
1162
|
+
}
|
|
1163
|
+
if (current !== undefined && target < current.getTime()) {
|
|
1164
|
+
return this.#fail("refused", `${new Date(target).toISOString()} is earlier than ${current.toISOString()}, the deadline ${ref.name} has now: an extend moves the deadline later, never earlier`);
|
|
1165
|
+
}
|
|
1166
|
+
if (current !== undefined && target === current.getTime())
|
|
1167
|
+
return ok({ deadline: current });
|
|
1168
|
+
const { requestMs } = this.#timeouts;
|
|
1169
|
+
let end;
|
|
1170
|
+
const setTimer = this.host.setTimer?.bind(this.host);
|
|
1171
|
+
if (this.host.facts.lifetime === "vendor" && setTimer) {
|
|
1172
|
+
const moved = await this.#call(`${this.#label}'s timer of ${ref.name}`, (ctx) => setTimer(ref.id, { end: new Date(target), most }, ctx), requestMs, signal);
|
|
1173
|
+
if (!moved.ok)
|
|
1174
|
+
return moved.error.code === "limit" ? moved : this.#fail(moved.error.code, `${this.#label}'s timer did not move, so nothing did: ${moved.error.message}`);
|
|
1175
|
+
const after = await this.#get(ref.id, signal);
|
|
1176
|
+
if (!after.ok || after.value?.endsAt === undefined) {
|
|
1177
|
+
const why = after.ok ? `${ref.name} read back with no end` : after.error.message;
|
|
1178
|
+
return this.#fail(after.ok ? "gone" : after.error.code, `${this.#label}'s timer was asked to move, and reading it back failed: ${why}; init's deadline did not move`);
|
|
1179
|
+
}
|
|
1180
|
+
end = after.value.endsAt;
|
|
1181
|
+
}
|
|
1182
|
+
else {
|
|
1183
|
+
const setLabels = this.host.setLabels?.bind(this.host);
|
|
1184
|
+
if (!setLabels)
|
|
1185
|
+
return this.#fail("unsupported", `${a(this.#label)} computer's deadline cannot move`);
|
|
1186
|
+
end = new Date(target);
|
|
1187
|
+
const moved = await this.#call(`the deadline label of ${ref.name}`, (ctx) => setLabels(ref.id, { [DEADLINE_LABEL]: end.toISOString() }, ctx), requestMs, signal);
|
|
1188
|
+
if (!moved.ok)
|
|
1189
|
+
return this.#fail(moved.error.code, `the deadline label did not move, so nothing did: ${moved.error.message}`);
|
|
1190
|
+
}
|
|
1191
|
+
const opened = await this.#open(ref, signal);
|
|
1192
|
+
if (!opened.ok)
|
|
1193
|
+
return this.#fail(opened.error.code, `${ref.name}'s end moved to ${end.toISOString()}, and init's deadline did not: ${opened.error.message}`);
|
|
1194
|
+
try {
|
|
1195
|
+
// The vendor's end is its clock, and the call's own transit adds to it: init's never goes past the maximum it was given.
|
|
1196
|
+
const at = new Date(Math.min(end.getTime(), most.getTime())).toISOString();
|
|
1197
|
+
const extended = await opened.value.client.call("deadline.extend", { at }, { signal: bounded(this.#timeouts.helloMs, signal) });
|
|
1198
|
+
if (!extended.ok)
|
|
1199
|
+
return this.#fail(extended.error.code, `${ref.name}'s end moved to ${end.toISOString()}, and init's deadline did not: ${extended.error.message}`);
|
|
1200
|
+
const answered = Date.parse(extended.value.at);
|
|
1201
|
+
return ok({ deadline: new Date(Number.isNaN(answered) ? at : answered) });
|
|
1202
|
+
}
|
|
1203
|
+
finally {
|
|
1204
|
+
await opened.value.close();
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
/**
|
|
1208
|
+
* delete reads the machine back to check it is this provider's, then deletes it, both never signalled, so a release
|
|
1209
|
+
* after an abort, or one aborted during the read, still sends the delete; it is idempotent: one the vendor no longer
|
|
1210
|
+
* has is ok. The vendor answers a delete before the machine is gone, so release then waits (#settle) until the vendor
|
|
1211
|
+
* reads it gone and no longer lists it, within goneMs and the caller's signal, the one step the signal ends. A running
|
|
1212
|
+
* Archil computer lets go of the run's folder first (archilRelease: the final sync through computerd, then checkin as
|
|
1213
|
+
* root); the delete runs whatever that answers. A folder not let go cleanly loses nothing (every call that changed it
|
|
1214
|
+
* synced, and the next claim revokes the hold), so it is said through onNote, and the release succeeds once the
|
|
1215
|
+
* machine is gone. stop, where the host declares it, stops the machine and keeps it.
|
|
1216
|
+
*/
|
|
1217
|
+
async release(ref, how, { signal } = {}) {
|
|
1218
|
+
const problem = this.#refProblem(ref);
|
|
1219
|
+
if (problem)
|
|
1220
|
+
return this.#fail("invalid", problem);
|
|
1221
|
+
if (how === "detach")
|
|
1222
|
+
return this.#fail("unsupported", `the ${this.#label} provider keeps no computer for an agent (it declares no persistence), so release detach is refused: release it with delete`);
|
|
1223
|
+
if (how !== "stop" && how !== "delete")
|
|
1224
|
+
return this.#fail("invalid", `release is "stop" or "delete", not ${String(how)}`);
|
|
1225
|
+
const stop = this.host.stop?.bind(this.host);
|
|
1226
|
+
if (how === "stop" && !(stop && this.host.facts.release.includes("stop")))
|
|
1227
|
+
return this.#fail("unsupported", `${a(this.#label)} computer has no stop that this provider declares: release it with delete`);
|
|
1228
|
+
const found = await this.#get(ref.id);
|
|
1229
|
+
if (!found.ok)
|
|
1230
|
+
return found.error.code === "not_found" ? ok(undefined) : found;
|
|
1231
|
+
if (found.value === undefined)
|
|
1232
|
+
return ok(undefined);
|
|
1233
|
+
if (!ours(found.value.labels, ref.name))
|
|
1234
|
+
return this.#fail("not_found", `no ${this.#label} computer is ${ref.name} (${ref.id}): the machine is not this provider's, so it is left as it is`);
|
|
1235
|
+
// A stop and a delete alike let go of a running Archil computer's folder first: a stopped one holds no folder.
|
|
1236
|
+
const letGo = recordedArchil(found.value.labels) !== undefined && found.value.state === "running" ? await this.#letGo(ref, signal) : ok(undefined);
|
|
1237
|
+
let done;
|
|
1238
|
+
if (how === "stop" && stop)
|
|
1239
|
+
done = await this.#call(`the stop of ${ref.name}`, (ctx) => stop(ref.id, ctx), this.#timeouts.goneMs, signal);
|
|
1240
|
+
else {
|
|
1241
|
+
this.#end(ref.name);
|
|
1242
|
+
const killed = await this.#kill(ref.id);
|
|
1243
|
+
done = killed.ok ? await this.#settle(ref, signal) : killed;
|
|
1244
|
+
}
|
|
1245
|
+
if (letGo.ok)
|
|
1246
|
+
return done;
|
|
1247
|
+
if (!done.ok)
|
|
1248
|
+
return this.#fail(done.error.code, `${done.error.message}; and ${letGo.error.message}`);
|
|
1249
|
+
this.#onNote?.({ computer: ref.name, note: `${ref.name} was ${how === "stop" ? "stopped" : "deleted"}, and ${letGo.error.message}` });
|
|
1250
|
+
return done;
|
|
1251
|
+
}
|
|
1252
|
+
/** A running Archil computer's folder let go: the final sync through a connection when it answers, then checkin as root. */
|
|
1253
|
+
async #letGo(ref, signal) {
|
|
1254
|
+
const opened = await this.#open(ref, signal);
|
|
1255
|
+
try {
|
|
1256
|
+
return await archilRelease({ root: rootOf(this.host, ref.id, ref.name), client: opened.ok ? opened.value.client : undefined, timeoutMs: this.#timeouts.mountMs, ...(signal ? { signal } : {}) });
|
|
1257
|
+
}
|
|
1258
|
+
finally {
|
|
1259
|
+
if (opened.ok)
|
|
1260
|
+
await opened.value.close();
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
/**
|
|
1264
|
+
* Waits, through waitUntil, until the vendor reads the machine gone (get answers none, or a state that is neither
|
|
1265
|
+
* running, stopped nor starting) and its name's listing no longer shows it, twice running. Pauses double from pollMs
|
|
1266
|
+
* to 5 s, bounded by goneMs and the caller's signal; a failed read ends the wait with that error.
|
|
1267
|
+
*/
|
|
1268
|
+
async #settle(ref, signal) {
|
|
1269
|
+
const settled = await settleGone(this.host, ref, { ...this.#timeouts, ...(signal ? { signal } : {}) });
|
|
1270
|
+
return settled;
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
/**
|
|
1274
|
+
* Waits until the host reads a machine gone and no longer lists it under its name, twice running (see #settle). Shared
|
|
1275
|
+
* with the live sweep, which waits the same way.
|
|
1276
|
+
*/
|
|
1277
|
+
export async function settleGone(host, ref, { requestMs, listMs, pollMs, goneMs, signal }) {
|
|
1278
|
+
const fail = failOf(host);
|
|
1279
|
+
let agreed = 0;
|
|
1280
|
+
let last = "unread";
|
|
1281
|
+
const read = async (readSignal) => {
|
|
1282
|
+
const got = await hostCall(host, `the read of ${ref.id}`, (ctx) => host.get(ref.id, ctx), requestMs, readSignal);
|
|
1283
|
+
if (!got.ok && got.error.code !== "not_found") {
|
|
1284
|
+
if (got.error.code === "aborted")
|
|
1285
|
+
return { last };
|
|
1286
|
+
return { failed: fail(got.error.code, `release of ${ref.name}: reading it back failed (${got.error.message}); it last read ${last}`) };
|
|
1287
|
+
}
|
|
1288
|
+
const state = got.ok ? got.value?.state : undefined;
|
|
1289
|
+
last = state ?? "gone (not found)";
|
|
1290
|
+
if (state !== undefined && alive(state)) {
|
|
1291
|
+
agreed = 0;
|
|
1292
|
+
return { last };
|
|
1293
|
+
}
|
|
1294
|
+
const listed = await hostCall(host, "the listing by name", (ctx) => host.list({ [COMPUTER_LABEL]: "1", [NAME_LABEL]: ref.name }, ctx), listMs, readSignal);
|
|
1295
|
+
if (!listed.ok) {
|
|
1296
|
+
if (listed.error.code === "aborted")
|
|
1297
|
+
return { last };
|
|
1298
|
+
return { failed: fail(listed.error.code, `release of ${ref.name}: the listing failed (${listed.error.message}); it last read ${last}`) };
|
|
1299
|
+
}
|
|
1300
|
+
if (listed.value.some((machine) => machine.id === ref.id)) {
|
|
1301
|
+
agreed = 0;
|
|
1302
|
+
last = `${last}, still listed`;
|
|
1303
|
+
return { last };
|
|
1304
|
+
}
|
|
1305
|
+
return ++agreed >= LISTED_ROUNDS ? { settled: true } : { last };
|
|
1306
|
+
};
|
|
1307
|
+
const waited = await waitUntil(read, (state) => !("last" in state), {
|
|
1308
|
+
boundMs: goneMs,
|
|
1309
|
+
...(signal ? { signal } : {}),
|
|
1310
|
+
minMs: Math.min(pollMs, RELEASE_POLL_MAX_MS),
|
|
1311
|
+
maxMs: RELEASE_POLL_MAX_MS,
|
|
1312
|
+
what: `${ref.name} to be gone after its delete`,
|
|
1313
|
+
describe: (state) => ("last" in state ? `the vendor read it ${state.last}` : "done"),
|
|
1314
|
+
});
|
|
1315
|
+
if (!waited.ok)
|
|
1316
|
+
return waited;
|
|
1317
|
+
return "failed" in waited.value ? waited.value.failed : ok(undefined);
|
|
1318
|
+
}
|
|
1319
|
+
/**
|
|
1320
|
+
* The order #converge keeps by: the oldest first, by createdAt when every machine has one, else by id; ties by id. The
|
|
1321
|
+
* same machines give the same order on every instance.
|
|
1322
|
+
*/
|
|
1323
|
+
function oldestFirst(machines) {
|
|
1324
|
+
const at = (machine) => (machine.createdAt instanceof Date ? machine.createdAt.getTime() : Number.NaN);
|
|
1325
|
+
const dated = machines.every((machine) => !Number.isNaN(at(machine)));
|
|
1326
|
+
const byId = (a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
1327
|
+
return (a, b) => (dated && at(a) !== at(b) ? at(a) - at(b) : byId(a, b));
|
|
1328
|
+
}
|
|
1329
|
+
/** The probe's kernel against the runtime declared: gVisor exactly where the host runs one (a pid1 host's GPU), a VM's elsewhere. */
|
|
1330
|
+
function runtimeDrift(runtime, kernel) {
|
|
1331
|
+
const gvisor = /gvisor/i.test(kernel);
|
|
1332
|
+
if (runtime === "vm" && gvisor)
|
|
1333
|
+
return [`runtime: declared vm, read back gVisor (the kernel reports ${JSON.stringify(kernel)})`];
|
|
1334
|
+
if (runtime === "gvisor" && !gvisor)
|
|
1335
|
+
return [`runtime: declared gVisor (a GPU computer), read back another kernel (${JSON.stringify(kernel)})`];
|
|
1336
|
+
return [];
|
|
1337
|
+
}
|
|
1338
|
+
/** A host's own test, its words kept: unauthorized and unreachable as the shared rule reads them. */
|
|
1339
|
+
function countTestedAs(label, tested) {
|
|
1340
|
+
return tested.ok ? tested : countTested(label, tested);
|
|
1341
|
+
}
|
|
1342
|
+
function labelProblem(key, value, rule) {
|
|
1343
|
+
if (typeof value !== "string")
|
|
1344
|
+
return `the label ${key} must be a string`;
|
|
1345
|
+
if (key.includes("\0") || value.includes("\0"))
|
|
1346
|
+
return `the label ${JSON.stringify(key)}: a NUL byte cannot be sent to the vendor`;
|
|
1347
|
+
if (key === "")
|
|
1348
|
+
return "a label name must be non-empty";
|
|
1349
|
+
if (key === COMPUTER_LABEL || key.startsWith(`${COMPUTER_LABEL}.`))
|
|
1350
|
+
return `the label ${key} is in the provider's own namespace (${COMPUTER_LABEL})`;
|
|
1351
|
+
if (key === ARCHIL_MOUNT_LABEL)
|
|
1352
|
+
return `the label ${key} is the provider's own: it records an Archil computer's mount`;
|
|
1353
|
+
if (rule !== undefined && !rule.test(key))
|
|
1354
|
+
return `the label name ${JSON.stringify(key)} is not one the vendor takes (${rule.source})`;
|
|
1355
|
+
return undefined;
|
|
1356
|
+
}
|
|
1357
|
+
/** "a" or "an" before a vendor's name, by its first letter. */
|
|
1358
|
+
function a(label) {
|
|
1359
|
+
return `${/^[AEIOU]/i.test(label) ? "an" : "a"} ${label}`;
|
|
1360
|
+
}
|
|
1361
|
+
/** The shared machine-host adapter: host's machines as a ComputerProvider (see HostedProvider). */
|
|
1362
|
+
export function hostedProvider(host, options) {
|
|
1363
|
+
return new HostedProvider(host, options);
|
|
1364
|
+
}
|