@kvbox/server 0.5.27 → 0.5.28
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/dist/kvbox-server.js +589 -281
- package/dist/kvbox-server.js.map +1 -1
- package/package.json +1 -1
- package/scripts/net-setup.sh +106 -19
package/dist/kvbox-server.js
CHANGED
|
@@ -448,6 +448,9 @@ var PortsRequest = z3.object({
|
|
|
448
448
|
ports: z3.array(z3.object({ guestPort: z3.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS)
|
|
449
449
|
});
|
|
450
450
|
var BoxPortSchema = z3.number().int().min(1).max(65535);
|
|
451
|
+
var MAX_BOX_LINKS = 32;
|
|
452
|
+
var BoxLinkSchema = z3.object({ from: z3.string(), port: BoxPortSchema });
|
|
453
|
+
var LinkRequest = z3.object({ from: z3.string().min(1), fromOwner: z3.string().optional(), port: BoxPortSchema });
|
|
451
454
|
var ClaimSubdomainRequest = z3.object({ name: z3.string(), port: BoxPortSchema });
|
|
452
455
|
var SubdomainPortRequest = z3.object({ port: BoxPortSchema });
|
|
453
456
|
var SubdomainRouteRequest = z3.object({ name: z3.string(), port: BoxPortSchema });
|
|
@@ -511,7 +514,9 @@ var MachineSchema = z3.object({
|
|
|
511
514
|
/** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
|
|
512
515
|
autoHibernateSec: z3.number().int().positive().optional(),
|
|
513
516
|
/** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */
|
|
514
|
-
volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int(), mountPath: z3.string() })).optional()
|
|
517
|
+
volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int(), mountPath: z3.string() })).optional(),
|
|
518
|
+
/** Boxes that may reach this one, each on one port (#98). Absent: none. */
|
|
519
|
+
links: z3.array(BoxLinkSchema).optional()
|
|
515
520
|
});
|
|
516
521
|
var VolumeSchema = z3.object({
|
|
517
522
|
/** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */
|
|
@@ -576,7 +581,12 @@ var CreateMachineRequest = z3.object({
|
|
|
576
581
|
*/
|
|
577
582
|
sshKeys: z3.array(z3.string()).optional(),
|
|
578
583
|
/** Seconds without network traffic before the box is hibernated (#47); 0: never. Absent: the host's default. */
|
|
579
|
-
autoHibernateSec: z3.number().int().min(0).optional()
|
|
584
|
+
autoHibernateSec: z3.number().int().min(0).optional(),
|
|
585
|
+
/**
|
|
586
|
+
* Place the box on the host of this box (#98, `kvbox new --near`), so the two can be linked. Only the
|
|
587
|
+
* control plane reads it; a host has one place to put a box.
|
|
588
|
+
*/
|
|
589
|
+
near: z3.string().optional()
|
|
580
590
|
});
|
|
581
591
|
var ForkMachineRequest = z3.object({
|
|
582
592
|
name: z3.string().optional(),
|
|
@@ -620,7 +630,9 @@ var SnapshotSchema = z3.object({
|
|
|
620
630
|
});
|
|
621
631
|
var CreateSnapshotRequest = z3.object({
|
|
622
632
|
box: z3.string(),
|
|
623
|
-
name: z3.string()
|
|
633
|
+
name: z3.string(),
|
|
634
|
+
/** Retake a snapshot under a name that exists (#83): the old one goes only once the new one is complete. */
|
|
635
|
+
replace: z3.boolean().optional()
|
|
624
636
|
});
|
|
625
637
|
var DiskCapacitySchema = z3.object({
|
|
626
638
|
totalGib: z3.number().int(),
|
|
@@ -1164,209 +1176,15 @@ async function requireKvm(device = KVM_DEVICE, groupFile = "/etc/group") {
|
|
|
1164
1176
|
);
|
|
1165
1177
|
}
|
|
1166
1178
|
|
|
1167
|
-
// src/core/
|
|
1168
|
-
import {
|
|
1169
|
-
import { closeSync as closeSync2, existsSync as existsSync4, openSync as openSync2, statSync as statSync2 } from "node:fs";
|
|
1170
|
-
import { link as link2, mkdir as mkdir6, readFile as readFile6, realpath, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
|
|
1171
|
-
import { basename } from "node:path";
|
|
1172
|
-
import { setTimeout as sleep } from "node:timers/promises";
|
|
1173
|
-
|
|
1174
|
-
// src/core/agent.ts
|
|
1175
|
-
import { connect } from "node:net";
|
|
1176
|
-
var AGENT_PORT = 52;
|
|
1177
|
-
async function agentCall(udsPath, req, timeoutMs = 5e3) {
|
|
1178
|
-
const reply = await new Promise((resolve, reject) => {
|
|
1179
|
-
const sock = connect(udsPath);
|
|
1180
|
-
let buf = "";
|
|
1181
|
-
let handshaken = false;
|
|
1182
|
-
const fail = (err) => {
|
|
1183
|
-
sock.destroy();
|
|
1184
|
-
reject(err);
|
|
1185
|
-
};
|
|
1186
|
-
sock.setTimeout(timeoutMs, () => fail(new KvboxError(handshaken ? `kvbox-agent did not answer within ${timeoutMs} ms` : `the guest did not accept the vsock connection within ${timeoutMs} ms`)));
|
|
1187
|
-
sock.once("error", (err) => fail(new KvboxError(`kvbox-agent unreachable: ${err.message}`)));
|
|
1188
|
-
sock.once("connect", () => sock.write(`CONNECT ${AGENT_PORT}
|
|
1189
|
-
`));
|
|
1190
|
-
sock.on("data", (chunk) => {
|
|
1191
|
-
buf += chunk.toString("utf8");
|
|
1192
|
-
let nl;
|
|
1193
|
-
while ((nl = buf.indexOf("\n")) !== -1) {
|
|
1194
|
-
const line = buf.slice(0, nl);
|
|
1195
|
-
buf = buf.slice(nl + 1);
|
|
1196
|
-
if (!handshaken) {
|
|
1197
|
-
if (!line.startsWith("OK ")) return fail(new KvboxError(`vsock connect refused: ${line}`));
|
|
1198
|
-
handshaken = true;
|
|
1199
|
-
sock.write(JSON.stringify(req) + "\n");
|
|
1200
|
-
} else {
|
|
1201
|
-
sock.end();
|
|
1202
|
-
return resolve(line);
|
|
1203
|
-
}
|
|
1204
|
-
}
|
|
1205
|
-
});
|
|
1206
|
-
sock.once("close", () => {
|
|
1207
|
-
if (!handshaken) fail(new KvboxError("vsock connection closed before the guest accepted"));
|
|
1208
|
-
else fail(new KvboxError("kvbox-agent closed the connection without a reply"));
|
|
1209
|
-
});
|
|
1210
|
-
});
|
|
1211
|
-
let parsed;
|
|
1212
|
-
try {
|
|
1213
|
-
parsed = JSON.parse(reply);
|
|
1214
|
-
} catch {
|
|
1215
|
-
throw new KvboxError(`kvbox-agent sent something that is not JSON: ${reply}`);
|
|
1216
|
-
}
|
|
1217
|
-
if (!parsed.ok) throw new KvboxError(`kvbox-agent: ${parsed.error}`);
|
|
1218
|
-
return parsed;
|
|
1219
|
-
}
|
|
1220
|
-
function setIdentity(udsPath, id, timeoutMs) {
|
|
1221
|
-
return agentCall(udsPath, { op: "identity", ...id }, timeoutMs);
|
|
1222
|
-
}
|
|
1223
|
-
function setAuthorizedKeys(udsPath, lines, timeoutMs) {
|
|
1224
|
-
return agentCall(udsPath, { op: "authorizedKeys", lines: [...lines] }, timeoutMs);
|
|
1225
|
-
}
|
|
1226
|
-
async function stats(udsPath, timeoutMs) {
|
|
1227
|
-
const reply = GuestStatsSchema.safeParse(await agentCall(udsPath, { op: "stats" }, timeoutMs));
|
|
1228
|
-
if (!reply.success) throw new KvboxError(`kvbox-agent sent stats kvbox does not understand: ${reply.error.issues[0]?.message ?? "invalid"}`);
|
|
1229
|
-
return reply.data;
|
|
1230
|
-
}
|
|
1231
|
-
async function dropVolumes(udsPath, timeoutMs) {
|
|
1232
|
-
const reply = await agentCall(udsPath, { op: "dropVolumes" }, timeoutMs);
|
|
1233
|
-
return Array.isArray(reply["dropped"]) ? reply["dropped"].map(String) : [];
|
|
1234
|
-
}
|
|
1235
|
-
function setEnv(udsPath, vars, timeoutMs) {
|
|
1236
|
-
return agentCall(udsPath, { op: "env", vars: vars.map((v) => [v.name, v.value]) }, timeoutMs);
|
|
1237
|
-
}
|
|
1238
|
-
var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
|
|
1239
|
-
var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
|
|
1240
|
-
var isNoAgent = (err) => /vsock connect refused|vsock connection closed before the guest accepted|did not accept the vsock connection|kvbox-agent unreachable: connect (ENOENT|ECONNREFUSED)/.test(err.message ?? "");
|
|
1179
|
+
// src/core/dns.ts
|
|
1180
|
+
import { createSocket } from "node:dgram";
|
|
1241
1181
|
|
|
1242
|
-
// src/core/
|
|
1182
|
+
// src/core/state.ts
|
|
1183
|
+
import { randomBytes } from "node:crypto";
|
|
1184
|
+
import { readFileSync } from "node:fs";
|
|
1243
1185
|
import { mkdir as mkdir2, readFile as readFile4, readdir, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
|
|
1244
1186
|
import { z as z4 } from "zod";
|
|
1245
1187
|
|
|
1246
|
-
// ../shared/src/env.ts
|
|
1247
|
-
var ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
1248
|
-
var ENV_RESERVED = ["PATH", "HOME", "USER", "SHELL"];
|
|
1249
|
-
var ENV_MAX_VALUE_BYTES = 4096;
|
|
1250
|
-
var ENV_MAX_VARS = 100;
|
|
1251
|
-
function envNameProblem(name) {
|
|
1252
|
-
if (!ENV_NAME_RE.test(name)) return `${JSON.stringify(name)} is not a variable name: letters, digits and _, not starting with a digit`;
|
|
1253
|
-
if (ENV_RESERVED.includes(name)) return `${name} is the box's own and cannot be set`;
|
|
1254
|
-
if (name.startsWith("KVBOX_")) return `${name}: names starting with KVBOX_ are kept for kvbox`;
|
|
1255
|
-
return null;
|
|
1256
|
-
}
|
|
1257
|
-
function envValueProblem(value) {
|
|
1258
|
-
if (/[\n\r\0]/.test(value)) return "a value is one line: no line breaks (base64 a multi-line value such as a key file)";
|
|
1259
|
-
if (Buffer.byteLength(value, "utf8") > ENV_MAX_VALUE_BYTES) return `a value is at most ${ENV_MAX_VALUE_BYTES / 1024} KB`;
|
|
1260
|
-
return null;
|
|
1261
|
-
}
|
|
1262
|
-
|
|
1263
|
-
// src/core/locks.ts
|
|
1264
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
1265
|
-
var tails = /* @__PURE__ */ new Map();
|
|
1266
|
-
var held = new AsyncLocalStorage();
|
|
1267
|
-
function withBoxLock(ref, fn) {
|
|
1268
|
-
return withLock(refKey(ref), fn);
|
|
1269
|
-
}
|
|
1270
|
-
function withHostLock(name, fn) {
|
|
1271
|
-
return withLock(`host:${name}`, fn);
|
|
1272
|
-
}
|
|
1273
|
-
async function withLock(key, fn) {
|
|
1274
|
-
const mine = held.getStore();
|
|
1275
|
-
if (mine?.has(key)) return fn();
|
|
1276
|
-
const previous = tails.get(key);
|
|
1277
|
-
let release;
|
|
1278
|
-
const tail = new Promise((resolve) => release = resolve);
|
|
1279
|
-
tails.set(key, tail);
|
|
1280
|
-
try {
|
|
1281
|
-
await previous;
|
|
1282
|
-
return await held.run(/* @__PURE__ */ new Set([...mine ?? [], key]), fn);
|
|
1283
|
-
} finally {
|
|
1284
|
-
release();
|
|
1285
|
-
if (tails.get(key) === tail) tails.delete(key);
|
|
1286
|
-
}
|
|
1287
|
-
}
|
|
1288
|
-
function boxBusy(ref) {
|
|
1289
|
-
return tails.has(refKey(ref));
|
|
1290
|
-
}
|
|
1291
|
-
function locked(fn) {
|
|
1292
|
-
return (...args) => withBoxLock(args[0], () => fn(...args));
|
|
1293
|
-
}
|
|
1294
|
-
|
|
1295
|
-
// src/core/env.ts
|
|
1296
|
-
var OwnerEnvSchema = z4.object({
|
|
1297
|
-
/** The control plane's counter for the list; only ever grows. */
|
|
1298
|
-
version: z4.number().int().min(0),
|
|
1299
|
-
vars: z4.array(z4.object({ name: z4.string(), value: z4.string() }))
|
|
1300
|
-
});
|
|
1301
|
-
async function readOwnerEnv(owner, p = paths()) {
|
|
1302
|
-
try {
|
|
1303
|
-
return OwnerEnvSchema.parse(JSON.parse(await readFile4(p.ownerEnv(owner), "utf8")));
|
|
1304
|
-
} catch (err) {
|
|
1305
|
-
if (err.code === "ENOENT") return null;
|
|
1306
|
-
throw err;
|
|
1307
|
-
}
|
|
1308
|
-
}
|
|
1309
|
-
async function envForBoot(owner, p = paths()) {
|
|
1310
|
-
const env = await readOwnerEnv(owner, p).catch(() => null);
|
|
1311
|
-
if (env !== null) return env.vars;
|
|
1312
|
-
return realmOf(owner) !== null ? [] : null;
|
|
1313
|
-
}
|
|
1314
|
-
async function setOwnerEnv(owner, req, p = paths()) {
|
|
1315
|
-
if (!OWNER_RE.test(owner)) throw new KvboxError(`invalid owner "${owner}"`);
|
|
1316
|
-
if (req.vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);
|
|
1317
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1318
|
-
for (const v of req.vars) {
|
|
1319
|
-
const problem = envNameProblem(v.name) ?? envValueProblem(v.value);
|
|
1320
|
-
if (problem !== null) throw new KvboxError(`${v.name}: ${problem}`);
|
|
1321
|
-
if (seen.has(v.name)) throw new KvboxError(`${v.name} is in the list twice`);
|
|
1322
|
-
seen.add(v.name);
|
|
1323
|
-
}
|
|
1324
|
-
return withHostLock("env", async () => {
|
|
1325
|
-
const have = await readOwnerEnv(owner, p);
|
|
1326
|
-
if (have !== null && have.version > req.version) return { version: have.version };
|
|
1327
|
-
const file = p.ownerEnv(owner);
|
|
1328
|
-
await mkdir2(p.env, { recursive: true, mode: 448 });
|
|
1329
|
-
const tmp = `${file}.tmp`;
|
|
1330
|
-
await writeFile2(tmp, JSON.stringify({ version: req.version, vars: req.vars }, null, 2) + "\n", { mode: 384 });
|
|
1331
|
-
await rename2(tmp, file);
|
|
1332
|
-
return { version: req.version };
|
|
1333
|
-
});
|
|
1334
|
-
}
|
|
1335
|
-
async function listEnvVersions(scope, p = paths()) {
|
|
1336
|
-
let files;
|
|
1337
|
-
try {
|
|
1338
|
-
files = await readdir(p.env);
|
|
1339
|
-
} catch (err) {
|
|
1340
|
-
if (err.code === "ENOENT") return [];
|
|
1341
|
-
throw err;
|
|
1342
|
-
}
|
|
1343
|
-
const out = [];
|
|
1344
|
-
for (const file of files.filter((f) => f.endsWith(".json")).sort()) {
|
|
1345
|
-
const owner = file.slice(0, -".json".length);
|
|
1346
|
-
if (!OWNER_RE.test(owner) || !inScope(owner, scope)) continue;
|
|
1347
|
-
const env = await readOwnerEnv(owner, p).catch(() => null);
|
|
1348
|
-
if (env !== null) out.push({ owner, version: env.version });
|
|
1349
|
-
}
|
|
1350
|
-
return out;
|
|
1351
|
-
}
|
|
1352
|
-
|
|
1353
|
-
// src/core/volumes.ts
|
|
1354
|
-
import { existsSync, statSync } from "node:fs";
|
|
1355
|
-
import { lstat, mkdir as mkdir4, readdir as readdir3, rm, statfs, symlink, truncate, writeFile as writeFile4 } from "node:fs/promises";
|
|
1356
|
-
|
|
1357
|
-
// ../shared/src/capacity.ts
|
|
1358
|
-
var MEM_HEADROOM_MIB = 2048;
|
|
1359
|
-
function sellableGib(d) {
|
|
1360
|
-
return Math.max(0, d.freeGib + d.volumesUsedGib - d.headroomGib);
|
|
1361
|
-
}
|
|
1362
|
-
function volumeRoomGib(d) {
|
|
1363
|
-
return Math.max(0, sellableGib(d) - d.volumesGib);
|
|
1364
|
-
}
|
|
1365
|
-
function hasDiskRoom(d, sizeGib) {
|
|
1366
|
-
return sizeGib <= volumeRoomGib(d);
|
|
1367
|
-
}
|
|
1368
|
-
var VCPU_OVERSUBSCRIPTION = 2;
|
|
1369
|
-
|
|
1370
1188
|
// src/core/db.ts
|
|
1371
1189
|
import { chmodSync, closeSync, mkdirSync, openSync } from "node:fs";
|
|
1372
1190
|
import { dirname } from "node:path";
|
|
@@ -1502,75 +1320,79 @@ function volumeEventsInScope(scope, window, p = paths()) {
|
|
|
1502
1320
|
}
|
|
1503
1321
|
|
|
1504
1322
|
// src/core/state.ts
|
|
1505
|
-
|
|
1506
|
-
import { readFileSync } from "node:fs";
|
|
1507
|
-
import { mkdir as mkdir3, readFile as readFile5, readdir as readdir2, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
|
|
1508
|
-
import { z as z5 } from "zod";
|
|
1509
|
-
var MachineMetaSchema = z5.object({
|
|
1323
|
+
var MachineMetaSchema = z4.object({
|
|
1510
1324
|
/** Host-unique, minted at `kvbox new` (fresh or restored) and kept for the box's life; the tap is `kv-<id>`. */
|
|
1511
|
-
id:
|
|
1512
|
-
name:
|
|
1325
|
+
id: z4.string(),
|
|
1326
|
+
name: z4.string(),
|
|
1513
1327
|
/** Part of the box's identity: machines/<owner>/<name>. See refs.ts. */
|
|
1514
|
-
owner:
|
|
1515
|
-
ip:
|
|
1516
|
-
mac:
|
|
1517
|
-
pid:
|
|
1328
|
+
owner: z4.string(),
|
|
1329
|
+
ip: z4.string(),
|
|
1330
|
+
mac: z4.string(),
|
|
1331
|
+
pid: z4.number().int().nullable(),
|
|
1518
1332
|
// null: stopped on purpose, disk kept
|
|
1519
1333
|
/**
|
|
1520
1334
|
* The host boot `pid` belongs to (/proc/sys/kernel/random/boot_id at launch, #29). After a reboot
|
|
1521
1335
|
* the number can name some other process; a pid from another boot is dead whatever `kill -0` says.
|
|
1522
1336
|
* Absent (boxes launched before #29): the pid alone decides.
|
|
1523
1337
|
*/
|
|
1524
|
-
bootId:
|
|
1525
|
-
vcpu:
|
|
1526
|
-
memMib:
|
|
1527
|
-
createdAt:
|
|
1528
|
-
source:
|
|
1338
|
+
bootId: z4.string().optional(),
|
|
1339
|
+
vcpu: z4.number().int(),
|
|
1340
|
+
memMib: z4.number().int(),
|
|
1341
|
+
createdAt: z4.string(),
|
|
1342
|
+
source: z4.string(),
|
|
1529
1343
|
/** Base image version (assets/rootfs-<version>.ext4) the box's overlay stacks on. */
|
|
1530
|
-
base:
|
|
1344
|
+
base: z4.string(),
|
|
1531
1345
|
/**
|
|
1532
1346
|
* Snapshots taken since this VM started (boot or restore). Firecracker resets its dirty-page bitmap at
|
|
1533
1347
|
* each one, so when this is > 0 the next diff is only standalone merged onto `mem.base`; if that file
|
|
1534
1348
|
* is missing the lineage is broken and the next snapshot has to be a full dump. Absent: 0.
|
|
1535
1349
|
*/
|
|
1536
|
-
memSnapshots:
|
|
1350
|
+
memSnapshots: z4.number().int().optional(),
|
|
1537
1351
|
/** `kvbox pause`: Firecracker is alive but the VM is frozen (standby). Absent: not paused. */
|
|
1538
|
-
paused:
|
|
1352
|
+
paused: z4.boolean().optional(),
|
|
1539
1353
|
/**
|
|
1540
1354
|
* authorized_keys lines the box gets on top of the host's own key, as the control plane sent them
|
|
1541
1355
|
* at `new` (#49). kvbox-init rewrites authorized_keys from the kernel cmdline at every boot, so
|
|
1542
1356
|
* `start` has to send the same lines again. Absent: host key only.
|
|
1543
1357
|
*/
|
|
1544
|
-
sshKeys:
|
|
1358
|
+
sshKeys: z4.array(z4.string()).optional(),
|
|
1545
1359
|
/**
|
|
1546
1360
|
* The guest's authorized_keys may not match `sshKeys`: they changed while the box was not running,
|
|
1547
1361
|
* or its agent could not take them (#55, #63). Cleared by a push through kvbox-agent or a boot.
|
|
1548
1362
|
*/
|
|
1549
|
-
sshKeysStale:
|
|
1363
|
+
sshKeysStale: z4.boolean().optional(),
|
|
1550
1364
|
/** Public port on the host DNATed to the box's SSH while it runs (#49); fixed for the box's life. Absent: none. */
|
|
1551
|
-
sshPort:
|
|
1365
|
+
sshPort: z4.number().int().optional(),
|
|
1552
1366
|
/**
|
|
1553
1367
|
* Box ports published on the host (#30, `kvbox vm proxy`): unique per guest port and protocol,
|
|
1554
1368
|
* each host port the box's for its life. DNATed while the box runs, rebuilt from here with its
|
|
1555
1369
|
* current IP every time it comes up. Absent: none.
|
|
1556
1370
|
*/
|
|
1557
|
-
ports:
|
|
1371
|
+
ports: z4.array(z4.object({ guestPort: z4.number().int(), hostPort: z4.number().int(), proto: z4.enum(["tcp", "udp"]) })).optional(),
|
|
1558
1372
|
/** Seconds without traffic on the box's tap before the server hibernates it (#47, core/idle.ts). Absent: never. */
|
|
1559
|
-
autoHibernateSec:
|
|
1373
|
+
autoHibernateSec: z4.number().int().positive().optional(),
|
|
1560
1374
|
/**
|
|
1561
1375
|
* Names of the owner's volumes attached to the box (#52), in the order they were attached, which is
|
|
1562
1376
|
* their drive order (/dev/vdc, /dev/vdd, …). This list is the one truth about what is attached: a
|
|
1563
1377
|
* volume's meta.json does not say. Absent: none.
|
|
1564
1378
|
*/
|
|
1565
|
-
volumes:
|
|
1379
|
+
volumes: z4.array(z4.string()).optional(),
|
|
1380
|
+
/**
|
|
1381
|
+
* Links into this box (#98, `kvbox vm link`): box `owner/name`, at `ip`, may open TCP connections to
|
|
1382
|
+
* `port`. The rule is open while this box runs, rebuilt from here at every boot; `ip` is the other
|
|
1383
|
+
* box's, fixed for its life, and checked against its meta.json before a rule opens. `stale`: that box
|
|
1384
|
+
* was removed but the rule would not close; kept only so this box's next stop closes it, never opened
|
|
1385
|
+
* again, never listed (a new box of the same name may get the same IP). Absent: none.
|
|
1386
|
+
*/
|
|
1387
|
+
links: z4.array(z4.object({ owner: z4.string(), name: z4.string(), ip: z4.string(), port: z4.number().int(), stale: z4.literal(true).optional() })).optional()
|
|
1566
1388
|
});
|
|
1567
|
-
var VolumeMetaSchema =
|
|
1389
|
+
var VolumeMetaSchema = z4.object({
|
|
1568
1390
|
/** Host-unique like a box id (#91): the ledger's key, so a name removed and made again is two volumes. */
|
|
1569
|
-
id:
|
|
1570
|
-
name:
|
|
1571
|
-
owner:
|
|
1572
|
-
sizeGib:
|
|
1573
|
-
createdAt:
|
|
1391
|
+
id: z4.string(),
|
|
1392
|
+
name: z4.string(),
|
|
1393
|
+
owner: z4.string(),
|
|
1394
|
+
sizeGib: z4.number().int(),
|
|
1395
|
+
createdAt: z4.string()
|
|
1574
1396
|
});
|
|
1575
1397
|
function newBoxId(taken) {
|
|
1576
1398
|
for (; ; ) {
|
|
@@ -1578,35 +1400,35 @@ function newBoxId(taken) {
|
|
|
1578
1400
|
if (!taken.has(id)) return id;
|
|
1579
1401
|
}
|
|
1580
1402
|
}
|
|
1581
|
-
var SnapshotMetaSchema =
|
|
1582
|
-
name:
|
|
1583
|
-
owner:
|
|
1403
|
+
var SnapshotMetaSchema = z4.object({
|
|
1404
|
+
name: z4.string(),
|
|
1405
|
+
owner: z4.string(),
|
|
1584
1406
|
/** The box it was taken from, as owner/name. */
|
|
1585
|
-
source:
|
|
1586
|
-
base:
|
|
1587
|
-
vcpu:
|
|
1588
|
-
memMib:
|
|
1589
|
-
sizeBytes:
|
|
1590
|
-
createdAt:
|
|
1407
|
+
source: z4.string(),
|
|
1408
|
+
base: z4.string(),
|
|
1409
|
+
vcpu: z4.number().int(),
|
|
1410
|
+
memMib: z4.number().int(),
|
|
1411
|
+
sizeBytes: z4.number().int(),
|
|
1412
|
+
createdAt: z4.string(),
|
|
1591
1413
|
/**
|
|
1592
1414
|
* The volumes the source box had attached when it was frozen (#52): their drives are in the vmstate
|
|
1593
1415
|
* and their mounts in the memory image, but their data is not here. A box restored from the snapshot
|
|
1594
1416
|
* gets an empty placeholder of each size at the drive's path and drops the mounts through kvbox-agent.
|
|
1595
1417
|
*/
|
|
1596
|
-
volumes:
|
|
1418
|
+
volumes: z4.array(z4.object({ name: z4.string(), sizeGib: z4.number().int() })).optional()
|
|
1597
1419
|
});
|
|
1598
1420
|
async function ensureLayout(p = paths()) {
|
|
1599
1421
|
for (const dir of [p.home, p.ssh, p.bin, p.assets, p.machines, p.snapshots, p.volumes]) {
|
|
1600
|
-
await
|
|
1422
|
+
await mkdir2(dir, { recursive: true, mode: 448 });
|
|
1601
1423
|
}
|
|
1602
1424
|
return p;
|
|
1603
1425
|
}
|
|
1604
1426
|
async function readJson(file, schema) {
|
|
1605
|
-
return schema.parse(JSON.parse(await
|
|
1427
|
+
return schema.parse(JSON.parse(await readFile4(file, "utf8")));
|
|
1606
1428
|
}
|
|
1607
1429
|
async function listDirs(dir) {
|
|
1608
1430
|
try {
|
|
1609
|
-
const entries = await
|
|
1431
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
1610
1432
|
return entries.filter((e) => e.isDirectory()).map((e) => e.name);
|
|
1611
1433
|
} catch (err) {
|
|
1612
1434
|
if (err.code === "ENOENT") return [];
|
|
@@ -1616,12 +1438,16 @@ async function listDirs(dir) {
|
|
|
1616
1438
|
async function readMachineMeta(ref, p = paths()) {
|
|
1617
1439
|
return readJson(p.machine(ref.owner, ref.name).meta, MachineMetaSchema);
|
|
1618
1440
|
}
|
|
1441
|
+
var boxListVersion = 0;
|
|
1442
|
+
var boxListVersionNow = () => boxListVersion;
|
|
1443
|
+
var boxListChanged = () => void (boxListVersion += 1);
|
|
1619
1444
|
async function writeMachineMeta(meta, p = paths()) {
|
|
1620
1445
|
const m = p.machine(meta.owner, meta.name);
|
|
1621
|
-
await
|
|
1446
|
+
await mkdir2(m.dir, { recursive: true });
|
|
1622
1447
|
const tmp = `${m.meta}.tmp`;
|
|
1623
|
-
await
|
|
1624
|
-
await
|
|
1448
|
+
await writeFile2(tmp, JSON.stringify(meta, null, 2) + "\n");
|
|
1449
|
+
await rename2(tmp, m.meta);
|
|
1450
|
+
boxListChanged();
|
|
1625
1451
|
}
|
|
1626
1452
|
async function listMachineRefs(p = paths()) {
|
|
1627
1453
|
return listRefs(p.machines);
|
|
@@ -1629,21 +1455,20 @@ async function listMachineRefs(p = paths()) {
|
|
|
1629
1455
|
async function readSnapshotMeta(ref, p = paths()) {
|
|
1630
1456
|
return readJson(p.snapshot(ref.owner, ref.name).meta, SnapshotMetaSchema);
|
|
1631
1457
|
}
|
|
1632
|
-
async function writeSnapshotMeta(meta, p = paths()) {
|
|
1633
|
-
|
|
1634
|
-
await
|
|
1635
|
-
await writeFile3(s.meta, JSON.stringify(meta, null, 2) + "\n");
|
|
1458
|
+
async function writeSnapshotMeta(meta, p = paths(), s = p.snapshot(meta.owner, meta.name)) {
|
|
1459
|
+
await mkdir2(s.dir, { recursive: true });
|
|
1460
|
+
await writeFile2(s.meta, JSON.stringify(meta, null, 2) + "\n");
|
|
1636
1461
|
}
|
|
1637
1462
|
async function listSnapshotRefs(p = paths()) {
|
|
1638
|
-
return listRefs(p.snapshots);
|
|
1463
|
+
return (await listRefs(p.snapshots)).filter((ref) => !ref.name.startsWith("."));
|
|
1639
1464
|
}
|
|
1640
1465
|
async function readVolumeMeta(ref, p = paths()) {
|
|
1641
|
-
const raw = await readJson(p.volume(ref.owner, ref.name).meta, VolumeMetaSchema.extend({ id:
|
|
1466
|
+
const raw = await readJson(p.volume(ref.owner, ref.name).meta, VolumeMetaSchema.extend({ id: z4.string().optional() }));
|
|
1642
1467
|
if (raw.id !== void 0) return { ...raw, id: raw.id };
|
|
1643
1468
|
const taken = /* @__PURE__ */ new Set();
|
|
1644
1469
|
for (const other of await listVolumeRefs(p)) {
|
|
1645
1470
|
try {
|
|
1646
|
-
const j = JSON.parse(await
|
|
1471
|
+
const j = JSON.parse(await readFile4(p.volume(other.owner, other.name).meta, "utf8"));
|
|
1647
1472
|
if (typeof j.id === "string") taken.add(j.id);
|
|
1648
1473
|
} catch {
|
|
1649
1474
|
}
|
|
@@ -1655,8 +1480,8 @@ async function readVolumeMeta(ref, p = paths()) {
|
|
|
1655
1480
|
}
|
|
1656
1481
|
async function writeVolumeMeta(meta, p = paths()) {
|
|
1657
1482
|
const v = p.volume(meta.owner, meta.name);
|
|
1658
|
-
await
|
|
1659
|
-
await
|
|
1483
|
+
await mkdir2(v.dir, { recursive: true, mode: 448 });
|
|
1484
|
+
await writeFile2(v.meta, JSON.stringify(meta, null, 2) + "\n");
|
|
1660
1485
|
}
|
|
1661
1486
|
async function listVolumeRefs(p = paths()) {
|
|
1662
1487
|
return listRefs(p.volumes);
|
|
@@ -1703,6 +1528,324 @@ function hostBootTime() {
|
|
|
1703
1528
|
}
|
|
1704
1529
|
}
|
|
1705
1530
|
|
|
1531
|
+
// src/core/dns.ts
|
|
1532
|
+
var DNS_PORT = 10053;
|
|
1533
|
+
var DNS_SUFFIX = ".kvbox";
|
|
1534
|
+
var DNS_RETRY_MS = 1e4;
|
|
1535
|
+
var TTL_SEC = 5;
|
|
1536
|
+
var BOXES_FRESH_MS = 6e4;
|
|
1537
|
+
var TYPE_A = 1;
|
|
1538
|
+
var CLASS_IN = 1;
|
|
1539
|
+
var RCODE = { ok: 0, nxDomain: 3, refused: 5 };
|
|
1540
|
+
function parseQuery(msg) {
|
|
1541
|
+
if (msg.length < 12) return null;
|
|
1542
|
+
const flags = msg.readUInt16BE(2);
|
|
1543
|
+
const isResponse = flags & 32768;
|
|
1544
|
+
const opcode = flags >> 11 & 15;
|
|
1545
|
+
if (isResponse || opcode !== 0 || msg.readUInt16BE(4) < 1) return null;
|
|
1546
|
+
const labels = [];
|
|
1547
|
+
let at = 12;
|
|
1548
|
+
for (; ; ) {
|
|
1549
|
+
if (at >= msg.length) return null;
|
|
1550
|
+
const len = msg[at];
|
|
1551
|
+
at += 1;
|
|
1552
|
+
if (len === 0) break;
|
|
1553
|
+
if (len > 63 || at + len > msg.length) return null;
|
|
1554
|
+
labels.push(msg.subarray(at, at + len).toString("latin1"));
|
|
1555
|
+
at += len;
|
|
1556
|
+
}
|
|
1557
|
+
if (at + 4 > msg.length) return null;
|
|
1558
|
+
return {
|
|
1559
|
+
id: msg.readUInt16BE(0),
|
|
1560
|
+
rd: Boolean(flags & 256),
|
|
1561
|
+
name: labels.join(".").toLowerCase(),
|
|
1562
|
+
type: msg.readUInt16BE(at),
|
|
1563
|
+
class: msg.readUInt16BE(at + 2),
|
|
1564
|
+
question: msg.subarray(12, at + 4)
|
|
1565
|
+
};
|
|
1566
|
+
}
|
|
1567
|
+
function buildAnswer(q, rcode, ip) {
|
|
1568
|
+
const header = Buffer.alloc(12);
|
|
1569
|
+
header.writeUInt16BE(q.id, 0);
|
|
1570
|
+
header.writeUInt16BE(32768 | 1024 | (q.rd ? 256 : 0) | rcode, 2);
|
|
1571
|
+
header.writeUInt16BE(1, 4);
|
|
1572
|
+
header.writeUInt16BE(ip ? 1 : 0, 6);
|
|
1573
|
+
if (!ip) return Buffer.concat([header, q.question]);
|
|
1574
|
+
const rr = Buffer.alloc(16);
|
|
1575
|
+
rr.writeUInt16BE(49164, 0);
|
|
1576
|
+
rr.writeUInt16BE(TYPE_A, 2);
|
|
1577
|
+
rr.writeUInt16BE(CLASS_IN, 4);
|
|
1578
|
+
rr.writeUInt32BE(TTL_SEC, 6);
|
|
1579
|
+
rr.writeUInt16BE(4, 10);
|
|
1580
|
+
ip.split(".").forEach((o, i) => rr.writeUInt8(Number(o), 12 + i));
|
|
1581
|
+
return Buffer.concat([header, q.question, rr]);
|
|
1582
|
+
}
|
|
1583
|
+
var slugOf = (owner) => owner.split("@")[0].toLowerCase();
|
|
1584
|
+
var isOurs = (q) => q.class === CLASS_IN && q.name.endsWith(DNS_SUFFIX);
|
|
1585
|
+
function answerFor(q, asker, boxes) {
|
|
1586
|
+
if (!isOurs(q)) return { rcode: RCODE.refused };
|
|
1587
|
+
const [name, slug, ...rest] = q.name.slice(0, -DNS_SUFFIX.length).split(".");
|
|
1588
|
+
const from = boxes.find((b) => b.ip === asker);
|
|
1589
|
+
let box;
|
|
1590
|
+
if (from && rest.length === 0) {
|
|
1591
|
+
box = slug === void 0 || slug === slugOf(from.owner) ? boxes.find((b) => b.owner === from.owner && b.name === name) : boxes.find((b) => slugOf(b.owner) === slug && b.name === name && b.linkedFrom?.includes(asker));
|
|
1592
|
+
}
|
|
1593
|
+
if (!box) return { rcode: RCODE.nxDomain };
|
|
1594
|
+
return q.type === TYPE_A ? { rcode: RCODE.ok, ip: box.ip } : { rcode: RCODE.ok };
|
|
1595
|
+
}
|
|
1596
|
+
async function boxAddresses(p) {
|
|
1597
|
+
const out = [];
|
|
1598
|
+
for (const ref of await listMachineRefs(p)) {
|
|
1599
|
+
const meta = await readMachineMeta(ref, p).catch(() => null);
|
|
1600
|
+
if (meta) out.push({ name: meta.name, owner: meta.owner, ip: meta.ip, ...meta.links ? { linkedFrom: meta.links.map((l) => l.ip) } : {} });
|
|
1601
|
+
}
|
|
1602
|
+
return out;
|
|
1603
|
+
}
|
|
1604
|
+
function sharedBoxes(load, freshMs = BOXES_FRESH_MS, version = boxListVersionNow) {
|
|
1605
|
+
let last = null;
|
|
1606
|
+
return () => {
|
|
1607
|
+
if (!last || last.version !== version() || Date.now() - last.at > freshMs) {
|
|
1608
|
+
const entry = { at: Date.now(), version: version(), list: load() };
|
|
1609
|
+
last = entry;
|
|
1610
|
+
entry.list.catch(() => {
|
|
1611
|
+
if (last === entry) last = null;
|
|
1612
|
+
});
|
|
1613
|
+
}
|
|
1614
|
+
return last.list;
|
|
1615
|
+
};
|
|
1616
|
+
}
|
|
1617
|
+
async function startDns(opts) {
|
|
1618
|
+
const p = opts.p ?? paths();
|
|
1619
|
+
const boxes = sharedBoxes(opts.boxes ?? (() => boxAddresses(p)));
|
|
1620
|
+
const socket = createSocket("udp4");
|
|
1621
|
+
socket.on("message", (msg, rinfo) => {
|
|
1622
|
+
const q = parseQuery(msg);
|
|
1623
|
+
if (!q) return;
|
|
1624
|
+
const reply = (a) => socket.send(buildAnswer(q, a.rcode, a.ip), rinfo.port, rinfo.address);
|
|
1625
|
+
if (!isOurs(q)) return reply({ rcode: RCODE.refused });
|
|
1626
|
+
void boxes().then((list) => answerFor(q, rinfo.address, list)).catch(() => ({ rcode: RCODE.refused })).then(reply);
|
|
1627
|
+
});
|
|
1628
|
+
await new Promise((resolve, reject) => {
|
|
1629
|
+
socket.once("error", (err) => {
|
|
1630
|
+
socket.close();
|
|
1631
|
+
reject(err);
|
|
1632
|
+
});
|
|
1633
|
+
socket.bind(opts.port ?? DNS_PORT, opts.host, () => {
|
|
1634
|
+
socket.removeAllListeners("error");
|
|
1635
|
+
socket.on("error", () => {
|
|
1636
|
+
});
|
|
1637
|
+
resolve();
|
|
1638
|
+
});
|
|
1639
|
+
});
|
|
1640
|
+
return { socket, close: () => new Promise((resolve) => socket.close(() => resolve())) };
|
|
1641
|
+
}
|
|
1642
|
+
|
|
1643
|
+
// src/core/machines.ts
|
|
1644
|
+
import { spawn } from "node:child_process";
|
|
1645
|
+
import { closeSync as closeSync2, existsSync as existsSync4, openSync as openSync2, statSync as statSync2 } from "node:fs";
|
|
1646
|
+
import { link as link2, mkdir as mkdir6, readFile as readFile6, realpath, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
|
|
1647
|
+
import { basename } from "node:path";
|
|
1648
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
1649
|
+
|
|
1650
|
+
// src/core/agent.ts
|
|
1651
|
+
import { connect } from "node:net";
|
|
1652
|
+
var AGENT_PORT = 52;
|
|
1653
|
+
async function agentCall(udsPath, req, timeoutMs = 5e3) {
|
|
1654
|
+
const reply = await new Promise((resolve, reject) => {
|
|
1655
|
+
const sock = connect(udsPath);
|
|
1656
|
+
let buf = "";
|
|
1657
|
+
let handshaken = false;
|
|
1658
|
+
const fail = (err) => {
|
|
1659
|
+
sock.destroy();
|
|
1660
|
+
reject(err);
|
|
1661
|
+
};
|
|
1662
|
+
sock.setTimeout(timeoutMs, () => fail(new KvboxError(handshaken ? `kvbox-agent did not answer within ${timeoutMs} ms` : `the guest did not accept the vsock connection within ${timeoutMs} ms`)));
|
|
1663
|
+
sock.once("error", (err) => fail(new KvboxError(`kvbox-agent unreachable: ${err.message}`)));
|
|
1664
|
+
sock.once("connect", () => sock.write(`CONNECT ${AGENT_PORT}
|
|
1665
|
+
`));
|
|
1666
|
+
sock.on("data", (chunk) => {
|
|
1667
|
+
buf += chunk.toString("utf8");
|
|
1668
|
+
let nl;
|
|
1669
|
+
while ((nl = buf.indexOf("\n")) !== -1) {
|
|
1670
|
+
const line = buf.slice(0, nl);
|
|
1671
|
+
buf = buf.slice(nl + 1);
|
|
1672
|
+
if (!handshaken) {
|
|
1673
|
+
if (!line.startsWith("OK ")) return fail(new KvboxError(`vsock connect refused: ${line}`));
|
|
1674
|
+
handshaken = true;
|
|
1675
|
+
sock.write(JSON.stringify(req) + "\n");
|
|
1676
|
+
} else {
|
|
1677
|
+
sock.end();
|
|
1678
|
+
return resolve(line);
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
});
|
|
1682
|
+
sock.once("close", () => {
|
|
1683
|
+
if (!handshaken) fail(new KvboxError("vsock connection closed before the guest accepted"));
|
|
1684
|
+
else fail(new KvboxError("kvbox-agent closed the connection without a reply"));
|
|
1685
|
+
});
|
|
1686
|
+
});
|
|
1687
|
+
let parsed;
|
|
1688
|
+
try {
|
|
1689
|
+
parsed = JSON.parse(reply);
|
|
1690
|
+
} catch {
|
|
1691
|
+
throw new KvboxError(`kvbox-agent sent something that is not JSON: ${reply}`);
|
|
1692
|
+
}
|
|
1693
|
+
if (!parsed.ok) throw new KvboxError(`kvbox-agent: ${parsed.error}`);
|
|
1694
|
+
return parsed;
|
|
1695
|
+
}
|
|
1696
|
+
function setIdentity(udsPath, id, timeoutMs) {
|
|
1697
|
+
return agentCall(udsPath, { op: "identity", ...id }, timeoutMs);
|
|
1698
|
+
}
|
|
1699
|
+
function setAuthorizedKeys(udsPath, lines, timeoutMs) {
|
|
1700
|
+
return agentCall(udsPath, { op: "authorizedKeys", lines: [...lines] }, timeoutMs);
|
|
1701
|
+
}
|
|
1702
|
+
async function stats(udsPath, timeoutMs) {
|
|
1703
|
+
const reply = GuestStatsSchema.safeParse(await agentCall(udsPath, { op: "stats" }, timeoutMs));
|
|
1704
|
+
if (!reply.success) throw new KvboxError(`kvbox-agent sent stats kvbox does not understand: ${reply.error.issues[0]?.message ?? "invalid"}`);
|
|
1705
|
+
return reply.data;
|
|
1706
|
+
}
|
|
1707
|
+
async function dropVolumes(udsPath, timeoutMs) {
|
|
1708
|
+
const reply = await agentCall(udsPath, { op: "dropVolumes" }, timeoutMs);
|
|
1709
|
+
return Array.isArray(reply["dropped"]) ? reply["dropped"].map(String) : [];
|
|
1710
|
+
}
|
|
1711
|
+
function setEnv(udsPath, vars, timeoutMs) {
|
|
1712
|
+
return agentCall(udsPath, { op: "env", vars: vars.map((v) => [v.name, v.value]) }, timeoutMs);
|
|
1713
|
+
}
|
|
1714
|
+
var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
|
|
1715
|
+
var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
|
|
1716
|
+
var isNoAgent = (err) => /vsock connect refused|vsock connection closed before the guest accepted|did not accept the vsock connection|kvbox-agent unreachable: connect (ENOENT|ECONNREFUSED)/.test(err.message ?? "");
|
|
1717
|
+
|
|
1718
|
+
// src/core/env.ts
|
|
1719
|
+
import { mkdir as mkdir3, readFile as readFile5, readdir as readdir2, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
|
|
1720
|
+
import { z as z5 } from "zod";
|
|
1721
|
+
|
|
1722
|
+
// ../shared/src/env.ts
|
|
1723
|
+
var ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
1724
|
+
var ENV_RESERVED = ["PATH", "HOME", "USER", "SHELL"];
|
|
1725
|
+
var ENV_MAX_VALUE_BYTES = 4096;
|
|
1726
|
+
var ENV_MAX_VARS = 100;
|
|
1727
|
+
function envNameProblem(name) {
|
|
1728
|
+
if (!ENV_NAME_RE.test(name)) return `${JSON.stringify(name)} is not a variable name: letters, digits and _, not starting with a digit`;
|
|
1729
|
+
if (ENV_RESERVED.includes(name)) return `${name} is the box's own and cannot be set`;
|
|
1730
|
+
if (name.startsWith("KVBOX_")) return `${name}: names starting with KVBOX_ are kept for kvbox`;
|
|
1731
|
+
return null;
|
|
1732
|
+
}
|
|
1733
|
+
function envValueProblem(value) {
|
|
1734
|
+
if (/[\n\r\0]/.test(value)) return "a value is one line: no line breaks (base64 a multi-line value such as a key file)";
|
|
1735
|
+
if (Buffer.byteLength(value, "utf8") > ENV_MAX_VALUE_BYTES) return `a value is at most ${ENV_MAX_VALUE_BYTES / 1024} KB`;
|
|
1736
|
+
return null;
|
|
1737
|
+
}
|
|
1738
|
+
|
|
1739
|
+
// src/core/locks.ts
|
|
1740
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
1741
|
+
var tails = /* @__PURE__ */ new Map();
|
|
1742
|
+
var held = new AsyncLocalStorage();
|
|
1743
|
+
function withBoxLock(ref, fn) {
|
|
1744
|
+
return withLock(refKey(ref), fn);
|
|
1745
|
+
}
|
|
1746
|
+
function withSnapshotLock(ref, fn) {
|
|
1747
|
+
return withLock(`snapshot:${refKey(ref)}`, fn);
|
|
1748
|
+
}
|
|
1749
|
+
function withHostLock(name, fn) {
|
|
1750
|
+
return withLock(`host:${name}`, fn);
|
|
1751
|
+
}
|
|
1752
|
+
async function withLock(key, fn) {
|
|
1753
|
+
const mine = held.getStore();
|
|
1754
|
+
if (mine?.has(key)) return fn();
|
|
1755
|
+
const previous = tails.get(key);
|
|
1756
|
+
let release;
|
|
1757
|
+
const tail = new Promise((resolve) => release = resolve);
|
|
1758
|
+
tails.set(key, tail);
|
|
1759
|
+
try {
|
|
1760
|
+
await previous;
|
|
1761
|
+
return await held.run(/* @__PURE__ */ new Set([...mine ?? [], key]), fn);
|
|
1762
|
+
} finally {
|
|
1763
|
+
release();
|
|
1764
|
+
if (tails.get(key) === tail) tails.delete(key);
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
function boxBusy(ref) {
|
|
1768
|
+
return tails.has(refKey(ref));
|
|
1769
|
+
}
|
|
1770
|
+
function locked(fn) {
|
|
1771
|
+
return (...args) => withBoxLock(args[0], () => fn(...args));
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
// src/core/env.ts
|
|
1775
|
+
var OwnerEnvSchema = z5.object({
|
|
1776
|
+
/** The control plane's counter for the list; only ever grows. */
|
|
1777
|
+
version: z5.number().int().min(0),
|
|
1778
|
+
vars: z5.array(z5.object({ name: z5.string(), value: z5.string() }))
|
|
1779
|
+
});
|
|
1780
|
+
async function readOwnerEnv(owner, p = paths()) {
|
|
1781
|
+
try {
|
|
1782
|
+
return OwnerEnvSchema.parse(JSON.parse(await readFile5(p.ownerEnv(owner), "utf8")));
|
|
1783
|
+
} catch (err) {
|
|
1784
|
+
if (err.code === "ENOENT") return null;
|
|
1785
|
+
throw err;
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
async function envForBoot(owner, p = paths()) {
|
|
1789
|
+
const env = await readOwnerEnv(owner, p).catch(() => null);
|
|
1790
|
+
if (env !== null) return env.vars;
|
|
1791
|
+
return realmOf(owner) !== null ? [] : null;
|
|
1792
|
+
}
|
|
1793
|
+
async function setOwnerEnv(owner, req, p = paths()) {
|
|
1794
|
+
if (!OWNER_RE.test(owner)) throw new KvboxError(`invalid owner "${owner}"`);
|
|
1795
|
+
if (req.vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);
|
|
1796
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1797
|
+
for (const v of req.vars) {
|
|
1798
|
+
const problem = envNameProblem(v.name) ?? envValueProblem(v.value);
|
|
1799
|
+
if (problem !== null) throw new KvboxError(`${v.name}: ${problem}`);
|
|
1800
|
+
if (seen.has(v.name)) throw new KvboxError(`${v.name} is in the list twice`);
|
|
1801
|
+
seen.add(v.name);
|
|
1802
|
+
}
|
|
1803
|
+
return withHostLock("env", async () => {
|
|
1804
|
+
const have = await readOwnerEnv(owner, p);
|
|
1805
|
+
if (have !== null && have.version > req.version) return { version: have.version };
|
|
1806
|
+
const file = p.ownerEnv(owner);
|
|
1807
|
+
await mkdir3(p.env, { recursive: true, mode: 448 });
|
|
1808
|
+
const tmp = `${file}.tmp`;
|
|
1809
|
+
await writeFile3(tmp, JSON.stringify({ version: req.version, vars: req.vars }, null, 2) + "\n", { mode: 384 });
|
|
1810
|
+
await rename3(tmp, file);
|
|
1811
|
+
return { version: req.version };
|
|
1812
|
+
});
|
|
1813
|
+
}
|
|
1814
|
+
async function listEnvVersions(scope, p = paths()) {
|
|
1815
|
+
let files;
|
|
1816
|
+
try {
|
|
1817
|
+
files = await readdir2(p.env);
|
|
1818
|
+
} catch (err) {
|
|
1819
|
+
if (err.code === "ENOENT") return [];
|
|
1820
|
+
throw err;
|
|
1821
|
+
}
|
|
1822
|
+
const out = [];
|
|
1823
|
+
for (const file of files.filter((f) => f.endsWith(".json")).sort()) {
|
|
1824
|
+
const owner = file.slice(0, -".json".length);
|
|
1825
|
+
if (!OWNER_RE.test(owner) || !inScope(owner, scope)) continue;
|
|
1826
|
+
const env = await readOwnerEnv(owner, p).catch(() => null);
|
|
1827
|
+
if (env !== null) out.push({ owner, version: env.version });
|
|
1828
|
+
}
|
|
1829
|
+
return out;
|
|
1830
|
+
}
|
|
1831
|
+
|
|
1832
|
+
// src/core/volumes.ts
|
|
1833
|
+
import { existsSync, statSync } from "node:fs";
|
|
1834
|
+
import { lstat, mkdir as mkdir4, readdir as readdir3, rm, statfs, symlink, truncate, writeFile as writeFile4 } from "node:fs/promises";
|
|
1835
|
+
|
|
1836
|
+
// ../shared/src/capacity.ts
|
|
1837
|
+
var MEM_HEADROOM_MIB = 2048;
|
|
1838
|
+
function sellableGib(d) {
|
|
1839
|
+
return Math.max(0, d.freeGib + d.volumesUsedGib - d.headroomGib);
|
|
1840
|
+
}
|
|
1841
|
+
function volumeRoomGib(d) {
|
|
1842
|
+
return Math.max(0, sellableGib(d) - d.volumesGib);
|
|
1843
|
+
}
|
|
1844
|
+
function hasDiskRoom(d, sizeGib) {
|
|
1845
|
+
return sizeGib <= volumeRoomGib(d);
|
|
1846
|
+
}
|
|
1847
|
+
var VCPU_OVERSUBSCRIPTION = 2;
|
|
1848
|
+
|
|
1706
1849
|
// src/core/volumes.ts
|
|
1707
1850
|
var volumeLabel = (name) => `kv:${name}`;
|
|
1708
1851
|
function toVolume(meta, attachedTo, p) {
|
|
@@ -2148,9 +2291,11 @@ async function snapshotBox(ref, req, owner, p) {
|
|
|
2148
2291
|
}
|
|
2149
2292
|
throw new KvboxError(`box ${req.box} is not running; a snapshot freezes a running box (kvbox start ${req.box} first)`);
|
|
2150
2293
|
}
|
|
2151
|
-
const
|
|
2152
|
-
if (existsSync2(
|
|
2294
|
+
const final = p.snapshot(owner, req.name);
|
|
2295
|
+
if (existsSync2(final.dir) && !req.replace) throw new KvboxError(`snapshot ${req.name} already exists (--replace retakes it)`);
|
|
2296
|
+
const s = req.replace ? p.snapshot(owner, `.${req.name}.new-${box.id}`) : final;
|
|
2153
2297
|
const cfg = await loadConfig(p);
|
|
2298
|
+
if (s !== final) await rm2(s.dir, { recursive: true, force: true });
|
|
2154
2299
|
await mkdir5(s.dir, { recursive: true, mode: 448 });
|
|
2155
2300
|
try {
|
|
2156
2301
|
const volumes = await captureDrivesOf(box, p);
|
|
@@ -2166,13 +2311,30 @@ async function snapshotBox(ref, req, owner, p) {
|
|
|
2166
2311
|
sizeBytes: await usedBytes(s.dir),
|
|
2167
2312
|
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2168
2313
|
};
|
|
2169
|
-
await writeSnapshotMeta(meta, p);
|
|
2314
|
+
await writeSnapshotMeta(meta, p, s);
|
|
2315
|
+
if (s !== final) await swapIn({ owner, name: req.name }, s.dir, box.id, p);
|
|
2170
2316
|
return toSnapshot(meta);
|
|
2171
2317
|
} catch (err) {
|
|
2172
2318
|
await rm2(s.dir, { recursive: true, force: true });
|
|
2173
2319
|
throw err;
|
|
2174
2320
|
}
|
|
2175
2321
|
}
|
|
2322
|
+
async function swapIn(ref, from, boxId, p) {
|
|
2323
|
+
const to = p.snapshot(ref.owner, ref.name).dir;
|
|
2324
|
+
const old = p.snapshot(ref.owner, `.${ref.name}.old-${boxId}`).dir;
|
|
2325
|
+
await withSnapshotLock(ref, async () => {
|
|
2326
|
+
await rm2(old, { recursive: true, force: true });
|
|
2327
|
+
const hadOld = existsSync2(to);
|
|
2328
|
+
if (hadOld) await rename4(to, old);
|
|
2329
|
+
try {
|
|
2330
|
+
await rename4(from, to);
|
|
2331
|
+
} catch (err) {
|
|
2332
|
+
if (hadOld) await rename4(old, to);
|
|
2333
|
+
throw err;
|
|
2334
|
+
}
|
|
2335
|
+
});
|
|
2336
|
+
await rm2(old, { recursive: true, force: true });
|
|
2337
|
+
}
|
|
2176
2338
|
async function captureBox(box, to, cfg, p) {
|
|
2177
2339
|
const m = p.machine(box.owner, box.name);
|
|
2178
2340
|
const fc = new FirecrackerClient(m.sock);
|
|
@@ -2218,8 +2380,8 @@ async function mergeOntoPrevious(previous, diffFile, editor) {
|
|
|
2218
2380
|
}
|
|
2219
2381
|
async function deleteSnapshot(ref, p = paths()) {
|
|
2220
2382
|
const dir = p.snapshot(ref.owner, ref.name).dir;
|
|
2221
|
-
if (!existsSync2(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);
|
|
2222
|
-
await rm2(dir, { recursive: true, force: true });
|
|
2383
|
+
if (ref.name.startsWith(".") || !existsSync2(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);
|
|
2384
|
+
await withSnapshotLock(ref, () => rm2(dir, { recursive: true, force: true }));
|
|
2223
2385
|
}
|
|
2224
2386
|
|
|
2225
2387
|
// src/core/network.ts
|
|
@@ -2263,12 +2425,15 @@ async function ensureHostNetwork(cfg) {
|
|
|
2263
2425
|
return "created";
|
|
2264
2426
|
}
|
|
2265
2427
|
async function createTap(box, cfg, opts = {}) {
|
|
2266
|
-
const tap = tapName(box);
|
|
2267
|
-
await netRun(cfg, ["tap", "add", tap, ...opts.detached ? ["detached"] : []]);
|
|
2428
|
+
const tap = tapName(box.id);
|
|
2429
|
+
await netRun(cfg, ["tap", "add", tap, box.ip, box.mac, ...opts.detached ? ["detached"] : []]);
|
|
2268
2430
|
return tap;
|
|
2269
2431
|
}
|
|
2270
2432
|
async function attachTap(box, cfg) {
|
|
2271
|
-
await netRun(cfg, ["tap", "attach", tapName(box)]);
|
|
2433
|
+
await netRun(cfg, ["tap", "attach", tapName(box.id), box.ip, box.mac]);
|
|
2434
|
+
}
|
|
2435
|
+
async function pinTap(box, cfg) {
|
|
2436
|
+
await netRun(cfg, ["tap", "pin", tapName(box.id), box.ip, box.mac]);
|
|
2272
2437
|
}
|
|
2273
2438
|
async function deleteTap(box, cfg) {
|
|
2274
2439
|
await netRun(cfg, ["tap", "del", tapName(box)]);
|
|
@@ -2313,6 +2478,13 @@ var proxyArgs = (p) => [p.box, p.boxIp, String(p.hostPort), String(p.guestPort),
|
|
|
2313
2478
|
async function openProxy(proxy, cfg) {
|
|
2314
2479
|
await netRun(cfg, ["proxy", "add", ...proxyArgs(proxy)]);
|
|
2315
2480
|
}
|
|
2481
|
+
var linkArgs = (l) => [l.box, l.fromIp, l.toIp, String(l.port)];
|
|
2482
|
+
async function openLink(link3, cfg) {
|
|
2483
|
+
await netRun(cfg, ["link", "add", ...linkArgs(link3)]);
|
|
2484
|
+
}
|
|
2485
|
+
async function closeLink(link3, cfg) {
|
|
2486
|
+
await netRun(cfg, ["link", "rm", ...linkArgs(link3)]);
|
|
2487
|
+
}
|
|
2316
2488
|
async function closeProxy(proxy, cfg) {
|
|
2317
2489
|
await netRun(cfg, ["proxy", "rm", ...proxyArgs(proxy)]);
|
|
2318
2490
|
}
|
|
@@ -2348,13 +2520,29 @@ function boxProxies(meta) {
|
|
|
2348
2520
|
const ssh = meta.sshPort === void 0 ? [] : [{ box: meta.id, boxIp: meta.ip, hostPort: meta.sshPort, guestPort: 22 }];
|
|
2349
2521
|
return [...ssh, ...(meta.ports ?? []).map((f) => ({ box: meta.id, boxIp: meta.ip, hostPort: f.hostPort, guestPort: f.guestPort, proto: f.proto }))];
|
|
2350
2522
|
}
|
|
2351
|
-
|
|
2523
|
+
function boxLinks(meta) {
|
|
2524
|
+
return (meta.links ?? []).map((l) => ({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }));
|
|
2525
|
+
}
|
|
2526
|
+
async function standingLinks(meta, p) {
|
|
2527
|
+
const links = boxLinks(meta);
|
|
2528
|
+
const stands = await Promise.all(
|
|
2529
|
+
(meta.links ?? []).map(async (l) => !l.stale && (await readMachineMeta({ owner: l.owner, name: l.name }, p).catch(() => null))?.ip === l.ip)
|
|
2530
|
+
);
|
|
2531
|
+
return links.filter((_, i) => stands[i]);
|
|
2532
|
+
}
|
|
2533
|
+
async function openPorts(meta, cfg, p) {
|
|
2352
2534
|
for (const proxy of boxProxies(meta)) await openProxy(proxy, cfg);
|
|
2535
|
+
for (const link3 of await standingLinks(meta, p)) {
|
|
2536
|
+
await openLink(link3, cfg).catch((err) => console.error(`warning: could not open the link from ${link3.fromIp}: ${err.message}`));
|
|
2537
|
+
}
|
|
2353
2538
|
}
|
|
2354
2539
|
async function closePorts(meta, cfg) {
|
|
2355
2540
|
for (const proxy of boxProxies(meta)) {
|
|
2356
2541
|
await closeProxy(proxy, cfg).catch((err) => console.error(`warning: could not close port ${proxy.hostPort}: ${err.message}`));
|
|
2357
2542
|
}
|
|
2543
|
+
for (const link3 of boxLinks(meta)) {
|
|
2544
|
+
await closeLink(link3, cfg).catch((err) => console.error(`warning: could not close the link from ${link3.fromIp}: ${err.message}`));
|
|
2545
|
+
}
|
|
2358
2546
|
}
|
|
2359
2547
|
var reservedPorts = /* @__PURE__ */ new Set();
|
|
2360
2548
|
async function drawPorts(count, p) {
|
|
@@ -2429,9 +2617,11 @@ function toMachine(meta, p = paths()) {
|
|
|
2429
2617
|
...meta.sshPort === void 0 ? {} : { sshPort: meta.sshPort },
|
|
2430
2618
|
...meta.ports?.length ? { ports: meta.ports.map((f) => ({ ...f })) } : {},
|
|
2431
2619
|
...meta.autoHibernateSec ? { autoHibernateSec: meta.autoHibernateSec } : {},
|
|
2432
|
-
...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {}
|
|
2620
|
+
...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {},
|
|
2621
|
+
...meta.links?.some((l) => !l.stale) ? { links: meta.links.filter((l) => !l.stale).map((l) => ({ from: linkFrom(l, meta.owner), port: l.port })) } : {}
|
|
2433
2622
|
};
|
|
2434
2623
|
}
|
|
2624
|
+
var linkFrom = (l, owner) => l.owner === owner ? l.name : `${l.owner.split("@")[0]}/${l.name}`;
|
|
2435
2625
|
function autoHibernateFor(req, cfg) {
|
|
2436
2626
|
return (req.autoHibernateSec ?? cfg.autoHibernateSec) || void 0;
|
|
2437
2627
|
}
|
|
@@ -2667,11 +2857,11 @@ async function bootInto(box, prepare, origin, cfg, p) {
|
|
|
2667
2857
|
drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
|
|
2668
2858
|
sshPort = drawn?.ports[0];
|
|
2669
2859
|
await prepare(m);
|
|
2670
|
-
const tap = await createTap(
|
|
2860
|
+
const tap = await createTap(box, cfg);
|
|
2671
2861
|
tapCreated = true;
|
|
2672
2862
|
const spec = { ...box, sshPort };
|
|
2673
2863
|
pid = await launch(spec, tap, cfg, keysB64, p);
|
|
2674
|
-
await openPorts(spec, cfg);
|
|
2864
|
+
await openPorts(spec, cfg, p);
|
|
2675
2865
|
void pushEnvAfterBoot(spec, pid, m.vsock, p);
|
|
2676
2866
|
const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin };
|
|
2677
2867
|
await writeMachineMeta(meta, p);
|
|
@@ -2682,12 +2872,14 @@ async function bootInto(box, prepare, origin, cfg, p) {
|
|
|
2682
2872
|
await closePorts({ id, ip, sshPort }, cfg);
|
|
2683
2873
|
if (tapCreated) await deleteTap(id, cfg).catch(() => void 0);
|
|
2684
2874
|
await rm3(m.dir, { recursive: true, force: true });
|
|
2875
|
+
boxListChanged();
|
|
2685
2876
|
throw err;
|
|
2686
2877
|
} finally {
|
|
2687
2878
|
drawn?.release();
|
|
2688
2879
|
}
|
|
2689
2880
|
}
|
|
2690
2881
|
async function readSnap(ref, p) {
|
|
2882
|
+
if (ref.name.startsWith(".")) throw new NotFoundError(`snapshot ${shown(ref)}`);
|
|
2691
2883
|
try {
|
|
2692
2884
|
return await readSnapshotMeta(ref, p);
|
|
2693
2885
|
} catch (err) {
|
|
@@ -2700,6 +2892,9 @@ function prefixLenOf(subnet) {
|
|
|
2700
2892
|
}
|
|
2701
2893
|
async function restoreMachine(fromText, owner, req, cfg, p) {
|
|
2702
2894
|
const from = parseRef(fromText, owner);
|
|
2895
|
+
return withSnapshotLock(from, () => restoreFrom(from, owner, req, cfg, p));
|
|
2896
|
+
}
|
|
2897
|
+
async function restoreFrom(from, owner, req, cfg, p) {
|
|
2703
2898
|
const snap = await readSnap(from, p);
|
|
2704
2899
|
if (req.size !== void 0) {
|
|
2705
2900
|
throw new KvboxError(`--size cannot be combined with --from: a restored box has the snapshot's size (${shown(from)}: ${snap.vcpu} vCPU, ${snap.memMib} MiB)`);
|
|
@@ -2742,7 +2937,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
|
|
|
2742
2937
|
drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
|
|
2743
2938
|
sshPort = drawn?.ports[0];
|
|
2744
2939
|
const image = await prepare(m);
|
|
2745
|
-
const tap = await createTap(
|
|
2940
|
+
const tap = await createTap(box, cfg, { detached: true });
|
|
2746
2941
|
tapCreated = true;
|
|
2747
2942
|
const spec = { ...box, sshPort };
|
|
2748
2943
|
pid = await loadSnapshot(spec, image, tap, cfg, p);
|
|
@@ -2755,8 +2950,8 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
|
|
|
2755
2950
|
if (stale && keysOrFail) throw new KvboxError(`${keysOrFail}: ${stale}`);
|
|
2756
2951
|
if (image.volumes?.length) await dropGuestVolumes(box, m.vsock);
|
|
2757
2952
|
await pushEnv(box, m.vsock, p);
|
|
2758
|
-
await attachTap(
|
|
2759
|
-
await openPorts(spec, cfg);
|
|
2953
|
+
await attachTap(box, cfg);
|
|
2954
|
+
await openPorts(spec, cfg, p);
|
|
2760
2955
|
const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin, memSnapshots: 1, sshKeysStale: stale ? true : void 0 };
|
|
2761
2956
|
await writeMachineMeta(meta, p);
|
|
2762
2957
|
recordState(meta, "running", "new", p, meta.createdAt);
|
|
@@ -2766,6 +2961,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
|
|
|
2766
2961
|
await closePorts({ id, ip, sshPort }, cfg);
|
|
2767
2962
|
if (tapCreated) await deleteTap(id, cfg).catch(() => void 0);
|
|
2768
2963
|
await rm3(m.dir, { recursive: true, force: true });
|
|
2964
|
+
boxListChanged();
|
|
2769
2965
|
throw err;
|
|
2770
2966
|
} finally {
|
|
2771
2967
|
drawn?.release();
|
|
@@ -2972,11 +3168,11 @@ var startMachine = locked(async function startMachine2(ref, p = paths()) {
|
|
|
2972
3168
|
assertAssets(cfg);
|
|
2973
3169
|
const keysB64 = authorizedKeysB64(await readHostPubkey(p), meta.sshKeys ?? []);
|
|
2974
3170
|
await ensureHostNetwork(cfg);
|
|
2975
|
-
const tap = await createTap(meta
|
|
3171
|
+
const tap = await createTap(meta, cfg);
|
|
2976
3172
|
let pid;
|
|
2977
3173
|
try {
|
|
2978
3174
|
pid = await launch(meta, tap, cfg, keysB64, p);
|
|
2979
|
-
await openPorts(meta, cfg);
|
|
3175
|
+
await openPorts(meta, cfg, p);
|
|
2980
3176
|
void pushEnvAfterBoot(meta, pid, p.machine(meta.owner, meta.name).vsock, p);
|
|
2981
3177
|
const started = { ...meta, pid, bootId: currentBootId(), sshKeysStale: void 0 };
|
|
2982
3178
|
await writeMachineMeta(started, p);
|
|
@@ -3112,7 +3308,7 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths()) {
|
|
|
3112
3308
|
}
|
|
3113
3309
|
const m = p.machine(ref.owner, ref.name);
|
|
3114
3310
|
await ensureHostNetwork(cfg);
|
|
3115
|
-
const tap = await createTap(meta
|
|
3311
|
+
const tap = await createTap(meta, cfg, { detached: true });
|
|
3116
3312
|
let pid;
|
|
3117
3313
|
let stale;
|
|
3118
3314
|
try {
|
|
@@ -3124,8 +3320,8 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths()) {
|
|
|
3124
3320
|
noAnswer: `the box stays hibernated. kvbox-agent inside it took the request but gave no answer; try kvbox wake ${shown(ref)} again`
|
|
3125
3321
|
});
|
|
3126
3322
|
stale = await pushAuthorizedKeys(meta, m.vsock, p);
|
|
3127
|
-
await attachTap(meta
|
|
3128
|
-
await openPorts(meta, cfg);
|
|
3323
|
+
await attachTap(meta, cfg);
|
|
3324
|
+
await openPorts(meta, cfg, p);
|
|
3129
3325
|
} catch (err) {
|
|
3130
3326
|
if (pid !== void 0) killQuietly(pid);
|
|
3131
3327
|
await closePorts(meta, cfg);
|
|
@@ -3272,6 +3468,49 @@ var removePorts = locked(async function removePorts2(ref, req, p = paths()) {
|
|
|
3272
3468
|
await writeMachineMeta(next, p);
|
|
3273
3469
|
return toMachine(next, p);
|
|
3274
3470
|
});
|
|
3471
|
+
function linkSource(req, caller, target) {
|
|
3472
|
+
if (req.fromOwner !== void 0) return { owner: ownerFor(req.fromOwner, caller), name: req.from, display: `${req.fromOwner}/${req.from}` };
|
|
3473
|
+
const ref = parseRef(req.from, caller);
|
|
3474
|
+
const realm = realmOf(target);
|
|
3475
|
+
return realm !== null && realmOf(ref.owner) === null && req.from.includes("/") ? { ...ref, owner: `${ref.owner}@${realm}` } : ref;
|
|
3476
|
+
}
|
|
3477
|
+
var addLink = locked(async function addLink2(ref, req, caller, p = paths()) {
|
|
3478
|
+
const meta = await readMeta(ref, p);
|
|
3479
|
+
const fromRef = linkSource(req, caller, meta.owner);
|
|
3480
|
+
if (fromRef.owner === meta.owner && fromRef.name === meta.name) throw new KvboxError(`box ${shown(ref)} already reaches itself`);
|
|
3481
|
+
const from = await readMeta(fromRef, p);
|
|
3482
|
+
if (realmOf(from.owner) !== realmOf(meta.owner)) {
|
|
3483
|
+
throw new KvboxError(`box ${shown(fromRef)} and box ${shown(ref)} belong to different realms (one is this host's, one a control plane's); a link joins boxes of one realm`);
|
|
3484
|
+
}
|
|
3485
|
+
const links = (meta.links ?? []).filter((l) => !(l.stale && l.owner === from.owner && l.name === from.name && l.ip === from.ip && l.port === req.port));
|
|
3486
|
+
const same = (l) => !l.stale && l.owner === from.owner && l.name === from.name && l.port === req.port;
|
|
3487
|
+
if (links.some(same)) throw new KvboxError(`box ${shown(fromRef)} already reaches box ${shown(ref)} on port ${req.port}`);
|
|
3488
|
+
if (links.length >= MAX_BOX_LINKS) throw new KvboxError(`a box takes at most ${MAX_BOX_LINKS} links; box ${shown(ref)} has ${links.length}`);
|
|
3489
|
+
const added = { owner: from.owner, name: from.name, ip: from.ip, port: req.port };
|
|
3490
|
+
const cfg = await loadConfig(p);
|
|
3491
|
+
if (vmAlive(meta)) await openLink({ box: meta.id, fromIp: from.ip, toIp: meta.ip, port: req.port }, cfg);
|
|
3492
|
+
const next = { ...meta, links: [...links, added] };
|
|
3493
|
+
try {
|
|
3494
|
+
await writeMachineMeta(next, p);
|
|
3495
|
+
} catch (err) {
|
|
3496
|
+
await closeLink({ box: meta.id, fromIp: from.ip, toIp: meta.ip, port: req.port }, cfg).catch(() => void 0);
|
|
3497
|
+
throw err;
|
|
3498
|
+
}
|
|
3499
|
+
return toMachine(next, p);
|
|
3500
|
+
});
|
|
3501
|
+
var removeLink = locked(async function removeLink2(ref, req, caller, p = paths()) {
|
|
3502
|
+
const meta = await readMeta(ref, p);
|
|
3503
|
+
const fromRef = linkSource(req, caller, meta.owner);
|
|
3504
|
+
const links = meta.links ?? [];
|
|
3505
|
+
const gone = links.filter((l) => !l.stale && l.owner === fromRef.owner && l.name === fromRef.name && l.port === req.port);
|
|
3506
|
+
if (gone.length === 0) throw new KvboxError(`box ${shown(fromRef)} is not linked to box ${shown(ref)} on port ${req.port}`);
|
|
3507
|
+
const cfg = await loadConfig(p);
|
|
3508
|
+
for (const l of gone) await closeLink({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }, cfg);
|
|
3509
|
+
const kept = links.filter((l) => !gone.includes(l));
|
|
3510
|
+
const next = { ...meta, links: kept.length > 0 ? kept : void 0 };
|
|
3511
|
+
await writeMachineMeta(next, p);
|
|
3512
|
+
return toMachine(next, p);
|
|
3513
|
+
});
|
|
3275
3514
|
async function growDisk(file, gib) {
|
|
3276
3515
|
await truncate2(file, gib * 1024 ** 3);
|
|
3277
3516
|
await run(["e2fsck", "-f", "-p", file], { okExitCodes: [1] });
|
|
@@ -3285,13 +3524,54 @@ async function readMeta(ref, p) {
|
|
|
3285
3524
|
throw err;
|
|
3286
3525
|
}
|
|
3287
3526
|
}
|
|
3288
|
-
|
|
3527
|
+
async function destroyMachine(ref, p = paths()) {
|
|
3528
|
+
const gone = await destroyBox(ref, p);
|
|
3529
|
+
await dropLinksFrom(gone, p);
|
|
3530
|
+
}
|
|
3531
|
+
var destroyBox = locked(async function destroyBox2(ref, p = paths()) {
|
|
3289
3532
|
const meta = await readMeta(ref, p);
|
|
3290
3533
|
const cfg = await loadConfig(p);
|
|
3291
3534
|
await shutdown(meta, cfg, p, 2e3);
|
|
3535
|
+
await closeLinksFrom(meta, cfg, p).catch((err) => {
|
|
3536
|
+
recordState(meta, "stopped", "stop", p);
|
|
3537
|
+
throw err;
|
|
3538
|
+
});
|
|
3292
3539
|
recordState(meta, "stopped", "rm", p);
|
|
3293
3540
|
await rm3(p.machine(ref.owner, ref.name).dir, { recursive: true, force: true });
|
|
3541
|
+
boxListChanged();
|
|
3542
|
+
return meta;
|
|
3294
3543
|
});
|
|
3544
|
+
var linkOf = (gone) => (l) => l.owner === gone.owner && l.name === gone.name && l.ip === gone.ip;
|
|
3545
|
+
async function closeLinksFrom(gone, cfg, p) {
|
|
3546
|
+
const isGone = linkOf(gone);
|
|
3547
|
+
for (const ref of await listMachineRefs(p)) {
|
|
3548
|
+
const meta = await readMachineMeta(ref, p).catch(() => null);
|
|
3549
|
+
for (const l of meta?.links?.filter(isGone) ?? []) {
|
|
3550
|
+
await closeLink({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }, cfg).catch((err) => {
|
|
3551
|
+
throw new KvboxError(`box ${shown(gone)} is stopped but not removed: could not close its link into ${shown(meta)} (${err.message}); try again`);
|
|
3552
|
+
});
|
|
3553
|
+
}
|
|
3554
|
+
}
|
|
3555
|
+
}
|
|
3556
|
+
async function dropLinksFrom(gone, p) {
|
|
3557
|
+
const cfg = await loadConfig(p);
|
|
3558
|
+
const isGone = linkOf(gone);
|
|
3559
|
+
for (const ref of await listMachineRefs(p)) {
|
|
3560
|
+
await withBoxLock(ref, async () => {
|
|
3561
|
+
const meta = await readMachineMeta(ref, p).catch(() => null);
|
|
3562
|
+
if (!meta?.links?.some(isGone)) return;
|
|
3563
|
+
const stuck = /* @__PURE__ */ new Set();
|
|
3564
|
+
for (const l of meta.links.filter(isGone)) {
|
|
3565
|
+
await closeLink({ box: meta.id, fromIp: l.ip, toIp: meta.ip, port: l.port }, cfg).catch((err) => {
|
|
3566
|
+
stuck.add(l);
|
|
3567
|
+
console.error(`warning: could not close the link from removed box ${gone.name} into ${meta.name}: ${err.message}`);
|
|
3568
|
+
});
|
|
3569
|
+
}
|
|
3570
|
+
const kept = meta.links.filter((l) => !isGone(l) || stuck.has(l)).map((l) => stuck.has(l) ? { ...l, stale: true } : l);
|
|
3571
|
+
await writeMachineMeta({ ...meta, links: kept.length > 0 ? kept : void 0 }, p);
|
|
3572
|
+
}).catch((err) => console.error(`warning: links of removed box ${gone.name}: ${err.message}`));
|
|
3573
|
+
}
|
|
3574
|
+
}
|
|
3295
3575
|
var RECOVERY_CONCURRENCY = 2;
|
|
3296
3576
|
async function settleDeadBoxes(p = paths()) {
|
|
3297
3577
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
@@ -3319,6 +3599,14 @@ async function settleDeadBoxes(p = paths()) {
|
|
|
3319
3599
|
function cutByReboot(meta) {
|
|
3320
3600
|
return meta.pid !== null && meta.bootId !== currentBootId();
|
|
3321
3601
|
}
|
|
3602
|
+
async function pinRunningTaps(p = paths()) {
|
|
3603
|
+
const cfg = await loadConfig(p);
|
|
3604
|
+
if (!bridgeExists(cfg.bridge)) return;
|
|
3605
|
+
for (const meta of await readAllMeta(p)) {
|
|
3606
|
+
if (!vmAlive(meta) || !existsSync4(`/sys/class/net/${tapName(meta.id)}`)) continue;
|
|
3607
|
+
await pinTap(meta, cfg).catch((err) => console.error(`warning: could not pin box ${meta.name}'s tap: ${err.message}`));
|
|
3608
|
+
}
|
|
3609
|
+
}
|
|
3322
3610
|
var recovery = null;
|
|
3323
3611
|
var recoveryStopping = false;
|
|
3324
3612
|
var recoveryRun = Promise.resolve();
|
|
@@ -3489,7 +3777,7 @@ function startIdleWatch(opts = {}) {
|
|
|
3489
3777
|
const started = [];
|
|
3490
3778
|
const watched = /* @__PURE__ */ new Set();
|
|
3491
3779
|
for (const box of await list()) {
|
|
3492
|
-
if (!box.autoHibernateSec || box.status !== "running") continue;
|
|
3780
|
+
if (!box.autoHibernateSec || box.status !== "running" || box.links?.length) continue;
|
|
3493
3781
|
if (inflight.has(box.id)) {
|
|
3494
3782
|
watched.add(box.id);
|
|
3495
3783
|
continue;
|
|
@@ -3609,7 +3897,7 @@ function versionOf(srcFileUrl, injected) {
|
|
|
3609
3897
|
}
|
|
3610
3898
|
|
|
3611
3899
|
// src/version.ts
|
|
3612
|
-
var VERSION = versionOf(import.meta.url, true ? "0.5.
|
|
3900
|
+
var VERSION = versionOf(import.meta.url, true ? "0.5.28" : void 0);
|
|
3613
3901
|
|
|
3614
3902
|
// src/caller.ts
|
|
3615
3903
|
import { createHash as createHash2, timingSafeEqual } from "node:crypto";
|
|
@@ -4028,6 +4316,13 @@ function machineRoutes() {
|
|
|
4028
4316
|
if (!body.success) throw new KvboxError("ports: expected a list of box ports");
|
|
4029
4317
|
return c.json(await removePorts(parseRef(c.req.param("name"), c.get("owner")), body.data));
|
|
4030
4318
|
});
|
|
4319
|
+
const linkBody = async (c) => {
|
|
4320
|
+
const body = LinkRequest.safeParse(await c.req.json().catch(() => ({})));
|
|
4321
|
+
if (!body.success) throw new KvboxError("links: expected {from, port}");
|
|
4322
|
+
return body.data;
|
|
4323
|
+
};
|
|
4324
|
+
r.post("/:name/links", async (c) => c.json(await addLink(parseRef(c.req.param("name"), c.get("owner")), await linkBody(c), c.get("owner")), 201));
|
|
4325
|
+
r.delete("/:name/links", async (c) => c.json(await removeLink(parseRef(c.req.param("name"), c.get("owner")), await linkBody(c), c.get("owner"))));
|
|
4031
4326
|
r.get("/:name/usage", async (c) => {
|
|
4032
4327
|
const since = c.req.query("since");
|
|
4033
4328
|
let from;
|
|
@@ -4258,9 +4553,22 @@ program.command("start", { isDefault: true }).description("serve the API on the
|
|
|
4258
4553
|
const cfg = await loadConfig(paths());
|
|
4259
4554
|
const state = await ensureHostNetwork(cfg);
|
|
4260
4555
|
console.log(`host network: bridge ${cfg.bridge} ${state}`);
|
|
4556
|
+
await pinRunningTaps(paths());
|
|
4261
4557
|
} catch (err) {
|
|
4262
4558
|
console.error(`warning: host network not ready (${err.message}); run: kvbox-server net up`);
|
|
4263
4559
|
}
|
|
4560
|
+
let dnsWarned = false;
|
|
4561
|
+
const bindDns = () => {
|
|
4562
|
+
loadConfig(paths()).then(async (cfg) => {
|
|
4563
|
+
await startDns({ host: cfg.gateway });
|
|
4564
|
+
console.log(`box names: <name>.kvbox answered on ${cfg.gateway}`);
|
|
4565
|
+
}).catch((err) => {
|
|
4566
|
+
if (!dnsWarned) console.error(`warning: box names (<name>.kvbox) do not resolve yet (${err.message}); retrying`);
|
|
4567
|
+
dnsWarned = true;
|
|
4568
|
+
setTimeout(bindDns, DNS_RETRY_MS).unref();
|
|
4569
|
+
});
|
|
4570
|
+
};
|
|
4571
|
+
bindDns();
|
|
4264
4572
|
startRelayWatch();
|
|
4265
4573
|
startIdleWatch();
|
|
4266
4574
|
const recovery2 = await bootRecovered(settled, paths());
|