@kvbox/server 0.5.44 → 0.5.46
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 +240 -47
- package/dist/kvbox-server.js.map +1 -1
- package/package.json +1 -1
package/dist/kvbox-server.js
CHANGED
|
@@ -34,6 +34,14 @@ function paths(home = kvboxHome()) {
|
|
|
34
34
|
serverSock: join(home, "server.sock"),
|
|
35
35
|
serverPid: join(home, "server.pid"),
|
|
36
36
|
serverLog: join(home, "server.log"),
|
|
37
|
+
/**
|
|
38
|
+
* The host's self-update (`POST /update`, the control plane's admin): `update.json` is its state
|
|
39
|
+
* (install-server.sh --update writes it), `update/` holds the downloaded script and its log.
|
|
40
|
+
*/
|
|
41
|
+
updateState: join(home, "update.json"),
|
|
42
|
+
updateDir: join(home, "update"),
|
|
43
|
+
updateScript: join(home, "update", "install-server.sh"),
|
|
44
|
+
updateLog: join(home, "update", "update.log"),
|
|
37
45
|
/** The CLI's login to the control plane (`kvbox login`): url, bearer token, user. Mode 600. */
|
|
38
46
|
cli: join(home, "cli.json"),
|
|
39
47
|
/** The CLI's last look at npm for a newer @kvbox/cli: `{checkedAt, latest}`, at most once a day (cli update.ts). */
|
|
@@ -958,8 +966,8 @@ async function startDns(opts) {
|
|
|
958
966
|
}
|
|
959
967
|
|
|
960
968
|
// src/core/machines.ts
|
|
961
|
-
import { spawn } from "node:child_process";
|
|
962
|
-
import { closeSync as closeSync3, existsSync as existsSync6, openSync as
|
|
969
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
970
|
+
import { closeSync as closeSync3, existsSync as existsSync6, openSync as openSync4, statSync as statSync2 } from "node:fs";
|
|
963
971
|
import { link as link2, mkdir as mkdir5, readFile as readFile5, rename as rename5, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
|
|
964
972
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
965
973
|
|
|
@@ -1227,6 +1235,11 @@ var CreateMachineRequest = z4.object({
|
|
|
1227
1235
|
* `@kvbox/shared/country`. Only the control plane reads it.
|
|
1228
1236
|
*/
|
|
1229
1237
|
country: z4.string().optional(),
|
|
1238
|
+
/**
|
|
1239
|
+
* Place the box on the host of this name and nowhere else (`kvbox new --host kvbox2`, a hidden flag):
|
|
1240
|
+
* an admin's, to try a host out. Only the control plane reads it, and refuses it from anyone else.
|
|
1241
|
+
*/
|
|
1242
|
+
host: z4.string().optional(),
|
|
1230
1243
|
/** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */
|
|
1231
1244
|
image: z4.string().optional(),
|
|
1232
1245
|
/** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
|
|
@@ -1306,7 +1319,9 @@ var CapacitySchema = z4.object({
|
|
|
1306
1319
|
* The images a new box can be made from here (#87), with the version `new` uses; the base is `base`.
|
|
1307
1320
|
* Absent on a host from before images: it has only the base.
|
|
1308
1321
|
*/
|
|
1309
|
-
images: z4.array(z4.object({ name: z4.string(), version: z4.string() })).optional()
|
|
1322
|
+
images: z4.array(z4.object({ name: z4.string(), version: z4.string() })).optional(),
|
|
1323
|
+
/** kvbox-server's version, so the control plane's host list shows it without a call per host. Older servers omit it. */
|
|
1324
|
+
version: z4.string().optional()
|
|
1310
1325
|
});
|
|
1311
1326
|
var ImageSchema = z4.object({ name: z4.string(), version: z4.string().nullable() });
|
|
1312
1327
|
var RecoveryReportSchema = z4.object({
|
|
@@ -1315,6 +1330,16 @@ var RecoveryReportSchema = z4.object({
|
|
|
1315
1330
|
leftStopped: z4.array(z4.string()),
|
|
1316
1331
|
failed: z4.array(z4.object({ box: z4.string(), error: z4.string() }))
|
|
1317
1332
|
});
|
|
1333
|
+
var HostUpdateSchema = z4.object({
|
|
1334
|
+
state: z4.enum(["running", "done", "failed"]),
|
|
1335
|
+
startedAt: z4.string(),
|
|
1336
|
+
finishedAt: z4.string().nullable(),
|
|
1337
|
+
/** kvbox-server's version when the update started, and when it ended (null while running or when it failed before). */
|
|
1338
|
+
from: z4.string(),
|
|
1339
|
+
to: z4.string().nullable(),
|
|
1340
|
+
error: z4.string().nullable(),
|
|
1341
|
+
needsManual: z4.array(z4.string())
|
|
1342
|
+
});
|
|
1318
1343
|
var HealthSchema = z4.object({
|
|
1319
1344
|
ok: z4.literal(true),
|
|
1320
1345
|
version: z4.string(),
|
|
@@ -1343,7 +1368,9 @@ var HealthSchema = z4.object({
|
|
|
1343
1368
|
lastRestartAt: z4.string().nullable().optional()
|
|
1344
1369
|
}).nullable().optional(),
|
|
1345
1370
|
/** Boxes brought back at the server's last start; null when there were none or it is still at it. Older servers omit it. */
|
|
1346
|
-
recovery: RecoveryReportSchema.nullable().optional()
|
|
1371
|
+
recovery: RecoveryReportSchema.nullable().optional(),
|
|
1372
|
+
/** The last self-update; null when none ran. Older servers omit it. */
|
|
1373
|
+
update: HostUpdateSchema.nullable().optional()
|
|
1347
1374
|
});
|
|
1348
1375
|
var MachineUsageSchema = z4.object({
|
|
1349
1376
|
name: z4.string(),
|
|
@@ -1478,7 +1505,9 @@ var CloudUserSchema = z4.object({
|
|
|
1478
1505
|
* gates nobody, hence the defaults: a newer CLI must still parse its answers.
|
|
1479
1506
|
*/
|
|
1480
1507
|
active: z4.boolean().default(true),
|
|
1481
|
-
activatedBy: ActivatedBySchema.nullable().default(null)
|
|
1508
|
+
activatedBy: ActivatedBySchema.nullable().default(null),
|
|
1509
|
+
/** When too many wrong passwords locked the account (#161); null when it is not locked. Older control planes omit it. */
|
|
1510
|
+
lockedAt: z4.string().nullable().default(null)
|
|
1482
1511
|
});
|
|
1483
1512
|
var ORG_ROLES = ["owner", "admin", "member"];
|
|
1484
1513
|
var OrgRoleSchema = z4.enum(ORG_ROLES);
|
|
@@ -1516,10 +1545,14 @@ var BalanceSchema = z4.object({
|
|
|
1516
1545
|
currency: z4.string(),
|
|
1517
1546
|
topUps: z4.number(),
|
|
1518
1547
|
spent: z4.number(),
|
|
1519
|
-
/** The first moment usage counts from: the slug's first top-up; null when it has none. */
|
|
1548
|
+
/** The first moment usage counts from: the slug's first top-up or redeemed code; null when it has none. */
|
|
1520
1549
|
since: z4.string().nullable(),
|
|
1521
1550
|
/** When the slug ran out and its boxes were hibernated (the `sweep-credit` job); null in good standing. Absent from a control plane older than this field. */
|
|
1522
|
-
suspendedAt: z4.string().nullable().default(null)
|
|
1551
|
+
suspendedAt: z4.string().nullable().default(null),
|
|
1552
|
+
/** Promo credit left (#163), already counted in `balance`; 0 with none. Absent from a control plane older than this field. */
|
|
1553
|
+
promo: z4.number().default(0),
|
|
1554
|
+
/** When the next promo credit expires; null with none left. */
|
|
1555
|
+
promoExpiresAt: z4.string().nullable().default(null)
|
|
1523
1556
|
});
|
|
1524
1557
|
var TopUpRequestSchema = z4.object({
|
|
1525
1558
|
slug: z4.string().min(1),
|
|
@@ -1537,6 +1570,41 @@ var TopUpSchema = z4.object({
|
|
|
1537
1570
|
note: z4.string().nullable(),
|
|
1538
1571
|
at: z4.string()
|
|
1539
1572
|
});
|
|
1573
|
+
var CreateCodeRequestSchema = z4.object({
|
|
1574
|
+
/** In the control plane's currency, cents at most. */
|
|
1575
|
+
amount: z4.number().positive().multipleOf(0.01, "amount is in cents at most"),
|
|
1576
|
+
/** A day (`2026-12-11`, through the end of it, UTC) or an ISO time. The credit is gone then, and so is the code. */
|
|
1577
|
+
expiresAt: z4.string().min(1),
|
|
1578
|
+
note: z4.string().max(200).optional()
|
|
1579
|
+
});
|
|
1580
|
+
var CreditCodeSchema = z4.object({
|
|
1581
|
+
code: z4.string(),
|
|
1582
|
+
amount: z4.number(),
|
|
1583
|
+
currency: z4.string(),
|
|
1584
|
+
expiresAt: z4.string(),
|
|
1585
|
+
note: z4.string().nullable(),
|
|
1586
|
+
status: z4.enum(["unused", "redeemed", "expired", "revoked"]),
|
|
1587
|
+
createdBy: z4.string(),
|
|
1588
|
+
createdAt: z4.string(),
|
|
1589
|
+
/** Who redeemed it and the slug the credit went to (their own, or an org they own). */
|
|
1590
|
+
redeemedBy: z4.string().nullable(),
|
|
1591
|
+
redeemedSlug: z4.string().nullable(),
|
|
1592
|
+
redeemedAt: z4.string().nullable(),
|
|
1593
|
+
revokedAt: z4.string().nullable()
|
|
1594
|
+
});
|
|
1595
|
+
var RedeemRequestSchema = z4.object({
|
|
1596
|
+
code: z4.string().min(1).max(64),
|
|
1597
|
+
org: z4.string().min(1).optional()
|
|
1598
|
+
});
|
|
1599
|
+
var RedeemResponseSchema = z4.object({
|
|
1600
|
+
slug: z4.string(),
|
|
1601
|
+
amount: z4.number(),
|
|
1602
|
+
currency: z4.string(),
|
|
1603
|
+
expiresAt: z4.string(),
|
|
1604
|
+
balance: BalanceSchema,
|
|
1605
|
+
/** The slug was out of credit and this put it back above zero: it may start boxes again. */
|
|
1606
|
+
reinstated: z4.boolean()
|
|
1607
|
+
});
|
|
1540
1608
|
var TOP_UP_AMOUNTS = [10, 25, 50, 100];
|
|
1541
1609
|
var BillingInfoSchema = z4.object({
|
|
1542
1610
|
card: z4.object({ brand: z4.string(), last4: z4.string() }).nullable(),
|
|
@@ -1628,7 +1696,14 @@ var CloudHostSchema = z4.object({
|
|
|
1628
1696
|
lastSeenAt: z4.string().nullable(),
|
|
1629
1697
|
capacity: CapacitySchema.nullable(),
|
|
1630
1698
|
/** ISO 3166-1 alpha-2 code (`RO`), null when nobody said where the host is. */
|
|
1631
|
-
country: z4.string().nullable()
|
|
1699
|
+
country: z4.string().nullable(),
|
|
1700
|
+
/** kvbox-server's version as of the poller's last look (`capacity.version`); null before one, or for a server older than 0.5.45. */
|
|
1701
|
+
version: z4.string().nullable()
|
|
1702
|
+
});
|
|
1703
|
+
var HostInfoSchema = z4.object({
|
|
1704
|
+
host: CloudHostSchema,
|
|
1705
|
+
health: HealthSchema.nullable(),
|
|
1706
|
+
error: z4.string().nullable()
|
|
1632
1707
|
});
|
|
1633
1708
|
var HostPatchRequest = z4.object({ country: z4.string().nullable() });
|
|
1634
1709
|
var CountrySchema = z4.object({ code: z4.string(), name: z4.string() });
|
|
@@ -1931,7 +2006,8 @@ import { basename } from "node:path";
|
|
|
1931
2006
|
import { z as z6 } from "zod";
|
|
1932
2007
|
|
|
1933
2008
|
// src/core/exec.ts
|
|
1934
|
-
import { execFile } from "node:child_process";
|
|
2009
|
+
import { execFile, spawn } from "node:child_process";
|
|
2010
|
+
import { openSync as openSync2 } from "node:fs";
|
|
1935
2011
|
import { promisify } from "node:util";
|
|
1936
2012
|
var execFileAsync = promisify(execFile);
|
|
1937
2013
|
async function run(argv, opts = {}) {
|
|
@@ -1953,6 +2029,19 @@ async function run(argv, opts = {}) {
|
|
|
1953
2029
|
throw new KvboxError(`${[cmd, ...args].join(" ")} failed${detail ? `: ${detail}` : ""}`);
|
|
1954
2030
|
}
|
|
1955
2031
|
}
|
|
2032
|
+
function spawnDetached(argv, logFile, env = process.env) {
|
|
2033
|
+
const [cmd, ...args] = argv;
|
|
2034
|
+
if (!cmd) throw new KvboxError("spawnDetached: empty argv");
|
|
2035
|
+
const out = openSync2(logFile, "a");
|
|
2036
|
+
const child = spawn(cmd, args, { detached: true, stdio: ["ignore", out, out], env });
|
|
2037
|
+
return new Promise((resolve2, reject) => {
|
|
2038
|
+
child.once("error", (err) => reject(new KvboxError(`${cmd} could not start: ${err.message}`)));
|
|
2039
|
+
child.once("spawn", () => {
|
|
2040
|
+
child.unref();
|
|
2041
|
+
resolve2(child.pid ?? -1);
|
|
2042
|
+
});
|
|
2043
|
+
});
|
|
2044
|
+
}
|
|
1956
2045
|
|
|
1957
2046
|
// src/core/images.ts
|
|
1958
2047
|
var BASE_IMAGE = "base";
|
|
@@ -2412,7 +2501,7 @@ async function assertRoomFor(vcpu, memMib, force, box, by, p = paths()) {
|
|
|
2412
2501
|
}
|
|
2413
2502
|
|
|
2414
2503
|
// src/core/ext4.ts
|
|
2415
|
-
import { closeSync as closeSync2, openSync as
|
|
2504
|
+
import { closeSync as closeSync2, openSync as openSync3, readSync } from "node:fs";
|
|
2416
2505
|
var SUPERBLOCK_OFFSET = 1024;
|
|
2417
2506
|
var EXT4_MAGIC = 61267;
|
|
2418
2507
|
var INCOMPAT_META_BG = 16;
|
|
@@ -2420,7 +2509,7 @@ var INCOMPAT_64BIT = 128;
|
|
|
2420
2509
|
function ext4Usage(file) {
|
|
2421
2510
|
let fd;
|
|
2422
2511
|
try {
|
|
2423
|
-
fd =
|
|
2512
|
+
fd = openSync3(file, "r");
|
|
2424
2513
|
const sb = Buffer.alloc(1024);
|
|
2425
2514
|
if (readSync(fd, sb, 0, sb.length, SUPERBLOCK_OFFSET) !== sb.length) return null;
|
|
2426
2515
|
if (sb.readUInt16LE(56) !== EXT4_MAGIC) return null;
|
|
@@ -3046,10 +3135,10 @@ async function spawnFirecracker(ref, cfg, p) {
|
|
|
3046
3135
|
const m = p.machine(ref.owner, ref.name);
|
|
3047
3136
|
await rm3(m.sock, { force: true });
|
|
3048
3137
|
await rm3(m.vsock, { force: true });
|
|
3049
|
-
const logFd =
|
|
3138
|
+
const logFd = openSync4(m.log, "a");
|
|
3050
3139
|
let child;
|
|
3051
3140
|
try {
|
|
3052
|
-
child =
|
|
3141
|
+
child = spawn2(cfg.firecracker, ["--api-sock", m.sock, "--id", ref.name, "--level", "Error"], {
|
|
3053
3142
|
cwd: m.dir,
|
|
3054
3143
|
detached: true,
|
|
3055
3144
|
stdio: ["ignore", logFd, logFd]
|
|
@@ -4802,8 +4891,8 @@ function startRelayWatch(opts = {}) {
|
|
|
4802
4891
|
}
|
|
4803
4892
|
|
|
4804
4893
|
// src/daemon.ts
|
|
4805
|
-
import { spawn as
|
|
4806
|
-
import { accessSync, constants as constants2, openSync as
|
|
4894
|
+
import { spawn as spawn3 } from "node:child_process";
|
|
4895
|
+
import { accessSync, constants as constants2, openSync as openSync5, readFileSync as readFileSync3, statSync as statSync3 } from "node:fs";
|
|
4807
4896
|
import { mkdir as mkdir9, readFile as readFile9, stat as stat4 } from "node:fs/promises";
|
|
4808
4897
|
import { userInfo as userInfo2 } from "node:os";
|
|
4809
4898
|
import { setTimeout as sleep3 } from "node:timers/promises";
|
|
@@ -4832,6 +4921,11 @@ function unitActive() {
|
|
|
4832
4921
|
const res = spawnSync("systemctl", ["is-active", UNIT], { encoding: "utf8" });
|
|
4833
4922
|
return (res.stdout ?? "").trim() === "active";
|
|
4834
4923
|
}
|
|
4924
|
+
function unitPid() {
|
|
4925
|
+
const res = spawnSync("systemctl", ["show", UNIT, "-p", "MainPID", "--value"], { encoding: "utf8" });
|
|
4926
|
+
const pid = Number.parseInt((res.stdout ?? "").trim(), 10);
|
|
4927
|
+
return Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
4928
|
+
}
|
|
4835
4929
|
function startsAtBoot(p) {
|
|
4836
4930
|
return hasUnitFor(p) && spawnSync("systemctl", ["is-enabled", "--quiet", UNIT]).status === 0;
|
|
4837
4931
|
}
|
|
@@ -4897,6 +4991,24 @@ async function runningPid(p = paths()) {
|
|
|
4897
4991
|
}
|
|
4898
4992
|
return Number.isInteger(pid) && alive(pid) ? pid : null;
|
|
4899
4993
|
}
|
|
4994
|
+
async function daemonPid(p = paths()) {
|
|
4995
|
+
return await runningPid(p) ?? (hasUnitFor(p) ? unitPid() : null);
|
|
4996
|
+
}
|
|
4997
|
+
async function refuseSecondDaemon(p = paths()) {
|
|
4998
|
+
const live = await answering(p);
|
|
4999
|
+
if (live) throw new KvboxError(`kvbox-server is already running (pid ${live.pid}); kvbox-server status shows it`);
|
|
5000
|
+
const pid = await daemonPid(p);
|
|
5001
|
+
if (pid !== null && pid !== process.pid && isKvboxServer(pid)) {
|
|
5002
|
+
throw new KvboxError(`kvbox-server is already running (pid ${pid}) but its socket is gone, so nothing can reach it; restart it: kvbox-server stop, then kvbox-server start -d`);
|
|
5003
|
+
}
|
|
5004
|
+
}
|
|
5005
|
+
function isKvboxServer(pid) {
|
|
5006
|
+
try {
|
|
5007
|
+
return readFileSync3(`/proc/${pid}/cmdline`, "utf8").split("\0").slice(1).some((arg) => arg.includes("kvbox"));
|
|
5008
|
+
} catch (err) {
|
|
5009
|
+
return err.code !== "ENOENT";
|
|
5010
|
+
}
|
|
5011
|
+
}
|
|
4900
5012
|
function alive(pid) {
|
|
4901
5013
|
try {
|
|
4902
5014
|
process.kill(pid, 0);
|
|
@@ -4930,9 +5042,9 @@ async function startDetached(p = paths(), timeoutMs = 5e3) {
|
|
|
4930
5042
|
const running = await answering(p);
|
|
4931
5043
|
if (running) return { pid: running.pid, socketPath: p.serverSock, viaGroup: void 0, viaUnit: false, alreadyRunning: running.version };
|
|
4932
5044
|
if (hasUnitFor(p)) return startUnit(p, timeoutMs);
|
|
4933
|
-
const log2 =
|
|
5045
|
+
const log2 = openSync5(p.serverLog, "a");
|
|
4934
5046
|
const launcher = selfLauncher();
|
|
4935
|
-
const child =
|
|
5047
|
+
const child = spawn3(launcher.cmd, launcher.args, { detached: true, stdio: ["ignore", log2, log2], env: { ...process.env, KVBOX_HOME: p.home } });
|
|
4936
5048
|
const failed = new Promise((_, reject) => {
|
|
4937
5049
|
child.once("error", (err) => reject(new KvboxError(`could not start kvbox-server: ${err.message}`)));
|
|
4938
5050
|
child.once("exit", (code) => {
|
|
@@ -5035,7 +5147,7 @@ function groupWithMember(gid, user, groupFile) {
|
|
|
5035
5147
|
}
|
|
5036
5148
|
|
|
5037
5149
|
// src/listen.ts
|
|
5038
|
-
import { readFile as
|
|
5150
|
+
import { readFile as readFile11, rm as rm6, writeFile as writeFile9 } from "node:fs/promises";
|
|
5039
5151
|
import { createServer as createHttpsServer } from "node:https";
|
|
5040
5152
|
import { createAdaptorServer } from "@hono/node-server";
|
|
5041
5153
|
|
|
@@ -5055,7 +5167,7 @@ function versionOf(srcFileUrl, injected) {
|
|
|
5055
5167
|
}
|
|
5056
5168
|
|
|
5057
5169
|
// src/version.ts
|
|
5058
|
-
var VERSION = versionOf(import.meta.url, true ? "0.5.
|
|
5170
|
+
var VERSION = versionOf(import.meta.url, true ? "0.5.46" : void 0);
|
|
5059
5171
|
|
|
5060
5172
|
// src/caller.ts
|
|
5061
5173
|
import { createHash as createHash2, timingSafeEqual } from "node:crypto";
|
|
@@ -5128,6 +5240,53 @@ function digest(secret) {
|
|
|
5128
5240
|
return createHash2("sha256").update(secret).digest();
|
|
5129
5241
|
}
|
|
5130
5242
|
|
|
5243
|
+
// src/core/update.ts
|
|
5244
|
+
import { mkdir as mkdir10, readFile as readFile10, writeFile as writeFile8 } from "node:fs/promises";
|
|
5245
|
+
var INSTALL_SERVER_URL = "https://kvbox.sh/install-server.sh";
|
|
5246
|
+
var UPDATE_STALE_MS = 60 * 6e4;
|
|
5247
|
+
async function readUpdateState(p = paths(), now = Date.now()) {
|
|
5248
|
+
let raw;
|
|
5249
|
+
try {
|
|
5250
|
+
raw = JSON.parse(await readFile10(p.updateState, "utf8"));
|
|
5251
|
+
} catch {
|
|
5252
|
+
return null;
|
|
5253
|
+
}
|
|
5254
|
+
const parsed = HostUpdateSchema.safeParse(raw);
|
|
5255
|
+
if (!parsed.success) return null;
|
|
5256
|
+
const u = parsed.data;
|
|
5257
|
+
if (u.state === "running" && now - Date.parse(u.startedAt) > UPDATE_STALE_MS) {
|
|
5258
|
+
return { ...u, state: "failed", error: `never finished; see ${p.updateLog}` };
|
|
5259
|
+
}
|
|
5260
|
+
return u;
|
|
5261
|
+
}
|
|
5262
|
+
async function startUpdate(version, p = paths(), deps = {}) {
|
|
5263
|
+
const current = await readUpdateState(p);
|
|
5264
|
+
if (current?.state === "running") throw new KvboxError(`an update is already running since ${current.startedAt}`);
|
|
5265
|
+
const url = deps.url ?? process.env["KVBOX_INSTALL_SERVER_URL"] ?? INSTALL_SERVER_URL;
|
|
5266
|
+
const res = await (deps.fetch ?? fetch)(url, { signal: AbortSignal.timeout(2e4) });
|
|
5267
|
+
if (!res.ok) throw new KvboxError(`could not download ${url}: HTTP ${res.status}`);
|
|
5268
|
+
const script = await res.text();
|
|
5269
|
+
if (!script.startsWith("#!") || !script.includes("--update")) throw new KvboxError(`${url} is not an install-server.sh that knows --update`);
|
|
5270
|
+
await mkdir10(p.updateDir, { recursive: true });
|
|
5271
|
+
await writeFile8(p.updateScript, script, { mode: 448 });
|
|
5272
|
+
const state = { state: "running", startedAt: (/* @__PURE__ */ new Date()).toISOString(), finishedAt: null, from: version, to: null, error: null, needsManual: [] };
|
|
5273
|
+
await writeFile8(p.updateState, `${JSON.stringify(state, null, 2)}
|
|
5274
|
+
`);
|
|
5275
|
+
await writeFile8(p.updateLog, `--- ${state.startedAt} update from ${version}, ${url}
|
|
5276
|
+
`, { flag: "a" });
|
|
5277
|
+
const env = { ...process.env, KVBOX_HOME: p.home, KVBOX_YES: "1" };
|
|
5278
|
+
try {
|
|
5279
|
+
await (deps.spawn ?? spawnDetached)(["bash", p.updateScript, "--update"], p.updateLog, env);
|
|
5280
|
+
} catch (err) {
|
|
5281
|
+
const failed = { ...state, state: "failed", finishedAt: (/* @__PURE__ */ new Date()).toISOString(), error: err.message };
|
|
5282
|
+
await writeFile8(p.updateState, `${JSON.stringify(failed, null, 2)}
|
|
5283
|
+
`);
|
|
5284
|
+
throw err;
|
|
5285
|
+
}
|
|
5286
|
+
log.info(`update started from ${version}: install-server.sh --update, log in ${p.updateLog}`);
|
|
5287
|
+
return state;
|
|
5288
|
+
}
|
|
5289
|
+
|
|
5131
5290
|
// src/routes/backups.ts
|
|
5132
5291
|
import { Hono } from "hono";
|
|
5133
5292
|
function backupMachineRoutes() {
|
|
@@ -5409,7 +5568,7 @@ ${lines.join("")}\r
|
|
|
5409
5568
|
import { Hono as Hono3 } from "hono";
|
|
5410
5569
|
function capacityRoutes() {
|
|
5411
5570
|
const r = new Hono3();
|
|
5412
|
-
r.get("/", async (c) => c.json(await capacity()));
|
|
5571
|
+
r.get("/", async (c) => c.json({ ...await capacity(), version: VERSION }));
|
|
5413
5572
|
return r;
|
|
5414
5573
|
}
|
|
5415
5574
|
|
|
@@ -5669,9 +5828,11 @@ function createApp(opts = {}) {
|
|
|
5669
5828
|
owner: cfg.owner,
|
|
5670
5829
|
controlPlane: cp ? { name: cp.name, url: cp.url, hostUrl: `https://${cp.advertise}:${cp.port}` } : null,
|
|
5671
5830
|
relay: cfg.relay ? { name: cfg.relay.name, publicIp: cfg.relay.publicIp, endpoint: cfg.relay.endpoint, ...relayWatchReport() } : null,
|
|
5672
|
-
recovery: lastRecovery()
|
|
5831
|
+
recovery: lastRecovery(),
|
|
5832
|
+
update: await readUpdateState()
|
|
5673
5833
|
});
|
|
5674
5834
|
});
|
|
5835
|
+
if (opts.controlPlane) app.post("/update", async (c) => c.json(await startUpdate(VERSION), 202));
|
|
5675
5836
|
if (opts.controlPlane) app.route("/machines", boxHttpRoutes());
|
|
5676
5837
|
if (opts.controlPlane) {
|
|
5677
5838
|
app.route("/machines", backupMachineRoutes());
|
|
@@ -5704,19 +5865,20 @@ async function listen(opts = {}) {
|
|
|
5704
5865
|
if (Buffer.byteLength(socketPath) > 100) {
|
|
5705
5866
|
throw new KvboxError(`socket path too long for a Unix socket (${socketPath}); set KVBOX_HOME to a shorter path`);
|
|
5706
5867
|
}
|
|
5868
|
+
if (socketPath === p.serverSock) await refuseSecondDaemon(p);
|
|
5707
5869
|
await rm6(socketPath, { force: true });
|
|
5708
5870
|
const server = createAdaptorServer({ fetch: createApp().fetch });
|
|
5709
5871
|
await new Promise((resolve2, reject) => {
|
|
5710
5872
|
server.once("error", reject);
|
|
5711
5873
|
server.listen(socketPath, () => resolve2());
|
|
5712
5874
|
});
|
|
5713
|
-
await
|
|
5875
|
+
await writeFile9(p.serverPid, `${process.pid}
|
|
5714
5876
|
`);
|
|
5715
5877
|
let https;
|
|
5716
5878
|
let httpsServer;
|
|
5717
5879
|
const cp = cfg.controlPlane;
|
|
5718
5880
|
if (cp) {
|
|
5719
|
-
const [key, cert] = await Promise.all([
|
|
5881
|
+
const [key, cert] = await Promise.all([readFile11(p.tlsKey), readFile11(p.tlsCert)]).catch((err) => {
|
|
5720
5882
|
throw new KvboxError(`joined ${cp.name} but the host's certificate is missing (${err.message}); run kvbox-server leave, then join again`);
|
|
5721
5883
|
});
|
|
5722
5884
|
httpsServer = createAdaptorServer({
|
|
@@ -5773,6 +5935,7 @@ var startCommand = new Command("start").description("run the daemon in the foreg
|
|
|
5773
5935
|
if (started.viaGroup !== void 0) console.log(`started through the ${started.viaGroup} group, which this shell does not have yet (log out and back in to get it)`);
|
|
5774
5936
|
return;
|
|
5775
5937
|
}
|
|
5938
|
+
if (opts.socket === void 0) await refuseSecondDaemon(paths());
|
|
5776
5939
|
daemon = true;
|
|
5777
5940
|
await requireKvm();
|
|
5778
5941
|
const settled = await settleDeadBoxes(paths());
|
|
@@ -5853,14 +6016,14 @@ var leaveCommand = new Command3("leave").description("take this host out from be
|
|
|
5853
6016
|
});
|
|
5854
6017
|
|
|
5855
6018
|
// src/commands/logs.ts
|
|
5856
|
-
import { open as open2, readFile as
|
|
6019
|
+
import { open as open2, readFile as readFile12, stat as stat5 } from "node:fs/promises";
|
|
5857
6020
|
import { setTimeout as sleep4 } from "node:timers/promises";
|
|
5858
6021
|
import { Command as Command4 } from "commander";
|
|
5859
6022
|
var logsCommand = new Command4("logs").description("show the daemon's log ($KVBOX_HOME/server.log); -f keeps printing as it grows").option("-n, --lines <n>", "how many lines to show from the end", "50").option("-f, --follow", "keep printing new lines until Ctrl-C").action(async (opts) => {
|
|
5860
6023
|
const n = Number.parseInt(opts.lines, 10);
|
|
5861
6024
|
if (!Number.isInteger(n) || n < 0) throw new KvboxError(`--lines: expected a number, got ${opts.lines}`);
|
|
5862
6025
|
const p = paths();
|
|
5863
|
-
const text = await
|
|
6026
|
+
const text = await readFile12(p.serverLog, "utf8").catch((err) => {
|
|
5864
6027
|
if (err.code === "ENOENT") throw new KvboxError(`no log yet at ${p.serverLog} (the daemon writes it once it has run)`);
|
|
5865
6028
|
throw err;
|
|
5866
6029
|
});
|
|
@@ -5926,11 +6089,13 @@ var relayCommand = new Command6("relay").description("reach the internet through
|
|
|
5926
6089
|
});
|
|
5927
6090
|
|
|
5928
6091
|
// src/commands/status.ts
|
|
6092
|
+
import { homedir as homedir2 } from "node:os";
|
|
6093
|
+
import { styleText } from "node:util";
|
|
5929
6094
|
import { Command as Command7 } from "commander";
|
|
5930
6095
|
var statusCommand = new Command7("status").description("show whether the daemon is running, its control plane and which base image new boxes get").option("--json", "print as JSON").action(async (opts) => {
|
|
5931
6096
|
const p = paths();
|
|
5932
6097
|
const atBoot = startsAtBoot(p);
|
|
5933
|
-
const pid = await
|
|
6098
|
+
const pid = await daemonPid(p);
|
|
5934
6099
|
if (pid === null) {
|
|
5935
6100
|
if (opts.json) {
|
|
5936
6101
|
console.log(JSON.stringify({ running: false, startsAtBoot: atBoot }, null, 2));
|
|
@@ -5939,6 +6104,14 @@ var statusCommand = new Command7("status").description("show whether the daemon
|
|
|
5939
6104
|
}
|
|
5940
6105
|
throw new KvboxError(`kvbox-server is not running (start it with: kvbox-server start -d)${atBoot ? "; it starts at boot" : ""}`);
|
|
5941
6106
|
}
|
|
6107
|
+
if (!await answering(p)) {
|
|
6108
|
+
if (opts.json) {
|
|
6109
|
+
console.log(JSON.stringify({ running: true, reachable: false, pid, startsAtBoot: atBoot }, null, 2));
|
|
6110
|
+
process.exitCode = 1;
|
|
6111
|
+
return;
|
|
6112
|
+
}
|
|
6113
|
+
throw new KvboxError(`kvbox-server is running (pid ${pid}) but its socket is gone, so nothing can reach it; restart it: kvbox-server stop, then kvbox-server start -d`);
|
|
6114
|
+
}
|
|
5942
6115
|
const client = new SocketClient(p.serverSock);
|
|
5943
6116
|
try {
|
|
5944
6117
|
const health = await client.health();
|
|
@@ -5946,34 +6119,54 @@ var statusCommand = new Command7("status").description("show whether the daemon
|
|
|
5946
6119
|
console.log(JSON.stringify({ running: true, ...health, startsAtBoot: atBoot }, null, 2));
|
|
5947
6120
|
return;
|
|
5948
6121
|
}
|
|
5949
|
-
|
|
5950
|
-
console.log(atBoot ? "starts at boot: yes, and brings back the boxes that were running" : "starts at boot: no (install-server.sh sets that up)");
|
|
5951
|
-
const r = health.recovery;
|
|
5952
|
-
if (r) {
|
|
5953
|
-
if (r.booted.length > 0) console.log(`after the last restart it booted again: ${r.booted.join(", ")}`);
|
|
5954
|
-
if (r.leftStopped.length > 0) console.log(`left stopped (were in standby, their memory was lost): ${r.leftStopped.join(", ")}`);
|
|
5955
|
-
for (const f of r.failed) console.log(`did not come back: ${f.box} (${f.error})`);
|
|
5956
|
-
}
|
|
5957
|
-
if (health.controlPlane) console.log(`control plane: ${health.controlPlane.name} at ${health.controlPlane.url}, this host answers it on ${health.controlPlane.hostUrl}`);
|
|
5958
|
-
else console.log("control plane: none (kvbox-server join <url> --token <token> puts this host behind one)");
|
|
5959
|
-
if (health.relay) {
|
|
5960
|
-
console.log(`relay: ${health.relay.name} lends this host ${health.relay.publicIp} (tunnel to ${health.relay.endpoint})`);
|
|
5961
|
-
if (health.relay.restarts && health.relay.lastRestartAt) {
|
|
5962
|
-
console.log(`the tunnel stopped carrying traffic and was redialed ${health.relay.restarts} time(s) since the server started, last at ${health.relay.lastRestartAt}`);
|
|
5963
|
-
}
|
|
5964
|
-
}
|
|
5965
|
-
if (health.base === null) console.log("base image: none usable yet (run install-server.sh)");
|
|
5966
|
-
else console.log(`base image: ${health.base} (what kvbox new uses; kvbox vm update <box> moves an older box onto it)`);
|
|
5967
|
-
console.log(`log: ${p.serverLog} (kvbox-server logs -f)`);
|
|
6122
|
+
printStatus(health, atBoot, p.serverLog);
|
|
5968
6123
|
} finally {
|
|
5969
6124
|
await client.close();
|
|
5970
6125
|
}
|
|
5971
6126
|
});
|
|
6127
|
+
function printStatus(health, atBoot, logPath) {
|
|
6128
|
+
const dim = (t) => styleText("dim", t, { stream: process.stdout });
|
|
6129
|
+
const rows = [];
|
|
6130
|
+
rows.push(["starts at boot", atBoot ? "yes, and brings back the boxes that were running" : `no ${dim("(install-server.sh sets that up)")}`]);
|
|
6131
|
+
if (health.controlPlane) {
|
|
6132
|
+
rows.push(["control plane", `${health.controlPlane.name} ${dim(`(${health.controlPlane.url})`)}`]);
|
|
6133
|
+
rows.push(["answers it on", health.controlPlane.hostUrl]);
|
|
6134
|
+
} else {
|
|
6135
|
+
rows.push(["control plane", `none ${dim("(kvbox-server join <url> --token <token>)")}`]);
|
|
6136
|
+
}
|
|
6137
|
+
if (health.relay) {
|
|
6138
|
+
rows.push(["relay", `${health.relay.name} lends this host ${health.relay.publicIp} ${dim(`(tunnel to ${health.relay.endpoint})`)}`]);
|
|
6139
|
+
if (health.relay.restarts && health.relay.lastRestartAt) {
|
|
6140
|
+
rows.push(["tunnel redialed", `${health.relay.restarts} time(s) since the server started, last at ${health.relay.lastRestartAt}`]);
|
|
6141
|
+
}
|
|
6142
|
+
}
|
|
6143
|
+
rows.push(["base image", health.base === null ? "none usable yet (run install-server.sh)" : `${health.base} ${dim("(what kvbox new uses)")}`]);
|
|
6144
|
+
const home = homedir2();
|
|
6145
|
+
rows.push(["log", `${logPath.startsWith(`${home}/`) ? `~${logPath.slice(home.length)}` : logPath} ${dim("(kvbox-server logs -f)")}`]);
|
|
6146
|
+
const r = health.recovery;
|
|
6147
|
+
const after = [];
|
|
6148
|
+
if (r) {
|
|
6149
|
+
if (r.booted.length > 0) after.push(["booted again", r.booted.join(", ")]);
|
|
6150
|
+
if (r.leftStopped.length > 0) after.push(["left stopped", `${r.leftStopped.join(", ")} ${dim("(were in standby, their memory was lost)")}`]);
|
|
6151
|
+
for (const f of r.failed) after.push(["did not come back", `${f.box} ${dim(`(${f.error})`)}`]);
|
|
6152
|
+
}
|
|
6153
|
+
const width = Math.max(...rows.map(([k]) => k.length));
|
|
6154
|
+
const line = ([k, v]) => console.log(` ${dim(k.padEnd(width))} ${v}`);
|
|
6155
|
+
console.log(`${styleText("bold", `kvbox-server ${health.version}`, { stream: process.stdout })} ${styleText("green", "\u25CF running", { stream: process.stdout })} ${dim(`(pid ${health.pid})`)}`);
|
|
6156
|
+
console.log();
|
|
6157
|
+
rows.forEach(line);
|
|
6158
|
+
if (after.length > 0) {
|
|
6159
|
+
console.log();
|
|
6160
|
+
console.log(" after the last restart");
|
|
6161
|
+
const w = Math.max(...after.map(([k]) => k.length));
|
|
6162
|
+
for (const [k, v] of after) console.log(` ${dim(k.padEnd(w))} ${v}`);
|
|
6163
|
+
}
|
|
6164
|
+
}
|
|
5972
6165
|
|
|
5973
6166
|
// src/commands/stop.ts
|
|
5974
6167
|
import { Command as Command8 } from "commander";
|
|
5975
6168
|
var stopCommand = new Command8("stop").description("stop the daemon (running boxes are not affected)").action(async () => {
|
|
5976
|
-
const pid = await
|
|
6169
|
+
const pid = await daemonPid(paths());
|
|
5977
6170
|
if (pid === null) throw new KvboxError("kvbox-server is not running");
|
|
5978
6171
|
await stopDaemon(pid);
|
|
5979
6172
|
console.log(`kvbox-server stopped (pid ${pid}); boxes keep running`);
|
|
@@ -6035,7 +6228,7 @@ function describeReport(report2) {
|
|
|
6035
6228
|
|
|
6036
6229
|
// src/program.ts
|
|
6037
6230
|
function buildProgram() {
|
|
6038
|
-
return new Command10("kvbox-server").description("kvbox host daemon: owns Firecracker and $KVBOX_HOME (~/.kvbox), serves the kvbox API").version(VERSION, "-v, --version").showHelpAfterError().addCommand(startCommand
|
|
6231
|
+
return new Command10("kvbox-server").description("kvbox host daemon: owns Firecracker and $KVBOX_HOME (~/.kvbox), serves the kvbox API").version(VERSION, "-v, --version").showHelpAfterError().addCommand(startCommand).addCommand(stopCommand).addCommand(statusCommand).addCommand(logsCommand).addCommand(joinCommand).addCommand(leaveCommand).addCommand(relayCommand).addCommand(trustCaCommand).addCommand(netCommand);
|
|
6039
6232
|
}
|
|
6040
6233
|
|
|
6041
6234
|
// src/index.ts
|