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