@catamorphic/microsandbox 0.0.0-stage → 0.1.0-alpha.31
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/LICENSE.txt +202 -0
- package/NOTICE.txt +32 -0
- package/dist/egress-policy.d.ts +16 -0
- package/dist/egress-policy.d.ts.map +1 -0
- package/dist/image-builder.d.ts +30 -0
- package/dist/image-builder.d.ts.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +683 -0
- package/dist/index.js.map +14 -0
- package/dist/sandbox-provider.d.ts +110 -0
- package/dist/sandbox-provider.d.ts.map +1 -0
- package/dist/stdio-runtime-provider.d.ts +13 -0
- package/dist/stdio-runtime-provider.d.ts.map +1 -0
- package/dist/support.d.ts +23 -0
- package/dist/support.d.ts.map +1 -0
- package/package.json +53 -4
- package/src/egress-policy.ts +71 -0
- package/src/image-builder.ts +79 -0
- package/src/index.ts +15 -0
- package/src/sandbox-provider.ts +773 -0
- package/src/stdio-runtime-provider.ts +60 -0
- package/src/support.ts +114 -0
- package/README.md +0 -3
|
@@ -0,0 +1,773 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import type {
|
|
4
|
+
CreateSandboxOpts,
|
|
5
|
+
DeploymentRuntimeProvider,
|
|
6
|
+
ExecOpts,
|
|
7
|
+
ExecResult,
|
|
8
|
+
GitCloneOpts,
|
|
9
|
+
SandboxCapability,
|
|
10
|
+
SandboxHandle,
|
|
11
|
+
SandboxProcessProvider,
|
|
12
|
+
SandboxProvider,
|
|
13
|
+
SandboxStatus,
|
|
14
|
+
SandboxVolume,
|
|
15
|
+
SandboxVolumeProvider,
|
|
16
|
+
} from "@catamorphic/sandbox";
|
|
17
|
+
import {
|
|
18
|
+
assertSandboxResources,
|
|
19
|
+
assertSandboxVolumes,
|
|
20
|
+
dockerfileImageReference,
|
|
21
|
+
gitCloneFailure,
|
|
22
|
+
gitCloneUrl,
|
|
23
|
+
imageUserHome,
|
|
24
|
+
machineSignInHome,
|
|
25
|
+
SANDBOX_CAPABILITIES,
|
|
26
|
+
shellSandboxProcesses,
|
|
27
|
+
signInHomePath,
|
|
28
|
+
VOLUME_KEY_PATTERN,
|
|
29
|
+
VolumeUsageLog,
|
|
30
|
+
volumeMountPath,
|
|
31
|
+
} from "@catamorphic/sandbox";
|
|
32
|
+
import {
|
|
33
|
+
APP_DATA_ENV,
|
|
34
|
+
APP_DATA_MOUNT,
|
|
35
|
+
} from "@catamorphic/workflow/project-layout";
|
|
36
|
+
import {
|
|
37
|
+
Image,
|
|
38
|
+
type SandboxStatus as MsbSandboxStatus,
|
|
39
|
+
type NetworkProfile,
|
|
40
|
+
Sandbox,
|
|
41
|
+
Volume,
|
|
42
|
+
} from "microsandbox";
|
|
43
|
+
import { microsandboxEgressPolicy } from "./egress-policy.js";
|
|
44
|
+
import { cachedImageBuilder, type ImageBuilder } from "./image-builder.js";
|
|
45
|
+
import { msbStdioRuntimeProvider } from "./stdio-runtime-provider.js";
|
|
46
|
+
|
|
47
|
+
const DEFAULT_IMAGE = "oven/bun";
|
|
48
|
+
const DEFAULT_MEMORY_MIB = 1024;
|
|
49
|
+
const DEFAULT_CPUS = 1;
|
|
50
|
+
const DEFAULT_CONTAINER_DISK_MIB = 8192;
|
|
51
|
+
/** Marks a VM whose Docker daemon should run whenever it boots. */
|
|
52
|
+
const CONTAINERS_MARKER = "/etc/work-containers";
|
|
53
|
+
const DOCKER_DATA = "/var/lib/docker";
|
|
54
|
+
|
|
55
|
+
function mapMsbStatus(status: MsbSandboxStatus): SandboxStatus {
|
|
56
|
+
switch (status) {
|
|
57
|
+
case "created":
|
|
58
|
+
case "starting":
|
|
59
|
+
return "creating";
|
|
60
|
+
case "running":
|
|
61
|
+
case "draining":
|
|
62
|
+
return "started";
|
|
63
|
+
// A paused VM is not serving; callers start it, which resumes it.
|
|
64
|
+
case "paused":
|
|
65
|
+
case "stopped":
|
|
66
|
+
return "stopped";
|
|
67
|
+
case "crashed":
|
|
68
|
+
return "error";
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface MicrosandboxProviderConfig {
|
|
73
|
+
/** Host-owned persistent data for a project's deployment runtimes. Never copied into source snapshots. */
|
|
74
|
+
projectDataDirectory?: (input: {
|
|
75
|
+
projectId: string;
|
|
76
|
+
}) => Promise<string | undefined>;
|
|
77
|
+
|
|
78
|
+
image?: string;
|
|
79
|
+
memoryMib?: number;
|
|
80
|
+
cpus?: number;
|
|
81
|
+
/** Seconds of inactivity before the sandbox auto-stops. */
|
|
82
|
+
idleTimeoutSeconds?: number;
|
|
83
|
+
namePrefix?: string;
|
|
84
|
+
/**
|
|
85
|
+
* Network reach of every sandbox, as microsandbox profiles. Unset keeps
|
|
86
|
+
* the runtime's default (public internet only). A development host adds
|
|
87
|
+
* `"private"` and `"host"` so builds can fetch from a registry served by
|
|
88
|
+
* the machine itself; production keeps sandboxes off the host network.
|
|
89
|
+
*/
|
|
90
|
+
networkProfiles?: readonly NetworkProfile[];
|
|
91
|
+
/**
|
|
92
|
+
* Shell command run once inside every new sandbox before it is handed to
|
|
93
|
+
* the caller. Defaults to installing git and bash when the image lacks
|
|
94
|
+
* them — core's agent sessions require git for change detection, and
|
|
95
|
+
* common runtime images (oven/bun, docker:dind) don't ship both. Pass an
|
|
96
|
+
* empty string to disable.
|
|
97
|
+
*/
|
|
98
|
+
setupCommand?: string;
|
|
99
|
+
/**
|
|
100
|
+
* Builds project Dockerfiles on this machine (ADR 0176), for example
|
|
101
|
+
* `dockerImageBuilder()`. Without one the provider boots registry images
|
|
102
|
+
* only and does not advertise `images.build`.
|
|
103
|
+
*/
|
|
104
|
+
imageBuilder?: ImageBuilder;
|
|
105
|
+
/**
|
|
106
|
+
* Nested containers (ADR 0176): a sandbox that asks for them gets a
|
|
107
|
+
* private disk for the image's Docker daemon, which runs inside the VM
|
|
108
|
+
* and dies with it. Default on.
|
|
109
|
+
*/
|
|
110
|
+
containers?: boolean;
|
|
111
|
+
/** Size of each container sandbox's Docker disk. Default 8 GiB. */
|
|
112
|
+
containerDiskMib?: number;
|
|
113
|
+
/**
|
|
114
|
+
* Where this machine keeps members' own harness sign-ins (ADR 0199),
|
|
115
|
+
* one home per harness and member (`machineSignInHome`). A sandbox
|
|
116
|
+
* created with `signIns` bind-mounts exactly those homes, read-write so
|
|
117
|
+
* the CLI's own token refresh keeps working. Without it the provider
|
|
118
|
+
* refuses `signIns`.
|
|
119
|
+
*/
|
|
120
|
+
signInRoot?: string;
|
|
121
|
+
/**
|
|
122
|
+
* Where the provider records when each volume was last mounted (ADR
|
|
123
|
+
* 0208). With it, sandboxes mount volumes (microsandbox named volumes:
|
|
124
|
+
* directories, or disks for exclusive ones) and the provider advertises
|
|
125
|
+
* `volumes`.
|
|
126
|
+
*/
|
|
127
|
+
stateDirectory?: string;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Labels a sandbox with the volumes it mounts, so pruning keeps them. */
|
|
131
|
+
const VOLUMES_LABEL = "work.volumes";
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Runs once per new sandbox; ~20s on first use, no-op when everything
|
|
135
|
+
* exists. Agent sessions need git and bash, and the agent runner needs Bun
|
|
136
|
+
* or Node (ADR 0198); an image without them gets them from its package
|
|
137
|
+
* manager (Node, the smaller of the two).
|
|
138
|
+
*/
|
|
139
|
+
const DEFAULT_SETUP_COMMAND =
|
|
140
|
+
"{ command -v git && command -v bash && { command -v bun || command -v node; }; } >/dev/null 2>&1 || " +
|
|
141
|
+
"if command -v apt-get >/dev/null 2>&1; then " +
|
|
142
|
+
"apt-get update -qq && apt-get install -y -qq git bash && " +
|
|
143
|
+
"{ command -v bun >/dev/null 2>&1 || command -v node >/dev/null 2>&1 || apt-get install -y -qq nodejs; }; " +
|
|
144
|
+
"elif command -v apk >/dev/null 2>&1; then apk add --no-cache -q git bash && " +
|
|
145
|
+
"{ command -v bun >/dev/null 2>&1 || command -v node >/dev/null 2>&1 || apk add --no-cache -q nodejs; }; " +
|
|
146
|
+
"else echo 'The image has neither git nor a known package manager' >&2; exit 1; fi; " +
|
|
147
|
+
// The runner needs Bun, or Node 20 or later; a distribution's Node can be older.
|
|
148
|
+
"command -v bun >/dev/null 2>&1 || node -e 'process.exit(Number(process.versions.node.split(\".\")[0]) >= 20 ? 0 : 1)' || " +
|
|
149
|
+
"{ echo 'The agent runner needs Bun, or Node 20 or later, and this image has an older Node: use an image with Bun or Node 20+' >&2; exit 1; }";
|
|
150
|
+
|
|
151
|
+
/** Start the image's Docker daemon unless it already answers. */
|
|
152
|
+
const ENSURE_DOCKER = [
|
|
153
|
+
"docker info >/dev/null 2>&1 && exit 0",
|
|
154
|
+
"command -v dockerd >/dev/null 2>&1 || { echo 'This image has no Docker daemon: use an image with Docker (docker:dind, or a Dockerfile FROM it)' >&2; exit 1; }",
|
|
155
|
+
"(dockerd >/var/log/dockerd.log 2>&1 &)",
|
|
156
|
+
"i=0; while [ $i -lt 120 ]; do docker info >/dev/null 2>&1 && exit 0; i=$((i+1)); sleep 0.5; done",
|
|
157
|
+
"tail -20 /var/log/dockerd.log >&2; exit 1",
|
|
158
|
+
].join("\n");
|
|
159
|
+
|
|
160
|
+
export class MicrosandboxSandboxProvider implements SandboxProvider {
|
|
161
|
+
readonly isolation = "sandbox";
|
|
162
|
+
readonly workspaceRoot = "/workspace";
|
|
163
|
+
/** `storageMb` sizes the VM's root disk, which holds the workspace. */
|
|
164
|
+
readonly resourceLimits = ["cpuMillis", "memoryMb", "storageMb"] as const;
|
|
165
|
+
readonly capabilities: readonly SandboxCapability[];
|
|
166
|
+
readonly deploymentRuntime: DeploymentRuntimeProvider;
|
|
167
|
+
/**
|
|
168
|
+
* Background processes (ADR 0174) run inside the VM in their own session;
|
|
169
|
+
* their output and state live in the VM, so they end when it does.
|
|
170
|
+
*/
|
|
171
|
+
readonly processes: SandboxProcessProvider = shellSandboxProcesses({
|
|
172
|
+
executeCommand: (sandboxId, command, opts) =>
|
|
173
|
+
this.executeCommand(sandboxId, command, opts),
|
|
174
|
+
workspaceRoot: this.workspaceRoot,
|
|
175
|
+
});
|
|
176
|
+
/** Named volumes kept across sandboxes (ADR 0208), with `stateDirectory`. */
|
|
177
|
+
readonly volumes?: SandboxVolumeProvider;
|
|
178
|
+
private readonly config: Required<
|
|
179
|
+
Omit<
|
|
180
|
+
MicrosandboxProviderConfig,
|
|
181
|
+
| "projectDataDirectory"
|
|
182
|
+
| "networkProfiles"
|
|
183
|
+
| "imageBuilder"
|
|
184
|
+
| "signInRoot"
|
|
185
|
+
| "stateDirectory"
|
|
186
|
+
>
|
|
187
|
+
> &
|
|
188
|
+
Pick<
|
|
189
|
+
MicrosandboxProviderConfig,
|
|
190
|
+
| "projectDataDirectory"
|
|
191
|
+
| "networkProfiles"
|
|
192
|
+
| "imageBuilder"
|
|
193
|
+
| "signInRoot"
|
|
194
|
+
| "stateDirectory"
|
|
195
|
+
>;
|
|
196
|
+
private readonly connections = new Map<string, Sandbox>();
|
|
197
|
+
private readonly usage: VolumeUsageLog | undefined;
|
|
198
|
+
|
|
199
|
+
constructor(config?: MicrosandboxProviderConfig) {
|
|
200
|
+
this.config = {
|
|
201
|
+
projectDataDirectory: config?.projectDataDirectory,
|
|
202
|
+
image: config?.image ?? DEFAULT_IMAGE,
|
|
203
|
+
memoryMib: config?.memoryMib ?? DEFAULT_MEMORY_MIB,
|
|
204
|
+
cpus: config?.cpus ?? DEFAULT_CPUS,
|
|
205
|
+
idleTimeoutSeconds: config?.idleTimeoutSeconds ?? 15 * 60,
|
|
206
|
+
namePrefix: config?.namePrefix ?? "cata",
|
|
207
|
+
networkProfiles: config?.networkProfiles,
|
|
208
|
+
setupCommand: config?.setupCommand ?? DEFAULT_SETUP_COMMAND,
|
|
209
|
+
imageBuilder: config?.imageBuilder
|
|
210
|
+
? cachedImageBuilder(config.imageBuilder)
|
|
211
|
+
: undefined,
|
|
212
|
+
containers: config?.containers ?? true,
|
|
213
|
+
containerDiskMib: config?.containerDiskMib ?? DEFAULT_CONTAINER_DISK_MIB,
|
|
214
|
+
signInRoot: config?.signInRoot,
|
|
215
|
+
stateDirectory: config?.stateDirectory,
|
|
216
|
+
};
|
|
217
|
+
const stateDirectory = this.config.stateDirectory;
|
|
218
|
+
this.usage = stateDirectory
|
|
219
|
+
? new VolumeUsageLog(path.join(stateDirectory, "volumes.json"))
|
|
220
|
+
: undefined;
|
|
221
|
+
if (this.usage)
|
|
222
|
+
this.volumes = {
|
|
223
|
+
prune: (args) => this.pruneVolumes(args),
|
|
224
|
+
removeAll: (args) => this.removeAllVolumes(args),
|
|
225
|
+
};
|
|
226
|
+
// No `network.setup` (ADR 0257): a VM's network policy is fixed when
|
|
227
|
+
// it is created.
|
|
228
|
+
this.capabilities = [
|
|
229
|
+
SANDBOX_CAPABILITIES.images,
|
|
230
|
+
SANDBOX_CAPABILITIES.egressPolicy,
|
|
231
|
+
...(this.config.containers ? [SANDBOX_CAPABILITIES.containers] : []),
|
|
232
|
+
...(this.config.imageBuilder ? [SANDBOX_CAPABILITIES.imageBuild] : []),
|
|
233
|
+
...(this.usage ? [SANDBOX_CAPABILITIES.volumes] : []),
|
|
234
|
+
];
|
|
235
|
+
this.deploymentRuntime = msbStdioRuntimeProvider({
|
|
236
|
+
connect: (sandboxId) => this.connect(sandboxId),
|
|
237
|
+
uploadFiles: (sandboxId, files, basePath) =>
|
|
238
|
+
this.uploadFiles(sandboxId, files, basePath),
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
async createSandbox(opts: CreateSandboxOpts): Promise<SandboxHandle> {
|
|
243
|
+
assertSandboxResources(opts.resources, this.resourceLimits);
|
|
244
|
+
const cpuMillis = opts.resources?.cpuMillis ?? this.config.cpus * 1000;
|
|
245
|
+
if (cpuMillis % 1000 !== 0)
|
|
246
|
+
throw new Error(
|
|
247
|
+
"Microsandbox CPU limits must be whole cores (multiples of 1000 millicores)",
|
|
248
|
+
);
|
|
249
|
+
if (opts.containers && !this.config.containers)
|
|
250
|
+
throw new Error("This machine does not run containers in sandboxes");
|
|
251
|
+
if (opts.volumes?.length && !this.usage)
|
|
252
|
+
throw new Error("This machine keeps no volumes for its sandboxes");
|
|
253
|
+
assertSandboxVolumes(opts.volumes);
|
|
254
|
+
const signIns = this.signInMounts(opts);
|
|
255
|
+
const image = await this.imageFor(opts);
|
|
256
|
+
const volumes = await this.volumeMounts({ image, volumes: opts.volumes });
|
|
257
|
+
const name = `${this.config.namePrefix}-${crypto.randomUUID().slice(0, 12)}`;
|
|
258
|
+
let builder = Sandbox.builder(name)
|
|
259
|
+
.image(image)
|
|
260
|
+
.memory(opts.resources?.memoryMb ?? this.config.memoryMib)
|
|
261
|
+
.cpus(cpuMillis / 1000)
|
|
262
|
+
.idleTimeout(
|
|
263
|
+
opts.autoStopInterval !== undefined
|
|
264
|
+
? opts.autoStopInterval * 60
|
|
265
|
+
: this.config.idleTimeoutSeconds,
|
|
266
|
+
)
|
|
267
|
+
// The workdir must exist before boot; images like oven/bun don't ship it.
|
|
268
|
+
.patch((patch) => patch.mkdir(this.workspaceRoot, { mode: 0o755 }))
|
|
269
|
+
.workdir(this.workspaceRoot)
|
|
270
|
+
.detached(true);
|
|
271
|
+
if (opts.resources?.storageMb)
|
|
272
|
+
builder = builder.rootDisk(opts.resources.storageMb);
|
|
273
|
+
if (opts.envVars) builder = builder.envs(opts.envVars);
|
|
274
|
+
const persistent = volumes.filter((volume) => !volume.temporary);
|
|
275
|
+
const labels = {
|
|
276
|
+
...opts.labels,
|
|
277
|
+
...(persistent.length > 0
|
|
278
|
+
? { [VOLUMES_LABEL]: persistent.map((volume) => volume.key).join(",") }
|
|
279
|
+
: {}),
|
|
280
|
+
};
|
|
281
|
+
if (Object.keys(labels).length > 0) builder = builder.labels(labels);
|
|
282
|
+
const policy = microsandboxEgressPolicy({
|
|
283
|
+
egress: opts.egress,
|
|
284
|
+
profiles: this.config.networkProfiles,
|
|
285
|
+
});
|
|
286
|
+
if (policy) builder = builder.network((network) => network.policy(policy));
|
|
287
|
+
for (const volume of volumes)
|
|
288
|
+
builder = builder.volume(volume.target, volume.mount);
|
|
289
|
+
this.usage?.touch(persistent.map((volume) => volume.key));
|
|
290
|
+
// A volume the Environment keeps at the Docker data root replaces the
|
|
291
|
+
// sandbox's own Docker disk.
|
|
292
|
+
if (
|
|
293
|
+
opts.containers &&
|
|
294
|
+
!volumes.some((volume) => volume.target === DOCKER_DATA)
|
|
295
|
+
) {
|
|
296
|
+
// Docker's overlay storage cannot sit on the VM's overlay root; a
|
|
297
|
+
// disk owned by this sandbox can, and is removed with it.
|
|
298
|
+
builder = builder.volume(DOCKER_DATA, (mount) =>
|
|
299
|
+
mount.owned({ kind: "disk", sizeMib: this.config.containerDiskMib }),
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
const dataDirectory =
|
|
303
|
+
opts.labels?.purpose === "deployment-runtime" && opts.labels.projectId
|
|
304
|
+
? await this.config.projectDataDirectory?.({
|
|
305
|
+
projectId: opts.labels.projectId,
|
|
306
|
+
})
|
|
307
|
+
: undefined;
|
|
308
|
+
if (dataDirectory) {
|
|
309
|
+
builder = builder
|
|
310
|
+
.volume(APP_DATA_MOUNT, (mount) => mount.bind(dataDirectory))
|
|
311
|
+
.env(APP_DATA_ENV, APP_DATA_MOUNT);
|
|
312
|
+
}
|
|
313
|
+
for (const signIn of signIns)
|
|
314
|
+
builder = builder.volume(signIn.guest, (mount) =>
|
|
315
|
+
mount.bind(signIn.host),
|
|
316
|
+
);
|
|
317
|
+
const sandbox = await builder.create();
|
|
318
|
+
this.connections.set(name, sandbox);
|
|
319
|
+
const prepare = async (command: string, what: string) => {
|
|
320
|
+
const result = await shellIn(sandbox, command, 300);
|
|
321
|
+
if (result.exitCode !== 0) {
|
|
322
|
+
await this.destroySandbox(name).catch(() => {});
|
|
323
|
+
throw new Error(`${what} failed: ${result.result}`);
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
if (this.config.setupCommand)
|
|
327
|
+
await prepare(
|
|
328
|
+
this.config.setupCommand,
|
|
329
|
+
opts.egress?.mode === "allowlist"
|
|
330
|
+
? "Sandbox setup command (egress is restricted, so the image must already have git, bash, and Bun or Node)"
|
|
331
|
+
: "Sandbox setup command",
|
|
332
|
+
);
|
|
333
|
+
if (opts.containers)
|
|
334
|
+
await prepare(
|
|
335
|
+
`touch ${CONTAINERS_MARKER}\n${ENSURE_DOCKER}`,
|
|
336
|
+
"Starting the sandbox's container runtime",
|
|
337
|
+
);
|
|
338
|
+
return {
|
|
339
|
+
id: name,
|
|
340
|
+
providerId: name,
|
|
341
|
+
sandboxType: "execution",
|
|
342
|
+
status: "started",
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async startSandbox(sandboxId: string): Promise<void> {
|
|
347
|
+
const handle = await Sandbox.get(sandboxId);
|
|
348
|
+
if (handle.status === "running") return;
|
|
349
|
+
this.connections.set(sandboxId, await booted(await bringUp(handle)));
|
|
350
|
+
this.usage?.touch(volumeKeysOf(handle));
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* How each volume mounts (ADR 0208): a named volume, a directory, or a
|
|
355
|
+
* disk for an exclusive one (a Docker data root needs a filesystem of
|
|
356
|
+
* its own); a temporary one is owned by the sandbox and removed with it.
|
|
357
|
+
*/
|
|
358
|
+
private async volumeMounts(args: {
|
|
359
|
+
image: string;
|
|
360
|
+
volumes: readonly SandboxVolume[] | undefined;
|
|
361
|
+
}): Promise<
|
|
362
|
+
Array<{
|
|
363
|
+
key: string;
|
|
364
|
+
temporary: boolean;
|
|
365
|
+
target: string;
|
|
366
|
+
mount: MountConfigure;
|
|
367
|
+
}>
|
|
368
|
+
> {
|
|
369
|
+
const volumes = args.volumes ?? [];
|
|
370
|
+
if (volumes.length === 0) return [];
|
|
371
|
+
// `~` is the image user's home; an image not yet cached counts as root's.
|
|
372
|
+
const detail = volumes.some((volume) => volume.path.startsWith("~"))
|
|
373
|
+
? await Image.inspect(args.image).catch(() => undefined)
|
|
374
|
+
: undefined;
|
|
375
|
+
const home = imageUserHome({
|
|
376
|
+
user: detail?.config?.user ?? null,
|
|
377
|
+
env: detail?.config?.env ?? null,
|
|
378
|
+
});
|
|
379
|
+
// A disk keeps the size it was made with: one that exists mounts as is.
|
|
380
|
+
const existing = new Set(
|
|
381
|
+
(await Volume.list().catch(() => [])).map((volume) => volume.name),
|
|
382
|
+
);
|
|
383
|
+
return volumes.map((volume) => {
|
|
384
|
+
const disk = volume.exclusive === true;
|
|
385
|
+
const sizeMib = volume.sizeMb ?? this.config.containerDiskMib;
|
|
386
|
+
return {
|
|
387
|
+
key: volume.key,
|
|
388
|
+
temporary: volume.temporary === true,
|
|
389
|
+
target: volumeMountPath({ path: volume.path, home }),
|
|
390
|
+
mount: (mount) =>
|
|
391
|
+
volume.temporary
|
|
392
|
+
? mount.owned(disk ? { kind: "disk", sizeMib } : { kind: "dir" })
|
|
393
|
+
: existing.has(volume.key)
|
|
394
|
+
? mount.named(volume.key)
|
|
395
|
+
: mount.namedWith(
|
|
396
|
+
volume.key,
|
|
397
|
+
"ensure-exists",
|
|
398
|
+
disk ? "disk" : "dir",
|
|
399
|
+
disk ? sizeMib : undefined,
|
|
400
|
+
),
|
|
401
|
+
};
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** Remove volumes no sandbox mounts that went unused for `unusedForMs`. */
|
|
406
|
+
private async pruneVolumes(args: { unusedForMs: number }): Promise<string[]> {
|
|
407
|
+
const usage = this.usage;
|
|
408
|
+
if (!usage) return [];
|
|
409
|
+
const mounted = await mountedVolumeKeys();
|
|
410
|
+
const removed: string[] = [];
|
|
411
|
+
for (const volume of await Volume.list()) {
|
|
412
|
+
if (!VOLUME_KEY_PATTERN.test(volume.name) || mounted.has(volume.name))
|
|
413
|
+
continue;
|
|
414
|
+
if (
|
|
415
|
+
!usage.unused({
|
|
416
|
+
key: volume.name,
|
|
417
|
+
unusedForMs: args.unusedForMs,
|
|
418
|
+
...(volume.createdAt ? { since: volume.createdAt.getTime() } : {}),
|
|
419
|
+
})
|
|
420
|
+
)
|
|
421
|
+
continue;
|
|
422
|
+
await Volume.remove(volume.name).then(
|
|
423
|
+
() => removed.push(volume.name),
|
|
424
|
+
() => {},
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
usage.forget(removed);
|
|
428
|
+
return removed;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Remove every volume. With `destroySandboxes`, the sandboxes that mount
|
|
433
|
+
* any first (a pooled machine's reset); without, mounted ones are kept.
|
|
434
|
+
*/
|
|
435
|
+
private async removeAllVolumes(args?: {
|
|
436
|
+
destroySandboxes?: boolean;
|
|
437
|
+
}): Promise<void> {
|
|
438
|
+
if (args?.destroySandboxes)
|
|
439
|
+
for (const name of await sandboxesMountingVolumes())
|
|
440
|
+
await this.destroySandbox(name);
|
|
441
|
+
const mounted = await mountedVolumeKeys();
|
|
442
|
+
const kept: string[] = [];
|
|
443
|
+
const removed: string[] = [];
|
|
444
|
+
for (const volume of await Volume.list()) {
|
|
445
|
+
if (!VOLUME_KEY_PATTERN.test(volume.name)) continue;
|
|
446
|
+
if (mounted.has(volume.name)) kept.push(volume.name);
|
|
447
|
+
else {
|
|
448
|
+
await Volume.remove(volume.name);
|
|
449
|
+
removed.push(volume.name);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
this.usage?.forget(removed);
|
|
453
|
+
if (kept.length > 0)
|
|
454
|
+
throw new Error(
|
|
455
|
+
`Volumes still mounted by sandboxes were kept: ${kept.join(", ")}. Destroy those sandboxes first.`,
|
|
456
|
+
);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* The sign-in homes a sandbox mounts (ADR 0199): each one this machine
|
|
461
|
+
* keeps for the member named, nothing else of the sign-in root.
|
|
462
|
+
*/
|
|
463
|
+
private signInMounts(
|
|
464
|
+
opts: CreateSandboxOpts,
|
|
465
|
+
): Array<{ host: string; guest: string }> {
|
|
466
|
+
const requested = opts.signIns ?? [];
|
|
467
|
+
if (requested.length === 0) return [];
|
|
468
|
+
const root = this.config.signInRoot;
|
|
469
|
+
if (!root)
|
|
470
|
+
throw new Error(
|
|
471
|
+
"This machine keeps no members' sign-ins, so its sandboxes cannot run on one",
|
|
472
|
+
);
|
|
473
|
+
return requested.map((signIn) => {
|
|
474
|
+
const host = machineSignInHome({ root, ...signIn });
|
|
475
|
+
if (!fs.statSync(host, { throwIfNoEntry: false })?.isDirectory())
|
|
476
|
+
throw new Error(
|
|
477
|
+
`This machine has no ${signIn.harness} sign-in for ${signIn.member}. Sign in on it with: work worker sign-in ${signIn.harness} --member ${signIn.member}`,
|
|
478
|
+
);
|
|
479
|
+
return {
|
|
480
|
+
host,
|
|
481
|
+
guest: signInHomePath({
|
|
482
|
+
workspaceRoot: this.workspaceRoot,
|
|
483
|
+
harness: signIn.harness,
|
|
484
|
+
}),
|
|
485
|
+
};
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** The image reference to boot, building a Dockerfile image when needed. */
|
|
490
|
+
private async imageFor(opts: CreateSandboxOpts): Promise<string> {
|
|
491
|
+
const image = opts.image;
|
|
492
|
+
if (!image) return opts.snapshotName ?? this.config.image;
|
|
493
|
+
if (image.kind === "oci") return image.reference;
|
|
494
|
+
if (!this.config.imageBuilder)
|
|
495
|
+
throw new Error(
|
|
496
|
+
`This machine cannot build ${image.path}; place the Environment on a machine that builds images`,
|
|
497
|
+
);
|
|
498
|
+
const reference = dockerfileImageReference(image.digest);
|
|
499
|
+
await this.config.imageBuilder.build({
|
|
500
|
+
reference,
|
|
501
|
+
dockerfile: image.content,
|
|
502
|
+
});
|
|
503
|
+
return reference;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
async stopSandbox(sandboxId: string): Promise<void> {
|
|
507
|
+
this.connections.delete(sandboxId);
|
|
508
|
+
const handle = await Sandbox.get(sandboxId);
|
|
509
|
+
await handle.stop();
|
|
510
|
+
await this.deploymentRuntime.releaseSandbox?.({ sandboxId });
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
async destroySandbox(sandboxId: string): Promise<void> {
|
|
514
|
+
const connected = this.connections.get(sandboxId);
|
|
515
|
+
this.connections.delete(sandboxId);
|
|
516
|
+
const handle = await Sandbox.get(sandboxId).catch((error: unknown) => {
|
|
517
|
+
if (
|
|
518
|
+
error instanceof Error &&
|
|
519
|
+
"code" in error &&
|
|
520
|
+
error.code === "sandboxNotFound"
|
|
521
|
+
)
|
|
522
|
+
return undefined;
|
|
523
|
+
throw error;
|
|
524
|
+
});
|
|
525
|
+
if (!handle) {
|
|
526
|
+
await this.deploymentRuntime.releaseSandbox?.({ sandboxId });
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
if (handle.status === "running") {
|
|
530
|
+
// A disk volume's writes wait in the guest's cache; killing the VM
|
|
531
|
+
// would lose them, so they reach the disk first. A VM that does not
|
|
532
|
+
// answer within the minute is killed anyway: destroying never hangs.
|
|
533
|
+
if (volumeKeysOf(handle).length > 0)
|
|
534
|
+
await withTimeout(
|
|
535
|
+
(async () =>
|
|
536
|
+
shellIn(connected ?? (await handle.connect()), "sync", 60))(),
|
|
537
|
+
60_000,
|
|
538
|
+
).catch(() => {});
|
|
539
|
+
await handle.kill();
|
|
540
|
+
}
|
|
541
|
+
await handle.remove();
|
|
542
|
+
await this.deploymentRuntime.releaseSandbox?.({ sandboxId });
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
async getSandboxStatus(sandboxId: string): Promise<SandboxStatus> {
|
|
546
|
+
const handle = await Sandbox.get(sandboxId);
|
|
547
|
+
return mapMsbStatus(handle.status);
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
async executeCommand(
|
|
551
|
+
sandboxId: string,
|
|
552
|
+
command: string,
|
|
553
|
+
opts?: ExecOpts,
|
|
554
|
+
): Promise<ExecResult> {
|
|
555
|
+
const sandbox = await this.connect(sandboxId);
|
|
556
|
+
const output = await sandbox.execWith("bash", (exec) => {
|
|
557
|
+
exec = exec.args(["-lc", command]);
|
|
558
|
+
if (opts?.cwd) exec = exec.cwd(opts.cwd);
|
|
559
|
+
if (opts?.env) exec = exec.envs(opts.env);
|
|
560
|
+
// ExecOpts.timeout is in seconds; msb wants ms.
|
|
561
|
+
if (opts?.timeout) exec = exec.timeout(opts.timeout * 1_000);
|
|
562
|
+
return exec;
|
|
563
|
+
});
|
|
564
|
+
const stdout = output.stdout();
|
|
565
|
+
const stderr = output.stderr();
|
|
566
|
+
return {
|
|
567
|
+
exitCode: output.code,
|
|
568
|
+
result:
|
|
569
|
+
stderr.length > 0 ? `${stdout}${stdout ? "\n" : ""}${stderr}` : stdout,
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
async uploadFiles(
|
|
574
|
+
sandboxId: string,
|
|
575
|
+
files: Record<string, string>,
|
|
576
|
+
basePath: string,
|
|
577
|
+
): Promise<void> {
|
|
578
|
+
const sandbox = await this.connect(sandboxId);
|
|
579
|
+
const fs = sandbox.fs();
|
|
580
|
+
const dirs = new Set<string>();
|
|
581
|
+
for (const filePath of Object.keys(files)) {
|
|
582
|
+
const destination = basePath ? `${basePath}/${filePath}` : filePath;
|
|
583
|
+
const dir = destination.slice(0, destination.lastIndexOf("/"));
|
|
584
|
+
if (dir) dirs.add(dir);
|
|
585
|
+
}
|
|
586
|
+
if (dirs.size > 0) {
|
|
587
|
+
await sandbox.shell(
|
|
588
|
+
`mkdir -p ${[...dirs].map((dir) => `'${dir.replaceAll("'", `'\\''`)}'`).join(" ")}`,
|
|
589
|
+
);
|
|
590
|
+
}
|
|
591
|
+
await Promise.all(
|
|
592
|
+
Object.entries(files).map(([filePath, content]) =>
|
|
593
|
+
fs.write(basePath ? `${basePath}/${filePath}` : filePath, content),
|
|
594
|
+
),
|
|
595
|
+
);
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
async downloadFile(sandboxId: string, filePath: string): Promise<string> {
|
|
599
|
+
const sandbox = await this.connect(sandboxId);
|
|
600
|
+
return sandbox.fs().readToString(filePath);
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
async gitClone(
|
|
604
|
+
sandboxId: string,
|
|
605
|
+
url: string,
|
|
606
|
+
path: string,
|
|
607
|
+
opts?: GitCloneOpts,
|
|
608
|
+
): Promise<void> {
|
|
609
|
+
const cloneUrl = gitCloneUrl(url, opts);
|
|
610
|
+
const branchArg = opts?.branch
|
|
611
|
+
? ` --branch ${shellQuote(opts.branch)}`
|
|
612
|
+
: "";
|
|
613
|
+
const clone = await this.executeCommand(
|
|
614
|
+
sandboxId,
|
|
615
|
+
`git clone${branchArg} ${shellQuote(cloneUrl)} ${shellQuote(path)}`,
|
|
616
|
+
{ timeout: 120 },
|
|
617
|
+
);
|
|
618
|
+
if (clone.exitCode !== 0) {
|
|
619
|
+
throw gitCloneFailure({
|
|
620
|
+
output: clone.result,
|
|
621
|
+
...(opts ? { opts } : {}),
|
|
622
|
+
});
|
|
623
|
+
}
|
|
624
|
+
if (opts?.commitId) {
|
|
625
|
+
await this.gitCheckout(sandboxId, path, opts.commitId);
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
async gitCheckout(
|
|
630
|
+
sandboxId: string,
|
|
631
|
+
path: string,
|
|
632
|
+
ref: string,
|
|
633
|
+
): Promise<void> {
|
|
634
|
+
const result = await this.executeCommand(
|
|
635
|
+
sandboxId,
|
|
636
|
+
`git -C ${shellQuote(path)} checkout ${shellQuote(ref)}`,
|
|
637
|
+
{ timeout: 60 },
|
|
638
|
+
);
|
|
639
|
+
if (result.exitCode !== 0) {
|
|
640
|
+
throw new Error(`git checkout failed: ${result.result}`);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
private async connect(sandboxId: string): Promise<Sandbox> {
|
|
645
|
+
const cached = this.connections.get(sandboxId);
|
|
646
|
+
if (cached) return cached;
|
|
647
|
+
const handle = await Sandbox.get(sandboxId);
|
|
648
|
+
const sandbox =
|
|
649
|
+
handle.status === "running"
|
|
650
|
+
? await handle.connect()
|
|
651
|
+
: await booted(await bringUp(handle));
|
|
652
|
+
this.connections.set(sandboxId, sandbox);
|
|
653
|
+
return sandbox;
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* A live connection to a sandbox that is not running. A paused VM resumes in
|
|
659
|
+
* place (restarting one is refused by msb); anything else boots.
|
|
660
|
+
*/
|
|
661
|
+
async function bringUp(
|
|
662
|
+
handle: Awaited<ReturnType<typeof Sandbox.get>>,
|
|
663
|
+
): Promise<Sandbox> {
|
|
664
|
+
if (handle.status === "paused") {
|
|
665
|
+
await handle.resume();
|
|
666
|
+
return handle.connect();
|
|
667
|
+
}
|
|
668
|
+
return handle.startDetached();
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/** Run a POSIX shell command: images without bash still prepare. */
|
|
672
|
+
async function shellIn(
|
|
673
|
+
sandbox: Sandbox,
|
|
674
|
+
command: string,
|
|
675
|
+
timeoutSeconds: number,
|
|
676
|
+
): Promise<ExecResult> {
|
|
677
|
+
const output = await sandbox.execWith("sh", (exec) =>
|
|
678
|
+
exec.args(["-c", command]).timeout(timeoutSeconds * 1_000),
|
|
679
|
+
);
|
|
680
|
+
const stdout = output.stdout();
|
|
681
|
+
const stderr = output.stderr();
|
|
682
|
+
return {
|
|
683
|
+
exitCode: output.code,
|
|
684
|
+
result:
|
|
685
|
+
stderr.length > 0 ? `${stdout}${stdout ? "\n" : ""}${stderr}` : stdout,
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/** Restart a container sandbox's Docker daemon after its VM boots again. */
|
|
690
|
+
async function booted(sandbox: Sandbox): Promise<Sandbox> {
|
|
691
|
+
const result = await shellIn(
|
|
692
|
+
sandbox,
|
|
693
|
+
`[ -f ${CONTAINERS_MARKER} ] || exit 0\n${ENSURE_DOCKER}`,
|
|
694
|
+
120,
|
|
695
|
+
);
|
|
696
|
+
if (result.exitCode !== 0)
|
|
697
|
+
throw new Error(
|
|
698
|
+
`The sandbox's container runtime did not start: ${result.result}`,
|
|
699
|
+
);
|
|
700
|
+
return sandbox;
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/** How one volume mounts, as the sandbox builder takes it. */
|
|
704
|
+
type MountConfigure = Parameters<
|
|
705
|
+
ReturnType<typeof Sandbox.builder>["volume"]
|
|
706
|
+
>[1];
|
|
707
|
+
|
|
708
|
+
/** The volumes a sandbox was created with, from its labels. */
|
|
709
|
+
function volumeKeysOf(handle: { config(): Record<string, unknown> }): string[] {
|
|
710
|
+
try {
|
|
711
|
+
const labels = handle.config().labels;
|
|
712
|
+
const keys =
|
|
713
|
+
typeof labels === "object" && labels !== null
|
|
714
|
+
? Reflect.get(labels, VOLUMES_LABEL)
|
|
715
|
+
: undefined;
|
|
716
|
+
return typeof keys === "string" ? keys.split(",").filter(Boolean) : [];
|
|
717
|
+
} catch {
|
|
718
|
+
return [];
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/** Every volume an existing sandbox (running or not) mounts. */
|
|
723
|
+
async function mountedVolumeKeys(): Promise<Set<string>> {
|
|
724
|
+
const keys = new Set<string>();
|
|
725
|
+
for (const handle of await everySandbox())
|
|
726
|
+
for (const key of volumeKeysOf(handle)) keys.add(key);
|
|
727
|
+
return keys;
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/** The sandboxes (running or not) that mount any volume. */
|
|
731
|
+
async function sandboxesMountingVolumes(): Promise<string[]> {
|
|
732
|
+
return (await everySandbox())
|
|
733
|
+
.filter((handle) => volumeKeysOf(handle).length > 0)
|
|
734
|
+
.map((handle) => handle.name);
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
async function everySandbox(): Promise<
|
|
738
|
+
Awaited<ReturnType<typeof Sandbox.list>>["sandboxes"]
|
|
739
|
+
> {
|
|
740
|
+
const handles: Awaited<ReturnType<typeof Sandbox.list>>["sandboxes"] = [];
|
|
741
|
+
let cursor: string | undefined;
|
|
742
|
+
do {
|
|
743
|
+
const after = cursor;
|
|
744
|
+
const page = await Sandbox.listWith((list) =>
|
|
745
|
+
after ? list.cursor(after) : list,
|
|
746
|
+
);
|
|
747
|
+
handles.push(...page.sandboxes);
|
|
748
|
+
cursor = page.nextCursor;
|
|
749
|
+
} while (cursor);
|
|
750
|
+
return handles;
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
/** `promise`, or a rejection after `ms`. */
|
|
754
|
+
async function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
|
|
755
|
+
let timer: NodeJS.Timeout | undefined;
|
|
756
|
+
try {
|
|
757
|
+
return await Promise.race([
|
|
758
|
+
promise,
|
|
759
|
+
new Promise<never>((_, reject) => {
|
|
760
|
+
timer = setTimeout(
|
|
761
|
+
() => reject(new Error(`No answer within ${ms}ms`)),
|
|
762
|
+
ms,
|
|
763
|
+
);
|
|
764
|
+
}),
|
|
765
|
+
]);
|
|
766
|
+
} finally {
|
|
767
|
+
clearTimeout(timer);
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
function shellQuote(value: string): string {
|
|
772
|
+
return `'${value.replaceAll("'", `'\\''`)}'`;
|
|
773
|
+
}
|