@catamorphic/microsandbox 0.0.0-stage → 0.1.0-alpha.30
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
package/dist/index.js
ADDED
|
@@ -0,0 +1,683 @@
|
|
|
1
|
+
// src/egress-policy.ts
|
|
2
|
+
import {
|
|
3
|
+
Destination,
|
|
4
|
+
NetworkPolicy,
|
|
5
|
+
PortRange,
|
|
6
|
+
Rule
|
|
7
|
+
} from "microsandbox";
|
|
8
|
+
var IPV4 = /^(\d{1,3})(\.\d{1,3}){3}$/;
|
|
9
|
+
function parseEntry(entry) {
|
|
10
|
+
const bracketed = entry.match(/^\[([^\]]+)\](?::(\d{1,5}))?$/);
|
|
11
|
+
if (bracketed)
|
|
12
|
+
return {
|
|
13
|
+
host: bracketed[1] ?? "",
|
|
14
|
+
...bracketed[2] ? { port: Number(bracketed[2]) } : {}
|
|
15
|
+
};
|
|
16
|
+
const withPort = entry.match(/^([^:]+):(\d{1,5})$/);
|
|
17
|
+
if (withPort)
|
|
18
|
+
return { host: withPort[1] ?? "", port: Number(withPort[2]) };
|
|
19
|
+
return { host: entry };
|
|
20
|
+
}
|
|
21
|
+
function destinationFor(host) {
|
|
22
|
+
if (host === "localhost" || host.startsWith("127.") || host === "::1")
|
|
23
|
+
return Destination.group("host");
|
|
24
|
+
if (IPV4.test(host))
|
|
25
|
+
return Destination.cidr(`${host}/32`);
|
|
26
|
+
if (host.includes(":"))
|
|
27
|
+
return Destination.cidr(`${host}/128`);
|
|
28
|
+
if (host.startsWith("*."))
|
|
29
|
+
return Destination.domainSuffix(host.slice(2));
|
|
30
|
+
return Destination.domain(host);
|
|
31
|
+
}
|
|
32
|
+
function allowRule(entry) {
|
|
33
|
+
const { host, port } = parseEntry(entry);
|
|
34
|
+
const rule = Rule.allowEgress(destinationFor(host));
|
|
35
|
+
return port === undefined ? rule : { ...rule, protocols: ["tcp"], ports: [PortRange.single(port)] };
|
|
36
|
+
}
|
|
37
|
+
function microsandboxEgressPolicy(args) {
|
|
38
|
+
if (!args.egress || args.egress.mode === "open") {
|
|
39
|
+
return args.profiles && args.profiles.length > 0 ? NetworkPolicy.fromProfiles(args.profiles) : undefined;
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
defaultEgress: "deny",
|
|
43
|
+
defaultIngress: "allow",
|
|
44
|
+
rules: [
|
|
45
|
+
Rule.allowDns(),
|
|
46
|
+
...args.egress.allow.map((entry) => allowRule(entry.toLowerCase()))
|
|
47
|
+
]
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
// src/image-builder.ts
|
|
51
|
+
import { execFile } from "node:child_process";
|
|
52
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
53
|
+
import os from "node:os";
|
|
54
|
+
import path from "node:path";
|
|
55
|
+
import { promisify } from "node:util";
|
|
56
|
+
import { Image } from "microsandbox";
|
|
57
|
+
var run = promisify(execFile);
|
|
58
|
+
function dockerImageBuilder(options) {
|
|
59
|
+
const command = options?.command ?? "docker";
|
|
60
|
+
const timeout = (options?.timeoutSeconds ?? 30 * 60) * 1000;
|
|
61
|
+
return {
|
|
62
|
+
build: async ({ reference, dockerfile }) => {
|
|
63
|
+
const directory = await mkdtemp(path.join(os.tmpdir(), "work-image-"));
|
|
64
|
+
try {
|
|
65
|
+
await writeFile(path.join(directory, "Dockerfile"), dockerfile);
|
|
66
|
+
await run(command, ["build", "-t", reference, directory], {
|
|
67
|
+
timeout,
|
|
68
|
+
...options?.env ? { env: options.env } : {},
|
|
69
|
+
maxBuffer: 64 * 1024 * 1024
|
|
70
|
+
}).catch((error) => {
|
|
71
|
+
throw new Error(`Image build failed: ${error instanceof Error && "stderr" in error ? String(error.stderr).slice(-2000) : String(error)}`);
|
|
72
|
+
});
|
|
73
|
+
const archive = path.join(directory, "image.tar");
|
|
74
|
+
await run(command, ["save", "-o", archive, reference], {
|
|
75
|
+
timeout,
|
|
76
|
+
...options?.env ? { env: options.env } : {}
|
|
77
|
+
});
|
|
78
|
+
await Image.load(archive, { tag: reference });
|
|
79
|
+
} finally {
|
|
80
|
+
await rm(directory, { recursive: true, force: true });
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
function cachedImageBuilder(builder) {
|
|
86
|
+
const inFlight = new Map;
|
|
87
|
+
return {
|
|
88
|
+
build: (args) => {
|
|
89
|
+
const running = inFlight.get(args.reference);
|
|
90
|
+
if (running)
|
|
91
|
+
return running;
|
|
92
|
+
const build = (async () => {
|
|
93
|
+
const cached = await Image.get(args.reference).catch(() => {
|
|
94
|
+
return;
|
|
95
|
+
});
|
|
96
|
+
if (!cached)
|
|
97
|
+
await builder.build(args);
|
|
98
|
+
})().finally(() => inFlight.delete(args.reference));
|
|
99
|
+
inFlight.set(args.reference, build);
|
|
100
|
+
return build;
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
// src/sandbox-provider.ts
|
|
105
|
+
import fs from "node:fs";
|
|
106
|
+
import path2 from "node:path";
|
|
107
|
+
import {
|
|
108
|
+
assertSandboxResources,
|
|
109
|
+
assertSandboxVolumes,
|
|
110
|
+
dockerfileImageReference,
|
|
111
|
+
gitCloneFailure,
|
|
112
|
+
gitCloneUrl,
|
|
113
|
+
imageUserHome,
|
|
114
|
+
machineSignInHome,
|
|
115
|
+
SANDBOX_CAPABILITIES,
|
|
116
|
+
shellSandboxProcesses,
|
|
117
|
+
signInHomePath,
|
|
118
|
+
VOLUME_KEY_PATTERN,
|
|
119
|
+
VolumeUsageLog,
|
|
120
|
+
volumeMountPath
|
|
121
|
+
} from "@catamorphic/sandbox";
|
|
122
|
+
import {
|
|
123
|
+
APP_DATA_ENV,
|
|
124
|
+
APP_DATA_MOUNT
|
|
125
|
+
} from "@catamorphic/workflow/project-layout";
|
|
126
|
+
import {
|
|
127
|
+
Image as Image2,
|
|
128
|
+
Sandbox,
|
|
129
|
+
Volume
|
|
130
|
+
} from "microsandbox";
|
|
131
|
+
|
|
132
|
+
// src/stdio-runtime-provider.ts
|
|
133
|
+
import {
|
|
134
|
+
StdioDeploymentRuntimeProvider
|
|
135
|
+
} from "@catamorphic/sandbox";
|
|
136
|
+
function msbStdioRuntimeProvider(options) {
|
|
137
|
+
return new StdioDeploymentRuntimeProvider({
|
|
138
|
+
uploadFiles: options.uploadFiles,
|
|
139
|
+
mkdirp: async (sandboxId, directory) => {
|
|
140
|
+
const sandbox = await options.connect(sandboxId);
|
|
141
|
+
await sandbox.shell(`mkdir -p '${directory.replaceAll("'", `'\\''`)}'`);
|
|
142
|
+
},
|
|
143
|
+
openSupervisor: async (args) => {
|
|
144
|
+
const sandbox = await options.connect(args.sandboxId);
|
|
145
|
+
const handle = await sandbox.execStreamWith("bun", (exec) => exec.args(["run", "entry.mjs"]).cwd(args.runtimeDirectory).envs(args.env).stdinPipe());
|
|
146
|
+
const stdin = await handle.takeStdin();
|
|
147
|
+
if (!stdin) {
|
|
148
|
+
await handle.kill().catch(() => {});
|
|
149
|
+
throw new Error("Supervisor exec stream has no stdin sink");
|
|
150
|
+
}
|
|
151
|
+
return {
|
|
152
|
+
write: (data) => stdin.write(data),
|
|
153
|
+
kill: async () => {
|
|
154
|
+
await handle.kill();
|
|
155
|
+
},
|
|
156
|
+
stdout: execStdout(handle)
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
async function* execStdout(handle) {
|
|
162
|
+
for await (const event of handle) {
|
|
163
|
+
if (event.kind === "stdout")
|
|
164
|
+
yield event.data;
|
|
165
|
+
if (event.kind === "exited")
|
|
166
|
+
break;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// src/sandbox-provider.ts
|
|
171
|
+
var DEFAULT_IMAGE = "oven/bun";
|
|
172
|
+
var DEFAULT_MEMORY_MIB = 1024;
|
|
173
|
+
var DEFAULT_CPUS = 1;
|
|
174
|
+
var DEFAULT_CONTAINER_DISK_MIB = 8192;
|
|
175
|
+
var CONTAINERS_MARKER = "/etc/work-containers";
|
|
176
|
+
var DOCKER_DATA = "/var/lib/docker";
|
|
177
|
+
function mapMsbStatus(status) {
|
|
178
|
+
switch (status) {
|
|
179
|
+
case "created":
|
|
180
|
+
case "starting":
|
|
181
|
+
return "creating";
|
|
182
|
+
case "running":
|
|
183
|
+
case "draining":
|
|
184
|
+
return "started";
|
|
185
|
+
case "paused":
|
|
186
|
+
case "stopped":
|
|
187
|
+
return "stopped";
|
|
188
|
+
case "crashed":
|
|
189
|
+
return "error";
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
var VOLUMES_LABEL = "work.volumes";
|
|
193
|
+
var DEFAULT_SETUP_COMMAND = "{ command -v git && command -v bash && { command -v bun || command -v node; }; } >/dev/null 2>&1 || " + "if command -v apt-get >/dev/null 2>&1; then " + "apt-get update -qq && apt-get install -y -qq git bash && " + "{ command -v bun >/dev/null 2>&1 || command -v node >/dev/null 2>&1 || apt-get install -y -qq nodejs; }; " + "elif command -v apk >/dev/null 2>&1; then apk add --no-cache -q git bash && " + "{ command -v bun >/dev/null 2>&1 || command -v node >/dev/null 2>&1 || apk add --no-cache -q nodejs; }; " + "else echo 'The image has neither git nor a known package manager' >&2; exit 1; fi; " + `command -v bun >/dev/null 2>&1 || node -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 20 ? 0 : 1)' || ` + "{ 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; }";
|
|
194
|
+
var ENSURE_DOCKER = [
|
|
195
|
+
"docker info >/dev/null 2>&1 && exit 0",
|
|
196
|
+
"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; }",
|
|
197
|
+
"(dockerd >/var/log/dockerd.log 2>&1 &)",
|
|
198
|
+
"i=0; while [ $i -lt 120 ]; do docker info >/dev/null 2>&1 && exit 0; i=$((i+1)); sleep 0.5; done",
|
|
199
|
+
"tail -20 /var/log/dockerd.log >&2; exit 1"
|
|
200
|
+
].join(`
|
|
201
|
+
`);
|
|
202
|
+
|
|
203
|
+
class MicrosandboxSandboxProvider {
|
|
204
|
+
isolation = "sandbox";
|
|
205
|
+
workspaceRoot = "/workspace";
|
|
206
|
+
resourceLimits = ["cpuMillis", "memoryMb", "storageMb"];
|
|
207
|
+
capabilities;
|
|
208
|
+
deploymentRuntime;
|
|
209
|
+
processes = shellSandboxProcesses({
|
|
210
|
+
executeCommand: (sandboxId, command, opts) => this.executeCommand(sandboxId, command, opts),
|
|
211
|
+
workspaceRoot: this.workspaceRoot
|
|
212
|
+
});
|
|
213
|
+
volumes;
|
|
214
|
+
config;
|
|
215
|
+
connections = new Map;
|
|
216
|
+
usage;
|
|
217
|
+
constructor(config) {
|
|
218
|
+
this.config = {
|
|
219
|
+
projectDataDirectory: config?.projectDataDirectory,
|
|
220
|
+
image: config?.image ?? DEFAULT_IMAGE,
|
|
221
|
+
memoryMib: config?.memoryMib ?? DEFAULT_MEMORY_MIB,
|
|
222
|
+
cpus: config?.cpus ?? DEFAULT_CPUS,
|
|
223
|
+
idleTimeoutSeconds: config?.idleTimeoutSeconds ?? 15 * 60,
|
|
224
|
+
namePrefix: config?.namePrefix ?? "cata",
|
|
225
|
+
networkProfiles: config?.networkProfiles,
|
|
226
|
+
setupCommand: config?.setupCommand ?? DEFAULT_SETUP_COMMAND,
|
|
227
|
+
imageBuilder: config?.imageBuilder ? cachedImageBuilder(config.imageBuilder) : undefined,
|
|
228
|
+
containers: config?.containers ?? true,
|
|
229
|
+
containerDiskMib: config?.containerDiskMib ?? DEFAULT_CONTAINER_DISK_MIB,
|
|
230
|
+
signInRoot: config?.signInRoot,
|
|
231
|
+
stateDirectory: config?.stateDirectory
|
|
232
|
+
};
|
|
233
|
+
const stateDirectory = this.config.stateDirectory;
|
|
234
|
+
this.usage = stateDirectory ? new VolumeUsageLog(path2.join(stateDirectory, "volumes.json")) : undefined;
|
|
235
|
+
if (this.usage)
|
|
236
|
+
this.volumes = {
|
|
237
|
+
prune: (args) => this.pruneVolumes(args),
|
|
238
|
+
removeAll: (args) => this.removeAllVolumes(args)
|
|
239
|
+
};
|
|
240
|
+
this.capabilities = [
|
|
241
|
+
SANDBOX_CAPABILITIES.images,
|
|
242
|
+
SANDBOX_CAPABILITIES.egressPolicy,
|
|
243
|
+
...this.config.containers ? [SANDBOX_CAPABILITIES.containers] : [],
|
|
244
|
+
...this.config.imageBuilder ? [SANDBOX_CAPABILITIES.imageBuild] : [],
|
|
245
|
+
...this.usage ? [SANDBOX_CAPABILITIES.volumes] : []
|
|
246
|
+
];
|
|
247
|
+
this.deploymentRuntime = msbStdioRuntimeProvider({
|
|
248
|
+
connect: (sandboxId) => this.connect(sandboxId),
|
|
249
|
+
uploadFiles: (sandboxId, files, basePath) => this.uploadFiles(sandboxId, files, basePath)
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
async createSandbox(opts) {
|
|
253
|
+
assertSandboxResources(opts.resources, this.resourceLimits);
|
|
254
|
+
const cpuMillis = opts.resources?.cpuMillis ?? this.config.cpus * 1000;
|
|
255
|
+
if (cpuMillis % 1000 !== 0)
|
|
256
|
+
throw new Error("Microsandbox CPU limits must be whole cores (multiples of 1000 millicores)");
|
|
257
|
+
if (opts.containers && !this.config.containers)
|
|
258
|
+
throw new Error("This machine does not run containers in sandboxes");
|
|
259
|
+
if (opts.volumes?.length && !this.usage)
|
|
260
|
+
throw new Error("This machine keeps no volumes for its sandboxes");
|
|
261
|
+
assertSandboxVolumes(opts.volumes);
|
|
262
|
+
const signIns = this.signInMounts(opts);
|
|
263
|
+
const image = await this.imageFor(opts);
|
|
264
|
+
const volumes = await this.volumeMounts({ image, volumes: opts.volumes });
|
|
265
|
+
const name = `${this.config.namePrefix}-${crypto.randomUUID().slice(0, 12)}`;
|
|
266
|
+
let builder = Sandbox.builder(name).image(image).memory(opts.resources?.memoryMb ?? this.config.memoryMib).cpus(cpuMillis / 1000).idleTimeout(opts.autoStopInterval !== undefined ? opts.autoStopInterval * 60 : this.config.idleTimeoutSeconds).patch((patch) => patch.mkdir(this.workspaceRoot, { mode: 493 })).workdir(this.workspaceRoot).detached(true);
|
|
267
|
+
if (opts.resources?.storageMb)
|
|
268
|
+
builder = builder.rootDisk(opts.resources.storageMb);
|
|
269
|
+
if (opts.envVars)
|
|
270
|
+
builder = builder.envs(opts.envVars);
|
|
271
|
+
const persistent = volumes.filter((volume) => !volume.temporary);
|
|
272
|
+
const labels = {
|
|
273
|
+
...opts.labels,
|
|
274
|
+
...persistent.length > 0 ? { [VOLUMES_LABEL]: persistent.map((volume) => volume.key).join(",") } : {}
|
|
275
|
+
};
|
|
276
|
+
if (Object.keys(labels).length > 0)
|
|
277
|
+
builder = builder.labels(labels);
|
|
278
|
+
const policy = microsandboxEgressPolicy({
|
|
279
|
+
egress: opts.egress,
|
|
280
|
+
profiles: this.config.networkProfiles
|
|
281
|
+
});
|
|
282
|
+
if (policy)
|
|
283
|
+
builder = builder.network((network) => network.policy(policy));
|
|
284
|
+
for (const volume of volumes)
|
|
285
|
+
builder = builder.volume(volume.target, volume.mount);
|
|
286
|
+
this.usage?.touch(persistent.map((volume) => volume.key));
|
|
287
|
+
if (opts.containers && !volumes.some((volume) => volume.target === DOCKER_DATA)) {
|
|
288
|
+
builder = builder.volume(DOCKER_DATA, (mount) => mount.owned({ kind: "disk", sizeMib: this.config.containerDiskMib }));
|
|
289
|
+
}
|
|
290
|
+
const dataDirectory = opts.labels?.purpose === "deployment-runtime" && opts.labels.projectId ? await this.config.projectDataDirectory?.({
|
|
291
|
+
projectId: opts.labels.projectId
|
|
292
|
+
}) : undefined;
|
|
293
|
+
if (dataDirectory) {
|
|
294
|
+
builder = builder.volume(APP_DATA_MOUNT, (mount) => mount.bind(dataDirectory)).env(APP_DATA_ENV, APP_DATA_MOUNT);
|
|
295
|
+
}
|
|
296
|
+
for (const signIn of signIns)
|
|
297
|
+
builder = builder.volume(signIn.guest, (mount) => mount.bind(signIn.host));
|
|
298
|
+
const sandbox = await builder.create();
|
|
299
|
+
this.connections.set(name, sandbox);
|
|
300
|
+
const prepare = async (command, what) => {
|
|
301
|
+
const result = await shellIn(sandbox, command, 300);
|
|
302
|
+
if (result.exitCode !== 0) {
|
|
303
|
+
await this.destroySandbox(name).catch(() => {});
|
|
304
|
+
throw new Error(`${what} failed: ${result.result}`);
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
if (this.config.setupCommand)
|
|
308
|
+
await prepare(this.config.setupCommand, opts.egress?.mode === "allowlist" ? "Sandbox setup command (egress is restricted, so the image must already have git, bash, and Bun or Node)" : "Sandbox setup command");
|
|
309
|
+
if (opts.containers)
|
|
310
|
+
await prepare(`touch ${CONTAINERS_MARKER}
|
|
311
|
+
${ENSURE_DOCKER}`, "Starting the sandbox's container runtime");
|
|
312
|
+
return {
|
|
313
|
+
id: name,
|
|
314
|
+
providerId: name,
|
|
315
|
+
sandboxType: "execution",
|
|
316
|
+
status: "started"
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
async startSandbox(sandboxId) {
|
|
320
|
+
const handle = await Sandbox.get(sandboxId);
|
|
321
|
+
if (handle.status === "running")
|
|
322
|
+
return;
|
|
323
|
+
this.connections.set(sandboxId, await booted(await bringUp(handle)));
|
|
324
|
+
this.usage?.touch(volumeKeysOf(handle));
|
|
325
|
+
}
|
|
326
|
+
async volumeMounts(args) {
|
|
327
|
+
const volumes = args.volumes ?? [];
|
|
328
|
+
if (volumes.length === 0)
|
|
329
|
+
return [];
|
|
330
|
+
const detail = volumes.some((volume) => volume.path.startsWith("~")) ? await Image2.inspect(args.image).catch(() => {
|
|
331
|
+
return;
|
|
332
|
+
}) : undefined;
|
|
333
|
+
const home = imageUserHome({
|
|
334
|
+
user: detail?.config?.user ?? null,
|
|
335
|
+
env: detail?.config?.env ?? null
|
|
336
|
+
});
|
|
337
|
+
const existing = new Set((await Volume.list().catch(() => [])).map((volume) => volume.name));
|
|
338
|
+
return volumes.map((volume) => {
|
|
339
|
+
const disk = volume.exclusive === true;
|
|
340
|
+
const sizeMib = volume.sizeMb ?? this.config.containerDiskMib;
|
|
341
|
+
return {
|
|
342
|
+
key: volume.key,
|
|
343
|
+
temporary: volume.temporary === true,
|
|
344
|
+
target: volumeMountPath({ path: volume.path, home }),
|
|
345
|
+
mount: (mount) => volume.temporary ? mount.owned(disk ? { kind: "disk", sizeMib } : { kind: "dir" }) : existing.has(volume.key) ? mount.named(volume.key) : mount.namedWith(volume.key, "ensure-exists", disk ? "disk" : "dir", disk ? sizeMib : undefined)
|
|
346
|
+
};
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
async pruneVolumes(args) {
|
|
350
|
+
const usage = this.usage;
|
|
351
|
+
if (!usage)
|
|
352
|
+
return [];
|
|
353
|
+
const mounted = await mountedVolumeKeys();
|
|
354
|
+
const removed = [];
|
|
355
|
+
for (const volume of await Volume.list()) {
|
|
356
|
+
if (!VOLUME_KEY_PATTERN.test(volume.name) || mounted.has(volume.name))
|
|
357
|
+
continue;
|
|
358
|
+
if (!usage.unused({
|
|
359
|
+
key: volume.name,
|
|
360
|
+
unusedForMs: args.unusedForMs,
|
|
361
|
+
...volume.createdAt ? { since: volume.createdAt.getTime() } : {}
|
|
362
|
+
}))
|
|
363
|
+
continue;
|
|
364
|
+
await Volume.remove(volume.name).then(() => removed.push(volume.name), () => {});
|
|
365
|
+
}
|
|
366
|
+
usage.forget(removed);
|
|
367
|
+
return removed;
|
|
368
|
+
}
|
|
369
|
+
async removeAllVolumes(args) {
|
|
370
|
+
if (args?.destroySandboxes)
|
|
371
|
+
for (const name of await sandboxesMountingVolumes())
|
|
372
|
+
await this.destroySandbox(name);
|
|
373
|
+
const mounted = await mountedVolumeKeys();
|
|
374
|
+
const kept = [];
|
|
375
|
+
const removed = [];
|
|
376
|
+
for (const volume of await Volume.list()) {
|
|
377
|
+
if (!VOLUME_KEY_PATTERN.test(volume.name))
|
|
378
|
+
continue;
|
|
379
|
+
if (mounted.has(volume.name))
|
|
380
|
+
kept.push(volume.name);
|
|
381
|
+
else {
|
|
382
|
+
await Volume.remove(volume.name);
|
|
383
|
+
removed.push(volume.name);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
this.usage?.forget(removed);
|
|
387
|
+
if (kept.length > 0)
|
|
388
|
+
throw new Error(`Volumes still mounted by sandboxes were kept: ${kept.join(", ")}. Destroy those sandboxes first.`);
|
|
389
|
+
}
|
|
390
|
+
signInMounts(opts) {
|
|
391
|
+
const requested = opts.signIns ?? [];
|
|
392
|
+
if (requested.length === 0)
|
|
393
|
+
return [];
|
|
394
|
+
const root = this.config.signInRoot;
|
|
395
|
+
if (!root)
|
|
396
|
+
throw new Error("This machine keeps no members' sign-ins, so its sandboxes cannot run on one");
|
|
397
|
+
return requested.map((signIn) => {
|
|
398
|
+
const host = machineSignInHome({ root, ...signIn });
|
|
399
|
+
if (!fs.statSync(host, { throwIfNoEntry: false })?.isDirectory())
|
|
400
|
+
throw new Error(`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}`);
|
|
401
|
+
return {
|
|
402
|
+
host,
|
|
403
|
+
guest: signInHomePath({
|
|
404
|
+
workspaceRoot: this.workspaceRoot,
|
|
405
|
+
harness: signIn.harness
|
|
406
|
+
})
|
|
407
|
+
};
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
async imageFor(opts) {
|
|
411
|
+
const image = opts.image;
|
|
412
|
+
if (!image)
|
|
413
|
+
return opts.snapshotName ?? this.config.image;
|
|
414
|
+
if (image.kind === "oci")
|
|
415
|
+
return image.reference;
|
|
416
|
+
if (!this.config.imageBuilder)
|
|
417
|
+
throw new Error(`This machine cannot build ${image.path}; place the Environment on a machine that builds images`);
|
|
418
|
+
const reference = dockerfileImageReference(image.digest);
|
|
419
|
+
await this.config.imageBuilder.build({
|
|
420
|
+
reference,
|
|
421
|
+
dockerfile: image.content
|
|
422
|
+
});
|
|
423
|
+
return reference;
|
|
424
|
+
}
|
|
425
|
+
async stopSandbox(sandboxId) {
|
|
426
|
+
this.connections.delete(sandboxId);
|
|
427
|
+
const handle = await Sandbox.get(sandboxId);
|
|
428
|
+
await handle.stop();
|
|
429
|
+
await this.deploymentRuntime.releaseSandbox?.({ sandboxId });
|
|
430
|
+
}
|
|
431
|
+
async destroySandbox(sandboxId) {
|
|
432
|
+
const connected = this.connections.get(sandboxId);
|
|
433
|
+
this.connections.delete(sandboxId);
|
|
434
|
+
const handle = await Sandbox.get(sandboxId).catch((error) => {
|
|
435
|
+
if (error instanceof Error && "code" in error && error.code === "sandboxNotFound")
|
|
436
|
+
return;
|
|
437
|
+
throw error;
|
|
438
|
+
});
|
|
439
|
+
if (!handle) {
|
|
440
|
+
await this.deploymentRuntime.releaseSandbox?.({ sandboxId });
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
if (handle.status === "running") {
|
|
444
|
+
if (volumeKeysOf(handle).length > 0)
|
|
445
|
+
await withTimeout((async () => shellIn(connected ?? await handle.connect(), "sync", 60))(), 60000).catch(() => {});
|
|
446
|
+
await handle.kill();
|
|
447
|
+
}
|
|
448
|
+
await handle.remove();
|
|
449
|
+
await this.deploymentRuntime.releaseSandbox?.({ sandboxId });
|
|
450
|
+
}
|
|
451
|
+
async getSandboxStatus(sandboxId) {
|
|
452
|
+
const handle = await Sandbox.get(sandboxId);
|
|
453
|
+
return mapMsbStatus(handle.status);
|
|
454
|
+
}
|
|
455
|
+
async executeCommand(sandboxId, command, opts) {
|
|
456
|
+
const sandbox = await this.connect(sandboxId);
|
|
457
|
+
const output = await sandbox.execWith("bash", (exec) => {
|
|
458
|
+
exec = exec.args(["-lc", command]);
|
|
459
|
+
if (opts?.cwd)
|
|
460
|
+
exec = exec.cwd(opts.cwd);
|
|
461
|
+
if (opts?.env)
|
|
462
|
+
exec = exec.envs(opts.env);
|
|
463
|
+
if (opts?.timeout)
|
|
464
|
+
exec = exec.timeout(opts.timeout * 1000);
|
|
465
|
+
return exec;
|
|
466
|
+
});
|
|
467
|
+
const stdout = output.stdout();
|
|
468
|
+
const stderr = output.stderr();
|
|
469
|
+
return {
|
|
470
|
+
exitCode: output.code,
|
|
471
|
+
result: stderr.length > 0 ? `${stdout}${stdout ? `
|
|
472
|
+
` : ""}${stderr}` : stdout
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
async uploadFiles(sandboxId, files, basePath) {
|
|
476
|
+
const sandbox = await this.connect(sandboxId);
|
|
477
|
+
const fs2 = sandbox.fs();
|
|
478
|
+
const dirs = new Set;
|
|
479
|
+
for (const filePath of Object.keys(files)) {
|
|
480
|
+
const destination = basePath ? `${basePath}/${filePath}` : filePath;
|
|
481
|
+
const dir = destination.slice(0, destination.lastIndexOf("/"));
|
|
482
|
+
if (dir)
|
|
483
|
+
dirs.add(dir);
|
|
484
|
+
}
|
|
485
|
+
if (dirs.size > 0) {
|
|
486
|
+
await sandbox.shell(`mkdir -p ${[...dirs].map((dir) => `'${dir.replaceAll("'", `'\\''`)}'`).join(" ")}`);
|
|
487
|
+
}
|
|
488
|
+
await Promise.all(Object.entries(files).map(([filePath, content]) => fs2.write(basePath ? `${basePath}/${filePath}` : filePath, content)));
|
|
489
|
+
}
|
|
490
|
+
async downloadFile(sandboxId, filePath) {
|
|
491
|
+
const sandbox = await this.connect(sandboxId);
|
|
492
|
+
return sandbox.fs().readToString(filePath);
|
|
493
|
+
}
|
|
494
|
+
async gitClone(sandboxId, url, path, opts) {
|
|
495
|
+
const cloneUrl = gitCloneUrl(url, opts);
|
|
496
|
+
const branchArg = opts?.branch ? ` --branch ${shellQuote(opts.branch)}` : "";
|
|
497
|
+
const clone = await this.executeCommand(sandboxId, `git clone${branchArg} ${shellQuote(cloneUrl)} ${shellQuote(path)}`, { timeout: 120 });
|
|
498
|
+
if (clone.exitCode !== 0) {
|
|
499
|
+
throw gitCloneFailure({
|
|
500
|
+
output: clone.result,
|
|
501
|
+
...opts ? { opts } : {}
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
if (opts?.commitId) {
|
|
505
|
+
await this.gitCheckout(sandboxId, path, opts.commitId);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
async gitCheckout(sandboxId, path, ref) {
|
|
509
|
+
const result = await this.executeCommand(sandboxId, `git -C ${shellQuote(path)} checkout ${shellQuote(ref)}`, { timeout: 60 });
|
|
510
|
+
if (result.exitCode !== 0) {
|
|
511
|
+
throw new Error(`git checkout failed: ${result.result}`);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
async connect(sandboxId) {
|
|
515
|
+
const cached = this.connections.get(sandboxId);
|
|
516
|
+
if (cached)
|
|
517
|
+
return cached;
|
|
518
|
+
const handle = await Sandbox.get(sandboxId);
|
|
519
|
+
const sandbox = handle.status === "running" ? await handle.connect() : await booted(await bringUp(handle));
|
|
520
|
+
this.connections.set(sandboxId, sandbox);
|
|
521
|
+
return sandbox;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
async function bringUp(handle) {
|
|
525
|
+
if (handle.status === "paused") {
|
|
526
|
+
await handle.resume();
|
|
527
|
+
return handle.connect();
|
|
528
|
+
}
|
|
529
|
+
return handle.startDetached();
|
|
530
|
+
}
|
|
531
|
+
async function shellIn(sandbox, command, timeoutSeconds) {
|
|
532
|
+
const output = await sandbox.execWith("sh", (exec) => exec.args(["-c", command]).timeout(timeoutSeconds * 1000));
|
|
533
|
+
const stdout = output.stdout();
|
|
534
|
+
const stderr = output.stderr();
|
|
535
|
+
return {
|
|
536
|
+
exitCode: output.code,
|
|
537
|
+
result: stderr.length > 0 ? `${stdout}${stdout ? `
|
|
538
|
+
` : ""}${stderr}` : stdout
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
async function booted(sandbox) {
|
|
542
|
+
const result = await shellIn(sandbox, `[ -f ${CONTAINERS_MARKER} ] || exit 0
|
|
543
|
+
${ENSURE_DOCKER}`, 120);
|
|
544
|
+
if (result.exitCode !== 0)
|
|
545
|
+
throw new Error(`The sandbox's container runtime did not start: ${result.result}`);
|
|
546
|
+
return sandbox;
|
|
547
|
+
}
|
|
548
|
+
function volumeKeysOf(handle) {
|
|
549
|
+
try {
|
|
550
|
+
const labels = handle.config().labels;
|
|
551
|
+
const keys = typeof labels === "object" && labels !== null ? Reflect.get(labels, VOLUMES_LABEL) : undefined;
|
|
552
|
+
return typeof keys === "string" ? keys.split(",").filter(Boolean) : [];
|
|
553
|
+
} catch {
|
|
554
|
+
return [];
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
async function mountedVolumeKeys() {
|
|
558
|
+
const keys = new Set;
|
|
559
|
+
for (const handle of await everySandbox())
|
|
560
|
+
for (const key of volumeKeysOf(handle))
|
|
561
|
+
keys.add(key);
|
|
562
|
+
return keys;
|
|
563
|
+
}
|
|
564
|
+
async function sandboxesMountingVolumes() {
|
|
565
|
+
return (await everySandbox()).filter((handle) => volumeKeysOf(handle).length > 0).map((handle) => handle.name);
|
|
566
|
+
}
|
|
567
|
+
async function everySandbox() {
|
|
568
|
+
const handles = [];
|
|
569
|
+
let cursor;
|
|
570
|
+
do {
|
|
571
|
+
const after = cursor;
|
|
572
|
+
const page = await Sandbox.listWith((list) => after ? list.cursor(after) : list);
|
|
573
|
+
handles.push(...page.sandboxes);
|
|
574
|
+
cursor = page.nextCursor;
|
|
575
|
+
} while (cursor);
|
|
576
|
+
return handles;
|
|
577
|
+
}
|
|
578
|
+
async function withTimeout(promise, ms) {
|
|
579
|
+
let timer;
|
|
580
|
+
try {
|
|
581
|
+
return await Promise.race([
|
|
582
|
+
promise,
|
|
583
|
+
new Promise((_, reject) => {
|
|
584
|
+
timer = setTimeout(() => reject(new Error(`No answer within ${ms}ms`)), ms);
|
|
585
|
+
})
|
|
586
|
+
]);
|
|
587
|
+
} finally {
|
|
588
|
+
clearTimeout(timer);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
function shellQuote(value) {
|
|
592
|
+
return `'${value.replaceAll("'", `'\\''`)}'`;
|
|
593
|
+
}
|
|
594
|
+
// src/support.ts
|
|
595
|
+
import fs2 from "node:fs";
|
|
596
|
+
import { createRequire } from "node:module";
|
|
597
|
+
import os2 from "node:os";
|
|
598
|
+
import path3 from "node:path";
|
|
599
|
+
var NO_KVM = "This machine has no usable /dev/kvm, so microsandbox cannot run here. Use WORK_SANDBOX=container (gVisor) or auto.";
|
|
600
|
+
function microsandboxSupport(input) {
|
|
601
|
+
const platform = input?.platform ?? process.platform;
|
|
602
|
+
const arch = input?.arch ?? process.arch;
|
|
603
|
+
const env = input?.env ?? process.env;
|
|
604
|
+
if (platform === "darwin") {
|
|
605
|
+
if (arch !== "arm64")
|
|
606
|
+
return {
|
|
607
|
+
ok: false,
|
|
608
|
+
reason: "Microsandbox runs on Apple silicon Macs only"
|
|
609
|
+
};
|
|
610
|
+
} else if (platform === "linux") {
|
|
611
|
+
if (arch !== "x64" && arch !== "arm64")
|
|
612
|
+
return {
|
|
613
|
+
ok: false,
|
|
614
|
+
reason: `Microsandbox does not run on Linux ${arch}`
|
|
615
|
+
};
|
|
616
|
+
if (!(input?.kvmUsable ?? kvmUsable)())
|
|
617
|
+
return { ok: false, reason: NO_KVM };
|
|
618
|
+
} else {
|
|
619
|
+
return {
|
|
620
|
+
ok: false,
|
|
621
|
+
reason: `Microsandbox does not run on ${platform}`
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
const msb = (input?.msbPath ?? (() => resolveMsb(env)))();
|
|
625
|
+
if (!msb)
|
|
626
|
+
return {
|
|
627
|
+
ok: false,
|
|
628
|
+
reason: "The microsandbox runtime (msb) is not installed on this machine: install it, or set MSB_PATH to its msb binary"
|
|
629
|
+
};
|
|
630
|
+
return { ok: true };
|
|
631
|
+
}
|
|
632
|
+
function kvmUsable() {
|
|
633
|
+
try {
|
|
634
|
+
fs2.closeSync(fs2.openSync("/dev/kvm", "r+"));
|
|
635
|
+
return true;
|
|
636
|
+
} catch {
|
|
637
|
+
return false;
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
function resolveMsb(env) {
|
|
641
|
+
const candidates = [
|
|
642
|
+
env.MSB_PATH,
|
|
643
|
+
path3.join(os2.homedir(), ".microsandbox", "bin", "msb"),
|
|
644
|
+
packagedMsb()
|
|
645
|
+
];
|
|
646
|
+
return candidates.find((candidate) => Boolean(candidate) && executable(candidate ?? ""));
|
|
647
|
+
}
|
|
648
|
+
function executable(file) {
|
|
649
|
+
try {
|
|
650
|
+
fs2.accessSync(file, fs2.constants.X_OK);
|
|
651
|
+
return fs2.statSync(file).isFile();
|
|
652
|
+
} catch {
|
|
653
|
+
return false;
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
function packagedMsb() {
|
|
657
|
+
const triples = {
|
|
658
|
+
"darwin-arm64": "darwin-arm64",
|
|
659
|
+
"linux-x64": "linux-x64-gnu",
|
|
660
|
+
"linux-arm64": "linux-arm64-gnu"
|
|
661
|
+
};
|
|
662
|
+
const triple = triples[`${process.platform}-${process.arch}`];
|
|
663
|
+
if (!triple)
|
|
664
|
+
return;
|
|
665
|
+
try {
|
|
666
|
+
const sdk = createRequire(import.meta.url).resolve("microsandbox/package.json");
|
|
667
|
+
const platformPackage = createRequire(sdk).resolve(`@superradcompany/microsandbox-${triple}/package.json`);
|
|
668
|
+
return path3.join(path3.dirname(platformPackage), "bin", "msb");
|
|
669
|
+
} catch {
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
export {
|
|
674
|
+
MicrosandboxSandboxProvider,
|
|
675
|
+
cachedImageBuilder,
|
|
676
|
+
dockerImageBuilder,
|
|
677
|
+
microsandboxEgressPolicy,
|
|
678
|
+
microsandboxSupport,
|
|
679
|
+
msbStdioRuntimeProvider
|
|
680
|
+
};
|
|
681
|
+
|
|
682
|
+
//# debugId=861992BFA677201D64756E2164756E21
|
|
683
|
+
//# sourceMappingURL=index.js.map
|