@kvbox/server 0.5.44 → 0.5.45

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.
@@ -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 openSync3, statSync as statSync2 } from "node:fs";
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
 
@@ -1306,7 +1314,9 @@ var CapacitySchema = z4.object({
1306
1314
  * The images a new box can be made from here (#87), with the version `new` uses; the base is `base`.
1307
1315
  * Absent on a host from before images: it has only the base.
1308
1316
  */
1309
- images: z4.array(z4.object({ name: z4.string(), version: z4.string() })).optional()
1317
+ images: z4.array(z4.object({ name: z4.string(), version: z4.string() })).optional(),
1318
+ /** kvbox-server's version, so the control plane's host list shows it without a call per host. Older servers omit it. */
1319
+ version: z4.string().optional()
1310
1320
  });
1311
1321
  var ImageSchema = z4.object({ name: z4.string(), version: z4.string().nullable() });
1312
1322
  var RecoveryReportSchema = z4.object({
@@ -1315,6 +1325,16 @@ var RecoveryReportSchema = z4.object({
1315
1325
  leftStopped: z4.array(z4.string()),
1316
1326
  failed: z4.array(z4.object({ box: z4.string(), error: z4.string() }))
1317
1327
  });
1328
+ var HostUpdateSchema = z4.object({
1329
+ state: z4.enum(["running", "done", "failed"]),
1330
+ startedAt: z4.string(),
1331
+ finishedAt: z4.string().nullable(),
1332
+ /** kvbox-server's version when the update started, and when it ended (null while running or when it failed before). */
1333
+ from: z4.string(),
1334
+ to: z4.string().nullable(),
1335
+ error: z4.string().nullable(),
1336
+ needsManual: z4.array(z4.string())
1337
+ });
1318
1338
  var HealthSchema = z4.object({
1319
1339
  ok: z4.literal(true),
1320
1340
  version: z4.string(),
@@ -1343,7 +1363,9 @@ var HealthSchema = z4.object({
1343
1363
  lastRestartAt: z4.string().nullable().optional()
1344
1364
  }).nullable().optional(),
1345
1365
  /** 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()
1366
+ recovery: RecoveryReportSchema.nullable().optional(),
1367
+ /** The last self-update; null when none ran. Older servers omit it. */
1368
+ update: HostUpdateSchema.nullable().optional()
1347
1369
  });
1348
1370
  var MachineUsageSchema = z4.object({
1349
1371
  name: z4.string(),
@@ -1628,7 +1650,14 @@ var CloudHostSchema = z4.object({
1628
1650
  lastSeenAt: z4.string().nullable(),
1629
1651
  capacity: CapacitySchema.nullable(),
1630
1652
  /** ISO 3166-1 alpha-2 code (`RO`), null when nobody said where the host is. */
1631
- country: z4.string().nullable()
1653
+ country: z4.string().nullable(),
1654
+ /** 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. */
1655
+ version: z4.string().nullable()
1656
+ });
1657
+ var HostInfoSchema = z4.object({
1658
+ host: CloudHostSchema,
1659
+ health: HealthSchema.nullable(),
1660
+ error: z4.string().nullable()
1632
1661
  });
1633
1662
  var HostPatchRequest = z4.object({ country: z4.string().nullable() });
1634
1663
  var CountrySchema = z4.object({ code: z4.string(), name: z4.string() });
@@ -1931,7 +1960,8 @@ import { basename } from "node:path";
1931
1960
  import { z as z6 } from "zod";
1932
1961
 
1933
1962
  // src/core/exec.ts
1934
- import { execFile } from "node:child_process";
1963
+ import { execFile, spawn } from "node:child_process";
1964
+ import { openSync as openSync2 } from "node:fs";
1935
1965
  import { promisify } from "node:util";
1936
1966
  var execFileAsync = promisify(execFile);
1937
1967
  async function run(argv, opts = {}) {
@@ -1953,6 +1983,19 @@ async function run(argv, opts = {}) {
1953
1983
  throw new KvboxError(`${[cmd, ...args].join(" ")} failed${detail ? `: ${detail}` : ""}`);
1954
1984
  }
1955
1985
  }
1986
+ function spawnDetached(argv, logFile, env = process.env) {
1987
+ const [cmd, ...args] = argv;
1988
+ if (!cmd) throw new KvboxError("spawnDetached: empty argv");
1989
+ const out = openSync2(logFile, "a");
1990
+ const child = spawn(cmd, args, { detached: true, stdio: ["ignore", out, out], env });
1991
+ return new Promise((resolve2, reject) => {
1992
+ child.once("error", (err) => reject(new KvboxError(`${cmd} could not start: ${err.message}`)));
1993
+ child.once("spawn", () => {
1994
+ child.unref();
1995
+ resolve2(child.pid ?? -1);
1996
+ });
1997
+ });
1998
+ }
1956
1999
 
1957
2000
  // src/core/images.ts
1958
2001
  var BASE_IMAGE = "base";
@@ -2412,7 +2455,7 @@ async function assertRoomFor(vcpu, memMib, force, box, by, p = paths()) {
2412
2455
  }
2413
2456
 
2414
2457
  // src/core/ext4.ts
2415
- import { closeSync as closeSync2, openSync as openSync2, readSync } from "node:fs";
2458
+ import { closeSync as closeSync2, openSync as openSync3, readSync } from "node:fs";
2416
2459
  var SUPERBLOCK_OFFSET = 1024;
2417
2460
  var EXT4_MAGIC = 61267;
2418
2461
  var INCOMPAT_META_BG = 16;
@@ -2420,7 +2463,7 @@ var INCOMPAT_64BIT = 128;
2420
2463
  function ext4Usage(file) {
2421
2464
  let fd;
2422
2465
  try {
2423
- fd = openSync2(file, "r");
2466
+ fd = openSync3(file, "r");
2424
2467
  const sb = Buffer.alloc(1024);
2425
2468
  if (readSync(fd, sb, 0, sb.length, SUPERBLOCK_OFFSET) !== sb.length) return null;
2426
2469
  if (sb.readUInt16LE(56) !== EXT4_MAGIC) return null;
@@ -3046,10 +3089,10 @@ async function spawnFirecracker(ref, cfg, p) {
3046
3089
  const m = p.machine(ref.owner, ref.name);
3047
3090
  await rm3(m.sock, { force: true });
3048
3091
  await rm3(m.vsock, { force: true });
3049
- const logFd = openSync3(m.log, "a");
3092
+ const logFd = openSync4(m.log, "a");
3050
3093
  let child;
3051
3094
  try {
3052
- child = spawn(cfg.firecracker, ["--api-sock", m.sock, "--id", ref.name, "--level", "Error"], {
3095
+ child = spawn2(cfg.firecracker, ["--api-sock", m.sock, "--id", ref.name, "--level", "Error"], {
3053
3096
  cwd: m.dir,
3054
3097
  detached: true,
3055
3098
  stdio: ["ignore", logFd, logFd]
@@ -4802,8 +4845,8 @@ function startRelayWatch(opts = {}) {
4802
4845
  }
4803
4846
 
4804
4847
  // src/daemon.ts
4805
- import { spawn as spawn2 } from "node:child_process";
4806
- import { accessSync, constants as constants2, openSync as openSync4, readFileSync as readFileSync3, statSync as statSync3 } from "node:fs";
4848
+ import { spawn as spawn3 } from "node:child_process";
4849
+ import { accessSync, constants as constants2, openSync as openSync5, readFileSync as readFileSync3, statSync as statSync3 } from "node:fs";
4807
4850
  import { mkdir as mkdir9, readFile as readFile9, stat as stat4 } from "node:fs/promises";
4808
4851
  import { userInfo as userInfo2 } from "node:os";
4809
4852
  import { setTimeout as sleep3 } from "node:timers/promises";
@@ -4832,6 +4875,11 @@ function unitActive() {
4832
4875
  const res = spawnSync("systemctl", ["is-active", UNIT], { encoding: "utf8" });
4833
4876
  return (res.stdout ?? "").trim() === "active";
4834
4877
  }
4878
+ function unitPid() {
4879
+ const res = spawnSync("systemctl", ["show", UNIT, "-p", "MainPID", "--value"], { encoding: "utf8" });
4880
+ const pid = Number.parseInt((res.stdout ?? "").trim(), 10);
4881
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
4882
+ }
4835
4883
  function startsAtBoot(p) {
4836
4884
  return hasUnitFor(p) && spawnSync("systemctl", ["is-enabled", "--quiet", UNIT]).status === 0;
4837
4885
  }
@@ -4897,6 +4945,24 @@ async function runningPid(p = paths()) {
4897
4945
  }
4898
4946
  return Number.isInteger(pid) && alive(pid) ? pid : null;
4899
4947
  }
4948
+ async function daemonPid(p = paths()) {
4949
+ return await runningPid(p) ?? (hasUnitFor(p) ? unitPid() : null);
4950
+ }
4951
+ async function refuseSecondDaemon(p = paths()) {
4952
+ const live = await answering(p);
4953
+ if (live) throw new KvboxError(`kvbox-server is already running (pid ${live.pid}); kvbox-server status shows it`);
4954
+ const pid = await daemonPid(p);
4955
+ if (pid !== null && pid !== process.pid && isKvboxServer(pid)) {
4956
+ 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`);
4957
+ }
4958
+ }
4959
+ function isKvboxServer(pid) {
4960
+ try {
4961
+ return readFileSync3(`/proc/${pid}/cmdline`, "utf8").split("\0").slice(1).some((arg) => arg.includes("kvbox"));
4962
+ } catch (err) {
4963
+ return err.code !== "ENOENT";
4964
+ }
4965
+ }
4900
4966
  function alive(pid) {
4901
4967
  try {
4902
4968
  process.kill(pid, 0);
@@ -4930,9 +4996,9 @@ async function startDetached(p = paths(), timeoutMs = 5e3) {
4930
4996
  const running = await answering(p);
4931
4997
  if (running) return { pid: running.pid, socketPath: p.serverSock, viaGroup: void 0, viaUnit: false, alreadyRunning: running.version };
4932
4998
  if (hasUnitFor(p)) return startUnit(p, timeoutMs);
4933
- const log2 = openSync4(p.serverLog, "a");
4999
+ const log2 = openSync5(p.serverLog, "a");
4934
5000
  const launcher = selfLauncher();
4935
- const child = spawn2(launcher.cmd, launcher.args, { detached: true, stdio: ["ignore", log2, log2], env: { ...process.env, KVBOX_HOME: p.home } });
5001
+ const child = spawn3(launcher.cmd, launcher.args, { detached: true, stdio: ["ignore", log2, log2], env: { ...process.env, KVBOX_HOME: p.home } });
4936
5002
  const failed = new Promise((_, reject) => {
4937
5003
  child.once("error", (err) => reject(new KvboxError(`could not start kvbox-server: ${err.message}`)));
4938
5004
  child.once("exit", (code) => {
@@ -5035,7 +5101,7 @@ function groupWithMember(gid, user, groupFile) {
5035
5101
  }
5036
5102
 
5037
5103
  // src/listen.ts
5038
- import { readFile as readFile10, rm as rm6, writeFile as writeFile8 } from "node:fs/promises";
5104
+ import { readFile as readFile11, rm as rm6, writeFile as writeFile9 } from "node:fs/promises";
5039
5105
  import { createServer as createHttpsServer } from "node:https";
5040
5106
  import { createAdaptorServer } from "@hono/node-server";
5041
5107
 
@@ -5055,7 +5121,7 @@ function versionOf(srcFileUrl, injected) {
5055
5121
  }
5056
5122
 
5057
5123
  // src/version.ts
5058
- var VERSION = versionOf(import.meta.url, true ? "0.5.44" : void 0);
5124
+ var VERSION = versionOf(import.meta.url, true ? "0.5.45" : void 0);
5059
5125
 
5060
5126
  // src/caller.ts
5061
5127
  import { createHash as createHash2, timingSafeEqual } from "node:crypto";
@@ -5128,6 +5194,53 @@ function digest(secret) {
5128
5194
  return createHash2("sha256").update(secret).digest();
5129
5195
  }
5130
5196
 
5197
+ // src/core/update.ts
5198
+ import { mkdir as mkdir10, readFile as readFile10, writeFile as writeFile8 } from "node:fs/promises";
5199
+ var INSTALL_SERVER_URL = "https://kvbox.sh/install-server.sh";
5200
+ var UPDATE_STALE_MS = 60 * 6e4;
5201
+ async function readUpdateState(p = paths(), now = Date.now()) {
5202
+ let raw;
5203
+ try {
5204
+ raw = JSON.parse(await readFile10(p.updateState, "utf8"));
5205
+ } catch {
5206
+ return null;
5207
+ }
5208
+ const parsed = HostUpdateSchema.safeParse(raw);
5209
+ if (!parsed.success) return null;
5210
+ const u = parsed.data;
5211
+ if (u.state === "running" && now - Date.parse(u.startedAt) > UPDATE_STALE_MS) {
5212
+ return { ...u, state: "failed", error: `never finished; see ${p.updateLog}` };
5213
+ }
5214
+ return u;
5215
+ }
5216
+ async function startUpdate(version, p = paths(), deps = {}) {
5217
+ const current = await readUpdateState(p);
5218
+ if (current?.state === "running") throw new KvboxError(`an update is already running since ${current.startedAt}`);
5219
+ const url = deps.url ?? process.env["KVBOX_INSTALL_SERVER_URL"] ?? INSTALL_SERVER_URL;
5220
+ const res = await (deps.fetch ?? fetch)(url, { signal: AbortSignal.timeout(2e4) });
5221
+ if (!res.ok) throw new KvboxError(`could not download ${url}: HTTP ${res.status}`);
5222
+ const script = await res.text();
5223
+ if (!script.startsWith("#!") || !script.includes("--update")) throw new KvboxError(`${url} is not an install-server.sh that knows --update`);
5224
+ await mkdir10(p.updateDir, { recursive: true });
5225
+ await writeFile8(p.updateScript, script, { mode: 448 });
5226
+ const state = { state: "running", startedAt: (/* @__PURE__ */ new Date()).toISOString(), finishedAt: null, from: version, to: null, error: null, needsManual: [] };
5227
+ await writeFile8(p.updateState, `${JSON.stringify(state, null, 2)}
5228
+ `);
5229
+ await writeFile8(p.updateLog, `--- ${state.startedAt} update from ${version}, ${url}
5230
+ `, { flag: "a" });
5231
+ const env = { ...process.env, KVBOX_HOME: p.home, KVBOX_YES: "1" };
5232
+ try {
5233
+ await (deps.spawn ?? spawnDetached)(["bash", p.updateScript, "--update"], p.updateLog, env);
5234
+ } catch (err) {
5235
+ const failed = { ...state, state: "failed", finishedAt: (/* @__PURE__ */ new Date()).toISOString(), error: err.message };
5236
+ await writeFile8(p.updateState, `${JSON.stringify(failed, null, 2)}
5237
+ `);
5238
+ throw err;
5239
+ }
5240
+ log.info(`update started from ${version}: install-server.sh --update, log in ${p.updateLog}`);
5241
+ return state;
5242
+ }
5243
+
5131
5244
  // src/routes/backups.ts
5132
5245
  import { Hono } from "hono";
5133
5246
  function backupMachineRoutes() {
@@ -5409,7 +5522,7 @@ ${lines.join("")}\r
5409
5522
  import { Hono as Hono3 } from "hono";
5410
5523
  function capacityRoutes() {
5411
5524
  const r = new Hono3();
5412
- r.get("/", async (c) => c.json(await capacity()));
5525
+ r.get("/", async (c) => c.json({ ...await capacity(), version: VERSION }));
5413
5526
  return r;
5414
5527
  }
5415
5528
 
@@ -5669,9 +5782,11 @@ function createApp(opts = {}) {
5669
5782
  owner: cfg.owner,
5670
5783
  controlPlane: cp ? { name: cp.name, url: cp.url, hostUrl: `https://${cp.advertise}:${cp.port}` } : null,
5671
5784
  relay: cfg.relay ? { name: cfg.relay.name, publicIp: cfg.relay.publicIp, endpoint: cfg.relay.endpoint, ...relayWatchReport() } : null,
5672
- recovery: lastRecovery()
5785
+ recovery: lastRecovery(),
5786
+ update: await readUpdateState()
5673
5787
  });
5674
5788
  });
5789
+ if (opts.controlPlane) app.post("/update", async (c) => c.json(await startUpdate(VERSION), 202));
5675
5790
  if (opts.controlPlane) app.route("/machines", boxHttpRoutes());
5676
5791
  if (opts.controlPlane) {
5677
5792
  app.route("/machines", backupMachineRoutes());
@@ -5704,19 +5819,20 @@ async function listen(opts = {}) {
5704
5819
  if (Buffer.byteLength(socketPath) > 100) {
5705
5820
  throw new KvboxError(`socket path too long for a Unix socket (${socketPath}); set KVBOX_HOME to a shorter path`);
5706
5821
  }
5822
+ if (socketPath === p.serverSock) await refuseSecondDaemon(p);
5707
5823
  await rm6(socketPath, { force: true });
5708
5824
  const server = createAdaptorServer({ fetch: createApp().fetch });
5709
5825
  await new Promise((resolve2, reject) => {
5710
5826
  server.once("error", reject);
5711
5827
  server.listen(socketPath, () => resolve2());
5712
5828
  });
5713
- await writeFile8(p.serverPid, `${process.pid}
5829
+ await writeFile9(p.serverPid, `${process.pid}
5714
5830
  `);
5715
5831
  let https;
5716
5832
  let httpsServer;
5717
5833
  const cp = cfg.controlPlane;
5718
5834
  if (cp) {
5719
- const [key, cert] = await Promise.all([readFile10(p.tlsKey), readFile10(p.tlsCert)]).catch((err) => {
5835
+ const [key, cert] = await Promise.all([readFile11(p.tlsKey), readFile11(p.tlsCert)]).catch((err) => {
5720
5836
  throw new KvboxError(`joined ${cp.name} but the host's certificate is missing (${err.message}); run kvbox-server leave, then join again`);
5721
5837
  });
5722
5838
  httpsServer = createAdaptorServer({
@@ -5773,6 +5889,7 @@ var startCommand = new Command("start").description("run the daemon in the foreg
5773
5889
  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
5890
  return;
5775
5891
  }
5892
+ if (opts.socket === void 0) await refuseSecondDaemon(paths());
5776
5893
  daemon = true;
5777
5894
  await requireKvm();
5778
5895
  const settled = await settleDeadBoxes(paths());
@@ -5853,14 +5970,14 @@ var leaveCommand = new Command3("leave").description("take this host out from be
5853
5970
  });
5854
5971
 
5855
5972
  // src/commands/logs.ts
5856
- import { open as open2, readFile as readFile11, stat as stat5 } from "node:fs/promises";
5973
+ import { open as open2, readFile as readFile12, stat as stat5 } from "node:fs/promises";
5857
5974
  import { setTimeout as sleep4 } from "node:timers/promises";
5858
5975
  import { Command as Command4 } from "commander";
5859
5976
  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
5977
  const n = Number.parseInt(opts.lines, 10);
5861
5978
  if (!Number.isInteger(n) || n < 0) throw new KvboxError(`--lines: expected a number, got ${opts.lines}`);
5862
5979
  const p = paths();
5863
- const text = await readFile11(p.serverLog, "utf8").catch((err) => {
5980
+ const text = await readFile12(p.serverLog, "utf8").catch((err) => {
5864
5981
  if (err.code === "ENOENT") throw new KvboxError(`no log yet at ${p.serverLog} (the daemon writes it once it has run)`);
5865
5982
  throw err;
5866
5983
  });
@@ -5926,11 +6043,13 @@ var relayCommand = new Command6("relay").description("reach the internet through
5926
6043
  });
5927
6044
 
5928
6045
  // src/commands/status.ts
6046
+ import { homedir as homedir2 } from "node:os";
6047
+ import { styleText } from "node:util";
5929
6048
  import { Command as Command7 } from "commander";
5930
6049
  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
6050
  const p = paths();
5932
6051
  const atBoot = startsAtBoot(p);
5933
- const pid = await runningPid(p);
6052
+ const pid = await daemonPid(p);
5934
6053
  if (pid === null) {
5935
6054
  if (opts.json) {
5936
6055
  console.log(JSON.stringify({ running: false, startsAtBoot: atBoot }, null, 2));
@@ -5939,6 +6058,14 @@ var statusCommand = new Command7("status").description("show whether the daemon
5939
6058
  }
5940
6059
  throw new KvboxError(`kvbox-server is not running (start it with: kvbox-server start -d)${atBoot ? "; it starts at boot" : ""}`);
5941
6060
  }
6061
+ if (!await answering(p)) {
6062
+ if (opts.json) {
6063
+ console.log(JSON.stringify({ running: true, reachable: false, pid, startsAtBoot: atBoot }, null, 2));
6064
+ process.exitCode = 1;
6065
+ return;
6066
+ }
6067
+ 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`);
6068
+ }
5942
6069
  const client = new SocketClient(p.serverSock);
5943
6070
  try {
5944
6071
  const health = await client.health();
@@ -5946,34 +6073,54 @@ var statusCommand = new Command7("status").description("show whether the daemon
5946
6073
  console.log(JSON.stringify({ running: true, ...health, startsAtBoot: atBoot }, null, 2));
5947
6074
  return;
5948
6075
  }
5949
- console.log(`kvbox-server ${health.version} running, pid ${health.pid}`);
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)`);
6076
+ printStatus(health, atBoot, p.serverLog);
5968
6077
  } finally {
5969
6078
  await client.close();
5970
6079
  }
5971
6080
  });
6081
+ function printStatus(health, atBoot, logPath) {
6082
+ const dim = (t) => styleText("dim", t, { stream: process.stdout });
6083
+ const rows = [];
6084
+ rows.push(["starts at boot", atBoot ? "yes, and brings back the boxes that were running" : `no ${dim("(install-server.sh sets that up)")}`]);
6085
+ if (health.controlPlane) {
6086
+ rows.push(["control plane", `${health.controlPlane.name} ${dim(`(${health.controlPlane.url})`)}`]);
6087
+ rows.push(["answers it on", health.controlPlane.hostUrl]);
6088
+ } else {
6089
+ rows.push(["control plane", `none ${dim("(kvbox-server join <url> --token <token>)")}`]);
6090
+ }
6091
+ if (health.relay) {
6092
+ rows.push(["relay", `${health.relay.name} lends this host ${health.relay.publicIp} ${dim(`(tunnel to ${health.relay.endpoint})`)}`]);
6093
+ if (health.relay.restarts && health.relay.lastRestartAt) {
6094
+ rows.push(["tunnel redialed", `${health.relay.restarts} time(s) since the server started, last at ${health.relay.lastRestartAt}`]);
6095
+ }
6096
+ }
6097
+ rows.push(["base image", health.base === null ? "none usable yet (run install-server.sh)" : `${health.base} ${dim("(what kvbox new uses)")}`]);
6098
+ const home = homedir2();
6099
+ rows.push(["log", `${logPath.startsWith(`${home}/`) ? `~${logPath.slice(home.length)}` : logPath} ${dim("(kvbox-server logs -f)")}`]);
6100
+ const r = health.recovery;
6101
+ const after = [];
6102
+ if (r) {
6103
+ if (r.booted.length > 0) after.push(["booted again", r.booted.join(", ")]);
6104
+ if (r.leftStopped.length > 0) after.push(["left stopped", `${r.leftStopped.join(", ")} ${dim("(were in standby, their memory was lost)")}`]);
6105
+ for (const f of r.failed) after.push(["did not come back", `${f.box} ${dim(`(${f.error})`)}`]);
6106
+ }
6107
+ const width = Math.max(...rows.map(([k]) => k.length));
6108
+ const line = ([k, v]) => console.log(` ${dim(k.padEnd(width))} ${v}`);
6109
+ console.log(`${styleText("bold", `kvbox-server ${health.version}`, { stream: process.stdout })} ${styleText("green", "\u25CF running", { stream: process.stdout })} ${dim(`(pid ${health.pid})`)}`);
6110
+ console.log();
6111
+ rows.forEach(line);
6112
+ if (after.length > 0) {
6113
+ console.log();
6114
+ console.log(" after the last restart");
6115
+ const w = Math.max(...after.map(([k]) => k.length));
6116
+ for (const [k, v] of after) console.log(` ${dim(k.padEnd(w))} ${v}`);
6117
+ }
6118
+ }
5972
6119
 
5973
6120
  // src/commands/stop.ts
5974
6121
  import { Command as Command8 } from "commander";
5975
6122
  var stopCommand = new Command8("stop").description("stop the daemon (running boxes are not affected)").action(async () => {
5976
- const pid = await runningPid(paths());
6123
+ const pid = await daemonPid(paths());
5977
6124
  if (pid === null) throw new KvboxError("kvbox-server is not running");
5978
6125
  await stopDaemon(pid);
5979
6126
  console.log(`kvbox-server stopped (pid ${pid}); boxes keep running`);
@@ -6035,7 +6182,7 @@ function describeReport(report2) {
6035
6182
 
6036
6183
  // src/program.ts
6037
6184
  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, { isDefault: true }).addCommand(stopCommand).addCommand(statusCommand).addCommand(logsCommand).addCommand(joinCommand).addCommand(leaveCommand).addCommand(relayCommand).addCommand(trustCaCommand).addCommand(netCommand);
6185
+ 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
6186
  }
6040
6187
 
6041
6188
  // src/index.ts