@kvbox/server 0.5.23 → 0.5.25
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/README.md +11 -0
- package/dist/kvbox-server.js +305 -142
- package/dist/kvbox-server.js.map +1 -1
- package/package.json +1 -1
package/dist/kvbox-server.js
CHANGED
|
@@ -106,6 +106,9 @@ function paths(home = kvboxHome()) {
|
|
|
106
106
|
disk: join(dir, "disk.ext4")
|
|
107
107
|
};
|
|
108
108
|
},
|
|
109
|
+
/** Each owner's environment variables as the control plane last sent them (#88): env/<owner>.json, mode 600. */
|
|
110
|
+
env: join(home, "env"),
|
|
111
|
+
ownerEnv: (owner) => join(home, "env", `${owner}.json`),
|
|
109
112
|
snapshot: (owner, name) => {
|
|
110
113
|
const dir = join(home, "snapshots", owner, name);
|
|
111
114
|
return {
|
|
@@ -513,15 +516,35 @@ var CreateVolumeRequest = z3.object({
|
|
|
513
516
|
name: z3.string(),
|
|
514
517
|
sizeGib: z3.number().int().min(1).max(MAX_VOLUME_GIB),
|
|
515
518
|
/**
|
|
516
|
-
* Through a control plane (#91): the box this volume is for, so it is made on that box's host
|
|
517
|
-
* volume attaches only to a box on its own host
|
|
518
|
-
* A host ignores it.
|
|
519
|
+
* Through a control plane (#91): the box this volume is for, so it is made on that box's host; the
|
|
520
|
+
* control plane requires it (a volume attaches only to a box on its own host, so one made for no box
|
|
521
|
+
* could never attach) and the CLI attaches right after. A host ignores it.
|
|
519
522
|
*/
|
|
520
523
|
box: z3.string().optional()
|
|
521
524
|
});
|
|
522
525
|
var AttachVolumeRequest = z3.object({
|
|
523
526
|
box: z3.string()
|
|
524
527
|
});
|
|
528
|
+
var EnvVarSchema = z3.object({
|
|
529
|
+
name: z3.string(),
|
|
530
|
+
value: z3.string().optional(),
|
|
531
|
+
secret: z3.boolean(),
|
|
532
|
+
updatedAt: z3.string()
|
|
533
|
+
});
|
|
534
|
+
var SetEnvRequest = z3.object({
|
|
535
|
+
value: z3.string(),
|
|
536
|
+
secret: z3.boolean().optional()
|
|
537
|
+
});
|
|
538
|
+
var EnvChangeSchema = z3.object({
|
|
539
|
+
owner: z3.string(),
|
|
540
|
+
name: z3.string(),
|
|
541
|
+
boxes: z3.number().int()
|
|
542
|
+
});
|
|
543
|
+
var HostEnvRequest = z3.object({
|
|
544
|
+
version: z3.number().int().min(0),
|
|
545
|
+
vars: z3.array(z3.object({ name: z3.string(), value: z3.string() }))
|
|
546
|
+
});
|
|
547
|
+
var HostEnvVersionsSchema = z3.array(z3.object({ owner: z3.string(), version: z3.number().int() }));
|
|
525
548
|
var CreateMachineRequest = z3.object({
|
|
526
549
|
name: z3.string().optional(),
|
|
527
550
|
/** Ignored over the local socket (the caller is the host owner); the control plane sets it over HTTPS. */
|
|
@@ -1111,7 +1134,7 @@ async function requireKvm(device = KVM_DEVICE, groupFile = "/etc/group") {
|
|
|
1111
1134
|
// src/core/machines.ts
|
|
1112
1135
|
import { spawn } from "node:child_process";
|
|
1113
1136
|
import { closeSync as closeSync2, existsSync as existsSync4, openSync as openSync2, statSync as statSync2 } from "node:fs";
|
|
1114
|
-
import { link as link2, mkdir as
|
|
1137
|
+
import { link as link2, mkdir as mkdir6, readFile as readFile6, realpath, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
|
|
1115
1138
|
import { basename } from "node:path";
|
|
1116
1139
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
1117
1140
|
|
|
@@ -1127,7 +1150,7 @@ async function agentCall(udsPath, req, timeoutMs = 5e3) {
|
|
|
1127
1150
|
sock.destroy();
|
|
1128
1151
|
reject(err);
|
|
1129
1152
|
};
|
|
1130
|
-
sock.setTimeout(timeoutMs, () => fail(new KvboxError(`kvbox-agent did not answer within ${timeoutMs} ms`)));
|
|
1153
|
+
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`)));
|
|
1131
1154
|
sock.once("error", (err) => fail(new KvboxError(`kvbox-agent unreachable: ${err.message}`)));
|
|
1132
1155
|
sock.once("connect", () => sock.write(`CONNECT ${AGENT_PORT}
|
|
1133
1156
|
`));
|
|
@@ -1176,12 +1199,127 @@ async function dropVolumes(udsPath, timeoutMs) {
|
|
|
1176
1199
|
const reply = await agentCall(udsPath, { op: "dropVolumes" }, timeoutMs);
|
|
1177
1200
|
return Array.isArray(reply["dropped"]) ? reply["dropped"].map(String) : [];
|
|
1178
1201
|
}
|
|
1202
|
+
function setEnv(udsPath, vars, timeoutMs) {
|
|
1203
|
+
return agentCall(udsPath, { op: "env", vars: vars.map((v) => [v.name, v.value]) }, timeoutMs);
|
|
1204
|
+
}
|
|
1179
1205
|
var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
|
|
1180
|
-
var
|
|
1206
|
+
var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
|
|
1207
|
+
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 ?? "");
|
|
1208
|
+
|
|
1209
|
+
// src/core/env.ts
|
|
1210
|
+
import { mkdir as mkdir2, readFile as readFile4, readdir, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
|
|
1211
|
+
import { z as z4 } from "zod";
|
|
1212
|
+
|
|
1213
|
+
// ../shared/src/env.ts
|
|
1214
|
+
var ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
1215
|
+
var ENV_RESERVED = ["PATH", "HOME", "USER", "SHELL"];
|
|
1216
|
+
var ENV_MAX_VALUE_BYTES = 4096;
|
|
1217
|
+
var ENV_MAX_VARS = 100;
|
|
1218
|
+
function envNameProblem(name) {
|
|
1219
|
+
if (!ENV_NAME_RE.test(name)) return `${JSON.stringify(name)} is not a variable name: letters, digits and _, not starting with a digit`;
|
|
1220
|
+
if (ENV_RESERVED.includes(name)) return `${name} is the box's own and cannot be set`;
|
|
1221
|
+
if (name.startsWith("KVBOX_")) return `${name}: names starting with KVBOX_ are kept for kvbox`;
|
|
1222
|
+
return null;
|
|
1223
|
+
}
|
|
1224
|
+
function envValueProblem(value) {
|
|
1225
|
+
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)";
|
|
1226
|
+
if (Buffer.byteLength(value, "utf8") > ENV_MAX_VALUE_BYTES) return `a value is at most ${ENV_MAX_VALUE_BYTES / 1024} KB`;
|
|
1227
|
+
return null;
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
// src/core/locks.ts
|
|
1231
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
1232
|
+
var tails = /* @__PURE__ */ new Map();
|
|
1233
|
+
var held = new AsyncLocalStorage();
|
|
1234
|
+
function withBoxLock(ref, fn) {
|
|
1235
|
+
return withLock(refKey(ref), fn);
|
|
1236
|
+
}
|
|
1237
|
+
function withHostLock(name, fn) {
|
|
1238
|
+
return withLock(`host:${name}`, fn);
|
|
1239
|
+
}
|
|
1240
|
+
async function withLock(key, fn) {
|
|
1241
|
+
const mine = held.getStore();
|
|
1242
|
+
if (mine?.has(key)) return fn();
|
|
1243
|
+
const previous = tails.get(key);
|
|
1244
|
+
let release;
|
|
1245
|
+
const tail = new Promise((resolve) => release = resolve);
|
|
1246
|
+
tails.set(key, tail);
|
|
1247
|
+
try {
|
|
1248
|
+
await previous;
|
|
1249
|
+
return await held.run(/* @__PURE__ */ new Set([...mine ?? [], key]), fn);
|
|
1250
|
+
} finally {
|
|
1251
|
+
release();
|
|
1252
|
+
if (tails.get(key) === tail) tails.delete(key);
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
function boxBusy(ref) {
|
|
1256
|
+
return tails.has(refKey(ref));
|
|
1257
|
+
}
|
|
1258
|
+
function locked(fn) {
|
|
1259
|
+
return (...args) => withBoxLock(args[0], () => fn(...args));
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
// src/core/env.ts
|
|
1263
|
+
var OwnerEnvSchema = z4.object({
|
|
1264
|
+
/** The control plane's counter for the list; only ever grows. */
|
|
1265
|
+
version: z4.number().int().min(0),
|
|
1266
|
+
vars: z4.array(z4.object({ name: z4.string(), value: z4.string() }))
|
|
1267
|
+
});
|
|
1268
|
+
async function readOwnerEnv(owner, p = paths()) {
|
|
1269
|
+
try {
|
|
1270
|
+
return OwnerEnvSchema.parse(JSON.parse(await readFile4(p.ownerEnv(owner), "utf8")));
|
|
1271
|
+
} catch (err) {
|
|
1272
|
+
if (err.code === "ENOENT") return null;
|
|
1273
|
+
throw err;
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
async function envForBoot(owner, p = paths()) {
|
|
1277
|
+
const env = await readOwnerEnv(owner, p).catch(() => null);
|
|
1278
|
+
if (env !== null) return env.vars;
|
|
1279
|
+
return realmOf(owner) !== null ? [] : null;
|
|
1280
|
+
}
|
|
1281
|
+
async function setOwnerEnv(owner, req, p = paths()) {
|
|
1282
|
+
if (!OWNER_RE.test(owner)) throw new KvboxError(`invalid owner "${owner}"`);
|
|
1283
|
+
if (req.vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);
|
|
1284
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1285
|
+
for (const v of req.vars) {
|
|
1286
|
+
const problem = envNameProblem(v.name) ?? envValueProblem(v.value);
|
|
1287
|
+
if (problem !== null) throw new KvboxError(`${v.name}: ${problem}`);
|
|
1288
|
+
if (seen.has(v.name)) throw new KvboxError(`${v.name} is in the list twice`);
|
|
1289
|
+
seen.add(v.name);
|
|
1290
|
+
}
|
|
1291
|
+
return withHostLock("env", async () => {
|
|
1292
|
+
const have = await readOwnerEnv(owner, p);
|
|
1293
|
+
if (have !== null && have.version > req.version) return { version: have.version };
|
|
1294
|
+
const file = p.ownerEnv(owner);
|
|
1295
|
+
await mkdir2(p.env, { recursive: true, mode: 448 });
|
|
1296
|
+
const tmp = `${file}.tmp`;
|
|
1297
|
+
await writeFile2(tmp, JSON.stringify({ version: req.version, vars: req.vars }, null, 2) + "\n", { mode: 384 });
|
|
1298
|
+
await rename2(tmp, file);
|
|
1299
|
+
return { version: req.version };
|
|
1300
|
+
});
|
|
1301
|
+
}
|
|
1302
|
+
async function listEnvVersions(scope, p = paths()) {
|
|
1303
|
+
let files;
|
|
1304
|
+
try {
|
|
1305
|
+
files = await readdir(p.env);
|
|
1306
|
+
} catch (err) {
|
|
1307
|
+
if (err.code === "ENOENT") return [];
|
|
1308
|
+
throw err;
|
|
1309
|
+
}
|
|
1310
|
+
const out = [];
|
|
1311
|
+
for (const file of files.filter((f) => f.endsWith(".json")).sort()) {
|
|
1312
|
+
const owner = file.slice(0, -".json".length);
|
|
1313
|
+
if (!OWNER_RE.test(owner) || !inScope(owner, scope)) continue;
|
|
1314
|
+
const env = await readOwnerEnv(owner, p).catch(() => null);
|
|
1315
|
+
if (env !== null) out.push({ owner, version: env.version });
|
|
1316
|
+
}
|
|
1317
|
+
return out;
|
|
1318
|
+
}
|
|
1181
1319
|
|
|
1182
1320
|
// src/core/volumes.ts
|
|
1183
1321
|
import { existsSync, statSync } from "node:fs";
|
|
1184
|
-
import { lstat, mkdir as
|
|
1322
|
+
import { lstat, mkdir as mkdir4, readdir as readdir3, rm, statfs, symlink, truncate, writeFile as writeFile4 } from "node:fs/promises";
|
|
1185
1323
|
|
|
1186
1324
|
// ../shared/src/capacity.ts
|
|
1187
1325
|
var MEM_HEADROOM_MIB = 2048;
|
|
@@ -1330,108 +1468,76 @@ function volumeEventsInScope(scope, window, p = paths()) {
|
|
|
1330
1468
|
return rows.filter((r) => inScope(r.owner, scope)).map(volumeWithId);
|
|
1331
1469
|
}
|
|
1332
1470
|
|
|
1333
|
-
// src/core/locks.ts
|
|
1334
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
1335
|
-
var tails = /* @__PURE__ */ new Map();
|
|
1336
|
-
var held = new AsyncLocalStorage();
|
|
1337
|
-
function withBoxLock(ref, fn) {
|
|
1338
|
-
return withLock(refKey(ref), fn);
|
|
1339
|
-
}
|
|
1340
|
-
function withHostLock(name, fn) {
|
|
1341
|
-
return withLock(`host:${name}`, fn);
|
|
1342
|
-
}
|
|
1343
|
-
async function withLock(key, fn) {
|
|
1344
|
-
const mine = held.getStore();
|
|
1345
|
-
if (mine?.has(key)) return fn();
|
|
1346
|
-
const previous = tails.get(key);
|
|
1347
|
-
let release;
|
|
1348
|
-
const tail = new Promise((resolve) => release = resolve);
|
|
1349
|
-
tails.set(key, tail);
|
|
1350
|
-
try {
|
|
1351
|
-
await previous;
|
|
1352
|
-
return await held.run(/* @__PURE__ */ new Set([...mine ?? [], key]), fn);
|
|
1353
|
-
} finally {
|
|
1354
|
-
release();
|
|
1355
|
-
if (tails.get(key) === tail) tails.delete(key);
|
|
1356
|
-
}
|
|
1357
|
-
}
|
|
1358
|
-
function boxBusy(ref) {
|
|
1359
|
-
return tails.has(refKey(ref));
|
|
1360
|
-
}
|
|
1361
|
-
function locked(fn) {
|
|
1362
|
-
return (...args) => withBoxLock(args[0], () => fn(...args));
|
|
1363
|
-
}
|
|
1364
|
-
|
|
1365
1471
|
// src/core/state.ts
|
|
1366
1472
|
import { randomBytes } from "node:crypto";
|
|
1367
1473
|
import { readFileSync } from "node:fs";
|
|
1368
|
-
import { mkdir as
|
|
1369
|
-
import { z as
|
|
1370
|
-
var MachineMetaSchema =
|
|
1474
|
+
import { mkdir as mkdir3, readFile as readFile5, readdir as readdir2, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
|
|
1475
|
+
import { z as z5 } from "zod";
|
|
1476
|
+
var MachineMetaSchema = z5.object({
|
|
1371
1477
|
/** Host-unique, minted at `kvbox new` (fresh or restored) and kept for the box's life; the tap is `kv-<id>`. */
|
|
1372
|
-
id:
|
|
1373
|
-
name:
|
|
1478
|
+
id: z5.string(),
|
|
1479
|
+
name: z5.string(),
|
|
1374
1480
|
/** Part of the box's identity: machines/<owner>/<name>. See refs.ts. */
|
|
1375
|
-
owner:
|
|
1376
|
-
ip:
|
|
1377
|
-
mac:
|
|
1378
|
-
pid:
|
|
1481
|
+
owner: z5.string(),
|
|
1482
|
+
ip: z5.string(),
|
|
1483
|
+
mac: z5.string(),
|
|
1484
|
+
pid: z5.number().int().nullable(),
|
|
1379
1485
|
// null: stopped on purpose, disk kept
|
|
1380
1486
|
/**
|
|
1381
1487
|
* The host boot `pid` belongs to (/proc/sys/kernel/random/boot_id at launch, #29). After a reboot
|
|
1382
1488
|
* the number can name some other process; a pid from another boot is dead whatever `kill -0` says.
|
|
1383
1489
|
* Absent (boxes launched before #29): the pid alone decides.
|
|
1384
1490
|
*/
|
|
1385
|
-
bootId:
|
|
1386
|
-
vcpu:
|
|
1387
|
-
memMib:
|
|
1388
|
-
createdAt:
|
|
1389
|
-
source:
|
|
1491
|
+
bootId: z5.string().optional(),
|
|
1492
|
+
vcpu: z5.number().int(),
|
|
1493
|
+
memMib: z5.number().int(),
|
|
1494
|
+
createdAt: z5.string(),
|
|
1495
|
+
source: z5.string(),
|
|
1390
1496
|
/** Base image version (assets/rootfs-<version>.ext4) the box's overlay stacks on. */
|
|
1391
|
-
base:
|
|
1497
|
+
base: z5.string(),
|
|
1392
1498
|
/**
|
|
1393
1499
|
* Snapshots taken since this VM started (boot or restore). Firecracker resets its dirty-page bitmap at
|
|
1394
1500
|
* each one, so when this is > 0 the next diff is only standalone merged onto `mem.base`; if that file
|
|
1395
1501
|
* is missing the lineage is broken and the next snapshot has to be a full dump. Absent: 0.
|
|
1396
1502
|
*/
|
|
1397
|
-
memSnapshots:
|
|
1503
|
+
memSnapshots: z5.number().int().optional(),
|
|
1398
1504
|
/** `kvbox pause`: Firecracker is alive but the VM is frozen (standby). Absent: not paused. */
|
|
1399
|
-
paused:
|
|
1505
|
+
paused: z5.boolean().optional(),
|
|
1400
1506
|
/**
|
|
1401
1507
|
* authorized_keys lines the box gets on top of the host's own key, as the control plane sent them
|
|
1402
1508
|
* at `new` (#49). kvbox-init rewrites authorized_keys from the kernel cmdline at every boot, so
|
|
1403
1509
|
* `start` has to send the same lines again. Absent: host key only.
|
|
1404
1510
|
*/
|
|
1405
|
-
sshKeys:
|
|
1511
|
+
sshKeys: z5.array(z5.string()).optional(),
|
|
1406
1512
|
/**
|
|
1407
1513
|
* The guest's authorized_keys may not match `sshKeys`: they changed while the box was not running,
|
|
1408
1514
|
* or its agent could not take them (#55, #63). Cleared by a push through kvbox-agent or a boot.
|
|
1409
1515
|
*/
|
|
1410
|
-
sshKeysStale:
|
|
1516
|
+
sshKeysStale: z5.boolean().optional(),
|
|
1411
1517
|
/** Public port on the host DNATed to the box's SSH while it runs (#49); fixed for the box's life. Absent: none. */
|
|
1412
|
-
sshPort:
|
|
1518
|
+
sshPort: z5.number().int().optional(),
|
|
1413
1519
|
/**
|
|
1414
1520
|
* Box ports published on the host (#30, `kvbox vm proxy`): unique per guest port and protocol,
|
|
1415
1521
|
* each host port the box's for its life. DNATed while the box runs, rebuilt from here with its
|
|
1416
1522
|
* current IP every time it comes up. Absent: none.
|
|
1417
1523
|
*/
|
|
1418
|
-
ports:
|
|
1524
|
+
ports: z5.array(z5.object({ guestPort: z5.number().int(), hostPort: z5.number().int(), proto: z5.enum(["tcp", "udp"]) })).optional(),
|
|
1419
1525
|
/** Seconds without traffic on the box's tap before the server hibernates it (#47, core/idle.ts). Absent: never. */
|
|
1420
|
-
autoHibernateSec:
|
|
1526
|
+
autoHibernateSec: z5.number().int().positive().optional(),
|
|
1421
1527
|
/**
|
|
1422
1528
|
* Names of the owner's volumes attached to the box (#52), in the order they were attached, which is
|
|
1423
1529
|
* their drive order (/dev/vdc, /dev/vdd, …). This list is the one truth about what is attached: a
|
|
1424
1530
|
* volume's meta.json does not say. Absent: none.
|
|
1425
1531
|
*/
|
|
1426
|
-
volumes:
|
|
1532
|
+
volumes: z5.array(z5.string()).optional()
|
|
1427
1533
|
});
|
|
1428
|
-
var VolumeMetaSchema =
|
|
1534
|
+
var VolumeMetaSchema = z5.object({
|
|
1429
1535
|
/** Host-unique like a box id (#91): the ledger's key, so a name removed and made again is two volumes. */
|
|
1430
|
-
id:
|
|
1431
|
-
name:
|
|
1432
|
-
owner:
|
|
1433
|
-
sizeGib:
|
|
1434
|
-
createdAt:
|
|
1536
|
+
id: z5.string(),
|
|
1537
|
+
name: z5.string(),
|
|
1538
|
+
owner: z5.string(),
|
|
1539
|
+
sizeGib: z5.number().int(),
|
|
1540
|
+
createdAt: z5.string()
|
|
1435
1541
|
});
|
|
1436
1542
|
function newBoxId(taken) {
|
|
1437
1543
|
for (; ; ) {
|
|
@@ -1439,35 +1545,35 @@ function newBoxId(taken) {
|
|
|
1439
1545
|
if (!taken.has(id)) return id;
|
|
1440
1546
|
}
|
|
1441
1547
|
}
|
|
1442
|
-
var SnapshotMetaSchema =
|
|
1443
|
-
name:
|
|
1444
|
-
owner:
|
|
1548
|
+
var SnapshotMetaSchema = z5.object({
|
|
1549
|
+
name: z5.string(),
|
|
1550
|
+
owner: z5.string(),
|
|
1445
1551
|
/** The box it was taken from, as owner/name. */
|
|
1446
|
-
source:
|
|
1447
|
-
base:
|
|
1448
|
-
vcpu:
|
|
1449
|
-
memMib:
|
|
1450
|
-
sizeBytes:
|
|
1451
|
-
createdAt:
|
|
1552
|
+
source: z5.string(),
|
|
1553
|
+
base: z5.string(),
|
|
1554
|
+
vcpu: z5.number().int(),
|
|
1555
|
+
memMib: z5.number().int(),
|
|
1556
|
+
sizeBytes: z5.number().int(),
|
|
1557
|
+
createdAt: z5.string(),
|
|
1452
1558
|
/**
|
|
1453
1559
|
* The volumes the source box had attached when it was frozen (#52): their drives are in the vmstate
|
|
1454
1560
|
* and their mounts in the memory image, but their data is not here. A box restored from the snapshot
|
|
1455
1561
|
* gets an empty placeholder of each size at the drive's path and drops the mounts through kvbox-agent.
|
|
1456
1562
|
*/
|
|
1457
|
-
volumes:
|
|
1563
|
+
volumes: z5.array(z5.object({ name: z5.string(), sizeGib: z5.number().int() })).optional()
|
|
1458
1564
|
});
|
|
1459
1565
|
async function ensureLayout(p = paths()) {
|
|
1460
1566
|
for (const dir of [p.home, p.ssh, p.bin, p.assets, p.machines, p.snapshots, p.volumes]) {
|
|
1461
|
-
await
|
|
1567
|
+
await mkdir3(dir, { recursive: true, mode: 448 });
|
|
1462
1568
|
}
|
|
1463
1569
|
return p;
|
|
1464
1570
|
}
|
|
1465
1571
|
async function readJson(file, schema) {
|
|
1466
|
-
return schema.parse(JSON.parse(await
|
|
1572
|
+
return schema.parse(JSON.parse(await readFile5(file, "utf8")));
|
|
1467
1573
|
}
|
|
1468
1574
|
async function listDirs(dir) {
|
|
1469
1575
|
try {
|
|
1470
|
-
const entries = await
|
|
1576
|
+
const entries = await readdir2(dir, { withFileTypes: true });
|
|
1471
1577
|
return entries.filter((e) => e.isDirectory()).map((e) => e.name);
|
|
1472
1578
|
} catch (err) {
|
|
1473
1579
|
if (err.code === "ENOENT") return [];
|
|
@@ -1479,10 +1585,10 @@ async function readMachineMeta(ref, p = paths()) {
|
|
|
1479
1585
|
}
|
|
1480
1586
|
async function writeMachineMeta(meta, p = paths()) {
|
|
1481
1587
|
const m = p.machine(meta.owner, meta.name);
|
|
1482
|
-
await
|
|
1588
|
+
await mkdir3(m.dir, { recursive: true });
|
|
1483
1589
|
const tmp = `${m.meta}.tmp`;
|
|
1484
|
-
await
|
|
1485
|
-
await
|
|
1590
|
+
await writeFile3(tmp, JSON.stringify(meta, null, 2) + "\n");
|
|
1591
|
+
await rename3(tmp, m.meta);
|
|
1486
1592
|
}
|
|
1487
1593
|
async function listMachineRefs(p = paths()) {
|
|
1488
1594
|
return listRefs(p.machines);
|
|
@@ -1492,19 +1598,19 @@ async function readSnapshotMeta(ref, p = paths()) {
|
|
|
1492
1598
|
}
|
|
1493
1599
|
async function writeSnapshotMeta(meta, p = paths()) {
|
|
1494
1600
|
const s = p.snapshot(meta.owner, meta.name);
|
|
1495
|
-
await
|
|
1496
|
-
await
|
|
1601
|
+
await mkdir3(s.dir, { recursive: true });
|
|
1602
|
+
await writeFile3(s.meta, JSON.stringify(meta, null, 2) + "\n");
|
|
1497
1603
|
}
|
|
1498
1604
|
async function listSnapshotRefs(p = paths()) {
|
|
1499
1605
|
return listRefs(p.snapshots);
|
|
1500
1606
|
}
|
|
1501
1607
|
async function readVolumeMeta(ref, p = paths()) {
|
|
1502
|
-
const raw = await readJson(p.volume(ref.owner, ref.name).meta, VolumeMetaSchema.extend({ id:
|
|
1608
|
+
const raw = await readJson(p.volume(ref.owner, ref.name).meta, VolumeMetaSchema.extend({ id: z5.string().optional() }));
|
|
1503
1609
|
if (raw.id !== void 0) return { ...raw, id: raw.id };
|
|
1504
1610
|
const taken = /* @__PURE__ */ new Set();
|
|
1505
1611
|
for (const other of await listVolumeRefs(p)) {
|
|
1506
1612
|
try {
|
|
1507
|
-
const j = JSON.parse(await
|
|
1613
|
+
const j = JSON.parse(await readFile5(p.volume(other.owner, other.name).meta, "utf8"));
|
|
1508
1614
|
if (typeof j.id === "string") taken.add(j.id);
|
|
1509
1615
|
} catch {
|
|
1510
1616
|
}
|
|
@@ -1516,8 +1622,8 @@ async function readVolumeMeta(ref, p = paths()) {
|
|
|
1516
1622
|
}
|
|
1517
1623
|
async function writeVolumeMeta(meta, p = paths()) {
|
|
1518
1624
|
const v = p.volume(meta.owner, meta.name);
|
|
1519
|
-
await
|
|
1520
|
-
await
|
|
1625
|
+
await mkdir3(v.dir, { recursive: true, mode: 448 });
|
|
1626
|
+
await writeFile3(v.meta, JSON.stringify(meta, null, 2) + "\n");
|
|
1521
1627
|
}
|
|
1522
1628
|
async function listVolumeRefs(p = paths()) {
|
|
1523
1629
|
return listRefs(p.volumes);
|
|
@@ -1656,7 +1762,7 @@ async function createVolume(req, owner, p = paths()) {
|
|
|
1656
1762
|
async function makeVolume(req, owner, p) {
|
|
1657
1763
|
const v = p.volume(owner, req.name);
|
|
1658
1764
|
if (existsSync(v.dir)) throw new KvboxError(`volume ${req.name} already exists`);
|
|
1659
|
-
await
|
|
1765
|
+
await mkdir4(p.ownerVolumes(owner), { recursive: true, mode: 448 });
|
|
1660
1766
|
const disk = await diskCapacity(p);
|
|
1661
1767
|
if (!hasDiskRoom(disk, req.sizeGib)) {
|
|
1662
1768
|
throw new KvboxError(
|
|
@@ -1671,13 +1777,13 @@ async function makeVolume(req, owner, p) {
|
|
|
1671
1777
|
}
|
|
1672
1778
|
}
|
|
1673
1779
|
try {
|
|
1674
|
-
await
|
|
1780
|
+
await mkdir4(v.dir, { mode: 448 });
|
|
1675
1781
|
} catch (err) {
|
|
1676
1782
|
if (err.code === "EEXIST") throw new KvboxError(`volume ${req.name} already exists`);
|
|
1677
1783
|
throw err;
|
|
1678
1784
|
}
|
|
1679
1785
|
try {
|
|
1680
|
-
await
|
|
1786
|
+
await writeFile4(v.disk, "", { mode: 384 });
|
|
1681
1787
|
await truncate(v.disk, req.sizeGib * 1024 ** 3);
|
|
1682
1788
|
await run(["mkfs.ext4", "-q", "-F", "-m", "0", "-L", volumeLabel(req.name), "-E", "lazy_itable_init=1,lazy_journal_init=1", v.disk]);
|
|
1683
1789
|
const meta = { id: newBoxId(taken), name: req.name, owner, sizeGib: req.sizeGib, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
@@ -1728,7 +1834,7 @@ async function captureDrivesOf(box, p) {
|
|
|
1728
1834
|
const drives = await volumeDrivesOf(box, p);
|
|
1729
1835
|
const named = new Set(drives.map((d) => d.name));
|
|
1730
1836
|
const dir = p.machine(box.owner, box.name).dir;
|
|
1731
|
-
for (const entry of (await
|
|
1837
|
+
for (const entry of (await readdir3(dir).catch(() => [])).sort()) {
|
|
1732
1838
|
const m = /^volume-(.+)\.ext4$/.exec(entry);
|
|
1733
1839
|
if (!m || named.has(m[1])) continue;
|
|
1734
1840
|
const st = await lstat(`${dir}/${entry}`);
|
|
@@ -1760,7 +1866,7 @@ async function placeVolumeDrives(box, p) {
|
|
|
1760
1866
|
return drives;
|
|
1761
1867
|
}
|
|
1762
1868
|
async function removeVolumeDrives(boxDir, keep) {
|
|
1763
|
-
for (const entry of await
|
|
1869
|
+
for (const entry of await readdir3(boxDir).catch(() => [])) {
|
|
1764
1870
|
const m = /^volume-(.+)\.ext4$/.exec(entry);
|
|
1765
1871
|
if (m && !keep.has(m[1])) await rm(`${boxDir}/${entry}`, { force: true });
|
|
1766
1872
|
}
|
|
@@ -1769,11 +1875,11 @@ async function placeholderDrives(boxDir, volumes) {
|
|
|
1769
1875
|
for (const v of volumes) {
|
|
1770
1876
|
const file = `${boxDir}/${volumeDriveRel(v.name)}`;
|
|
1771
1877
|
await rm(file, { force: true });
|
|
1772
|
-
await
|
|
1878
|
+
await writeFile4(file, "", { mode: 384 });
|
|
1773
1879
|
await truncate(file, v.sizeGib * 1024 ** 3);
|
|
1774
1880
|
}
|
|
1775
1881
|
}
|
|
1776
|
-
var volumeDriveId = (name) => `
|
|
1882
|
+
var volumeDriveId = (name) => `vol_${name.replace(/-/g, "_")}`;
|
|
1777
1883
|
async function attachedBox(ref, p) {
|
|
1778
1884
|
return (await attachments(ref.owner, p)).get(ref.name) ?? null;
|
|
1779
1885
|
}
|
|
@@ -1839,7 +1945,7 @@ async function assertRoomFor(vcpu, memMib, force, p = paths()) {
|
|
|
1839
1945
|
|
|
1840
1946
|
// src/core/snapshots.ts
|
|
1841
1947
|
import { existsSync as existsSync2 } from "node:fs";
|
|
1842
|
-
import { link, mkdir as
|
|
1948
|
+
import { link, mkdir as mkdir5, readdir as readdir4, rename as rename4, rm as rm2, stat as stat2 } from "node:fs/promises";
|
|
1843
1949
|
|
|
1844
1950
|
// src/core/firecracker.ts
|
|
1845
1951
|
import { Agent, request as request2 } from "undici";
|
|
@@ -1982,7 +2088,7 @@ async function listSnapshots(scope, p = paths()) {
|
|
|
1982
2088
|
}
|
|
1983
2089
|
async function usedBytes(dir) {
|
|
1984
2090
|
let total = 0;
|
|
1985
|
-
for (const entry of await
|
|
2091
|
+
for (const entry of await readdir4(dir)) {
|
|
1986
2092
|
total += (await stat2(`${dir}/${entry}`)).blocks * 512;
|
|
1987
2093
|
}
|
|
1988
2094
|
return total;
|
|
@@ -2013,7 +2119,7 @@ async function snapshotBox(ref, req, owner, p) {
|
|
|
2013
2119
|
const s = p.snapshot(owner, req.name);
|
|
2014
2120
|
if (existsSync2(s.dir)) throw new KvboxError(`snapshot ${req.name} already exists`);
|
|
2015
2121
|
const cfg = await loadConfig(p);
|
|
2016
|
-
await
|
|
2122
|
+
await mkdir5(s.dir, { recursive: true, mode: 448 });
|
|
2017
2123
|
try {
|
|
2018
2124
|
const volumes = await captureDrivesOf(box, p);
|
|
2019
2125
|
await captureBox(box, s, cfg, p);
|
|
@@ -2076,7 +2182,7 @@ async function mergeOntoPrevious(previous, diffFile, editor) {
|
|
|
2076
2182
|
const merged = `${diffFile}.merged`;
|
|
2077
2183
|
await run(["cp", "--sparse=always", "--reflink=auto", previous, merged]);
|
|
2078
2184
|
await run([editor, "edit-memory", "rebase", "--memory-path", merged, "--diff-path", diffFile]);
|
|
2079
|
-
await
|
|
2185
|
+
await rename4(merged, diffFile);
|
|
2080
2186
|
}
|
|
2081
2187
|
async function deleteSnapshot(ref, p = paths()) {
|
|
2082
2188
|
const dir = p.snapshot(ref.owner, ref.name).dir;
|
|
@@ -2377,7 +2483,7 @@ async function assertOverlayCapable(baseFile, version) {
|
|
|
2377
2483
|
if (!ok) throw new KvboxError(`base image ${version} is not a kvbox base image (no /sbin/overlay-init); rerun install-server.sh`);
|
|
2378
2484
|
}
|
|
2379
2485
|
async function createOverlay(file, gib) {
|
|
2380
|
-
await
|
|
2486
|
+
await writeFile5(file, "", { mode: 384 });
|
|
2381
2487
|
await truncate2(file, gib * 1024 ** 3);
|
|
2382
2488
|
await run(["mkfs.ext4", "-q", "-F", "-m", "0", "-L", "kvbox-box", "-E", "lazy_itable_init=1,lazy_journal_init=1", file]);
|
|
2383
2489
|
}
|
|
@@ -2391,7 +2497,7 @@ async function waitFor(pred, timeoutMs, stepMs = 50) {
|
|
|
2391
2497
|
}
|
|
2392
2498
|
async function tailOf(file, lines = 5) {
|
|
2393
2499
|
try {
|
|
2394
|
-
return (await
|
|
2500
|
+
return (await readFile6(file, "utf8")).trim().split("\n").slice(-lines).join("\n");
|
|
2395
2501
|
} catch {
|
|
2396
2502
|
return "";
|
|
2397
2503
|
}
|
|
@@ -2480,7 +2586,7 @@ async function currentBaseVersion(p = paths()) {
|
|
|
2480
2586
|
}
|
|
2481
2587
|
async function readHostPubkey(p) {
|
|
2482
2588
|
try {
|
|
2483
|
-
return (await
|
|
2589
|
+
return (await readFile6(`${p.sshKey}.pub`, "utf8")).trim();
|
|
2484
2590
|
} catch {
|
|
2485
2591
|
throw new KvboxError(`SSH key missing at ${p.sshKey}.pub; run install-server.sh`);
|
|
2486
2592
|
}
|
|
@@ -2520,7 +2626,7 @@ async function bootInto(box, prepare, origin, cfg, p) {
|
|
|
2520
2626
|
const keysB64 = authorizedKeysB64(await readHostPubkey(p), box.sshKeys ?? []);
|
|
2521
2627
|
const m = p.machine(owner, name);
|
|
2522
2628
|
await ensureHostNetwork(cfg);
|
|
2523
|
-
await
|
|
2629
|
+
await mkdir6(m.dir, { recursive: true, mode: 448 });
|
|
2524
2630
|
let tapCreated = false;
|
|
2525
2631
|
let pid;
|
|
2526
2632
|
let sshPort;
|
|
@@ -2534,6 +2640,7 @@ async function bootInto(box, prepare, origin, cfg, p) {
|
|
|
2534
2640
|
const spec = { ...box, sshPort };
|
|
2535
2641
|
pid = await launch(spec, tap, cfg, keysB64, p);
|
|
2536
2642
|
await openPorts(spec, cfg);
|
|
2643
|
+
void pushEnvAfterBoot(spec, pid, m.vsock, p);
|
|
2537
2644
|
const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin };
|
|
2538
2645
|
await writeMachineMeta(meta, p);
|
|
2539
2646
|
recordState(meta, "running", "new", p, meta.createdAt);
|
|
@@ -2594,7 +2701,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
|
|
|
2594
2701
|
const { id, ip, owner, name } = box;
|
|
2595
2702
|
const m = p.machine(owner, name);
|
|
2596
2703
|
await ensureHostNetwork(cfg);
|
|
2597
|
-
await
|
|
2704
|
+
await mkdir6(m.dir, { recursive: true, mode: 448 });
|
|
2598
2705
|
let tapCreated = false;
|
|
2599
2706
|
let pid;
|
|
2600
2707
|
let sshPort;
|
|
@@ -2615,6 +2722,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
|
|
|
2615
2722
|
const stale = await pushAuthorizedKeys(box, m.vsock, p);
|
|
2616
2723
|
if (stale && keysOrFail) throw new KvboxError(`${keysOrFail}: ${stale}`);
|
|
2617
2724
|
if (image.volumes?.length) await dropGuestVolumes(box, m.vsock);
|
|
2725
|
+
await pushEnv(box, m.vsock, p);
|
|
2618
2726
|
await attachTap(id, cfg);
|
|
2619
2727
|
await openPorts(spec, cfg);
|
|
2620
2728
|
const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin, memSnapshots: 1, sshKeysStale: stale ? true : void 0 };
|
|
@@ -2732,6 +2840,46 @@ async function dropGuestVolumes(box, vsock) {
|
|
|
2732
2840
|
console.error(`warning: box ${shown(box)} keeps the volume mounts it was frozen with, over empty disks now: ${why}`);
|
|
2733
2841
|
}
|
|
2734
2842
|
}
|
|
2843
|
+
async function pushEnv(box, vsock, p) {
|
|
2844
|
+
const vars = await envForBoot(box.owner, p);
|
|
2845
|
+
if (vars === null) return;
|
|
2846
|
+
try {
|
|
2847
|
+
await setEnv(vsock, vars, AGENT_REPLY_MS);
|
|
2848
|
+
} catch (err) {
|
|
2849
|
+
warnEnv(box, vars, err);
|
|
2850
|
+
}
|
|
2851
|
+
}
|
|
2852
|
+
function warnEnv(box, vars, err) {
|
|
2853
|
+
if (isUnknownOp(err)) {
|
|
2854
|
+
if (vars.length === 0) return;
|
|
2855
|
+
console.error(`warning: box ${shown(box)} did not get its environment variables: its image predates base v0.10.0, whose kvbox-agent takes them (kvbox vm update ${shown(box)} moves it onto the current base)`);
|
|
2856
|
+
return;
|
|
2857
|
+
}
|
|
2858
|
+
console.error(`warning: box ${shown(box)} did not get its environment variables: ${err.message}`);
|
|
2859
|
+
}
|
|
2860
|
+
var ENV_BOOT_WAIT_MS = 12e4;
|
|
2861
|
+
function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs: AGENT_REPLY_MS, waitMs: ENV_BOOT_WAIT_MS }) {
|
|
2862
|
+
return (async () => {
|
|
2863
|
+
const deadline = Date.now() + timing.waitMs;
|
|
2864
|
+
for (; ; ) {
|
|
2865
|
+
if (!pidAlive(pid)) return;
|
|
2866
|
+
const vars = await envForBoot(box.owner, p);
|
|
2867
|
+
if (vars === null) return;
|
|
2868
|
+
try {
|
|
2869
|
+
await setEnv(vsock, vars, timing.replyMs);
|
|
2870
|
+
return;
|
|
2871
|
+
} catch (err) {
|
|
2872
|
+
if (!pidAlive(pid)) return;
|
|
2873
|
+
if (isNoAgent(err) && Date.now() < deadline) {
|
|
2874
|
+
await sleep(500);
|
|
2875
|
+
continue;
|
|
2876
|
+
}
|
|
2877
|
+
warnEnv(box, vars, err);
|
|
2878
|
+
return;
|
|
2879
|
+
}
|
|
2880
|
+
}
|
|
2881
|
+
})();
|
|
2882
|
+
}
|
|
2735
2883
|
async function resumeVm(sock) {
|
|
2736
2884
|
const fc = new FirecrackerClient(sock);
|
|
2737
2885
|
try {
|
|
@@ -2797,6 +2945,7 @@ var startMachine = locked(async function startMachine2(ref, p = paths()) {
|
|
|
2797
2945
|
try {
|
|
2798
2946
|
pid = await launch(meta, tap, cfg, keysB64, p);
|
|
2799
2947
|
await openPorts(meta, cfg);
|
|
2948
|
+
void pushEnvAfterBoot(meta, pid, p.machine(meta.owner, meta.name).vsock, p);
|
|
2800
2949
|
const started = { ...meta, pid, bootId: currentBootId(), sshKeysStale: void 0 };
|
|
2801
2950
|
await writeMachineMeta(started, p);
|
|
2802
2951
|
recordState(started, "running", "start", p);
|
|
@@ -2895,7 +3044,7 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
|
|
|
2895
3044
|
if (status === "stopped") throw new KvboxError(`${stateMessage(ref, status)}; only a running box can be hibernated (there is no memory to keep)`);
|
|
2896
3045
|
const m = p.machine(ref.owner, ref.name);
|
|
2897
3046
|
await rm3(m.hibernateDir, { recursive: true, force: true });
|
|
2898
|
-
await
|
|
3047
|
+
await mkdir6(m.hibernateDir, { recursive: true, mode: 448 });
|
|
2899
3048
|
const fc = new FirecrackerClient(m.sock);
|
|
2900
3049
|
try {
|
|
2901
3050
|
try {
|
|
@@ -3173,27 +3322,27 @@ async function bootRecovered(settled, p = paths()) {
|
|
|
3173
3322
|
}
|
|
3174
3323
|
|
|
3175
3324
|
// src/core/relay.ts
|
|
3176
|
-
import { chmod as chmod3, mkdir as
|
|
3325
|
+
import { chmod as chmod3, mkdir as mkdir7, rm as rm4, writeFile as writeFile6 } from "node:fs/promises";
|
|
3177
3326
|
|
|
3178
3327
|
// ../shared/src/relay.ts
|
|
3179
|
-
import { z as
|
|
3328
|
+
import { z as z6 } from "zod";
|
|
3180
3329
|
var RELAY_TUNNEL_GATEWAY = "10.77.0.1";
|
|
3181
3330
|
var IPV4_RE = /^(\d{1,3})(\.\d{1,3}){3}$/;
|
|
3182
3331
|
var WG_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
|
|
3183
|
-
var RelayJoinSchema =
|
|
3184
|
-
v:
|
|
3332
|
+
var RelayJoinSchema = z6.object({
|
|
3333
|
+
v: z6.literal(1),
|
|
3185
3334
|
/** How the relay lists this host. */
|
|
3186
|
-
name:
|
|
3335
|
+
name: z6.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),
|
|
3187
3336
|
/** `<relay-primary-ip>:<port>`, the WireGuard endpoint the host dials. */
|
|
3188
|
-
relay:
|
|
3337
|
+
relay: z6.string().regex(/^(\d{1,3})(\.\d{1,3}){3}:\d{1,5}$/),
|
|
3189
3338
|
/** The relay's WireGuard public key. */
|
|
3190
|
-
relayKey:
|
|
3339
|
+
relayKey: z6.string().regex(WG_KEY_RE),
|
|
3191
3340
|
/** This host's address inside the tunnel. */
|
|
3192
|
-
tunnelIp:
|
|
3341
|
+
tunnelIp: z6.string().regex(IPV4_RE),
|
|
3193
3342
|
/** This host's WireGuard private key, generated on the relay, kept nowhere else. */
|
|
3194
|
-
privateKey:
|
|
3343
|
+
privateKey: z6.string().regex(WG_KEY_RE),
|
|
3195
3344
|
/** The extra public IPv4 the relay owns for this host; what the host advertises to the control plane. */
|
|
3196
|
-
publicIp:
|
|
3345
|
+
publicIp: z6.string().regex(IPV4_RE)
|
|
3197
3346
|
});
|
|
3198
3347
|
function decodeRelayJoin(text) {
|
|
3199
3348
|
let parsed;
|
|
@@ -3237,8 +3386,8 @@ async function useRelay(joinString, p = paths()) {
|
|
|
3237
3386
|
`${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${join2.publicIp}; run kvbox server leave first, then join again`
|
|
3238
3387
|
);
|
|
3239
3388
|
}
|
|
3240
|
-
await
|
|
3241
|
-
await
|
|
3389
|
+
await mkdir7(p.relay, { recursive: true, mode: 448 });
|
|
3390
|
+
await writeFile6(p.relayConf, relayConf(join2), { mode: 384 });
|
|
3242
3391
|
await chmod3(p.relayConf, 384);
|
|
3243
3392
|
await netSetup(cfg, ["relay", "up", p.relayConf, String(cfg.controlPlane?.port ?? DEFAULT_HTTPS_PORT)]);
|
|
3244
3393
|
const relay = { name: join2.name, publicIp: join2.publicIp, tunnelIp: join2.tunnelIp, endpoint: join2.relay };
|
|
@@ -3260,12 +3409,12 @@ async function dropRelay(p = paths()) {
|
|
|
3260
3409
|
}
|
|
3261
3410
|
|
|
3262
3411
|
// src/core/idle.ts
|
|
3263
|
-
import { readFile as
|
|
3412
|
+
import { readFile as readFile7 } from "node:fs/promises";
|
|
3264
3413
|
var HIBERNATE_CONCURRENCY = 2;
|
|
3265
3414
|
async function tapTraffic(id) {
|
|
3266
3415
|
const dir = `/sys/class/net/${tapName(id)}/statistics`;
|
|
3267
3416
|
try {
|
|
3268
|
-
const [rx, tx] = await Promise.all([
|
|
3417
|
+
const [rx, tx] = await Promise.all([readFile7(`${dir}/rx_bytes`, "utf8"), readFile7(`${dir}/tx_bytes`, "utf8")]);
|
|
3269
3418
|
return Number(rx) + Number(tx);
|
|
3270
3419
|
} catch {
|
|
3271
3420
|
return null;
|
|
@@ -3408,12 +3557,12 @@ function startRelayWatch(opts = {}) {
|
|
|
3408
3557
|
}
|
|
3409
3558
|
|
|
3410
3559
|
// src/listen.ts
|
|
3411
|
-
import { readFile as
|
|
3560
|
+
import { readFile as readFile8, rm as rm5, writeFile as writeFile7 } from "node:fs/promises";
|
|
3412
3561
|
import { createServer as createHttpsServer } from "node:https";
|
|
3413
3562
|
import { createAdaptorServer } from "@hono/node-server";
|
|
3414
3563
|
|
|
3415
3564
|
// src/app.ts
|
|
3416
|
-
import { Hono as
|
|
3565
|
+
import { Hono as Hono9 } from "hono";
|
|
3417
3566
|
|
|
3418
3567
|
// ../shared/src/version.ts
|
|
3419
3568
|
import { createRequire } from "node:module";
|
|
@@ -3428,7 +3577,7 @@ function versionOf(srcFileUrl, injected) {
|
|
|
3428
3577
|
}
|
|
3429
3578
|
|
|
3430
3579
|
// src/version.ts
|
|
3431
|
-
var VERSION = versionOf(import.meta.url, true ? "0.5.
|
|
3580
|
+
var VERSION = versionOf(import.meta.url, true ? "0.5.25" : void 0);
|
|
3432
3581
|
|
|
3433
3582
|
// src/caller.ts
|
|
3434
3583
|
import { createHash as createHash2, timingSafeEqual } from "node:crypto";
|
|
@@ -3469,8 +3618,8 @@ function resolveCaller(opts = {}) {
|
|
|
3469
3618
|
const user = c.req.header(OWNER_HEADER);
|
|
3470
3619
|
if (user === void 0) {
|
|
3471
3620
|
const path = c.req.path.replace(/\/$/, "");
|
|
3472
|
-
const realmListing = c.req.method === "GET" && (path === "/machines" || path === "/snapshots" || path === "/volumes");
|
|
3473
|
-
if (!realmListing && /^\/(machines|snapshots|volumes)(\/|$)/.test(c.req.path)) {
|
|
3621
|
+
const realmListing = c.req.method === "GET" && (path === "/machines" || path === "/snapshots" || path === "/volumes" || path === "/env");
|
|
3622
|
+
if (!realmListing && /^\/(machines|snapshots|volumes|env)(\/|$)/.test(c.req.path)) {
|
|
3474
3623
|
return c.json({ error: "X-Kvbox-Owner header required" }, 400);
|
|
3475
3624
|
}
|
|
3476
3625
|
c.set("owner", "");
|
|
@@ -3756,18 +3905,31 @@ function capacityRoutes() {
|
|
|
3756
3905
|
return r;
|
|
3757
3906
|
}
|
|
3758
3907
|
|
|
3759
|
-
// src/routes/
|
|
3908
|
+
// src/routes/env.ts
|
|
3760
3909
|
import { Hono as Hono3 } from "hono";
|
|
3910
|
+
function envRoutes() {
|
|
3911
|
+
const r = new Hono3();
|
|
3912
|
+
r.get("/", async (c) => c.json(await listEnvVersions(c.get("listScope"))));
|
|
3913
|
+
r.post("/", async (c) => {
|
|
3914
|
+
const body = HostEnvRequest.safeParse(await c.req.json().catch(() => ({})));
|
|
3915
|
+
if (!body.success) throw new KvboxError("env: expected {version, vars: [{name, value}]}");
|
|
3916
|
+
return c.json(await setOwnerEnv(c.get("owner"), body.data));
|
|
3917
|
+
});
|
|
3918
|
+
return r;
|
|
3919
|
+
}
|
|
3920
|
+
|
|
3921
|
+
// src/routes/machines.ts
|
|
3922
|
+
import { Hono as Hono4 } from "hono";
|
|
3761
3923
|
|
|
3762
3924
|
// src/core/stats.ts
|
|
3763
3925
|
var STATS_REPLY_MS = 3e3;
|
|
3764
|
-
async function machineStats(ref, p = paths()) {
|
|
3926
|
+
async function machineStats(ref, p = paths(), replyMs = STATS_REPLY_MS) {
|
|
3765
3927
|
const m = await getMachine(ref, p);
|
|
3766
3928
|
if (m.status !== "running") throw new KvboxError(`${stateMessage(ref, m.status)}; only a running box can say how it is doing`);
|
|
3767
3929
|
try {
|
|
3768
|
-
return { name: m.name, owner: m.owner, stats: await stats(p.machine(m.owner, m.name).vsock,
|
|
3930
|
+
return { name: m.name, owner: m.owner, stats: await stats(p.machine(m.owner, m.name).vsock, replyMs) };
|
|
3769
3931
|
} catch (err) {
|
|
3770
|
-
if (isUnknownOp(err) || isNoAgent(err)) return { name: m.name, owner: m.owner, stats: null };
|
|
3932
|
+
if (isUnknownOp(err) || isNoAgent(err) && !isGuestBooting(err)) return { name: m.name, owner: m.owner, stats: null };
|
|
3771
3933
|
throw err;
|
|
3772
3934
|
}
|
|
3773
3935
|
}
|
|
@@ -3791,7 +3953,7 @@ async function usageReport(scope, window, p = paths()) {
|
|
|
3791
3953
|
|
|
3792
3954
|
// src/routes/machines.ts
|
|
3793
3955
|
function machineRoutes() {
|
|
3794
|
-
const r = new
|
|
3956
|
+
const r = new Hono4();
|
|
3795
3957
|
r.get("/", async (c) => c.json(await listMachines(c.get("listScope"))));
|
|
3796
3958
|
r.post("/", async (c) => {
|
|
3797
3959
|
const body = CreateMachineRequest.parse(await c.req.json().catch(() => ({})));
|
|
@@ -3853,9 +4015,9 @@ function machineRoutes() {
|
|
|
3853
4015
|
}
|
|
3854
4016
|
|
|
3855
4017
|
// src/routes/snapshots.ts
|
|
3856
|
-
import { Hono as
|
|
4018
|
+
import { Hono as Hono5 } from "hono";
|
|
3857
4019
|
function snapshotRoutes() {
|
|
3858
|
-
const r = new
|
|
4020
|
+
const r = new Hono5();
|
|
3859
4021
|
r.get("/", async (c) => c.json(await listSnapshots(c.get("listScope"))));
|
|
3860
4022
|
r.post("/", async (c) => {
|
|
3861
4023
|
const body = CreateSnapshotRequest.parse(await c.req.json());
|
|
@@ -3869,9 +4031,9 @@ function snapshotRoutes() {
|
|
|
3869
4031
|
}
|
|
3870
4032
|
|
|
3871
4033
|
// src/routes/ssh.ts
|
|
3872
|
-
import { Hono as
|
|
4034
|
+
import { Hono as Hono6 } from "hono";
|
|
3873
4035
|
function sshRoutes(opts = {}) {
|
|
3874
|
-
const r = new
|
|
4036
|
+
const r = new Hono6();
|
|
3875
4037
|
if (opts.controlPlane) {
|
|
3876
4038
|
r.all("/*", (c) => c.json({ error: "trusting a CA is done on the host itself (kvbox server trust-ca there); the control plane cannot ask a host to" }, 403));
|
|
3877
4039
|
return r;
|
|
@@ -3886,10 +4048,10 @@ function sshRoutes(opts = {}) {
|
|
|
3886
4048
|
}
|
|
3887
4049
|
|
|
3888
4050
|
// src/routes/usage.ts
|
|
3889
|
-
import { Hono as
|
|
4051
|
+
import { Hono as Hono7 } from "hono";
|
|
3890
4052
|
var PULL_LIMIT = 1e3;
|
|
3891
4053
|
function usageRoutes(opts = {}) {
|
|
3892
|
-
const r = new
|
|
4054
|
+
const r = new Hono7();
|
|
3893
4055
|
r.get("/", async (c) => {
|
|
3894
4056
|
let window;
|
|
3895
4057
|
try {
|
|
@@ -3922,9 +4084,9 @@ function whole(value, name) {
|
|
|
3922
4084
|
}
|
|
3923
4085
|
|
|
3924
4086
|
// src/routes/volumes.ts
|
|
3925
|
-
import { Hono as
|
|
4087
|
+
import { Hono as Hono8 } from "hono";
|
|
3926
4088
|
function volumeRoutes() {
|
|
3927
|
-
const r = new
|
|
4089
|
+
const r = new Hono8();
|
|
3928
4090
|
r.get("/", async (c) => c.json(await listVolumes(c.get("listScope"))));
|
|
3929
4091
|
r.post("/", async (c) => {
|
|
3930
4092
|
const body = CreateVolumeRequest.parse(await c.req.json().catch(() => ({})));
|
|
@@ -3950,7 +4112,7 @@ function volumeRoutes() {
|
|
|
3950
4112
|
|
|
3951
4113
|
// src/app.ts
|
|
3952
4114
|
function createApp(opts = {}) {
|
|
3953
|
-
const app = new
|
|
4115
|
+
const app = new Hono9();
|
|
3954
4116
|
app.use(resolveCaller(opts));
|
|
3955
4117
|
app.get("/health", async (c) => {
|
|
3956
4118
|
const cfg = await loadConfig();
|
|
@@ -3971,6 +4133,7 @@ function createApp(opts = {}) {
|
|
|
3971
4133
|
app.route("/snapshots", snapshotRoutes());
|
|
3972
4134
|
app.route("/volumes", volumeRoutes());
|
|
3973
4135
|
app.route("/capacity", capacityRoutes());
|
|
4136
|
+
app.route("/env", envRoutes());
|
|
3974
4137
|
app.route("/ssh", sshRoutes(opts));
|
|
3975
4138
|
app.route("/usage", usageRoutes(opts));
|
|
3976
4139
|
app.notFound((c) => c.json({ error: `no route: ${c.req.method} ${c.req.path}` }, 404));
|
|
@@ -3999,13 +4162,13 @@ async function listen(opts = {}) {
|
|
|
3999
4162
|
server.once("error", reject);
|
|
4000
4163
|
server.listen(socketPath, () => resolve());
|
|
4001
4164
|
});
|
|
4002
|
-
await
|
|
4165
|
+
await writeFile7(p.serverPid, `${process.pid}
|
|
4003
4166
|
`);
|
|
4004
4167
|
let https;
|
|
4005
4168
|
let httpsServer;
|
|
4006
4169
|
const cp = cfg.controlPlane;
|
|
4007
4170
|
if (cp) {
|
|
4008
|
-
const [key, cert] = await Promise.all([
|
|
4171
|
+
const [key, cert] = await Promise.all([readFile8(p.tlsKey), readFile8(p.tlsCert)]).catch((err) => {
|
|
4009
4172
|
throw new KvboxError(`joined ${cp.name} but the host's certificate is missing (${err.message}); run kvbox-server leave, then join again`);
|
|
4010
4173
|
});
|
|
4011
4174
|
httpsServer = createAdaptorServer({
|