@kvbox/server 0.5.50 → 0.5.51
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 +765 -245
- package/dist/kvbox-server.js.map +1 -1
- package/package.json +1 -1
package/dist/kvbox-server.js
CHANGED
|
@@ -63,6 +63,15 @@ function paths(home = kvboxHome()) {
|
|
|
63
63
|
firecracker: join(home, "bin", "firecracker"),
|
|
64
64
|
/** Firecracker's snapshot-editor, from the same release: merges a diff snapshot onto a full memory image. */
|
|
65
65
|
snapshotEditor: join(home, "bin", "snapshot-editor"),
|
|
66
|
+
/** Garage, on a host that is a backup store (`kvbox-server backup setup` downloads it). */
|
|
67
|
+
garage: join(home, "bin", "garage"),
|
|
68
|
+
/** The store's Garage as this host runs it: its configuration, pid and log. The data is on the disk the operator named. */
|
|
69
|
+
backupStore: {
|
|
70
|
+
dir: join(home, "backup-store"),
|
|
71
|
+
conf: join(home, "backup-store", "garage.toml"),
|
|
72
|
+
pid: join(home, "backup-store", "garage.pid"),
|
|
73
|
+
log: join(home, "backup-store", "garage.log")
|
|
74
|
+
},
|
|
66
75
|
assets: join(home, "assets"),
|
|
67
76
|
kernel: join(home, "assets", "vmlinux"),
|
|
68
77
|
/** Symlink to the current base image, assets/rootfs-<version>.ext4; boxes keep using the version they were made from. */
|
|
@@ -416,6 +425,16 @@ var RelaySchema = z2.object({
|
|
|
416
425
|
/** `<relay-ip>:<port>` the tunnel dials. */
|
|
417
426
|
endpoint: z2.string().min(1)
|
|
418
427
|
});
|
|
428
|
+
var BackupStoreSchema = z2.object({
|
|
429
|
+
/** A directory on the disk bought for backups. */
|
|
430
|
+
path: z2.string().min(1),
|
|
431
|
+
bucket: z2.string().min(1),
|
|
432
|
+
region: z2.string().min(1),
|
|
433
|
+
accessKey: z2.string().min(1),
|
|
434
|
+
secretKey: z2.string().min(1),
|
|
435
|
+
/** Whether the control plane took the store; false after a setup that could not reach it. */
|
|
436
|
+
registered: z2.boolean().default(false)
|
|
437
|
+
});
|
|
419
438
|
var ConfigSchema = z2.object({
|
|
420
439
|
kernel: z2.string(),
|
|
421
440
|
rootfs: z2.string(),
|
|
@@ -439,7 +458,9 @@ var ConfigSchema = z2.object({
|
|
|
439
458
|
/** Absent until the host joins a control plane; then the server also listens on HTTPS. */
|
|
440
459
|
controlPlane: ControlPlaneSchema.optional(),
|
|
441
460
|
/** Absent unless the host sits behind a relay. */
|
|
442
|
-
relay: RelaySchema.optional()
|
|
461
|
+
relay: RelaySchema.optional(),
|
|
462
|
+
/** Absent unless the host is a backup store. */
|
|
463
|
+
backupStore: BackupStoreSchema.optional()
|
|
443
464
|
});
|
|
444
465
|
async function saveConfig(cfg, p = paths()) {
|
|
445
466
|
const parsed = ConfigSchema.parse(cfg);
|
|
@@ -960,7 +981,7 @@ async function startDns(opts) {
|
|
|
960
981
|
if (!isOurs(q)) return reply({ rcode: RCODE.refused });
|
|
961
982
|
void boxes().then((list) => answerFor(q, rinfo.address, list)).catch(() => ({ rcode: RCODE.refused })).then(reply);
|
|
962
983
|
});
|
|
963
|
-
await new Promise((
|
|
984
|
+
await new Promise((resolve3, reject) => {
|
|
964
985
|
socket.once("error", (err) => {
|
|
965
986
|
socket.close();
|
|
966
987
|
reject(err);
|
|
@@ -969,17 +990,17 @@ async function startDns(opts) {
|
|
|
969
990
|
socket.removeAllListeners("error");
|
|
970
991
|
socket.on("error", () => {
|
|
971
992
|
});
|
|
972
|
-
|
|
993
|
+
resolve3();
|
|
973
994
|
});
|
|
974
995
|
});
|
|
975
|
-
return { socket, close: () => new Promise((
|
|
996
|
+
return { socket, close: () => new Promise((resolve3) => socket.close(() => resolve3())) };
|
|
976
997
|
}
|
|
977
998
|
|
|
978
999
|
// src/core/machines.ts
|
|
979
1000
|
import { spawn as spawn2 } from "node:child_process";
|
|
980
|
-
import { closeSync as closeSync3, existsSync as
|
|
981
|
-
import { link as link2, mkdir as
|
|
982
|
-
import { setTimeout as
|
|
1001
|
+
import { closeSync as closeSync3, existsSync as existsSync7, openSync as openSync4, statSync as statSync2 } from "node:fs";
|
|
1002
|
+
import { link as link2, mkdir as mkdir6, readFile as readFile6, rename as rename6, rm as rm4, truncate as truncate2, writeFile as writeFile6 } from "node:fs/promises";
|
|
1003
|
+
import { setTimeout as sleep2 } from "node:timers/promises";
|
|
983
1004
|
|
|
984
1005
|
// ../shared/src/duration.ts
|
|
985
1006
|
var UNIT_SEC = { m: 60, h: 3600, d: 86400 };
|
|
@@ -1091,7 +1112,7 @@ var HostBackupManifestSchema = z4.object({
|
|
|
1091
1112
|
vcpu: z4.number().int(),
|
|
1092
1113
|
memMib: z4.number().int()
|
|
1093
1114
|
});
|
|
1094
|
-
var HostUploadRequest = z4.object({ key: z4.string(), urls: z4.record(z4.string(), z4.string()) });
|
|
1115
|
+
var HostUploadRequest = z4.object({ key: z4.string(), urls: z4.record(z4.string(), z4.string()), pin: z4.string().optional() });
|
|
1095
1116
|
var HostUploadResultSchema = z4.object({ chunks: z4.number().int(), bytes: z4.number().int(), sizes: z4.record(z4.string(), z4.number().int()) });
|
|
1096
1117
|
var HostRestoreRequest = z4.object({
|
|
1097
1118
|
/** The backup's id: its variables were sealed under it. */
|
|
@@ -1101,7 +1122,45 @@ var HostRestoreRequest = z4.object({
|
|
|
1101
1122
|
base: z4.string(),
|
|
1102
1123
|
image: z4.string().optional(),
|
|
1103
1124
|
env: z4.string().nullable(),
|
|
1104
|
-
chunks: z4.array(z4.object({ index: z4.number().int().nonnegative(), hash: z4.string(), url: z4.string() }))
|
|
1125
|
+
chunks: z4.array(z4.object({ index: z4.number().int().nonnegative(), hash: z4.string(), url: z4.string() })),
|
|
1126
|
+
/** The certificate fingerprint of the store the URLs point at (see HostUploadRequest). */
|
|
1127
|
+
pin: z4.string().optional()
|
|
1128
|
+
});
|
|
1129
|
+
var BACKUP_STORE_BUCKET = "kvbox-backups";
|
|
1130
|
+
var BACKUP_STORE_REGION = "kvbox";
|
|
1131
|
+
var BackupStoreSetupRequest = z4.object({ path: z4.string().min(1), force: z4.boolean().optional(), newStore: z4.boolean().optional() });
|
|
1132
|
+
var BackupStoreStatusSchema = z4.object({
|
|
1133
|
+
path: z4.string(),
|
|
1134
|
+
bucket: z4.string(),
|
|
1135
|
+
accessKey: z4.string(),
|
|
1136
|
+
/** Whether Garage is running and can store. */
|
|
1137
|
+
running: z4.boolean(),
|
|
1138
|
+
/** The filesystem the path is on. */
|
|
1139
|
+
totalBytes: z4.number().int(),
|
|
1140
|
+
freeBytes: z4.number().int(),
|
|
1141
|
+
/** What the bucket holds, when Garage answers. */
|
|
1142
|
+
objects: z4.number().int().optional(),
|
|
1143
|
+
storedBytes: z4.number().int().optional(),
|
|
1144
|
+
/** Whether the control plane took the store's registration at setup. */
|
|
1145
|
+
registered: z4.boolean().optional()
|
|
1146
|
+
});
|
|
1147
|
+
var BackupStoreRegistration = z4.object({ bucket: z4.string().min(1), region: z4.string().min(1), accessKey: z4.string().min(1), secretKey: z4.string().min(1) });
|
|
1148
|
+
var CloudBackupStoreSchema = z4.object({
|
|
1149
|
+
id: z4.string(),
|
|
1150
|
+
/** Null while no host serves it (its host left; it comes back when a host registers its key and secret again). */
|
|
1151
|
+
host: z4.string().nullable(),
|
|
1152
|
+
endpoint: z4.string().nullable(),
|
|
1153
|
+
bucket: z4.string(),
|
|
1154
|
+
accessKey: z4.string(),
|
|
1155
|
+
createdAt: z4.string(),
|
|
1156
|
+
/** The host answered a poll in the last minute and its Garage runs. */
|
|
1157
|
+
live: z4.boolean(),
|
|
1158
|
+
/** From the host's last poll; null when it never reported a store. */
|
|
1159
|
+
totalBytes: z4.number().int().nullable(),
|
|
1160
|
+
freeBytes: z4.number().int().nullable(),
|
|
1161
|
+
/** Ready backups kept here, and what their chunks take (encrypted, compressed). */
|
|
1162
|
+
backups: z4.number().int(),
|
|
1163
|
+
storedBytes: z4.number().int()
|
|
1105
1164
|
});
|
|
1106
1165
|
var MachineSchema = z4.object({
|
|
1107
1166
|
/** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */
|
|
@@ -1343,7 +1402,11 @@ var CapacitySchema = z4.object({
|
|
|
1343
1402
|
*/
|
|
1344
1403
|
images: z4.array(z4.object({ name: z4.string(), version: z4.string() })).optional(),
|
|
1345
1404
|
/** kvbox-server's version, so the control plane's host list shows it without a call per host. Older servers omit it. */
|
|
1346
|
-
version: z4.string().optional()
|
|
1405
|
+
version: z4.string().optional(),
|
|
1406
|
+
/** Present on a host set up as a backup store: the disk its Garage keeps chunks on, and whether Garage runs. */
|
|
1407
|
+
backupStore: z4.object({ totalBytes: z4.number().int(), freeBytes: z4.number().int(), running: z4.boolean() }).optional(),
|
|
1408
|
+
/** True on a kvbox-server that reaches a backup store by its certificate's `pin`; older ones omit it and cannot back up to a store. */
|
|
1409
|
+
storeClient: z4.boolean().optional()
|
|
1347
1410
|
});
|
|
1348
1411
|
var ImageSchema = z4.object({ name: z4.string(), version: z4.string().nullable() });
|
|
1349
1412
|
var ImageIndexSchema = z4.object({
|
|
@@ -1758,6 +1821,8 @@ var CloudHostSchema = z4.object({
|
|
|
1758
1821
|
capacity: CapacitySchema.nullable(),
|
|
1759
1822
|
/** ISO 3166-1 alpha-2 code (`RO`), null when nobody said where the host is. */
|
|
1760
1823
|
country: z4.string().nullable(),
|
|
1824
|
+
/** The S3 region a storage made on this host answers to (`ro-west-1`); null: it takes no storage. */
|
|
1825
|
+
region: z4.string().nullable(),
|
|
1761
1826
|
/** 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. */
|
|
1762
1827
|
version: z4.string().nullable()
|
|
1763
1828
|
});
|
|
@@ -1766,7 +1831,7 @@ var HostInfoSchema = z4.object({
|
|
|
1766
1831
|
health: HealthSchema.nullable(),
|
|
1767
1832
|
error: z4.string().nullable()
|
|
1768
1833
|
});
|
|
1769
|
-
var HostPatchRequest = z4.object({ country: z4.string().nullable() });
|
|
1834
|
+
var HostPatchRequest = z4.object({ country: z4.string().nullable().optional(), region: z4.string().nullable().optional() }).refine((b) => b.country !== void 0 || b.region !== void 0, { message: "give country, region or both" });
|
|
1770
1835
|
var CountrySchema = z4.object({ code: z4.string(), name: z4.string() });
|
|
1771
1836
|
|
|
1772
1837
|
// ../shared/src/ssh.ts
|
|
@@ -1793,7 +1858,7 @@ var isCaLine = (line) => /^cert-authority(,|\s)/.test(line.trim());
|
|
|
1793
1858
|
import { connect } from "node:net";
|
|
1794
1859
|
var AGENT_PORT = 52;
|
|
1795
1860
|
async function agentCall(udsPath, req, timeoutMs = 5e3) {
|
|
1796
|
-
const reply = await new Promise((
|
|
1861
|
+
const reply = await new Promise((resolve3, reject) => {
|
|
1797
1862
|
const sock = connect(udsPath);
|
|
1798
1863
|
let buf = "";
|
|
1799
1864
|
let handshaken = false;
|
|
@@ -1817,7 +1882,7 @@ async function agentCall(udsPath, req, timeoutMs = 5e3) {
|
|
|
1817
1882
|
sock.write(JSON.stringify(req) + "\n");
|
|
1818
1883
|
} else {
|
|
1819
1884
|
sock.end();
|
|
1820
|
-
return
|
|
1885
|
+
return resolve3(line);
|
|
1821
1886
|
}
|
|
1822
1887
|
}
|
|
1823
1888
|
});
|
|
@@ -1903,7 +1968,7 @@ async function withLock(key, fn) {
|
|
|
1903
1968
|
if (mine?.has(key)) return fn();
|
|
1904
1969
|
const previous = tails.get(key);
|
|
1905
1970
|
let release;
|
|
1906
|
-
const tail = new Promise((
|
|
1971
|
+
const tail = new Promise((resolve3) => release = resolve3);
|
|
1907
1972
|
tails.set(key, tail);
|
|
1908
1973
|
try {
|
|
1909
1974
|
await previous;
|
|
@@ -2098,11 +2163,11 @@ function spawnDetached(argv, logFile, env = process.env) {
|
|
|
2098
2163
|
if (!cmd) throw new KvboxError("spawnDetached: empty argv");
|
|
2099
2164
|
const out = openSync2(logFile, "a");
|
|
2100
2165
|
const child = spawn(cmd, args, { detached: true, stdio: ["ignore", out, out], env });
|
|
2101
|
-
return new Promise((
|
|
2166
|
+
return new Promise((resolve3, reject) => {
|
|
2102
2167
|
child.once("error", (err) => reject(new KvboxError(`${cmd} could not start: ${err.message}`)));
|
|
2103
2168
|
child.once("spawn", () => {
|
|
2104
2169
|
child.unref();
|
|
2105
|
-
|
|
2170
|
+
resolve3(child.pid ?? -1);
|
|
2106
2171
|
});
|
|
2107
2172
|
});
|
|
2108
2173
|
}
|
|
@@ -2526,6 +2591,331 @@ async function attachedBox(ref, p) {
|
|
|
2526
2591
|
|
|
2527
2592
|
// src/core/capacity.ts
|
|
2528
2593
|
import { cpus, totalmem } from "node:os";
|
|
2594
|
+
|
|
2595
|
+
// src/core/backupStore.ts
|
|
2596
|
+
import { createHash as createHash2, randomBytes as randomBytes3 } from "node:crypto";
|
|
2597
|
+
import { existsSync as existsSync4 } from "node:fs";
|
|
2598
|
+
import { chmod as chmod2, mkdir as mkdir4, readFile as readFile5, rename as rename4, rm as rm2, stat as stat2, statfs as statfs2, writeFile as writeFile5 } from "node:fs/promises";
|
|
2599
|
+
import { request as httpRequest } from "node:http";
|
|
2600
|
+
import { userInfo as userInfo2 } from "node:os";
|
|
2601
|
+
import { isAbsolute, join as join2 } from "node:path";
|
|
2602
|
+
import { pipeline } from "node:stream";
|
|
2603
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
2604
|
+
import { request } from "undici";
|
|
2605
|
+
var GARAGE_VERSION = "2.5.0";
|
|
2606
|
+
var GARAGE_SHA256 = {
|
|
2607
|
+
x64: { arch: "x86_64", sha256: "2ff667286217cd73ebcb1c03af993822365000441dfe31a80cb64c5189a9dea8" },
|
|
2608
|
+
arm64: { arch: "aarch64", sha256: "69b6040cef428b993500c17dd0d0c1240acf2f3f667b9b05ceba4b9660db4e8c" }
|
|
2609
|
+
};
|
|
2610
|
+
var GARAGE_S3_PORT = 3900;
|
|
2611
|
+
var GARAGE_RPC_PORT = 3901;
|
|
2612
|
+
var KEY_NAME = "kvbox-control-plane";
|
|
2613
|
+
var START_WAIT_MS = 6e4;
|
|
2614
|
+
var WATCH_MS = 3e4;
|
|
2615
|
+
var garage = (p, args, timeoutMs = 2e4) => run([p.garage, "-c", p.backupStore.conf, ...args], { timeoutMs });
|
|
2616
|
+
var realDeps = {
|
|
2617
|
+
install: installGarage,
|
|
2618
|
+
start: (p) => spawnDetached([p.garage, "-c", p.backupStore.conf, "server"], p.backupStore.log),
|
|
2619
|
+
running: (p) => garageRunning(p),
|
|
2620
|
+
stop: stopGarage,
|
|
2621
|
+
api: async (p, operation, body) => {
|
|
2622
|
+
const { stdout } = await garage(p, ["json-api", operation, ...body === void 0 ? [] : [JSON.stringify(body)]]);
|
|
2623
|
+
const text = stdout.trim();
|
|
2624
|
+
return text === "" ? null : JSON.parse(text);
|
|
2625
|
+
},
|
|
2626
|
+
cli: async (p, args) => (await garage(p, args)).stdout,
|
|
2627
|
+
register: registerWithControlPlane,
|
|
2628
|
+
device: async (path) => (await stat2(path)).dev
|
|
2629
|
+
};
|
|
2630
|
+
var versionFile = (p) => `${p.garage}.version`;
|
|
2631
|
+
async function installGarage(p) {
|
|
2632
|
+
if (existsSync4(p.garage) && (await readFile5(versionFile(p), "utf8").catch(() => "")).trim() === GARAGE_VERSION) return false;
|
|
2633
|
+
const build = GARAGE_SHA256[process.arch];
|
|
2634
|
+
if (!build) throw new KvboxError(`there is no Garage build for this machine (${process.arch})`);
|
|
2635
|
+
const url = `https://garagehq.deuxfleurs.fr/_releases/v${GARAGE_VERSION}/${build.arch}-unknown-linux-musl/garage`;
|
|
2636
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(3e5) }).catch((err) => {
|
|
2637
|
+
throw new KvboxError(`could not download Garage from ${url} (${err.message})`);
|
|
2638
|
+
});
|
|
2639
|
+
if (!res.ok) throw new KvboxError(`could not download Garage from ${url}: HTTP ${res.status}`);
|
|
2640
|
+
const bytes = Buffer.from(await res.arrayBuffer());
|
|
2641
|
+
const got = createHash2("sha256").update(bytes).digest("hex");
|
|
2642
|
+
if (got !== build.sha256) throw new KvboxError(`the Garage download is not the expected file (sha256 ${got}); nothing was installed`);
|
|
2643
|
+
await mkdir4(p.bin, { recursive: true });
|
|
2644
|
+
const tmp = `${p.garage}.tmp`;
|
|
2645
|
+
await writeFile5(tmp, bytes, { mode: 493 });
|
|
2646
|
+
await chmod2(tmp, 493);
|
|
2647
|
+
await rename4(tmp, p.garage);
|
|
2648
|
+
await writeFile5(versionFile(p), `${GARAGE_VERSION}
|
|
2649
|
+
`);
|
|
2650
|
+
return true;
|
|
2651
|
+
}
|
|
2652
|
+
async function registerWithControlPlane(cfg, body) {
|
|
2653
|
+
const cp = cfg.controlPlane;
|
|
2654
|
+
if (!cp) throw new KvboxError("this host has not joined a control plane");
|
|
2655
|
+
const res = await request(`${cp.url}/hosts/self/backup-store`, {
|
|
2656
|
+
method: "PUT",
|
|
2657
|
+
headers: { authorization: `Bearer ${cp.secret}`, "content-type": "application/json" },
|
|
2658
|
+
body: JSON.stringify(body),
|
|
2659
|
+
headersTimeout: 1e4,
|
|
2660
|
+
bodyTimeout: 1e4
|
|
2661
|
+
}).catch((err) => {
|
|
2662
|
+
throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);
|
|
2663
|
+
});
|
|
2664
|
+
const text = await res.body.text();
|
|
2665
|
+
if (res.statusCode === 404) throw new KvboxError(`${cp.name} does not know backup stores yet: it is older than this host`);
|
|
2666
|
+
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
2667
|
+
let error;
|
|
2668
|
+
try {
|
|
2669
|
+
error = JSON.parse(text).error;
|
|
2670
|
+
} catch {
|
|
2671
|
+
}
|
|
2672
|
+
throw new KvboxError(typeof error === "string" ? error : `${cp.name} answered ${res.statusCode}`);
|
|
2673
|
+
}
|
|
2674
|
+
}
|
|
2675
|
+
function garageToml(path) {
|
|
2676
|
+
const q = (s) => JSON.stringify(s);
|
|
2677
|
+
return [
|
|
2678
|
+
"# written by kvbox-server backup setup: this host's backup store",
|
|
2679
|
+
`metadata_dir = ${q(join2(path, "meta"))}`,
|
|
2680
|
+
`data_dir = ${q(join2(path, "data"))}`,
|
|
2681
|
+
'db_engine = "lmdb"',
|
|
2682
|
+
"metadata_fsync = true",
|
|
2683
|
+
"data_fsync = true",
|
|
2684
|
+
"replication_factor = 1",
|
|
2685
|
+
`rpc_bind_addr = "127.0.0.1:${GARAGE_RPC_PORT}"`,
|
|
2686
|
+
`rpc_public_addr = "127.0.0.1:${GARAGE_RPC_PORT}"`,
|
|
2687
|
+
`rpc_secret_file = ${q(join2(path, "rpc_secret"))}`,
|
|
2688
|
+
"",
|
|
2689
|
+
"[s3_api]",
|
|
2690
|
+
`s3_region = ${q(BACKUP_STORE_REGION)}`,
|
|
2691
|
+
`api_bind_addr = "127.0.0.1:${GARAGE_S3_PORT}"`,
|
|
2692
|
+
""
|
|
2693
|
+
].join("\n");
|
|
2694
|
+
}
|
|
2695
|
+
async function readPid(p) {
|
|
2696
|
+
const n = Number((await readFile5(p.backupStore.pid, "utf8").catch(() => "")).trim());
|
|
2697
|
+
return Number.isInteger(n) && n > 0 ? n : null;
|
|
2698
|
+
}
|
|
2699
|
+
async function garageRunning(p = paths()) {
|
|
2700
|
+
const pid = await readPid(p);
|
|
2701
|
+
if (!pidAlive(pid)) return false;
|
|
2702
|
+
const cmdline = await readFile5(`/proc/${pid}/cmdline`, "utf8").catch(() => null);
|
|
2703
|
+
return cmdline === null || cmdline.split("\0")[0] === p.garage;
|
|
2704
|
+
}
|
|
2705
|
+
async function stopGarage(p) {
|
|
2706
|
+
const pid = await readPid(p);
|
|
2707
|
+
if (pid === null || !await garageRunning(p)) return;
|
|
2708
|
+
const cmdline = await readFile5(`/proc/${pid}/cmdline`, "utf8").catch(() => null);
|
|
2709
|
+
if (cmdline?.split("\0")[0] !== p.garage) throw new KvboxError(`cannot tell whether pid ${pid} is this host's Garage, so it was not stopped; stop Garage by hand and run this again`);
|
|
2710
|
+
process.kill(pid, "SIGTERM");
|
|
2711
|
+
const until = Date.now() + 15e3;
|
|
2712
|
+
while (pidAlive(pid)) {
|
|
2713
|
+
if (Date.now() > until) throw new KvboxError(`Garage (pid ${pid}) did not stop within 15s`);
|
|
2714
|
+
await sleep(200);
|
|
2715
|
+
}
|
|
2716
|
+
await rm2(p.backupStore.pid, { force: true });
|
|
2717
|
+
}
|
|
2718
|
+
async function ensureGarage(p, deps) {
|
|
2719
|
+
if (!await deps.running(p)) {
|
|
2720
|
+
const pid = await deps.start(p);
|
|
2721
|
+
await writeFile5(p.backupStore.pid, `${pid}
|
|
2722
|
+
`);
|
|
2723
|
+
}
|
|
2724
|
+
const until = Date.now() + START_WAIT_MS;
|
|
2725
|
+
for (; ; ) {
|
|
2726
|
+
try {
|
|
2727
|
+
await deps.cli(p, ["status"]);
|
|
2728
|
+
return;
|
|
2729
|
+
} catch (err) {
|
|
2730
|
+
if (Date.now() > until) throw new KvboxError(`Garage did not answer after ${START_WAIT_MS / 1e3}s (see ${p.backupStore.log}): ${err.message}`);
|
|
2731
|
+
await sleep(500);
|
|
2732
|
+
}
|
|
2733
|
+
}
|
|
2734
|
+
}
|
|
2735
|
+
function setupBackupStore(req, p = paths(), deps = realDeps) {
|
|
2736
|
+
return serial(() => setup(req, p, deps));
|
|
2737
|
+
}
|
|
2738
|
+
var turn = Promise.resolve();
|
|
2739
|
+
function serial(step) {
|
|
2740
|
+
const mine = turn.then(step, step);
|
|
2741
|
+
turn = mine.catch(() => void 0);
|
|
2742
|
+
return mine;
|
|
2743
|
+
}
|
|
2744
|
+
async function setup(req, p, deps) {
|
|
2745
|
+
const path = req.path.replace(/\/+$/, "") || "/";
|
|
2746
|
+
if (!isAbsolute(path) || /["\\\n\0]/.test(path)) throw new KvboxError(`${req.path} is not a path a store can use: give the full path of a directory on the backup disk`);
|
|
2747
|
+
const cfg = await loadConfig(p);
|
|
2748
|
+
if (!cfg.controlPlane) throw new KvboxError("this host has not joined a control plane, which is what takes backups; run kvbox-server join first");
|
|
2749
|
+
if (cfg.backupStore && cfg.backupStore.path !== path) {
|
|
2750
|
+
throw new KvboxError(`this host already is a backup store, with its data in ${cfg.backupStore.path}; a host has one store`);
|
|
2751
|
+
}
|
|
2752
|
+
const dir = await stat2(path).catch(() => null);
|
|
2753
|
+
if (!dir?.isDirectory()) throw new KvboxError(`${path} is not a directory: mount the backup disk and give a directory on it`);
|
|
2754
|
+
if (!req.force && await deps.device(path) === await deps.device(p.home)) {
|
|
2755
|
+
throw new KvboxError(`${path} is on the same disk as this host's boxes, so the backups would be lost with them; mount a disk for backups there, or pass --force to use it anyway`);
|
|
2756
|
+
}
|
|
2757
|
+
if (cfg.backupStore && !req.newStore && !existsSync4(join2(path, "rpc_secret"))) throw notTheStoreDisk(path);
|
|
2758
|
+
const newBinary = await deps.install(p);
|
|
2759
|
+
await mkdir4(p.backupStore.dir, { recursive: true, mode: 448 });
|
|
2760
|
+
try {
|
|
2761
|
+
for (const sub of ["meta", "data"]) await mkdir4(join2(path, sub), { recursive: true, mode: 448 });
|
|
2762
|
+
const rpcSecret = join2(path, "rpc_secret");
|
|
2763
|
+
if (!existsSync4(rpcSecret)) await writeFile5(rpcSecret, `${randomBytes3(32).toString("hex")}
|
|
2764
|
+
`, { mode: 384 });
|
|
2765
|
+
} catch (err) {
|
|
2766
|
+
const code = err.code;
|
|
2767
|
+
if (code !== "EACCES" && code !== "EPERM" && code !== "EROFS") throw err;
|
|
2768
|
+
const user = userInfo2().username;
|
|
2769
|
+
throw new KvboxError(`kvbox-server (user ${user}) cannot write in ${path}: make the directory ${user}'s (sudo chown ${user} ${path}) and run this again`);
|
|
2770
|
+
}
|
|
2771
|
+
const conf = garageToml(path);
|
|
2772
|
+
const had = await readFile5(p.backupStore.conf, "utf8").catch(() => null);
|
|
2773
|
+
await writeFile5(p.backupStore.conf, conf, { mode: 384 });
|
|
2774
|
+
if ((newBinary || had !== null && had !== conf) && await deps.running(p)) await deps.stop(p);
|
|
2775
|
+
await ensureGarage(p, deps);
|
|
2776
|
+
const layout = await deps.api(p, "GetClusterLayout");
|
|
2777
|
+
if ((layout?.version ?? 0) === 0) {
|
|
2778
|
+
const node = (await deps.cli(p, ["node", "id", "-q"])).trim().split("@")[0];
|
|
2779
|
+
const fs = await statfs2(path);
|
|
2780
|
+
await deps.cli(p, ["layout", "assign", "-z", "kvbox", "-c", String(fs.blocks * fs.bsize), node]);
|
|
2781
|
+
await deps.cli(p, ["layout", "apply", "--version", "1"]);
|
|
2782
|
+
}
|
|
2783
|
+
const bucket = await bucketInfo(p, deps).then(async (info) => info ?? await deps.api(p, "CreateBucket", { globalAlias: BACKUP_STORE_BUCKET }));
|
|
2784
|
+
let store;
|
|
2785
|
+
if (cfg.backupStore && await hasKey(p, deps, cfg.backupStore.accessKey)) {
|
|
2786
|
+
store = cfg.backupStore;
|
|
2787
|
+
} else {
|
|
2788
|
+
if (cfg.backupStore && !req.newStore) {
|
|
2789
|
+
await deps.stop(p);
|
|
2790
|
+
throw notTheStoreDisk(path);
|
|
2791
|
+
}
|
|
2792
|
+
if (cfg.backupStore) log.warn(`backup store: a new store in ${path} replaces the one with key ${cfg.backupStore.accessKey}; the backups kept on the old disk are gone`);
|
|
2793
|
+
const key = await deps.api(p, "CreateKey", { name: KEY_NAME });
|
|
2794
|
+
store = { path, bucket: BACKUP_STORE_BUCKET, region: BACKUP_STORE_REGION, accessKey: key.accessKeyId, secretKey: key.secretAccessKey, registered: false };
|
|
2795
|
+
}
|
|
2796
|
+
await deps.api(p, "AllowBucketKey", { bucketId: bucket.id, accessKeyId: store.accessKey, permissions: { read: true, write: true, owner: false } });
|
|
2797
|
+
const now = await loadConfig(p);
|
|
2798
|
+
await saveConfig({ ...now, backupStore: { ...store, registered: false } }, p);
|
|
2799
|
+
log.info(`backup store: Garage keeps its data in ${path}`);
|
|
2800
|
+
try {
|
|
2801
|
+
await deps.register(now, { bucket: store.bucket, region: store.region, accessKey: store.accessKey, secretKey: store.secretKey });
|
|
2802
|
+
} catch (err) {
|
|
2803
|
+
throw new KvboxError(`the store is set up, but the control plane did not take it: ${err.message}. Run the same command again once that is solved`);
|
|
2804
|
+
}
|
|
2805
|
+
await saveConfig({ ...await loadConfig(p), backupStore: { ...store, registered: true } }, p);
|
|
2806
|
+
log.info(`backup store: registered with ${now.controlPlane?.name ?? cfg.controlPlane.name}`);
|
|
2807
|
+
return backupStoreStatus(p, deps);
|
|
2808
|
+
}
|
|
2809
|
+
var notTheStoreDisk = (path) => new KvboxError(
|
|
2810
|
+
`${path} does not hold this host's backup store: is its disk mounted there? Mount it and run this again. If that disk is gone for good, pass --new-store to start a new store here (the backups kept on the old disk can no longer be restored)`
|
|
2811
|
+
);
|
|
2812
|
+
async function hasKey(p, deps, id) {
|
|
2813
|
+
const keys = await deps.api(p, "ListKeys");
|
|
2814
|
+
return (keys ?? []).some((k) => k.id === id);
|
|
2815
|
+
}
|
|
2816
|
+
async function bucketInfo(p, deps) {
|
|
2817
|
+
try {
|
|
2818
|
+
return await deps.api(p, "GetBucketInfo", { globalAlias: BACKUP_STORE_BUCKET });
|
|
2819
|
+
} catch (err) {
|
|
2820
|
+
if (/not found|nosuchbucket/i.test(err.message)) return null;
|
|
2821
|
+
throw err;
|
|
2822
|
+
}
|
|
2823
|
+
}
|
|
2824
|
+
async function backupStoreStatus(p = paths(), deps = realDeps) {
|
|
2825
|
+
const store = (await loadConfig(p)).backupStore;
|
|
2826
|
+
if (!store) throw new KvboxError("this host is not a backup store; make it one with: kvbox-server backup setup --path <directory on the backup disk>");
|
|
2827
|
+
const fs = await statfs2(store.path).catch(() => null);
|
|
2828
|
+
const running = await deps.running(p);
|
|
2829
|
+
const info = running ? await bucketInfo(p, deps).catch(() => null) : null;
|
|
2830
|
+
return {
|
|
2831
|
+
path: store.path,
|
|
2832
|
+
bucket: store.bucket,
|
|
2833
|
+
accessKey: store.accessKey,
|
|
2834
|
+
running: running && info !== null,
|
|
2835
|
+
totalBytes: fs ? fs.blocks * fs.bsize : 0,
|
|
2836
|
+
freeBytes: fs ? fs.bavail * fs.bsize : 0,
|
|
2837
|
+
...info ? { objects: info.objects ?? 0, storedBytes: info.bytes ?? 0 } : {},
|
|
2838
|
+
registered: store.registered
|
|
2839
|
+
};
|
|
2840
|
+
}
|
|
2841
|
+
async function backupStoreCapacity(p = paths(), deps = realDeps) {
|
|
2842
|
+
const store = (await loadConfig(p)).backupStore;
|
|
2843
|
+
if (!store) return void 0;
|
|
2844
|
+
const fs = await statfs2(store.path).catch(() => null);
|
|
2845
|
+
return { totalBytes: fs ? fs.blocks * fs.bsize : 0, freeBytes: fs ? fs.bavail * fs.bsize : 0, running: fs !== null && await deps.running(p) };
|
|
2846
|
+
}
|
|
2847
|
+
function reviveBackupStore(p = paths(), deps = realDeps) {
|
|
2848
|
+
return serial(() => revive(p, deps));
|
|
2849
|
+
}
|
|
2850
|
+
var upgraded = /* @__PURE__ */ new Set();
|
|
2851
|
+
var restartDue = /* @__PURE__ */ new Set();
|
|
2852
|
+
async function revive(p, deps) {
|
|
2853
|
+
const store = (await loadConfig(p)).backupStore;
|
|
2854
|
+
if (!store) return "none";
|
|
2855
|
+
if (!upgraded.has(p.home)) {
|
|
2856
|
+
upgraded.add(p.home);
|
|
2857
|
+
const fresh = await deps.install(p).catch((err) => {
|
|
2858
|
+
log.warn(`backup store: Garage ${GARAGE_VERSION} could not be installed, the one there keeps running (${err.message})`);
|
|
2859
|
+
return false;
|
|
2860
|
+
});
|
|
2861
|
+
if (fresh) restartDue.add(p.home);
|
|
2862
|
+
}
|
|
2863
|
+
if (restartDue.has(p.home) && existsSync4(join2(store.path, "rpc_secret"))) {
|
|
2864
|
+
if (await deps.running(p)) await deps.stop(p);
|
|
2865
|
+
const pid2 = await deps.start(p);
|
|
2866
|
+
await writeFile5(p.backupStore.pid, `${pid2}
|
|
2867
|
+
`);
|
|
2868
|
+
restartDue.delete(p.home);
|
|
2869
|
+
return "upgraded";
|
|
2870
|
+
}
|
|
2871
|
+
if (await deps.running(p)) return "running";
|
|
2872
|
+
if (!existsSync4(join2(store.path, "rpc_secret"))) return "no-disk";
|
|
2873
|
+
await rm2(p.backupStore.pid, { force: true });
|
|
2874
|
+
const pid = await deps.start(p);
|
|
2875
|
+
await writeFile5(p.backupStore.pid, `${pid}
|
|
2876
|
+
`);
|
|
2877
|
+
return "started";
|
|
2878
|
+
}
|
|
2879
|
+
var watch;
|
|
2880
|
+
function startBackupStoreWatch(p = paths()) {
|
|
2881
|
+
let warned = false;
|
|
2882
|
+
const tick = () => {
|
|
2883
|
+
reviveBackupStore(p).then((state) => {
|
|
2884
|
+
if (state === "started") log.info("backup store: Garage was not running; started it");
|
|
2885
|
+
if (state === "upgraded") log.info(`backup store: Garage ${GARAGE_VERSION} installed and started`);
|
|
2886
|
+
if (state === "no-disk" && !warned) log.warn("backup store: its disk is not mounted, so Garage is not started; backups to this host fail until it is back");
|
|
2887
|
+
warned = state === "no-disk";
|
|
2888
|
+
}).catch((err) => log.warn(`backup store: Garage did not start (${err.message})`));
|
|
2889
|
+
};
|
|
2890
|
+
tick();
|
|
2891
|
+
watch ??= setInterval(tick, WATCH_MS);
|
|
2892
|
+
watch.unref();
|
|
2893
|
+
}
|
|
2894
|
+
function isStoreRequest(url) {
|
|
2895
|
+
return url !== void 0 && (url.startsWith(`/${BACKUP_STORE_BUCKET}/`) || url.startsWith(`/${BACKUP_STORE_BUCKET}?`) || url === `/${BACKUP_STORE_BUCKET}`);
|
|
2896
|
+
}
|
|
2897
|
+
function forStore(url, p = paths()) {
|
|
2898
|
+
return isStoreRequest(url) && existsSync4(p.backupStore.conf);
|
|
2899
|
+
}
|
|
2900
|
+
function storeProxy(req, res, port = GARAGE_S3_PORT) {
|
|
2901
|
+
const up = httpRequest({ host: "127.0.0.1", port, method: req.method, path: req.url, headers: req.headers }, (answer) => {
|
|
2902
|
+
res.writeHead(answer.statusCode ?? 502, answer.headers);
|
|
2903
|
+
pipeline(answer, res, (err) => {
|
|
2904
|
+
if (err) res.destroy();
|
|
2905
|
+
});
|
|
2906
|
+
});
|
|
2907
|
+
up.on("error", () => {
|
|
2908
|
+
if (res.headersSent) return res.destroy();
|
|
2909
|
+
res.writeHead(503, { "content-type": "application/json" });
|
|
2910
|
+
res.end(JSON.stringify({ error: "this host's backup store is not running" }));
|
|
2911
|
+
});
|
|
2912
|
+
res.once("close", () => {
|
|
2913
|
+
if (!res.writableFinished) up.destroy();
|
|
2914
|
+
});
|
|
2915
|
+
req.pipe(up);
|
|
2916
|
+
}
|
|
2917
|
+
|
|
2918
|
+
// src/core/capacity.ts
|
|
2529
2919
|
function hostResources() {
|
|
2530
2920
|
return { memMib: Math.floor(totalmem() / 1024 ** 2), cores: cpus().length };
|
|
2531
2921
|
}
|
|
@@ -2551,7 +2941,10 @@ async function capacity(p = paths()) {
|
|
|
2551
2941
|
running: running.length,
|
|
2552
2942
|
disk: await diskCapacity(p),
|
|
2553
2943
|
// What a box can be made from here (#87): the control plane places `--base postgres` by it.
|
|
2554
|
-
images: await listImages(await loadConfig(p), p)
|
|
2944
|
+
images: await listImages(await loadConfig(p), p),
|
|
2945
|
+
...await backupStoreCapacity(p).then((store) => store ? { backupStore: store } : {}),
|
|
2946
|
+
// Backups and restores here reach a store by its certificate's pin (core/storeFetch.ts).
|
|
2947
|
+
storeClient: true
|
|
2555
2948
|
};
|
|
2556
2949
|
}
|
|
2557
2950
|
function gb(mib) {
|
|
@@ -2635,11 +3028,11 @@ function ext4Usage(file) {
|
|
|
2635
3028
|
}
|
|
2636
3029
|
|
|
2637
3030
|
// src/core/snapshots.ts
|
|
2638
|
-
import { existsSync as
|
|
2639
|
-
import { link, mkdir as
|
|
3031
|
+
import { existsSync as existsSync5 } from "node:fs";
|
|
3032
|
+
import { link, mkdir as mkdir5, readdir as readdir5, rename as rename5, rm as rm3, stat as stat3 } from "node:fs/promises";
|
|
2640
3033
|
|
|
2641
3034
|
// src/core/firecracker.ts
|
|
2642
|
-
import { Agent, request } from "undici";
|
|
3035
|
+
import { Agent, request as request2 } from "undici";
|
|
2643
3036
|
var FirecrackerClient = class {
|
|
2644
3037
|
constructor(socketPath) {
|
|
2645
3038
|
this.socketPath = socketPath;
|
|
@@ -2648,7 +3041,7 @@ var FirecrackerClient = class {
|
|
|
2648
3041
|
socketPath;
|
|
2649
3042
|
agent;
|
|
2650
3043
|
async call(method, path, body) {
|
|
2651
|
-
const res = await
|
|
3044
|
+
const res = await request2(`http://localhost${path}`, {
|
|
2652
3045
|
dispatcher: this.agent,
|
|
2653
3046
|
method,
|
|
2654
3047
|
headers: body === void 0 ? {} : { "content-type": "application/json" },
|
|
@@ -2781,7 +3174,7 @@ async function listSnapshots(scope, p = paths()) {
|
|
|
2781
3174
|
async function usedBytes(dir) {
|
|
2782
3175
|
let total = 0;
|
|
2783
3176
|
for (const entry of await readdir5(dir)) {
|
|
2784
|
-
total += (await
|
|
3177
|
+
total += (await stat3(`${dir}/${entry}`)).blocks * 512;
|
|
2785
3178
|
}
|
|
2786
3179
|
return total;
|
|
2787
3180
|
}
|
|
@@ -2803,17 +3196,17 @@ async function saveSnapshot(req, owner, p = paths()) {
|
|
|
2803
3196
|
async function snapshotBox(ref, req, owner, p) {
|
|
2804
3197
|
const box = await readBox(ref, p);
|
|
2805
3198
|
if (!vmAlive(box)) {
|
|
2806
|
-
if (
|
|
3199
|
+
if (existsSync5(p.machine(box.owner, box.name).hibernateVmstate)) {
|
|
2807
3200
|
throw new KvboxError(`box ${req.box} is hibernated; a snapshot freezes a running box (kvbox wake ${req.box} first)`);
|
|
2808
3201
|
}
|
|
2809
3202
|
throw new KvboxError(`box ${req.box} is not running; a snapshot freezes a running box (kvbox start ${req.box} first)`);
|
|
2810
3203
|
}
|
|
2811
3204
|
const final = p.snapshot(owner, req.name);
|
|
2812
|
-
if (
|
|
3205
|
+
if (existsSync5(final.dir) && !req.replace) throw new KvboxError(`snapshot ${req.name} already exists (--replace retakes it)`);
|
|
2813
3206
|
const s = req.replace ? p.snapshot(owner, `.${req.name}.new-${box.id}`) : final;
|
|
2814
3207
|
const cfg = await loadConfig(p);
|
|
2815
|
-
if (s !== final) await
|
|
2816
|
-
await
|
|
3208
|
+
if (s !== final) await rm3(s.dir, { recursive: true, force: true });
|
|
3209
|
+
await mkdir5(s.dir, { recursive: true, mode: 448 });
|
|
2817
3210
|
try {
|
|
2818
3211
|
const volumes = await captureDrivesOf(box, p);
|
|
2819
3212
|
await captureBox(box, s, cfg, p);
|
|
@@ -2834,7 +3227,7 @@ async function snapshotBox(ref, req, owner, p) {
|
|
|
2834
3227
|
if (s !== final) await swapIn({ owner, name: req.name }, s.dir, box.id, p);
|
|
2835
3228
|
return toSnapshot(meta);
|
|
2836
3229
|
} catch (err) {
|
|
2837
|
-
await
|
|
3230
|
+
await rm3(s.dir, { recursive: true, force: true });
|
|
2838
3231
|
throw err;
|
|
2839
3232
|
}
|
|
2840
3233
|
}
|
|
@@ -2842,17 +3235,17 @@ async function swapIn(ref, from, boxId, p) {
|
|
|
2842
3235
|
const to = p.snapshot(ref.owner, ref.name).dir;
|
|
2843
3236
|
const old = p.snapshot(ref.owner, `.${ref.name}.old-${boxId}`).dir;
|
|
2844
3237
|
await withSnapshotLock(ref, async () => {
|
|
2845
|
-
await
|
|
2846
|
-
const hadOld =
|
|
2847
|
-
if (hadOld) await
|
|
3238
|
+
await rm3(old, { recursive: true, force: true });
|
|
3239
|
+
const hadOld = existsSync5(to);
|
|
3240
|
+
if (hadOld) await rename5(to, old);
|
|
2848
3241
|
try {
|
|
2849
|
-
await
|
|
3242
|
+
await rename5(from, to);
|
|
2850
3243
|
} catch (err) {
|
|
2851
|
-
if (hadOld) await
|
|
3244
|
+
if (hadOld) await rename5(old, to);
|
|
2852
3245
|
throw err;
|
|
2853
3246
|
}
|
|
2854
3247
|
});
|
|
2855
|
-
await
|
|
3248
|
+
await rm3(old, { recursive: true, force: true });
|
|
2856
3249
|
}
|
|
2857
3250
|
async function captureBox(box, to, cfg, p) {
|
|
2858
3251
|
const m = p.machine(box.owner, box.name);
|
|
@@ -2860,7 +3253,7 @@ async function captureBox(box, to, cfg, p) {
|
|
|
2860
3253
|
let lineageTouched = false;
|
|
2861
3254
|
try {
|
|
2862
3255
|
const since = box.memSnapshots ?? 0;
|
|
2863
|
-
const mode = since === 0 ||
|
|
3256
|
+
const mode = since === 0 || existsSync5(m.memBase) ? "Diff" : "Full";
|
|
2864
3257
|
let failure2;
|
|
2865
3258
|
await fc.pause();
|
|
2866
3259
|
try {
|
|
@@ -2881,31 +3274,31 @@ async function captureBox(box, to, cfg, p) {
|
|
|
2881
3274
|
} else if (since > 0) {
|
|
2882
3275
|
await mergeOntoPrevious(m.memBase, to.mem, cfg.snapshotEditor ?? p.snapshotEditor);
|
|
2883
3276
|
}
|
|
2884
|
-
await
|
|
3277
|
+
await rm3(m.memBase, { force: true });
|
|
2885
3278
|
await link(to.mem, m.memBase);
|
|
2886
3279
|
} catch (err) {
|
|
2887
|
-
if (lineageTouched) await
|
|
3280
|
+
if (lineageTouched) await rm3(m.memBase, { force: true }).catch(() => void 0);
|
|
2888
3281
|
throw err;
|
|
2889
3282
|
} finally {
|
|
2890
3283
|
await fc.close();
|
|
2891
3284
|
}
|
|
2892
3285
|
}
|
|
2893
3286
|
async function mergeOntoPrevious(previous, diffFile, editor) {
|
|
2894
|
-
if (!
|
|
3287
|
+
if (!existsSync5(editor)) throw new KvboxError(`snapshot-editor missing at ${editor}; rerun install-server.sh`);
|
|
2895
3288
|
const merged = `${diffFile}.merged`;
|
|
2896
3289
|
await run(["cp", "--sparse=always", "--reflink=auto", previous, merged]);
|
|
2897
3290
|
await run([editor, "edit-memory", "rebase", "--memory-path", merged, "--diff-path", diffFile]);
|
|
2898
|
-
await
|
|
3291
|
+
await rename5(merged, diffFile);
|
|
2899
3292
|
}
|
|
2900
3293
|
async function deleteSnapshot(ref, p = paths()) {
|
|
2901
3294
|
const dir = p.snapshot(ref.owner, ref.name).dir;
|
|
2902
|
-
if (ref.name.startsWith(".") || !
|
|
2903
|
-
await withSnapshotLock(ref, () =>
|
|
3295
|
+
if (ref.name.startsWith(".") || !existsSync5(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);
|
|
3296
|
+
await withSnapshotLock(ref, () => rm3(dir, { recursive: true, force: true }));
|
|
2904
3297
|
}
|
|
2905
3298
|
|
|
2906
3299
|
// src/core/network.ts
|
|
2907
3300
|
import { randomInt } from "node:crypto";
|
|
2908
|
-
import { existsSync as
|
|
3301
|
+
import { existsSync as existsSync6 } from "node:fs";
|
|
2909
3302
|
import { fileURLToPath } from "node:url";
|
|
2910
3303
|
var TAP_PREFIX = "kv-";
|
|
2911
3304
|
var PRIVILEGED_SCRIPT = "/usr/local/lib/kvbox/net-setup.sh";
|
|
@@ -2915,15 +3308,15 @@ function tapName(box) {
|
|
|
2915
3308
|
function netSetupScript() {
|
|
2916
3309
|
const override = process.env["KVBOX_NET_SETUP"];
|
|
2917
3310
|
if (override) return override;
|
|
2918
|
-
if (
|
|
3311
|
+
if (existsSync6(PRIVILEGED_SCRIPT)) return PRIVILEGED_SCRIPT;
|
|
2919
3312
|
for (const rel of ["../scripts/net-setup.sh", "../../scripts/net-setup.sh"]) {
|
|
2920
3313
|
const candidate = fileURLToPath(new URL(rel, import.meta.url));
|
|
2921
|
-
if (
|
|
3314
|
+
if (existsSync6(candidate)) return candidate;
|
|
2922
3315
|
}
|
|
2923
3316
|
throw new KvboxError("net-setup.sh not found next to kvbox-server");
|
|
2924
3317
|
}
|
|
2925
3318
|
function bridgeExists(bridge) {
|
|
2926
|
-
return
|
|
3319
|
+
return existsSync6(`/sys/class/net/${bridge}`);
|
|
2927
3320
|
}
|
|
2928
3321
|
function netRun(cfg, args) {
|
|
2929
3322
|
return run([netSetupScript(), ...args], {
|
|
@@ -3106,7 +3499,7 @@ function recordState(meta, state, by, p, at = (/* @__PURE__ */ new Date()).toISO
|
|
|
3106
3499
|
}
|
|
3107
3500
|
}
|
|
3108
3501
|
function isHibernated(meta, p) {
|
|
3109
|
-
return !vmAlive(meta) &&
|
|
3502
|
+
return !vmAlive(meta) && existsSync7(p.machine(meta.owner, meta.name).hibernateVmstate);
|
|
3110
3503
|
}
|
|
3111
3504
|
function statusOf(meta, p = paths()) {
|
|
3112
3505
|
if (vmAlive(meta)) return meta.paused ? "standby" : "running";
|
|
@@ -3208,7 +3601,7 @@ function bootArgs(name, ip, cfg, pubkeyB64) {
|
|
|
3208
3601
|
return process.arch === "arm64" ? `keep_bootcon ${args}` : args;
|
|
3209
3602
|
}
|
|
3210
3603
|
async function createOverlay(file, gib) {
|
|
3211
|
-
await
|
|
3604
|
+
await writeFile6(file, "", { mode: 384 });
|
|
3212
3605
|
await truncate2(file, gib * 1024 ** 3);
|
|
3213
3606
|
await run(["mkfs.ext4", "-q", "-F", "-m", "0", "-L", "kvbox-box", "-E", "lazy_itable_init=1,lazy_journal_init=1", file]);
|
|
3214
3607
|
}
|
|
@@ -3216,21 +3609,21 @@ async function waitFor(pred, timeoutMs, stepMs = 50) {
|
|
|
3216
3609
|
const deadline = Date.now() + timeoutMs;
|
|
3217
3610
|
while (Date.now() < deadline) {
|
|
3218
3611
|
if (pred()) return true;
|
|
3219
|
-
await
|
|
3612
|
+
await sleep2(stepMs);
|
|
3220
3613
|
}
|
|
3221
3614
|
return pred();
|
|
3222
3615
|
}
|
|
3223
3616
|
async function tailOf(file, lines = 5) {
|
|
3224
3617
|
try {
|
|
3225
|
-
return (await
|
|
3618
|
+
return (await readFile6(file, "utf8")).trim().split("\n").slice(-lines).join("\n");
|
|
3226
3619
|
} catch {
|
|
3227
3620
|
return "";
|
|
3228
3621
|
}
|
|
3229
3622
|
}
|
|
3230
3623
|
async function spawnFirecracker(ref, cfg, p) {
|
|
3231
3624
|
const m = p.machine(ref.owner, ref.name);
|
|
3232
|
-
await
|
|
3233
|
-
await
|
|
3625
|
+
await rm4(m.sock, { force: true });
|
|
3626
|
+
await rm4(m.vsock, { force: true });
|
|
3234
3627
|
const logFd = openSync4(m.log, "a");
|
|
3235
3628
|
let child;
|
|
3236
3629
|
try {
|
|
@@ -3245,7 +3638,7 @@ async function spawnFirecracker(ref, cfg, p) {
|
|
|
3245
3638
|
child.unref();
|
|
3246
3639
|
const pid = child.pid;
|
|
3247
3640
|
if (pid === void 0) throw new KvboxError("could not start firecracker");
|
|
3248
|
-
if (!await waitFor(() =>
|
|
3641
|
+
if (!await waitFor(() => existsSync7(m.sock), 3e3)) {
|
|
3249
3642
|
killQuietly(pid);
|
|
3250
3643
|
throw new KvboxError(`firecracker did not open its API socket; last log lines:
|
|
3251
3644
|
${await tailOf(m.log)}`);
|
|
@@ -3311,14 +3704,14 @@ async function currentBaseVersion(p = paths()) {
|
|
|
3311
3704
|
}
|
|
3312
3705
|
async function readHostPubkey(p) {
|
|
3313
3706
|
try {
|
|
3314
|
-
return (await
|
|
3707
|
+
return (await readFile6(`${p.sshKey}.pub`, "utf8")).trim();
|
|
3315
3708
|
} catch {
|
|
3316
3709
|
throw new KvboxError(`SSH key missing at ${p.sshKey}.pub; run install-server.sh`);
|
|
3317
3710
|
}
|
|
3318
3711
|
}
|
|
3319
3712
|
function assertAssets(cfg) {
|
|
3320
3713
|
for (const [what, file] of [["kernel", cfg.kernel], ["base image", cfg.rootfs], ["firecracker", cfg.firecracker]]) {
|
|
3321
|
-
if (!
|
|
3714
|
+
if (!existsSync7(file)) throw new KvboxError(`${what} missing at ${file}; run install-server.sh`);
|
|
3322
3715
|
}
|
|
3323
3716
|
}
|
|
3324
3717
|
async function createMachine(req, owner, p = paths()) {
|
|
@@ -3326,9 +3719,9 @@ async function createMachine(req, owner, p = paths()) {
|
|
|
3326
3719
|
if (req.from !== void 0) return restoreMachine(req.from, owner, req, cfg, p);
|
|
3327
3720
|
const sizeName = req.size ?? cfg.defaultSize;
|
|
3328
3721
|
if (!isSizeName(sizeName)) throw new KvboxError(`unknown size "${sizeName}"; use one of ${Object.keys(SIZES).join(", ")}`);
|
|
3329
|
-
const
|
|
3722
|
+
const size2 = SIZES[sizeName];
|
|
3330
3723
|
assertAssets(cfg);
|
|
3331
|
-
await assertRoomFor(
|
|
3724
|
+
await assertRoomFor(size2.vcpu, size2.memMib, req.force ?? false, { owner }, "new", p);
|
|
3332
3725
|
const sshKeys = isCloudBox(owner) && req.sshKeys !== void 0 && req.sshKeys.length > 0 ? req.sshKeys : void 0;
|
|
3333
3726
|
authorizedKeysB64(await readHostPubkey(p), sshKeys ?? []);
|
|
3334
3727
|
const existing = await readAllMeta(p);
|
|
@@ -3344,10 +3737,10 @@ async function createMachine(req, owner, p = paths()) {
|
|
|
3344
3737
|
const autoHibernateSec = autoHibernateFor(req, cfg, manifest);
|
|
3345
3738
|
const vars = env.vars.map((v) => ({ ...v, secret: env.secrets.includes(v.name), updatedAt: now }));
|
|
3346
3739
|
const machine = await bootInto(
|
|
3347
|
-
{ id, name, owner, ip, mac: macFor(ip), vcpu:
|
|
3740
|
+
{ id, name, owner, ip, mac: macFor(ip), vcpu: size2.vcpu, memMib: size2.memMib, base: base.version, image, sshKeys },
|
|
3348
3741
|
// The image is shared read-only by every box; only the box's own writes land in its overlay.
|
|
3349
3742
|
async (m) => {
|
|
3350
|
-
await createOverlay(m.overlay,
|
|
3743
|
+
await createOverlay(m.overlay, size2.diskGib);
|
|
3351
3744
|
if (vars.length > 0) await writeBoxEnv({ owner, name }, vars, p);
|
|
3352
3745
|
},
|
|
3353
3746
|
{ source: "base", autoHibernateSec, idleCheck: manifest.idle, url: maskedUrl(manifest, vars) },
|
|
@@ -3361,7 +3754,7 @@ async function bootInto(box, prepare, origin, cfg, p) {
|
|
|
3361
3754
|
const keysB64 = authorizedKeysB64(await readHostPubkey(p), box.sshKeys ?? []);
|
|
3362
3755
|
const m = p.machine(owner, name);
|
|
3363
3756
|
await ensureHostNetwork(cfg);
|
|
3364
|
-
await
|
|
3757
|
+
await mkdir6(m.dir, { recursive: true, mode: 448 });
|
|
3365
3758
|
let tapCreated = false;
|
|
3366
3759
|
let pid;
|
|
3367
3760
|
let sshPort;
|
|
@@ -3384,7 +3777,7 @@ async function bootInto(box, prepare, origin, cfg, p) {
|
|
|
3384
3777
|
if (pid !== void 0) killQuietly(pid);
|
|
3385
3778
|
await closePorts({ id, ip, sshPort }, cfg);
|
|
3386
3779
|
if (tapCreated) await deleteTap(id, cfg).catch(() => void 0);
|
|
3387
|
-
await
|
|
3780
|
+
await rm4(m.dir, { recursive: true, force: true });
|
|
3388
3781
|
boxListChanged();
|
|
3389
3782
|
throw err;
|
|
3390
3783
|
} finally {
|
|
@@ -3413,7 +3806,7 @@ async function restoreFrom(from, owner, req, cfg, p) {
|
|
|
3413
3806
|
throw new KvboxError(`--size cannot be combined with --from: a restored box has the snapshot's size (${shown(from)}: ${snap.vcpu} vCPU, ${snap.memMib} MiB)`);
|
|
3414
3807
|
}
|
|
3415
3808
|
assertAssets(cfg);
|
|
3416
|
-
if (!
|
|
3809
|
+
if (!existsSync7(imageFile(snap.image, snap.base, p))) {
|
|
3417
3810
|
throw new KvboxError(`snapshot ${shown(from)} stacks on ${imageLabel(snap.image)} ${snap.base}, which is gone from ${p.assets}`);
|
|
3418
3811
|
}
|
|
3419
3812
|
const manifest = await imageManifest(imageFile(snap.image, snap.base, p));
|
|
@@ -3449,7 +3842,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
|
|
|
3449
3842
|
const { id, ip, owner, name } = box;
|
|
3450
3843
|
const m = p.machine(owner, name);
|
|
3451
3844
|
await ensureHostNetwork(cfg);
|
|
3452
|
-
await
|
|
3845
|
+
await mkdir6(m.dir, { recursive: true, mode: 448 });
|
|
3453
3846
|
let tapCreated = false;
|
|
3454
3847
|
let pid;
|
|
3455
3848
|
let sshPort;
|
|
@@ -3481,7 +3874,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
|
|
|
3481
3874
|
if (pid !== void 0) killQuietly(pid);
|
|
3482
3875
|
await closePorts({ id, ip, sshPort }, cfg);
|
|
3483
3876
|
if (tapCreated) await deleteTap(id, cfg).catch(() => void 0);
|
|
3484
|
-
await
|
|
3877
|
+
await rm4(m.dir, { recursive: true, force: true });
|
|
3485
3878
|
boxListChanged();
|
|
3486
3879
|
throw err;
|
|
3487
3880
|
} finally {
|
|
@@ -3549,7 +3942,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
|
|
|
3549
3942
|
// another slug. Such a fork is discarded rather than kept stale; a cold fork boots with the new line.
|
|
3550
3943
|
owner === src.owner ? void 0 : `box ${shown(ref)} was not forked into ${owner}: the copy would still let ${src.owner} in (stop the box and fork it cold, which boots with ${owner}'s keys)`
|
|
3551
3944
|
);
|
|
3552
|
-
await
|
|
3945
|
+
await rm4(p.machine(owner, name).forkVmstate, { force: true });
|
|
3553
3946
|
return machine;
|
|
3554
3947
|
});
|
|
3555
3948
|
var AGENT_REPLY_MS = 2e4;
|
|
@@ -3564,7 +3957,7 @@ async function introduce(spec, vsock, cfg, failure2) {
|
|
|
3564
3957
|
const msg = err.message;
|
|
3565
3958
|
const transient = /unreachable|refused|before the guest accepted/.test(msg);
|
|
3566
3959
|
if (transient && Date.now() < deadline) {
|
|
3567
|
-
await
|
|
3960
|
+
await sleep2(100);
|
|
3568
3961
|
continue;
|
|
3569
3962
|
}
|
|
3570
3963
|
if (transient) throw new KvboxError(`${msg}
|
|
@@ -3623,7 +4016,7 @@ function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs: AGENT_REPLY_MS
|
|
|
3623
4016
|
} catch (err) {
|
|
3624
4017
|
if (!pidAlive(pid)) return;
|
|
3625
4018
|
if (isNoAgent(err) && Date.now() < deadline) {
|
|
3626
|
-
await
|
|
4019
|
+
await sleep2(500);
|
|
3627
4020
|
continue;
|
|
3628
4021
|
}
|
|
3629
4022
|
warnEnv(box, vars, err);
|
|
@@ -3666,8 +4059,8 @@ async function cleanupProcess(meta, cfg, p) {
|
|
|
3666
4059
|
await closePorts(meta, cfg);
|
|
3667
4060
|
await deleteTap(meta.id, cfg);
|
|
3668
4061
|
const m = p.machine(meta.owner, meta.name);
|
|
3669
|
-
await
|
|
3670
|
-
await
|
|
4062
|
+
await rm4(m.sock, { force: true });
|
|
4063
|
+
await rm4(m.vsock, { force: true });
|
|
3671
4064
|
}
|
|
3672
4065
|
var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
|
|
3673
4066
|
const meta = await readMeta(ref, p);
|
|
@@ -3676,8 +4069,8 @@ var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
|
|
|
3676
4069
|
if (!vmAlive(meta) && !isHibernated(meta, p)) throw new KvboxError(`box ${shown(ref)} is already stopped`);
|
|
3677
4070
|
await shutdown(meta, cfg, p, 1e4);
|
|
3678
4071
|
await compactDisk(m.overlay).catch((err) => log.warn(`box ${shown(ref)}: disk not compacted: ${err.message}`));
|
|
3679
|
-
await
|
|
3680
|
-
await
|
|
4072
|
+
await rm4(m.hibernateDir, { recursive: true, force: true });
|
|
4073
|
+
await rm4(m.memBase, { force: true });
|
|
3681
4074
|
const stopped = { ...meta, pid: null, memSnapshots: void 0, paused: void 0 };
|
|
3682
4075
|
await writeMachineMeta(stopped, p);
|
|
3683
4076
|
recordState(stopped, "stopped", "stop", p);
|
|
@@ -3801,15 +4194,15 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
|
|
|
3801
4194
|
if (status === "hibernated") throw new KvboxError(`${stateMessage(ref, status)} already`);
|
|
3802
4195
|
if (status === "stopped") throw new KvboxError(`${stateMessage(ref, status)}; only a running box can be hibernated (there is no memory to keep)`);
|
|
3803
4196
|
const m = p.machine(ref.owner, ref.name);
|
|
3804
|
-
await
|
|
3805
|
-
await
|
|
4197
|
+
await rm4(m.hibernateDir, { recursive: true, force: true });
|
|
4198
|
+
await mkdir6(m.hibernateDir, { recursive: true, mode: 448 });
|
|
3806
4199
|
const fc = new FirecrackerClient(m.sock);
|
|
3807
4200
|
try {
|
|
3808
4201
|
try {
|
|
3809
4202
|
await fc.pause();
|
|
3810
4203
|
await fc.snapshotCreate(m.hibernateVmstate, m.hibernateMem, "Full");
|
|
3811
4204
|
} catch (err) {
|
|
3812
|
-
await
|
|
4205
|
+
await rm4(m.hibernateDir, { recursive: true, force: true });
|
|
3813
4206
|
if (!meta.paused) await fc.resume().catch(() => void 0);
|
|
3814
4207
|
throw err;
|
|
3815
4208
|
}
|
|
@@ -3820,7 +4213,7 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
|
|
|
3820
4213
|
await waitFor(() => !pidAlive(meta.pid), 5e3, 50);
|
|
3821
4214
|
await cleanupProcess(meta, cfg, p);
|
|
3822
4215
|
await run(["fallocate", "--dig-holes", m.hibernateMem]);
|
|
3823
|
-
await
|
|
4216
|
+
await rm4(m.memBase, { force: true });
|
|
3824
4217
|
const hibernated = { ...meta, pid: null, memSnapshots: void 0, paused: void 0 };
|
|
3825
4218
|
await writeMachineMeta(hibernated, p);
|
|
3826
4219
|
recordState(hibernated, "hibernated", by, p);
|
|
@@ -3833,7 +4226,7 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths(), force = f
|
|
|
3833
4226
|
if (status === "running" || status === "standby") throw new KvboxError(`${stateMessage(ref, status)}, not hibernated`);
|
|
3834
4227
|
if (status === "stopped") throw new KvboxError(`${stateMessage(ref, status)}, not hibernated; kvbox start ${shown(ref)} boots it`);
|
|
3835
4228
|
assertAssets(cfg);
|
|
3836
|
-
if (!
|
|
4229
|
+
if (!existsSync7(imageFile(meta.image, meta.base, p))) {
|
|
3837
4230
|
throw new KvboxError(`box ${shown(ref)} stacks on ${imageLabel(meta.image)} ${meta.base}, which is gone from ${p.assets}`);
|
|
3838
4231
|
}
|
|
3839
4232
|
await assertRoomFor(meta.vcpu, meta.memMib, force, meta, "start", p);
|
|
@@ -3859,9 +4252,9 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths(), force = f
|
|
|
3859
4252
|
await deleteTap(meta.id, cfg).catch(() => void 0);
|
|
3860
4253
|
throw err;
|
|
3861
4254
|
}
|
|
3862
|
-
await
|
|
4255
|
+
await rm4(m.memBase, { force: true });
|
|
3863
4256
|
await link2(m.hibernateMem, m.memBase);
|
|
3864
|
-
await
|
|
4257
|
+
await rm4(m.hibernateDir, { recursive: true, force: true });
|
|
3865
4258
|
const running = { ...meta, pid, bootId: currentBootId(), memSnapshots: 1, paused: void 0, sshKeysStale: stale ? true : void 0 };
|
|
3866
4259
|
await writeMachineMeta(running, p);
|
|
3867
4260
|
recordState(running, "running", "wake", p);
|
|
@@ -3871,7 +4264,7 @@ async function applyAtNextBoot(meta, changes, by, cfg, p, whileStopped) {
|
|
|
3871
4264
|
const wasRunning = vmAlive(meta);
|
|
3872
4265
|
if (wasRunning) {
|
|
3873
4266
|
await shutdown(meta, cfg, p, 1e4);
|
|
3874
|
-
await
|
|
4267
|
+
await rm4(p.machine(meta.owner, meta.name).memBase, { force: true });
|
|
3875
4268
|
}
|
|
3876
4269
|
const updated = { ...meta, ...changes, pid: null, memSnapshots: void 0, paused: void 0 };
|
|
3877
4270
|
await writeMachineMeta(updated, p);
|
|
@@ -3941,9 +4334,9 @@ var replaceDisk = locked(async function replaceDisk2(ref, file, disk, p = paths(
|
|
|
3941
4334
|
const currentGib = Math.round(statSync2(m.overlay).size / 1024 ** 3);
|
|
3942
4335
|
const restoredGib = Math.round(statSync2(file).size / 1024 ** 3);
|
|
3943
4336
|
return applyAtNextBoot(meta, { base: disk.base, image: disk.image }, "restore", cfg, p, async () => {
|
|
3944
|
-
if (disk.vars === null) await
|
|
4337
|
+
if (disk.vars === null) await rm4(m.env, { force: true });
|
|
3945
4338
|
else await writeBoxEnv(ref, disk.vars, p);
|
|
3946
|
-
await
|
|
4339
|
+
await rename6(file, m.overlay);
|
|
3947
4340
|
if (currentGib > restoredGib) await growDisk(m.overlay, currentGib);
|
|
3948
4341
|
});
|
|
3949
4342
|
});
|
|
@@ -3969,7 +4362,7 @@ var detachVolume = locked(async function detachVolume2(ref, volume, p = paths())
|
|
|
3969
4362
|
if (!meta.volumes?.includes(volume.name) || volume.owner !== meta.owner) throw new KvboxError(`volume ${shown(volume)} is not attached to box ${shown(ref)}`);
|
|
3970
4363
|
assertNotHibernated(meta, p);
|
|
3971
4364
|
const kept = meta.volumes.filter((v) => v !== volume.name);
|
|
3972
|
-
return applyAtNextBoot(meta, { volumes: kept.length > 0 ? kept : void 0 }, "detach", cfg, p, () =>
|
|
4365
|
+
return applyAtNextBoot(meta, { volumes: kept.length > 0 ? kept : void 0 }, "detach", cfg, p, () => rm4(p.machine(ref.owner, ref.name).volumeDrive(volume.name), { force: true }));
|
|
3973
4366
|
});
|
|
3974
4367
|
async function resizeVolume(volume, sizeGib, p = paths()) {
|
|
3975
4368
|
await assertCanGrow(volume, sizeGib, p);
|
|
@@ -4127,7 +4520,7 @@ var destroyBox = locked(async function destroyBox2(ref, p = paths()) {
|
|
|
4127
4520
|
throw err;
|
|
4128
4521
|
});
|
|
4129
4522
|
recordState(meta, "stopped", "rm", p);
|
|
4130
|
-
await
|
|
4523
|
+
await rm4(p.machine(ref.owner, ref.name).dir, { recursive: true, force: true });
|
|
4131
4524
|
boxListChanged();
|
|
4132
4525
|
return meta;
|
|
4133
4526
|
});
|
|
@@ -4175,7 +4568,7 @@ async function settleDeadBoxes(p = paths()) {
|
|
|
4175
4568
|
} catch (err) {
|
|
4176
4569
|
log.warn(`usage ledger: ${err.message}`);
|
|
4177
4570
|
}
|
|
4178
|
-
await
|
|
4571
|
+
await rm4(p.machine(meta.owner, meta.name).memBase, { force: true });
|
|
4179
4572
|
if (meta.paused) {
|
|
4180
4573
|
await writeMachineMeta({ ...meta, pid: null, bootId: void 0, memSnapshots: void 0, paused: void 0 }, p);
|
|
4181
4574
|
leftStopped.push(refKey(meta));
|
|
@@ -4193,7 +4586,7 @@ async function pinRunningTaps(p = paths()) {
|
|
|
4193
4586
|
const cfg = await loadConfig(p);
|
|
4194
4587
|
if (!bridgeExists(cfg.bridge)) return;
|
|
4195
4588
|
for (const meta of await readAllMeta(p)) {
|
|
4196
|
-
if (!vmAlive(meta) || !
|
|
4589
|
+
if (!vmAlive(meta) || !existsSync7(`/sys/class/net/${tapName(meta.id)}`)) continue;
|
|
4197
4590
|
await pinTap(meta, cfg).catch((err) => log.warn(`could not pin box ${meta.name}'s tap: ${err.message}`));
|
|
4198
4591
|
}
|
|
4199
4592
|
}
|
|
@@ -4232,14 +4625,14 @@ async function bootRecovered(settled, p = paths()) {
|
|
|
4232
4625
|
}
|
|
4233
4626
|
|
|
4234
4627
|
// src/core/backups.ts
|
|
4235
|
-
import { randomBytes as
|
|
4236
|
-
import { existsSync as
|
|
4237
|
-
import { mkdir as
|
|
4238
|
-
import { basename as basename2, join as
|
|
4239
|
-
import { setTimeout as
|
|
4628
|
+
import { randomBytes as randomBytes5 } from "node:crypto";
|
|
4629
|
+
import { existsSync as existsSync8 } from "node:fs";
|
|
4630
|
+
import { mkdir as mkdir7, open, readdir as readdir6, readFile as readFile7, rm as rm5, stat as stat4, statfs as statfs3, writeFile as writeFile7 } from "node:fs/promises";
|
|
4631
|
+
import { basename as basename2, join as join3 } from "node:path";
|
|
4632
|
+
import { setTimeout as sleep3 } from "node:timers/promises";
|
|
4240
4633
|
|
|
4241
4634
|
// ../shared/src/backup.ts
|
|
4242
|
-
import { createCipheriv, createDecipheriv, createHmac, randomBytes as
|
|
4635
|
+
import { createCipheriv, createDecipheriv, createHmac, randomBytes as randomBytes4 } from "node:crypto";
|
|
4243
4636
|
import { promisify as promisify2 } from "node:util";
|
|
4244
4637
|
import { deflateRaw as deflateRawCb, inflateRaw as inflateRawCb, constants as zlib } from "node:zlib";
|
|
4245
4638
|
var deflateRaw = promisify2(deflateRawCb);
|
|
@@ -4291,7 +4684,7 @@ function openText(keys, sealedB64, label) {
|
|
|
4291
4684
|
return unseal(keys.seal, Buffer.from(sealedB64, "base64"), label, label).toString("utf8");
|
|
4292
4685
|
}
|
|
4293
4686
|
function seal(key, prefix, plain, aad) {
|
|
4294
|
-
const nonce =
|
|
4687
|
+
const nonce = randomBytes4(NONCE);
|
|
4295
4688
|
const cipher = createCipheriv("aes-256-gcm", key, nonce);
|
|
4296
4689
|
cipher.setAAD(Buffer.from(aad));
|
|
4297
4690
|
const data = Buffer.concat([cipher.update(plain), cipher.final()]);
|
|
@@ -4315,12 +4708,49 @@ function chunkCount(bytes) {
|
|
|
4315
4708
|
return Math.ceil(bytes / CHUNK_SIZE);
|
|
4316
4709
|
}
|
|
4317
4710
|
|
|
4711
|
+
// src/core/storeFetch.ts
|
|
4712
|
+
import { Agent as Agent2, buildConnector, fetch as pinnedFetch } from "undici";
|
|
4713
|
+
var dispatchers = /* @__PURE__ */ new Map();
|
|
4714
|
+
function storeDispatcher(pin, local) {
|
|
4715
|
+
const id = `${pin}|${local}`;
|
|
4716
|
+
const have = dispatchers.get(id);
|
|
4717
|
+
if (have) return have;
|
|
4718
|
+
const plain = buildConnector({ rejectUnauthorized: false, maxCachedSessions: 0, timeout: 1e4 });
|
|
4719
|
+
const connect3 = (opts, cb) => {
|
|
4720
|
+
plain(local ? { ...opts, hostname: "127.0.0.1" } : opts, (err, socket) => {
|
|
4721
|
+
if (err || !socket) return cb(err ?? new Error("no socket"), null);
|
|
4722
|
+
const tls = socket;
|
|
4723
|
+
const got = typeof tls.getPeerCertificate === "function" ? tls.getPeerCertificate().fingerprint256 : void 0;
|
|
4724
|
+
if (got !== pin) {
|
|
4725
|
+
socket.destroy();
|
|
4726
|
+
return cb(new Error("the backup store's certificate is not the one the control plane knows (fingerprint mismatch)"), null);
|
|
4727
|
+
}
|
|
4728
|
+
cb(null, socket);
|
|
4729
|
+
});
|
|
4730
|
+
};
|
|
4731
|
+
const agent = new Agent2({ connect: connect3 });
|
|
4732
|
+
dispatchers.set(id, agent);
|
|
4733
|
+
return agent;
|
|
4734
|
+
}
|
|
4735
|
+
async function chunkFetcher(pin, sampleUrl, p = paths()) {
|
|
4736
|
+
if (pin === void 0) return (url, init) => fetch(url, init);
|
|
4737
|
+
const cfg = await loadConfig(p);
|
|
4738
|
+
const cp = cfg.controlPlane;
|
|
4739
|
+
let local = false;
|
|
4740
|
+
if (cfg.backupStore && cp && sampleUrl !== void 0) {
|
|
4741
|
+
const target = new URL(sampleUrl);
|
|
4742
|
+
local = target.hostname === cp.advertise && Number(target.port || 443) === cp.port;
|
|
4743
|
+
}
|
|
4744
|
+
const dispatcher = storeDispatcher(pin, local);
|
|
4745
|
+
return (url, init) => pinnedFetch(url, { ...init, dispatcher });
|
|
4746
|
+
}
|
|
4747
|
+
|
|
4318
4748
|
// src/core/backups.ts
|
|
4319
4749
|
var PARALLEL = 4;
|
|
4320
4750
|
var TRIES = 4;
|
|
4321
4751
|
var CHUNK_TIMEOUT_MS = 12e4;
|
|
4322
4752
|
async function assertRoom(dir, bytes, what, p) {
|
|
4323
|
-
const st = await
|
|
4753
|
+
const st = await statfs3(dir);
|
|
4324
4754
|
const free = st.bavail * st.bsize;
|
|
4325
4755
|
const headroom = (await loadConfig(p)).volumeHeadroomGib * 1024 ** 3;
|
|
4326
4756
|
if (free - bytes < headroom) {
|
|
@@ -4340,22 +4770,22 @@ async function readBox2(ref, p) {
|
|
|
4340
4770
|
}
|
|
4341
4771
|
}
|
|
4342
4772
|
async function chunkNames(file, keys) {
|
|
4343
|
-
const { size } = await
|
|
4773
|
+
const { size: size2 } = await stat4(file);
|
|
4344
4774
|
const chunks = [];
|
|
4345
4775
|
const fh = await open(file, "r");
|
|
4346
4776
|
try {
|
|
4347
4777
|
const buf = Buffer.alloc(CHUNK_SIZE);
|
|
4348
|
-
for (let i = 0; i < chunkCount(
|
|
4349
|
-
const slot = await readSlot(fh, buf, i,
|
|
4778
|
+
for (let i = 0; i < chunkCount(size2); i++) {
|
|
4779
|
+
const slot = await readSlot(fh, buf, i, size2);
|
|
4350
4780
|
chunks.push(isZero(slot) ? null : chunkName(keys, slot));
|
|
4351
4781
|
}
|
|
4352
4782
|
} finally {
|
|
4353
4783
|
await fh.close();
|
|
4354
4784
|
}
|
|
4355
|
-
return { sizeBytes:
|
|
4785
|
+
return { sizeBytes: size2, chunks };
|
|
4356
4786
|
}
|
|
4357
|
-
async function readSlot(fh, buf, index,
|
|
4358
|
-
const length = Math.min(CHUNK_SIZE,
|
|
4787
|
+
async function readSlot(fh, buf, index, size2) {
|
|
4788
|
+
const length = Math.min(CHUNK_SIZE, size2 - index * CHUNK_SIZE);
|
|
4359
4789
|
let got = 0;
|
|
4360
4790
|
while (got < length) {
|
|
4361
4791
|
const { bytesRead } = await fh.read(buf, got, length - got, index * CHUNK_SIZE + got);
|
|
@@ -4368,13 +4798,13 @@ async function stageBackup(ref, req, p = paths()) {
|
|
|
4368
4798
|
checkId(req.id);
|
|
4369
4799
|
const keys = backupKeys(req.key);
|
|
4370
4800
|
const s = p.backup(req.id);
|
|
4371
|
-
await
|
|
4372
|
-
await
|
|
4801
|
+
await rm5(s.dir, { recursive: true, force: true });
|
|
4802
|
+
await mkdir7(s.dir, { recursive: true, mode: 448 });
|
|
4373
4803
|
try {
|
|
4374
4804
|
const { meta, envText } = await withBoxLock(ref, async () => {
|
|
4375
4805
|
const meta2 = await readBox2(ref, p);
|
|
4376
4806
|
const m = p.machine(meta2.owner, meta2.name);
|
|
4377
|
-
await assertRoom(s.dir, (await
|
|
4807
|
+
await assertRoom(s.dir, (await stat4(m.overlay)).blocks * 512, `a backup of box ${shown(ref)}`, p);
|
|
4378
4808
|
const copy = () => run(["cp", "--sparse=always", "--reflink=auto", m.overlay, s.disk], { timeoutMs: 6e5 });
|
|
4379
4809
|
if (vmAlive(meta2) && !meta2.paused) {
|
|
4380
4810
|
const fc = new FirecrackerClient(m.sock);
|
|
@@ -4391,11 +4821,11 @@ async function stageBackup(ref, req, p = paths()) {
|
|
|
4391
4821
|
} else {
|
|
4392
4822
|
await copy();
|
|
4393
4823
|
}
|
|
4394
|
-
const envText2 =
|
|
4824
|
+
const envText2 = existsSync8(m.env) ? await readFile7(m.env, "utf8") : null;
|
|
4395
4825
|
return { meta: meta2, envText: envText2 };
|
|
4396
4826
|
});
|
|
4397
4827
|
const { sizeBytes, chunks } = await chunkNames(s.disk, keys);
|
|
4398
|
-
await
|
|
4828
|
+
await writeFile7(s.chunks, JSON.stringify({ chunks }), { mode: 384 });
|
|
4399
4829
|
return {
|
|
4400
4830
|
id: req.id,
|
|
4401
4831
|
sizeBytes,
|
|
@@ -4407,7 +4837,7 @@ async function stageBackup(ref, req, p = paths()) {
|
|
|
4407
4837
|
memMib: meta.memMib
|
|
4408
4838
|
};
|
|
4409
4839
|
} catch (err) {
|
|
4410
|
-
await
|
|
4840
|
+
await rm5(s.dir, { recursive: true, force: true });
|
|
4411
4841
|
throw err;
|
|
4412
4842
|
}
|
|
4413
4843
|
}
|
|
@@ -4441,9 +4871,9 @@ async function uploadBackup(id, req, p = paths()) {
|
|
|
4441
4871
|
}
|
|
4442
4872
|
async function uploadOnce(id, req, signal, p) {
|
|
4443
4873
|
const s = p.backup(id);
|
|
4444
|
-
if (!
|
|
4874
|
+
if (!existsSync8(s.chunks)) throw new NotFoundError(`backup ${id}`);
|
|
4445
4875
|
const keys = backupKeys(req.key);
|
|
4446
|
-
const { chunks } = JSON.parse(await
|
|
4876
|
+
const { chunks } = JSON.parse(await readFile7(s.chunks, "utf8"));
|
|
4447
4877
|
const slotOf = /* @__PURE__ */ new Map();
|
|
4448
4878
|
chunks.forEach((name, i) => {
|
|
4449
4879
|
if (name !== null && !slotOf.has(name)) slotOf.set(name, i);
|
|
@@ -4453,16 +4883,17 @@ async function uploadOnce(id, req, signal, p) {
|
|
|
4453
4883
|
if (index === void 0) throw new KvboxError(`backup ${id} has no chunk ${name.slice(0, 12)}`);
|
|
4454
4884
|
return { name, url, index };
|
|
4455
4885
|
});
|
|
4456
|
-
const { size } = await
|
|
4886
|
+
const { size: size2 } = await stat4(s.disk);
|
|
4887
|
+
const fetchChunk = await chunkFetcher(req.pin, work[0]?.url, p);
|
|
4457
4888
|
const fh = await open(s.disk, "r");
|
|
4458
4889
|
let bytes = 0;
|
|
4459
4890
|
const sizes = {};
|
|
4460
4891
|
try {
|
|
4461
4892
|
await pool(work, async ({ name, url, index }) => {
|
|
4462
|
-
const slot = Buffer.from(await readSlot(fh, Buffer.alloc(CHUNK_SIZE), index,
|
|
4893
|
+
const slot = Buffer.from(await readSlot(fh, Buffer.alloc(CHUNK_SIZE), index, size2));
|
|
4463
4894
|
const sealed = await sealChunk(keys, name, slot);
|
|
4464
4895
|
await withTries(`upload of chunk ${index}`, async () => {
|
|
4465
|
-
const res = await
|
|
4896
|
+
const res = await fetchChunk(url, { method: "PUT", body: sealed, signal: AbortSignal.any([signal, AbortSignal.timeout(CHUNK_TIMEOUT_MS)]) });
|
|
4466
4897
|
if (!res.ok) throw new Error(`storage answered ${res.status}: ${(await res.text()).slice(0, 200)}`);
|
|
4467
4898
|
}, signal);
|
|
4468
4899
|
bytes += sealed.length;
|
|
@@ -4471,36 +4902,37 @@ async function uploadOnce(id, req, signal, p) {
|
|
|
4471
4902
|
} finally {
|
|
4472
4903
|
await fh.close();
|
|
4473
4904
|
}
|
|
4474
|
-
await
|
|
4905
|
+
await rm5(s.dir, { recursive: true, force: true });
|
|
4475
4906
|
return { chunks: work.length, bytes, sizes };
|
|
4476
4907
|
}
|
|
4477
4908
|
async function dropBackup(id, p = paths()) {
|
|
4478
4909
|
checkId(id);
|
|
4479
4910
|
uploads.get(id)?.abort();
|
|
4480
|
-
await
|
|
4911
|
+
await rm5(p.backup(id).dir, { recursive: true, force: true });
|
|
4481
4912
|
}
|
|
4482
4913
|
async function clearStagedBackups(p = paths()) {
|
|
4483
|
-
await
|
|
4914
|
+
await rm5(p.backups, { recursive: true, force: true });
|
|
4484
4915
|
const prefix = basename2(p.machine("x", "x").restoring);
|
|
4485
4916
|
for (const ref of await listMachineRefs(p)) {
|
|
4486
4917
|
const dir = p.machine(ref.owner, ref.name).dir;
|
|
4487
|
-
for (const f of await readdir6(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await
|
|
4918
|
+
for (const f of await readdir6(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await rm5(join3(dir, f), { force: true });
|
|
4488
4919
|
}
|
|
4489
4920
|
}
|
|
4490
|
-
async function downloadDisk(file, req) {
|
|
4921
|
+
async function downloadDisk(file, req, p = paths()) {
|
|
4491
4922
|
const keys = backupKeys(req.key);
|
|
4492
4923
|
const slots = chunkCount(req.sizeBytes);
|
|
4493
4924
|
for (const c of req.chunks) {
|
|
4494
4925
|
if (c.index >= slots) throw new KvboxError(`chunk ${c.index} is past the end of a ${req.sizeBytes}-byte disk`);
|
|
4495
4926
|
if (!CHUNK_HASH_RE.test(c.hash)) throw new KvboxError(`chunk ${c.index}: not a chunk name`);
|
|
4496
4927
|
}
|
|
4497
|
-
await
|
|
4928
|
+
const fetchChunk = await chunkFetcher(req.pin, req.chunks[0]?.url, p);
|
|
4929
|
+
await writeFile7(file, "", { mode: 384 });
|
|
4498
4930
|
const fh = await open(file, "r+");
|
|
4499
4931
|
try {
|
|
4500
4932
|
await fh.truncate(req.sizeBytes);
|
|
4501
4933
|
await pool(req.chunks, async ({ index, hash, url }) => {
|
|
4502
4934
|
const plain = await withTries(`download of chunk ${index}`, async () => {
|
|
4503
|
-
const res = await
|
|
4935
|
+
const res = await fetchChunk(url, { signal: AbortSignal.timeout(CHUNK_TIMEOUT_MS) });
|
|
4504
4936
|
if (!res.ok) throw new Error(`storage answered ${res.status}`);
|
|
4505
4937
|
return Buffer.from(await res.arrayBuffer());
|
|
4506
4938
|
});
|
|
@@ -4530,34 +4962,34 @@ async function restoreBackup(ref, req, p = paths()) {
|
|
|
4530
4962
|
}
|
|
4531
4963
|
async function restoreOnce(ref, req, p) {
|
|
4532
4964
|
const meta = await readBox2(ref, p);
|
|
4533
|
-
if (!vmAlive(meta) &&
|
|
4965
|
+
if (!vmAlive(meta) && existsSync8(p.machine(ref.owner, ref.name).hibernateVmstate)) {
|
|
4534
4966
|
throw new KvboxError(`box ${shown(ref)} is hibernated; its memory belongs to the disk it has: kvbox wake ${shown(ref)} or kvbox stop ${shown(ref)} first`);
|
|
4535
4967
|
}
|
|
4536
|
-
if (!
|
|
4968
|
+
if (!existsSync8(imageFile(req.image, req.base, p))) {
|
|
4537
4969
|
throw new KvboxError(`this backup stacks on ${imageLabel(req.image)} ${req.base}, which this host does not have`);
|
|
4538
4970
|
}
|
|
4539
4971
|
const keys = backupKeys(req.key);
|
|
4540
4972
|
const m = p.machine(ref.owner, ref.name);
|
|
4541
|
-
const current = (await
|
|
4973
|
+
const current = (await stat4(m.overlay)).size;
|
|
4542
4974
|
if (req.sizeBytes > current) {
|
|
4543
4975
|
const gb2 = (n) => `${Math.ceil(n / 1024 ** 3)}GB`;
|
|
4544
4976
|
throw new KvboxError(`this backup's disk is ${gb2(req.sizeBytes)} and box ${shown(ref)}'s is ${gb2(current)}: kvbox vm rescale ${shown(ref)} --disk ${gb2(req.sizeBytes)} first`);
|
|
4545
4977
|
}
|
|
4546
|
-
const file = `${m.restoring}.${
|
|
4978
|
+
const file = `${m.restoring}.${randomBytes5(4).toString("hex")}`;
|
|
4547
4979
|
const envFile = `${file}.env`;
|
|
4548
4980
|
try {
|
|
4549
4981
|
let vars = null;
|
|
4550
4982
|
if (req.env !== null) {
|
|
4551
|
-
await
|
|
4983
|
+
await writeFile7(envFile, openText(keys, req.env, `env:${req.id}`), { mode: 384 });
|
|
4552
4984
|
vars = await readBoxEnvFile(envFile);
|
|
4553
4985
|
checkBoxEnv(vars);
|
|
4554
4986
|
}
|
|
4555
4987
|
await assertRoom(m.dir, req.chunks.length * CHUNK_SIZE, `a restore of box ${shown(ref)}`, p);
|
|
4556
|
-
await downloadDisk(file, req);
|
|
4988
|
+
await downloadDisk(file, req, p);
|
|
4557
4989
|
return await replaceDisk(ref, file, { base: req.base, image: req.image, vars }, p);
|
|
4558
4990
|
} finally {
|
|
4559
|
-
await
|
|
4560
|
-
await
|
|
4991
|
+
await rm5(file, { force: true });
|
|
4992
|
+
await rm5(envFile, { force: true });
|
|
4561
4993
|
}
|
|
4562
4994
|
}
|
|
4563
4995
|
async function pool(items, fn) {
|
|
@@ -4585,14 +5017,14 @@ async function withTries(what, fn, signal) {
|
|
|
4585
5017
|
} catch (err) {
|
|
4586
5018
|
if (signal?.aborted) throw new KvboxError(`${what}: the backup was dropped`);
|
|
4587
5019
|
last = err;
|
|
4588
|
-
await
|
|
5020
|
+
await sleep3(250 * 2 ** i);
|
|
4589
5021
|
}
|
|
4590
5022
|
}
|
|
4591
5023
|
throw new KvboxError(`${what} failed ${TRIES} times: ${last.message}`);
|
|
4592
5024
|
}
|
|
4593
5025
|
|
|
4594
5026
|
// src/core/relay.ts
|
|
4595
|
-
import { access as access2, chmod as
|
|
5027
|
+
import { access as access2, chmod as chmod4, mkdir as mkdir9, rm as rm6, writeFile as writeFile8 } from "node:fs/promises";
|
|
4596
5028
|
|
|
4597
5029
|
// ../shared/src/relay.ts
|
|
4598
5030
|
import { z as z7 } from "zod";
|
|
@@ -4627,9 +5059,9 @@ function decodeRelayJoin(text) {
|
|
|
4627
5059
|
|
|
4628
5060
|
// src/core/controlPlane.ts
|
|
4629
5061
|
import { X509Certificate } from "node:crypto";
|
|
4630
|
-
import { chmod as
|
|
5062
|
+
import { chmod as chmod3, mkdir as mkdir8, readFile as readFile8 } from "node:fs/promises";
|
|
4631
5063
|
import { hostname as osHostname } from "node:os";
|
|
4632
|
-
import { request as
|
|
5064
|
+
import { request as request3 } from "undici";
|
|
4633
5065
|
|
|
4634
5066
|
// ../shared/src/country.ts
|
|
4635
5067
|
var names = new Intl.DisplayNames(["en"], { type: "region", fallback: "none" });
|
|
@@ -4667,10 +5099,10 @@ function parseCountry(input) {
|
|
|
4667
5099
|
// src/core/controlPlane.ts
|
|
4668
5100
|
var DEFAULT_HTTPS_PORT = 7777;
|
|
4669
5101
|
async function ensureTlsCert(p = paths()) {
|
|
4670
|
-
const have = await
|
|
4671
|
-
const haveKey = await
|
|
5102
|
+
const have = await readFile8(p.tlsCert, "utf8").catch(() => null);
|
|
5103
|
+
const haveKey = await readFile8(p.tlsKey).then(() => true, () => false);
|
|
4672
5104
|
if (have === null || !haveKey) {
|
|
4673
|
-
await
|
|
5105
|
+
await mkdir8(p.tls, { recursive: true, mode: 448 });
|
|
4674
5106
|
try {
|
|
4675
5107
|
await run([
|
|
4676
5108
|
"openssl",
|
|
@@ -4693,9 +5125,9 @@ async function ensureTlsCert(p = paths()) {
|
|
|
4693
5125
|
} catch (err) {
|
|
4694
5126
|
throw new KvboxError(`could not make the host's certificate (is openssl installed?): ${err.message}`);
|
|
4695
5127
|
}
|
|
4696
|
-
await
|
|
5128
|
+
await chmod3(p.tlsKey, 384);
|
|
4697
5129
|
}
|
|
4698
|
-
const pem = await
|
|
5130
|
+
const pem = await readFile8(p.tlsCert, "utf8");
|
|
4699
5131
|
return { fingerprint: new X509Certificate(pem).fingerprint256 };
|
|
4700
5132
|
}
|
|
4701
5133
|
function isPrivateAddress(ip) {
|
|
@@ -4734,7 +5166,7 @@ async function joinControlPlane(opts, p = paths(), guessAddress = defaultAdverti
|
|
|
4734
5166
|
const { fingerprint } = await ensureTlsCert(p);
|
|
4735
5167
|
const hostUrl = `https://${advertise}:${port}`;
|
|
4736
5168
|
const body = { token: opts.token, name, url: hostUrl, fingerprint, publicAddress: advertise, ...country !== void 0 ? { country } : {} };
|
|
4737
|
-
const res = await
|
|
5169
|
+
const res = await request3(`${url}/hosts/join`, {
|
|
4738
5170
|
method: "POST",
|
|
4739
5171
|
headers: { "content-type": "application/json" },
|
|
4740
5172
|
body: JSON.stringify(body),
|
|
@@ -4759,7 +5191,7 @@ async function fetchCloudCa(p = paths()) {
|
|
|
4759
5191
|
const cfg = await loadConfig(p);
|
|
4760
5192
|
const cp = cfg.controlPlane;
|
|
4761
5193
|
if (!cp) throw new KvboxError("this host has not joined a control plane, so there is no CA to fetch; paste the key instead: kvbox-server trust-ca <public-key>");
|
|
4762
|
-
const res = await
|
|
5194
|
+
const res = await request3(`${cp.url}/hosts/self/ssh-ca`, {
|
|
4763
5195
|
headers: { authorization: `Bearer ${cp.secret}` },
|
|
4764
5196
|
headersTimeout: 1e4,
|
|
4765
5197
|
bodyTimeout: 1e4
|
|
@@ -4778,7 +5210,7 @@ async function leaveControlPlane(p = paths()) {
|
|
|
4778
5210
|
const cfg = await loadConfig(p);
|
|
4779
5211
|
const cp = cfg.controlPlane;
|
|
4780
5212
|
if (!cp) throw new KvboxError("this host has not joined a control plane");
|
|
4781
|
-
const told = await
|
|
5213
|
+
const told = await request3(`${cp.url}/hosts/self`, {
|
|
4782
5214
|
method: "DELETE",
|
|
4783
5215
|
headers: { authorization: `Bearer ${cp.secret}` },
|
|
4784
5216
|
headersTimeout: 3e3,
|
|
@@ -4788,7 +5220,7 @@ async function leaveControlPlane(p = paths()) {
|
|
|
4788
5220
|
return res.statusCode >= 200 && res.statusCode < 300;
|
|
4789
5221
|
}).catch(() => false);
|
|
4790
5222
|
const { controlPlane: _gone, ...rest } = cfg;
|
|
4791
|
-
await saveConfig(rest, p);
|
|
5223
|
+
await saveConfig({ ...rest, ...rest.backupStore ? { backupStore: { ...rest.backupStore, registered: false } } : {} }, p);
|
|
4792
5224
|
return { controlPlane: cp.name, told };
|
|
4793
5225
|
}
|
|
4794
5226
|
function jsonOrNull(text) {
|
|
@@ -4805,16 +5237,16 @@ function errorIn(text) {
|
|
|
4805
5237
|
}
|
|
4806
5238
|
|
|
4807
5239
|
// src/core/relay.ts
|
|
4808
|
-
function relayConf(
|
|
5240
|
+
function relayConf(join4) {
|
|
4809
5241
|
return [
|
|
4810
5242
|
"# kvbox relay tunnel: made by `kvbox-server relay`, installed by net-setup.sh. Do not edit.",
|
|
4811
5243
|
"[Interface]",
|
|
4812
|
-
`PrivateKey = ${
|
|
4813
|
-
`Address = ${
|
|
5244
|
+
`PrivateKey = ${join4.privateKey}`,
|
|
5245
|
+
`Address = ${join4.tunnelIp}/32`,
|
|
4814
5246
|
"",
|
|
4815
5247
|
"[Peer]",
|
|
4816
|
-
`PublicKey = ${
|
|
4817
|
-
`Endpoint = ${
|
|
5248
|
+
`PublicKey = ${join4.relayKey}`,
|
|
5249
|
+
`Endpoint = ${join4.relay}`,
|
|
4818
5250
|
// Only the relay's own tunnel address goes through the tunnel: the host keeps its normal internet
|
|
4819
5251
|
// route, and the relay SNATs forwarded connections so their replies come back this way.
|
|
4820
5252
|
`AllowedIPs = ${RELAY_TUNNEL_GATEWAY}/32`,
|
|
@@ -4824,22 +5256,22 @@ function relayConf(join3) {
|
|
|
4824
5256
|
].join("\n");
|
|
4825
5257
|
}
|
|
4826
5258
|
async function useRelay(joinString, p = paths()) {
|
|
4827
|
-
const
|
|
4828
|
-
if (!
|
|
5259
|
+
const join4 = decodeRelayJoin(joinString);
|
|
5260
|
+
if (!join4) throw new KvboxError("that is not a relay join string; copy the whole line `kvbox-relay add` printed on the relay");
|
|
4829
5261
|
const cfg = await loadConfig(p);
|
|
4830
|
-
if (cfg.relay && cfg.relay.name !==
|
|
5262
|
+
if (cfg.relay && cfg.relay.name !== join4.name) {
|
|
4831
5263
|
throw new KvboxError(`this host already goes through relay ${cfg.relay.name} (${cfg.relay.publicIp}); run kvbox-server relay off first`);
|
|
4832
5264
|
}
|
|
4833
|
-
if (cfg.relay && cfg.relay.publicIp !==
|
|
5265
|
+
if (cfg.relay && cfg.relay.publicIp !== join4.publicIp && cfg.controlPlane?.advertise === cfg.relay.publicIp) {
|
|
4834
5266
|
throw new KvboxError(
|
|
4835
|
-
`${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${
|
|
5267
|
+
`${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${join4.publicIp}; run kvbox-server leave first, then join again`
|
|
4836
5268
|
);
|
|
4837
5269
|
}
|
|
4838
|
-
await
|
|
4839
|
-
await
|
|
4840
|
-
await
|
|
5270
|
+
await mkdir9(p.relay, { recursive: true, mode: 448 });
|
|
5271
|
+
await writeFile8(p.relayConf, relayConf(join4), { mode: 384 });
|
|
5272
|
+
await chmod4(p.relayConf, 384);
|
|
4841
5273
|
await netSetup(cfg, ["relay", "up", p.relayConf, String(cfg.controlPlane?.port ?? DEFAULT_HTTPS_PORT)]);
|
|
4842
|
-
const relay = { name:
|
|
5274
|
+
const relay = { name: join4.name, publicIp: join4.publicIp, tunnelIp: join4.tunnelIp, endpoint: join4.relay };
|
|
4843
5275
|
await saveConfig({ ...cfg, relay }, p);
|
|
4844
5276
|
return relay;
|
|
4845
5277
|
}
|
|
@@ -4858,19 +5290,19 @@ async function dropRelay(p = paths()) {
|
|
|
4858
5290
|
throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox-server leave first`);
|
|
4859
5291
|
}
|
|
4860
5292
|
await netSetup(cfg, ["relay", "down"]);
|
|
4861
|
-
await
|
|
5293
|
+
await rm6(p.relayConf, { force: true });
|
|
4862
5294
|
const { relay: _gone, ...rest } = cfg;
|
|
4863
5295
|
await saveConfig(rest, p);
|
|
4864
5296
|
return relay;
|
|
4865
5297
|
}
|
|
4866
5298
|
|
|
4867
5299
|
// src/core/idle.ts
|
|
4868
|
-
import { readFile as
|
|
5300
|
+
import { readFile as readFile9 } from "node:fs/promises";
|
|
4869
5301
|
var HIBERNATE_CONCURRENCY = 2;
|
|
4870
5302
|
async function tapTraffic(id) {
|
|
4871
5303
|
const dir = `/sys/class/net/${tapName(id)}/statistics`;
|
|
4872
5304
|
try {
|
|
4873
|
-
const [rx, tx] = await Promise.all([
|
|
5305
|
+
const [rx, tx] = await Promise.all([readFile9(`${dir}/rx_bytes`, "utf8"), readFile9(`${dir}/tx_bytes`, "utf8")]);
|
|
4874
5306
|
return Number(rx) + Number(tx);
|
|
4875
5307
|
} catch {
|
|
4876
5308
|
return null;
|
|
@@ -5034,9 +5466,9 @@ function startRelayWatch(opts = {}) {
|
|
|
5034
5466
|
// src/daemon.ts
|
|
5035
5467
|
import { spawn as spawn3 } from "node:child_process";
|
|
5036
5468
|
import { accessSync, constants as constants2, openSync as openSync5, readFileSync as readFileSync3, statSync as statSync3 } from "node:fs";
|
|
5037
|
-
import { mkdir as
|
|
5038
|
-
import { userInfo as
|
|
5039
|
-
import { setTimeout as
|
|
5469
|
+
import { mkdir as mkdir10, readFile as readFile10, stat as stat5 } from "node:fs/promises";
|
|
5470
|
+
import { userInfo as userInfo3 } from "node:os";
|
|
5471
|
+
import { setTimeout as sleep4 } from "node:timers/promises";
|
|
5040
5472
|
|
|
5041
5473
|
// ../shared/src/systemd.ts
|
|
5042
5474
|
import { spawnSync } from "node:child_process";
|
|
@@ -5072,11 +5504,11 @@ function startsAtBoot(p) {
|
|
|
5072
5504
|
}
|
|
5073
5505
|
|
|
5074
5506
|
// src/socketClient.ts
|
|
5075
|
-
import { Agent as
|
|
5507
|
+
import { Agent as Agent3, request as request4 } from "undici";
|
|
5076
5508
|
var SocketClient = class {
|
|
5077
5509
|
agent;
|
|
5078
5510
|
constructor(socketPath) {
|
|
5079
|
-
this.agent = new
|
|
5511
|
+
this.agent = new Agent3({ connect: { socketPath } });
|
|
5080
5512
|
}
|
|
5081
5513
|
health() {
|
|
5082
5514
|
return this.call("GET", "/health", HealthSchema);
|
|
@@ -5087,15 +5519,23 @@ var SocketClient = class {
|
|
|
5087
5519
|
trustCa(req) {
|
|
5088
5520
|
return this.call("POST", "/ssh/trust-ca", TrustCaReportSchema, req);
|
|
5089
5521
|
}
|
|
5522
|
+
backupStore() {
|
|
5523
|
+
return this.call("GET", "/backup-store", BackupStoreStatusSchema);
|
|
5524
|
+
}
|
|
5525
|
+
/** Downloads Garage the first time, so it may take minutes. */
|
|
5526
|
+
setupBackupStore(req) {
|
|
5527
|
+
return this.call("POST", "/backup-store", BackupStoreStatusSchema, req, 15 * 6e4);
|
|
5528
|
+
}
|
|
5090
5529
|
async close() {
|
|
5091
5530
|
await this.agent.close();
|
|
5092
5531
|
}
|
|
5093
|
-
async call(method, path, schema, body) {
|
|
5532
|
+
async call(method, path, schema, body, timeoutMs) {
|
|
5094
5533
|
let res;
|
|
5095
5534
|
try {
|
|
5096
|
-
res = await
|
|
5535
|
+
res = await request4(`http://kvbox-server${path}`, {
|
|
5097
5536
|
method,
|
|
5098
5537
|
dispatcher: this.agent,
|
|
5538
|
+
...timeoutMs === void 0 ? {} : { headersTimeout: timeoutMs, bodyTimeout: timeoutMs },
|
|
5099
5539
|
...body === void 0 ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }
|
|
5100
5540
|
});
|
|
5101
5541
|
} catch (err) {
|
|
@@ -5126,7 +5566,7 @@ function safeJson(text) {
|
|
|
5126
5566
|
async function runningPid(p = paths()) {
|
|
5127
5567
|
let pid;
|
|
5128
5568
|
try {
|
|
5129
|
-
pid = Number.parseInt(await
|
|
5569
|
+
pid = Number.parseInt(await readFile10(p.serverPid, "utf8"), 10);
|
|
5130
5570
|
} catch {
|
|
5131
5571
|
return null;
|
|
5132
5572
|
}
|
|
@@ -5163,11 +5603,11 @@ async function stopDaemon(pid, timeoutMs = 1e4) {
|
|
|
5163
5603
|
const deadline = Date.now() + timeoutMs;
|
|
5164
5604
|
while (alive(pid)) {
|
|
5165
5605
|
if (Date.now() > deadline) throw new KvboxError(`kvbox-server (pid ${pid}) did not stop within ${timeoutMs / 1e3}s`);
|
|
5166
|
-
await
|
|
5606
|
+
await sleep4(100);
|
|
5167
5607
|
}
|
|
5168
5608
|
}
|
|
5169
5609
|
async function answering(p = paths()) {
|
|
5170
|
-
if (!await
|
|
5610
|
+
if (!await stat5(p.serverSock).then(() => true, () => false)) return null;
|
|
5171
5611
|
const probe = new SocketClient(p.serverSock);
|
|
5172
5612
|
try {
|
|
5173
5613
|
const health = await probe.health();
|
|
@@ -5179,7 +5619,7 @@ async function answering(p = paths()) {
|
|
|
5179
5619
|
}
|
|
5180
5620
|
}
|
|
5181
5621
|
async function startDetached(p = paths(), timeoutMs = 5e3) {
|
|
5182
|
-
await
|
|
5622
|
+
await mkdir10(p.home, { recursive: true });
|
|
5183
5623
|
const running = await answering(p);
|
|
5184
5624
|
if (running) return { pid: running.pid, socketPath: p.serverSock, viaGroup: void 0, viaUnit: false, alreadyRunning: running.version };
|
|
5185
5625
|
if (hasUnitFor(p)) return startUnit(p, timeoutMs);
|
|
@@ -5205,7 +5645,7 @@ async function restartDaemon(p = paths()) {
|
|
|
5205
5645
|
return startDetached(p);
|
|
5206
5646
|
}
|
|
5207
5647
|
async function startUnit(p, timeoutMs) {
|
|
5208
|
-
const logFrom = await
|
|
5648
|
+
const logFrom = await stat5(p.serverLog).then((s) => s.size, () => 0);
|
|
5209
5649
|
const res = startUnitProcess();
|
|
5210
5650
|
if (!res.ok) {
|
|
5211
5651
|
const why = res.out || await lastErrorLine(p.serverLog, logFrom) || "systemctl start failed";
|
|
@@ -5219,14 +5659,14 @@ async function startUnit(p, timeoutMs) {
|
|
|
5219
5659
|
return { pid: await pidFile(p, -1), socketPath: p.serverSock, viaGroup: void 0, viaUnit: true };
|
|
5220
5660
|
}
|
|
5221
5661
|
async function pidFile(p, fallback) {
|
|
5222
|
-
const pid = Number.parseInt(await
|
|
5662
|
+
const pid = Number.parseInt(await readFile10(p.serverPid, "utf8").catch(() => ""), 10);
|
|
5223
5663
|
return Number.isNaN(pid) ? fallback : pid;
|
|
5224
5664
|
}
|
|
5225
5665
|
async function serving(p, timeoutMs, check) {
|
|
5226
5666
|
const deadline = Date.now() + timeoutMs;
|
|
5227
5667
|
while (Date.now() < deadline) {
|
|
5228
5668
|
await check?.();
|
|
5229
|
-
if (await
|
|
5669
|
+
if (await stat5(p.serverSock).then(() => true, () => false)) {
|
|
5230
5670
|
const probe = new SocketClient(p.serverSock);
|
|
5231
5671
|
try {
|
|
5232
5672
|
await probe.health();
|
|
@@ -5236,12 +5676,12 @@ async function serving(p, timeoutMs, check) {
|
|
|
5236
5676
|
await probe.close();
|
|
5237
5677
|
}
|
|
5238
5678
|
}
|
|
5239
|
-
await
|
|
5679
|
+
await sleep4(100);
|
|
5240
5680
|
}
|
|
5241
5681
|
throw new KvboxError(`kvbox-server did not start within ${timeoutMs / 1e3}s; see ${p.serverLog}`);
|
|
5242
5682
|
}
|
|
5243
5683
|
async function lastErrorLine(logPath, from = 0) {
|
|
5244
|
-
const text = (await
|
|
5684
|
+
const text = (await readFile10(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString("utf8");
|
|
5245
5685
|
for (const line of text.trimEnd().split("\n").slice(-20).reverse()) {
|
|
5246
5686
|
const m = /^(?:\[[^\]]*\])?\[?error\]?: (.*)$/.exec(line);
|
|
5247
5687
|
if (m?.[1] !== void 0) return m[1];
|
|
@@ -5265,7 +5705,7 @@ function selfLauncher(opts = {}) {
|
|
|
5265
5705
|
} catch {
|
|
5266
5706
|
return plain;
|
|
5267
5707
|
}
|
|
5268
|
-
const group = groupWithMember(gid, opts.user ??
|
|
5708
|
+
const group = groupWithMember(gid, opts.user ?? userInfo3().username, opts.groupFile ?? "/etc/group");
|
|
5269
5709
|
if (group === void 0) return plain;
|
|
5270
5710
|
return { cmd: "sg", args: [group, "-c", argv.map(shellQuote).join(" ")], viaGroup: group };
|
|
5271
5711
|
}
|
|
@@ -5288,7 +5728,7 @@ function groupWithMember(gid, user, groupFile) {
|
|
|
5288
5728
|
}
|
|
5289
5729
|
|
|
5290
5730
|
// src/listen.ts
|
|
5291
|
-
import { readFile as
|
|
5731
|
+
import { readFile as readFile12, rm as rm7, writeFile as writeFile10 } from "node:fs/promises";
|
|
5292
5732
|
import { createServer as createHttpsServer } from "node:https";
|
|
5293
5733
|
import { createAdaptorServer } from "@hono/node-server";
|
|
5294
5734
|
|
|
@@ -5310,7 +5750,7 @@ function edgeCredential(hostSecret) {
|
|
|
5310
5750
|
}
|
|
5311
5751
|
|
|
5312
5752
|
// src/app.ts
|
|
5313
|
-
import { Hono as
|
|
5753
|
+
import { Hono as Hono11 } from "hono";
|
|
5314
5754
|
|
|
5315
5755
|
// ../shared/src/version.ts
|
|
5316
5756
|
import { createRequire } from "node:module";
|
|
@@ -5325,10 +5765,10 @@ function versionOf(srcFileUrl, injected) {
|
|
|
5325
5765
|
}
|
|
5326
5766
|
|
|
5327
5767
|
// src/version.ts
|
|
5328
|
-
var VERSION = versionOf(import.meta.url, true ? "0.5.
|
|
5768
|
+
var VERSION = versionOf(import.meta.url, true ? "0.5.51" : void 0);
|
|
5329
5769
|
|
|
5330
5770
|
// src/caller.ts
|
|
5331
|
-
import { createHash as
|
|
5771
|
+
import { createHash as createHash3, timingSafeEqual } from "node:crypto";
|
|
5332
5772
|
var OWNER_HEADER = "x-kvbox-owner";
|
|
5333
5773
|
function resolveCaller(opts = {}) {
|
|
5334
5774
|
const cp = opts.controlPlane;
|
|
@@ -5377,17 +5817,17 @@ function bearerCheck(token) {
|
|
|
5377
5817
|
};
|
|
5378
5818
|
}
|
|
5379
5819
|
function digest(secret) {
|
|
5380
|
-
return
|
|
5820
|
+
return createHash3("sha256").update(secret).digest();
|
|
5381
5821
|
}
|
|
5382
5822
|
|
|
5383
5823
|
// src/core/update.ts
|
|
5384
|
-
import { mkdir as
|
|
5824
|
+
import { mkdir as mkdir11, readFile as readFile11, writeFile as writeFile9 } from "node:fs/promises";
|
|
5385
5825
|
var INSTALL_SERVER_URL = "https://kvbox.sh/install-server.sh";
|
|
5386
5826
|
var UPDATE_STALE_MS = 60 * 6e4;
|
|
5387
5827
|
async function readUpdateState(p = paths(), now = Date.now()) {
|
|
5388
5828
|
let raw;
|
|
5389
5829
|
try {
|
|
5390
|
-
raw = JSON.parse(await
|
|
5830
|
+
raw = JSON.parse(await readFile11(p.updateState, "utf8"));
|
|
5391
5831
|
} catch {
|
|
5392
5832
|
return null;
|
|
5393
5833
|
}
|
|
@@ -5407,19 +5847,19 @@ async function startUpdate(version, p = paths(), deps = {}) {
|
|
|
5407
5847
|
if (!res.ok) throw new KvboxError(`could not download ${url}: HTTP ${res.status}`);
|
|
5408
5848
|
const script = await res.text();
|
|
5409
5849
|
if (!script.startsWith("#!") || !script.includes("--update")) throw new KvboxError(`${url} is not an install-server.sh that knows --update`);
|
|
5410
|
-
await
|
|
5411
|
-
await
|
|
5850
|
+
await mkdir11(p.updateDir, { recursive: true });
|
|
5851
|
+
await writeFile9(p.updateScript, script, { mode: 448 });
|
|
5412
5852
|
const state = { state: "running", startedAt: (/* @__PURE__ */ new Date()).toISOString(), finishedAt: null, from: version, to: null, error: null, needsManual: [] };
|
|
5413
|
-
await
|
|
5853
|
+
await writeFile9(p.updateState, `${JSON.stringify(state, null, 2)}
|
|
5414
5854
|
`);
|
|
5415
|
-
await
|
|
5855
|
+
await writeFile9(p.updateLog, `--- ${state.startedAt} update from ${version}, ${url}
|
|
5416
5856
|
`, { flag: "a" });
|
|
5417
5857
|
const env = { ...process.env, KVBOX_HOME: p.home, KVBOX_YES: "1" };
|
|
5418
5858
|
try {
|
|
5419
5859
|
await (deps.spawn ?? spawnDetached)(["bash", p.updateScript, "--update"], p.updateLog, env);
|
|
5420
5860
|
} catch (err) {
|
|
5421
5861
|
const failed = { ...state, state: "failed", finishedAt: (/* @__PURE__ */ new Date()).toISOString(), error: err.message };
|
|
5422
|
-
await
|
|
5862
|
+
await writeFile9(p.updateState, `${JSON.stringify(failed, null, 2)}
|
|
5423
5863
|
`);
|
|
5424
5864
|
throw err;
|
|
5425
5865
|
}
|
|
@@ -5457,18 +5897,35 @@ function backupRoutes() {
|
|
|
5457
5897
|
return r;
|
|
5458
5898
|
}
|
|
5459
5899
|
|
|
5900
|
+
// src/routes/backupStore.ts
|
|
5901
|
+
import { Hono as Hono2 } from "hono";
|
|
5902
|
+
function backupStoreRoutes(opts = {}) {
|
|
5903
|
+
const r = new Hono2();
|
|
5904
|
+
if (opts.controlPlane) {
|
|
5905
|
+
r.all("/*", (c) => c.json({ error: "a backup store is set up on the host itself (kvbox-server backup setup there)" }, 403));
|
|
5906
|
+
return r;
|
|
5907
|
+
}
|
|
5908
|
+
r.get("/", async (c) => c.json(await backupStoreStatus()));
|
|
5909
|
+
r.post("/", async (c) => {
|
|
5910
|
+
const body = BackupStoreSetupRequest.safeParse(await c.req.json().catch(() => ({})));
|
|
5911
|
+
if (!body.success) throw new KvboxError("backup setup: expected the directory as path");
|
|
5912
|
+
return c.json(await setupBackupStore(body.data));
|
|
5913
|
+
});
|
|
5914
|
+
return r;
|
|
5915
|
+
}
|
|
5916
|
+
|
|
5460
5917
|
// src/routes/boxHttp.ts
|
|
5461
5918
|
import { connect as connect2 } from "node:net";
|
|
5462
5919
|
import { Readable } from "node:stream";
|
|
5463
|
-
import { Hono as
|
|
5464
|
-
import { request as
|
|
5920
|
+
import { Hono as Hono3 } from "hono";
|
|
5921
|
+
import { request as request5 } from "undici";
|
|
5465
5922
|
|
|
5466
5923
|
// ../shared/src/httpHead.ts
|
|
5467
5924
|
var END = "\r\n\r\n";
|
|
5468
5925
|
var HeadTimeoutError = class extends Error {
|
|
5469
5926
|
};
|
|
5470
5927
|
function readHead(socket, opts) {
|
|
5471
|
-
return new Promise((
|
|
5928
|
+
return new Promise((resolve3, reject) => {
|
|
5472
5929
|
let bytes = Buffer.alloc(0);
|
|
5473
5930
|
const done = (err) => {
|
|
5474
5931
|
clearTimeout(timer);
|
|
@@ -5477,7 +5934,7 @@ function readHead(socket, opts) {
|
|
|
5477
5934
|
socket.pause();
|
|
5478
5935
|
if (err) return reject(err);
|
|
5479
5936
|
const end = bytes.indexOf(END);
|
|
5480
|
-
|
|
5937
|
+
resolve3({ head: bytes.subarray(0, end).toString("latin1"), rest: bytes.subarray(end + END.length) });
|
|
5481
5938
|
};
|
|
5482
5939
|
const onData = (chunk) => {
|
|
5483
5940
|
bytes = Buffer.concat([bytes, chunk]);
|
|
@@ -5586,7 +6043,7 @@ function boxHeaders(incoming, target, upgrade = false) {
|
|
|
5586
6043
|
var failure = (err, woke = false) => new Response(JSON.stringify({ error: err.message }), { status: err.status, headers: { "content-type": "application/json", [PROXY_ERROR_HEADER]: err.code, ...woke ? { [WOKE_HEADER]: "1" } : {} } });
|
|
5587
6044
|
var wants = (value) => value === "1";
|
|
5588
6045
|
function boxHttpRoutes(wake = wakeBox) {
|
|
5589
|
-
const r = new
|
|
6046
|
+
const r = new Hono3();
|
|
5590
6047
|
r.all("/:name/http/:port", (c) => forward(c, wake));
|
|
5591
6048
|
return r;
|
|
5592
6049
|
}
|
|
@@ -5603,7 +6060,7 @@ async function forward(c, wake) {
|
|
|
5603
6060
|
raw.headers.forEach((value, name) => pairs.push([name, value]));
|
|
5604
6061
|
let res;
|
|
5605
6062
|
try {
|
|
5606
|
-
res = await
|
|
6063
|
+
res = await request5(`http://${target.ip}:${target.port}${target.path}`, {
|
|
5607
6064
|
method: raw.method,
|
|
5608
6065
|
headers: boxHeaders(pairs, target).flat(),
|
|
5609
6066
|
body: raw.body === null ? null : Readable.fromWeb(raw.body),
|
|
@@ -5705,17 +6162,17 @@ ${lines.join("")}\r
|
|
|
5705
6162
|
}
|
|
5706
6163
|
|
|
5707
6164
|
// src/routes/capacity.ts
|
|
5708
|
-
import { Hono as
|
|
6165
|
+
import { Hono as Hono4 } from "hono";
|
|
5709
6166
|
function capacityRoutes() {
|
|
5710
|
-
const r = new
|
|
6167
|
+
const r = new Hono4();
|
|
5711
6168
|
r.get("/", async (c) => c.json({ ...await capacity(), version: VERSION }));
|
|
5712
6169
|
return r;
|
|
5713
6170
|
}
|
|
5714
6171
|
|
|
5715
6172
|
// src/routes/env.ts
|
|
5716
|
-
import { Hono as
|
|
6173
|
+
import { Hono as Hono5 } from "hono";
|
|
5717
6174
|
function envRoutes() {
|
|
5718
|
-
const r = new
|
|
6175
|
+
const r = new Hono5();
|
|
5719
6176
|
r.get("/", async (c) => c.json(await listEnvVersions(c.get("listScope"))));
|
|
5720
6177
|
r.post("/", async (c) => {
|
|
5721
6178
|
const body = HostEnvRequest.safeParse(await c.req.json().catch(() => ({})));
|
|
@@ -5726,7 +6183,7 @@ function envRoutes() {
|
|
|
5726
6183
|
}
|
|
5727
6184
|
|
|
5728
6185
|
// src/routes/machines.ts
|
|
5729
|
-
import { Hono as
|
|
6186
|
+
import { Hono as Hono6 } from "hono";
|
|
5730
6187
|
|
|
5731
6188
|
// src/core/stats.ts
|
|
5732
6189
|
var STATS_REPLY_MS = 3e3;
|
|
@@ -5781,7 +6238,7 @@ async function usageReport(scope, window, p = paths()) {
|
|
|
5781
6238
|
|
|
5782
6239
|
// src/routes/machines.ts
|
|
5783
6240
|
function machineRoutes() {
|
|
5784
|
-
const r = new
|
|
6241
|
+
const r = new Hono6();
|
|
5785
6242
|
r.get("/", async (c) => c.json(await listMachines(c.get("listScope"))));
|
|
5786
6243
|
r.post("/", async (c) => {
|
|
5787
6244
|
const body = CreateMachineRequest.parse(await c.req.json().catch(() => ({})));
|
|
@@ -5883,9 +6340,9 @@ function machineRoutes() {
|
|
|
5883
6340
|
}
|
|
5884
6341
|
|
|
5885
6342
|
// src/routes/snapshots.ts
|
|
5886
|
-
import { Hono as
|
|
6343
|
+
import { Hono as Hono7 } from "hono";
|
|
5887
6344
|
function snapshotRoutes() {
|
|
5888
|
-
const r = new
|
|
6345
|
+
const r = new Hono7();
|
|
5889
6346
|
r.get("/", async (c) => c.json(await listSnapshots(c.get("listScope"))));
|
|
5890
6347
|
r.post("/", async (c) => {
|
|
5891
6348
|
const body = CreateSnapshotRequest.parse(await c.req.json());
|
|
@@ -5899,9 +6356,9 @@ function snapshotRoutes() {
|
|
|
5899
6356
|
}
|
|
5900
6357
|
|
|
5901
6358
|
// src/routes/ssh.ts
|
|
5902
|
-
import { Hono as
|
|
6359
|
+
import { Hono as Hono8 } from "hono";
|
|
5903
6360
|
function sshRoutes(opts = {}) {
|
|
5904
|
-
const r = new
|
|
6361
|
+
const r = new Hono8();
|
|
5905
6362
|
if (opts.controlPlane) {
|
|
5906
6363
|
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));
|
|
5907
6364
|
return r;
|
|
@@ -5916,10 +6373,10 @@ function sshRoutes(opts = {}) {
|
|
|
5916
6373
|
}
|
|
5917
6374
|
|
|
5918
6375
|
// src/routes/usage.ts
|
|
5919
|
-
import { Hono as
|
|
6376
|
+
import { Hono as Hono9 } from "hono";
|
|
5920
6377
|
var PULL_LIMIT = 1e3;
|
|
5921
6378
|
function usageRoutes(opts = {}) {
|
|
5922
|
-
const r = new
|
|
6379
|
+
const r = new Hono9();
|
|
5923
6380
|
r.get("/", async (c) => {
|
|
5924
6381
|
let window;
|
|
5925
6382
|
try {
|
|
@@ -5952,9 +6409,9 @@ function whole(value, name) {
|
|
|
5952
6409
|
}
|
|
5953
6410
|
|
|
5954
6411
|
// src/routes/volumes.ts
|
|
5955
|
-
import { Hono as
|
|
6412
|
+
import { Hono as Hono10 } from "hono";
|
|
5956
6413
|
function volumeRoutes() {
|
|
5957
|
-
const r = new
|
|
6414
|
+
const r = new Hono10();
|
|
5958
6415
|
r.get("/", async (c) => c.json(await listVolumes(c.get("listScope"))));
|
|
5959
6416
|
r.post("/", async (c) => {
|
|
5960
6417
|
const body = CreateVolumeRequest.parse(await c.req.json().catch(() => ({})));
|
|
@@ -5984,7 +6441,7 @@ function volumeRoutes() {
|
|
|
5984
6441
|
|
|
5985
6442
|
// src/app.ts
|
|
5986
6443
|
function createApp(opts = {}) {
|
|
5987
|
-
const app = new
|
|
6444
|
+
const app = new Hono11();
|
|
5988
6445
|
app.use(resolveCaller(opts));
|
|
5989
6446
|
app.get("/health", async (c) => {
|
|
5990
6447
|
const cfg = await loadConfig();
|
|
@@ -6013,6 +6470,7 @@ function createApp(opts = {}) {
|
|
|
6013
6470
|
app.route("/capacity", capacityRoutes());
|
|
6014
6471
|
app.route("/env", envRoutes());
|
|
6015
6472
|
app.route("/ssh", sshRoutes(opts));
|
|
6473
|
+
app.route("/backup-store", backupStoreRoutes(opts));
|
|
6016
6474
|
app.route("/usage", usageRoutes(opts));
|
|
6017
6475
|
app.notFound((c) => c.json({ error: `no route: ${c.req.method} ${c.req.path}` }, 404));
|
|
6018
6476
|
app.onError((err, c) => {
|
|
@@ -6035,19 +6493,19 @@ async function listen(opts = {}) {
|
|
|
6035
6493
|
throw new KvboxError(`socket path too long for a Unix socket (${socketPath}); set KVBOX_HOME to a shorter path`);
|
|
6036
6494
|
}
|
|
6037
6495
|
if (socketPath === p.serverSock) await refuseSecondDaemon(p);
|
|
6038
|
-
await
|
|
6496
|
+
await rm7(socketPath, { force: true });
|
|
6039
6497
|
const server = createAdaptorServer({ fetch: createApp().fetch });
|
|
6040
|
-
await new Promise((
|
|
6498
|
+
await new Promise((resolve3, reject) => {
|
|
6041
6499
|
server.once("error", reject);
|
|
6042
|
-
server.listen(socketPath, () =>
|
|
6500
|
+
server.listen(socketPath, () => resolve3());
|
|
6043
6501
|
});
|
|
6044
|
-
await
|
|
6502
|
+
await writeFile10(p.serverPid, `${process.pid}
|
|
6045
6503
|
`);
|
|
6046
6504
|
let https;
|
|
6047
6505
|
let httpsServer;
|
|
6048
6506
|
const cp = cfg.controlPlane;
|
|
6049
6507
|
if (cp) {
|
|
6050
|
-
const [key, cert] = await Promise.all([
|
|
6508
|
+
const [key, cert] = await Promise.all([readFile12(p.tlsKey), readFile12(p.tlsCert)]).catch((err) => {
|
|
6051
6509
|
throw new KvboxError(`joined ${cp.name} but the host's certificate is missing (${err.message}); run kvbox-server leave, then join again`);
|
|
6052
6510
|
});
|
|
6053
6511
|
httpsServer = createAdaptorServer({
|
|
@@ -6056,18 +6514,24 @@ async function listen(opts = {}) {
|
|
|
6056
6514
|
// A body forwarded to a box may take long to arrive (a large upload through the edge, #182).
|
|
6057
6515
|
serverOptions: { key, cert, requestTimeout: REQUEST_TIMEOUT_MS }
|
|
6058
6516
|
});
|
|
6517
|
+
const appListeners = httpsServer.listeners("request");
|
|
6518
|
+
httpsServer.removeAllListeners("request");
|
|
6519
|
+
httpsServer.on("request", (req, res) => {
|
|
6520
|
+
if (forStore(req.url, p)) return storeProxy(req, res);
|
|
6521
|
+
for (const l of appListeners) l.call(httpsServer, req, res);
|
|
6522
|
+
});
|
|
6059
6523
|
const secret = secretCheck(cp);
|
|
6060
6524
|
const edge = edgeCheck(cp);
|
|
6061
6525
|
limitUntrusted(httpsServer, (req) => secret(req.headers.authorization) || edge(req.headers.authorization));
|
|
6062
6526
|
httpsServer.on("upgrade", boxUpgradeHandler({ name: cp.name, secret: cp.secret }));
|
|
6063
6527
|
const port = opts.httpsPort ?? cp.port;
|
|
6064
|
-
await new Promise((
|
|
6528
|
+
await new Promise((resolve3, reject) => {
|
|
6065
6529
|
httpsServer.once("error", reject);
|
|
6066
|
-
httpsServer.listen(port, "0.0.0.0", () =>
|
|
6530
|
+
httpsServer.listen(port, "0.0.0.0", () => resolve3());
|
|
6067
6531
|
}).catch(async (err) => {
|
|
6068
6532
|
server.close();
|
|
6069
|
-
await
|
|
6070
|
-
await
|
|
6533
|
+
await rm7(socketPath, { force: true });
|
|
6534
|
+
await rm7(p.serverPid, { force: true });
|
|
6071
6535
|
throw new KvboxError(`cannot listen on port ${port} for ${cp.name} (${err.message})`);
|
|
6072
6536
|
});
|
|
6073
6537
|
const bound = httpsServer.address().port;
|
|
@@ -6075,18 +6539,18 @@ async function listen(opts = {}) {
|
|
|
6075
6539
|
}
|
|
6076
6540
|
const close = async () => {
|
|
6077
6541
|
await Promise.all([
|
|
6078
|
-
new Promise((
|
|
6079
|
-
httpsServer ? new Promise((
|
|
6542
|
+
new Promise((resolve3) => server.close(() => resolve3())),
|
|
6543
|
+
httpsServer ? new Promise((resolve3) => httpsServer.close(() => resolve3())) : void 0
|
|
6080
6544
|
]);
|
|
6081
|
-
await
|
|
6082
|
-
await
|
|
6545
|
+
await rm7(socketPath, { force: true });
|
|
6546
|
+
await rm7(p.serverPid, { force: true });
|
|
6083
6547
|
};
|
|
6084
6548
|
const shutdown2 = async () => {
|
|
6085
6549
|
server.close();
|
|
6086
6550
|
httpsServer?.close();
|
|
6087
6551
|
await stopRecovery();
|
|
6088
|
-
await
|
|
6089
|
-
await
|
|
6552
|
+
await rm7(socketPath, { force: true });
|
|
6553
|
+
await rm7(p.serverPid, { force: true });
|
|
6090
6554
|
process.exit(0);
|
|
6091
6555
|
};
|
|
6092
6556
|
process.once("SIGINT", () => void shutdown2());
|
|
@@ -6158,6 +6622,7 @@ var startCommand = new Command("start").description("run the daemon in the foreg
|
|
|
6158
6622
|
bindDns();
|
|
6159
6623
|
startRelayWatch();
|
|
6160
6624
|
startIdleWatch();
|
|
6625
|
+
startBackupStoreWatch();
|
|
6161
6626
|
const recovery2 = await bootRecovered(settled, paths());
|
|
6162
6627
|
if (recovery2) {
|
|
6163
6628
|
for (const box of recovery2.booted) log.info(`box ${box} was running when it went down; booted it again`);
|
|
@@ -6167,11 +6632,66 @@ var startCommand = new Command("start").description("run the daemon in the foreg
|
|
|
6167
6632
|
});
|
|
6168
6633
|
|
|
6169
6634
|
// src/program.ts
|
|
6170
|
-
import { Command as
|
|
6635
|
+
import { Command as Command13 } from "commander";
|
|
6171
6636
|
|
|
6172
|
-
// src/commands/
|
|
6637
|
+
// src/commands/backup/index.ts
|
|
6638
|
+
import { Command as Command4 } from "commander";
|
|
6639
|
+
|
|
6640
|
+
// src/commands/backup/setup.ts
|
|
6641
|
+
import { resolve as resolve2 } from "node:path";
|
|
6173
6642
|
import { Command as Command2 } from "commander";
|
|
6174
|
-
|
|
6643
|
+
|
|
6644
|
+
// src/commands/backup/output.ts
|
|
6645
|
+
function size(bytes) {
|
|
6646
|
+
const gib = bytes / 1024 ** 3;
|
|
6647
|
+
return gib >= 1024 ? `${(gib / 1024).toFixed(1)} TB` : `${gib.toFixed(1)} GB`;
|
|
6648
|
+
}
|
|
6649
|
+
function printStore(s) {
|
|
6650
|
+
const rows = [
|
|
6651
|
+
["path", s.path],
|
|
6652
|
+
["storage", s.running ? "running" : "not running (the daemon starts it again within a minute; kvbox-server logs says why if it does not)"],
|
|
6653
|
+
["disk", `${size(s.totalBytes - s.freeBytes)} used of ${size(s.totalBytes)}, ${size(s.freeBytes)} free`]
|
|
6654
|
+
];
|
|
6655
|
+
if (s.storedBytes !== void 0) rows.push(["backups", `${size(s.storedBytes)} in ${s.objects ?? 0} chunks`]);
|
|
6656
|
+
rows.push(["key", s.accessKey]);
|
|
6657
|
+
rows.push(["control plane", s.registered ? "knows this store" : "does not know this store yet: run kvbox-server backup setup again with the same path"]);
|
|
6658
|
+
const width = Math.max(...rows.map(([label]) => label.length));
|
|
6659
|
+
for (const [label, value] of rows) console.log(`${label.padEnd(width)} ${value}`);
|
|
6660
|
+
}
|
|
6661
|
+
|
|
6662
|
+
// src/commands/backup/setup.ts
|
|
6663
|
+
var setupCommand = new Command2("setup").description("keep box backups on this host: run Garage with its data in a directory on the backup disk, and tell the control plane").requiredOption("--path <dir>", "a directory on the disk for backups (mounted already)").option("--force", "use the path even when it is on the same disk as this host's boxes").option("--new-store", "the store's disk is gone for good: start a new store at the path (the old backups are lost)").option("--json", "print the store as JSON").action(async (opts) => {
|
|
6664
|
+
const client = new SocketClient(paths().serverSock);
|
|
6665
|
+
try {
|
|
6666
|
+
if (!opts.json) console.log("setting up the backup store (the first time downloads Garage, which can take a minute)");
|
|
6667
|
+
const store = await client.setupBackupStore({ path: resolve2(opts.path), ...opts.force ? { force: true } : {}, ...opts.newStore ? { newStore: true } : {} });
|
|
6668
|
+
if (opts.json) return console.log(JSON.stringify(store, null, 2));
|
|
6669
|
+
console.log("this host is now a backup store; new backups can be kept here");
|
|
6670
|
+
printStore(store);
|
|
6671
|
+
} finally {
|
|
6672
|
+
await client.close();
|
|
6673
|
+
}
|
|
6674
|
+
});
|
|
6675
|
+
|
|
6676
|
+
// src/commands/backup/status.ts
|
|
6677
|
+
import { Command as Command3 } from "commander";
|
|
6678
|
+
var statusCommand = new Command3("status").description("show this host's backup store: its disk, whether it runs and what it holds").option("--json", "print as JSON").action(async (opts) => {
|
|
6679
|
+
const client = new SocketClient(paths().serverSock);
|
|
6680
|
+
try {
|
|
6681
|
+
const store = await client.backupStore();
|
|
6682
|
+
if (opts.json) console.log(JSON.stringify(store, null, 2));
|
|
6683
|
+
else printStore(store);
|
|
6684
|
+
} finally {
|
|
6685
|
+
await client.close();
|
|
6686
|
+
}
|
|
6687
|
+
});
|
|
6688
|
+
|
|
6689
|
+
// src/commands/backup/index.ts
|
|
6690
|
+
var backupCommand = new Command4("backup").description("make this host a backup store: box backups are kept on a disk of its own, in Garage").addCommand(setupCommand).addCommand(statusCommand);
|
|
6691
|
+
|
|
6692
|
+
// src/commands/join.ts
|
|
6693
|
+
import { Command as Command5 } from "commander";
|
|
6694
|
+
var joinCommand = new Command5("join").description("put this host behind a control plane (needs a one-time token minted there) and restart the daemon").argument("<control-plane-url>", "the control plane, e.g. https://api.kvbox.sh").requiredOption("--token <token>", "one-time join token from the control plane").option("--advertise <host-or-ip>", "address the control plane reaches this host at (default: this host's default-route address)").option("--name <name>", "how the control plane lists this host (default: hostname)").option("--country <country>", "where this host is, a name or a code (romania, US); kvbox new --country places boxes by it").action(async (url, opts) => {
|
|
6175
6695
|
const p = paths();
|
|
6176
6696
|
const joined = await joinControlPlane({ url, ...opts }, p);
|
|
6177
6697
|
console.log(`joined ${joined.controlPlane} as host ${joined.hostName}`);
|
|
@@ -6185,8 +6705,8 @@ var joinCommand = new Command2("join").description("put this host behind a contr
|
|
|
6185
6705
|
});
|
|
6186
6706
|
|
|
6187
6707
|
// src/commands/leave.ts
|
|
6188
|
-
import { Command as
|
|
6189
|
-
var leaveCommand = new
|
|
6708
|
+
import { Command as Command6 } from "commander";
|
|
6709
|
+
var leaveCommand = new Command6("leave").description("take this host out from behind its control plane and restart the daemon").action(async () => {
|
|
6190
6710
|
const p = paths();
|
|
6191
6711
|
const left = await leaveControlPlane(p);
|
|
6192
6712
|
console.log(`left ${left.controlPlane}`);
|
|
@@ -6200,14 +6720,14 @@ var leaveCommand = new Command3("leave").description("take this host out from be
|
|
|
6200
6720
|
});
|
|
6201
6721
|
|
|
6202
6722
|
// src/commands/logs.ts
|
|
6203
|
-
import { open as open2, readFile as
|
|
6204
|
-
import { setTimeout as
|
|
6205
|
-
import { Command as
|
|
6206
|
-
var logsCommand = new
|
|
6723
|
+
import { open as open2, readFile as readFile13, stat as stat6 } from "node:fs/promises";
|
|
6724
|
+
import { setTimeout as sleep5 } from "node:timers/promises";
|
|
6725
|
+
import { Command as Command7 } from "commander";
|
|
6726
|
+
var logsCommand = new Command7("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) => {
|
|
6207
6727
|
const n = Number.parseInt(opts.lines, 10);
|
|
6208
6728
|
if (!Number.isInteger(n) || n < 0) throw new KvboxError(`--lines: expected a number, got ${opts.lines}`);
|
|
6209
6729
|
const p = paths();
|
|
6210
|
-
const text = await
|
|
6730
|
+
const text = await readFile13(p.serverLog, "utf8").catch((err) => {
|
|
6211
6731
|
if (err.code === "ENOENT") throw new KvboxError(`no log yet at ${p.serverLog} (the daemon writes it once it has run)`);
|
|
6212
6732
|
throw err;
|
|
6213
6733
|
});
|
|
@@ -6227,14 +6747,14 @@ function tailLines(text, n) {
|
|
|
6227
6747
|
}
|
|
6228
6748
|
async function follow(path, write, opts = {}) {
|
|
6229
6749
|
const intervalMs = opts.intervalMs ?? 250;
|
|
6230
|
-
let offset = opts.from ?? await
|
|
6750
|
+
let offset = opts.from ?? await stat6(path).then((s) => s.size, () => 0);
|
|
6231
6751
|
while (!opts.signal?.aborted) {
|
|
6232
|
-
const
|
|
6233
|
-
if (
|
|
6234
|
-
if (
|
|
6752
|
+
const size2 = await stat6(path).then((s) => s.size, () => 0);
|
|
6753
|
+
if (size2 < offset) offset = 0;
|
|
6754
|
+
if (size2 > offset) {
|
|
6235
6755
|
const fh = await open2(path, "r");
|
|
6236
6756
|
try {
|
|
6237
|
-
const buf = Buffer.alloc(
|
|
6757
|
+
const buf = Buffer.alloc(size2 - offset);
|
|
6238
6758
|
const { bytesRead } = await fh.read(buf, 0, buf.length, offset);
|
|
6239
6759
|
write(buf.subarray(0, bytesRead).toString("utf8"));
|
|
6240
6760
|
offset += bytesRead;
|
|
@@ -6242,14 +6762,14 @@ async function follow(path, write, opts = {}) {
|
|
|
6242
6762
|
await fh.close();
|
|
6243
6763
|
}
|
|
6244
6764
|
}
|
|
6245
|
-
await
|
|
6765
|
+
await sleep5(intervalMs, void 0, { signal: opts.signal }).catch(() => void 0);
|
|
6246
6766
|
}
|
|
6247
6767
|
}
|
|
6248
6768
|
|
|
6249
6769
|
// src/commands/net.ts
|
|
6250
6770
|
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
6251
|
-
import { Command as
|
|
6252
|
-
var netCommand = new
|
|
6771
|
+
import { Command as Command8 } from "commander";
|
|
6772
|
+
var netCommand = new Command8("net").description("host network: up | down | status (bridge, forwarding, NAT; uses sudo)").argument("<action>", "up, down or status").action(async (action) => {
|
|
6253
6773
|
if (!["up", "down", "status"].includes(action)) throw new KvboxError("net: expected up, down or status");
|
|
6254
6774
|
const cfg = await loadConfig(paths());
|
|
6255
6775
|
const res = spawnSync2(netSetupScript(), [action], {
|
|
@@ -6260,8 +6780,8 @@ var netCommand = new Command5("net").description("host network: up | down | stat
|
|
|
6260
6780
|
});
|
|
6261
6781
|
|
|
6262
6782
|
// src/commands/relay.ts
|
|
6263
|
-
import { Command as
|
|
6264
|
-
var relayCommand = new
|
|
6783
|
+
import { Command as Command9 } from "commander";
|
|
6784
|
+
var relayCommand = new Command9("relay").description("reach the internet through a relay (paste what `kvbox-relay add` printed on the relay VM); `off` takes the tunnel down").argument("<join-string>", "the line `kvbox-relay add` printed, or `off`").action(async (joinString) => {
|
|
6265
6785
|
if (joinString === "off") {
|
|
6266
6786
|
const relay2 = await dropRelay(paths());
|
|
6267
6787
|
console.log(`tunnel to relay ${relay2.name} is down; this host no longer answers at ${relay2.publicIp}`);
|
|
@@ -6275,8 +6795,8 @@ var relayCommand = new Command6("relay").description("reach the internet through
|
|
|
6275
6795
|
// src/commands/status.ts
|
|
6276
6796
|
import { homedir as homedir2 } from "node:os";
|
|
6277
6797
|
import { styleText } from "node:util";
|
|
6278
|
-
import { Command as
|
|
6279
|
-
var
|
|
6798
|
+
import { Command as Command10 } from "commander";
|
|
6799
|
+
var statusCommand2 = new Command10("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) => {
|
|
6280
6800
|
const p = paths();
|
|
6281
6801
|
const atBoot = startsAtBoot(p);
|
|
6282
6802
|
const pid = await daemonPid(p);
|
|
@@ -6348,8 +6868,8 @@ function printStatus(health, atBoot, logPath) {
|
|
|
6348
6868
|
}
|
|
6349
6869
|
|
|
6350
6870
|
// src/commands/stop.ts
|
|
6351
|
-
import { Command as
|
|
6352
|
-
var stopCommand = new
|
|
6871
|
+
import { Command as Command11 } from "commander";
|
|
6872
|
+
var stopCommand = new Command11("stop").description("stop the daemon (running boxes are not affected)").action(async () => {
|
|
6353
6873
|
const pid = await daemonPid(paths());
|
|
6354
6874
|
if (pid === null) throw new KvboxError("kvbox-server is not running");
|
|
6355
6875
|
await stopDaemon(pid);
|
|
@@ -6357,8 +6877,8 @@ var stopCommand = new Command8("stop").description("stop the daemon (running box
|
|
|
6357
6877
|
});
|
|
6358
6878
|
|
|
6359
6879
|
// src/commands/trust-ca.ts
|
|
6360
|
-
import { Command as
|
|
6361
|
-
var trustCaCommand = new
|
|
6880
|
+
import { Command as Command12 } from "commander";
|
|
6881
|
+
var trustCaCommand = new Command12("trust-ca").description("make every cloud box on this host trust a new SSH CA (after `ca rotate` on the control plane)").argument("[public-key]", "the CA public key (or its cert-authority line); or --from-cloud").option("--from-cloud", "ask the control plane this host joined for its current CA, show the fingerprint, then ask").option("-y, --yes", "do not ask for confirmation").option("--json", "print the report as JSON").action(async (publicKey, opts) => {
|
|
6362
6882
|
if (publicKey === void 0 && !opts.fromCloud) throw new KvboxError("give the CA public key, or --from-cloud to fetch it from the control plane this host joined");
|
|
6363
6883
|
if (publicKey !== void 0 && opts.fromCloud) throw new KvboxError("either a public key or --from-cloud, not both");
|
|
6364
6884
|
const client = new SocketClient(paths().serverSock);
|
|
@@ -6414,7 +6934,7 @@ function describeReport(report2) {
|
|
|
6414
6934
|
|
|
6415
6935
|
// src/program.ts
|
|
6416
6936
|
function buildProgram() {
|
|
6417
|
-
return new
|
|
6937
|
+
return new Command13("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(statusCommand2).addCommand(logsCommand).addCommand(joinCommand).addCommand(leaveCommand).addCommand(relayCommand).addCommand(trustCaCommand).addCommand(backupCommand).addCommand(netCommand);
|
|
6418
6938
|
}
|
|
6419
6939
|
|
|
6420
6940
|
// src/index.ts
|