@kvbox/server 0.5.50 → 0.6.0
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 +772 -246
- 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. */
|
|
@@ -1150,6 +1209,11 @@ var MachineSchema = z4.object({
|
|
|
1150
1209
|
host: z4.string().optional(),
|
|
1151
1210
|
/** The country code of that host (`RO`, `US`), when its admin gave one. Only the control plane fills it in. */
|
|
1152
1211
|
country: z4.string().optional(),
|
|
1212
|
+
/**
|
|
1213
|
+
* The kind of managed service the box runs (`postgres`, `redis`, `storage`). Only an admin's
|
|
1214
|
+
* `GET /machines?all=1` lists such boxes, so a host's boxes add up; every other listing hides them.
|
|
1215
|
+
*/
|
|
1216
|
+
managed: z4.string().optional(),
|
|
1153
1217
|
/** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
|
|
1154
1218
|
autoHibernateSec: z4.number().int().positive().optional(),
|
|
1155
1219
|
/** A script inside the box that says it is idle (#102, exit 0): auto-hibernate asks it instead of watching the traffic. */
|
|
@@ -1343,7 +1407,11 @@ var CapacitySchema = z4.object({
|
|
|
1343
1407
|
*/
|
|
1344
1408
|
images: z4.array(z4.object({ name: z4.string(), version: z4.string() })).optional(),
|
|
1345
1409
|
/** 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()
|
|
1410
|
+
version: z4.string().optional(),
|
|
1411
|
+
/** Present on a host set up as a backup store: the disk its Garage keeps chunks on, and whether Garage runs. */
|
|
1412
|
+
backupStore: z4.object({ totalBytes: z4.number().int(), freeBytes: z4.number().int(), running: z4.boolean() }).optional(),
|
|
1413
|
+
/** 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. */
|
|
1414
|
+
storeClient: z4.boolean().optional()
|
|
1347
1415
|
});
|
|
1348
1416
|
var ImageSchema = z4.object({ name: z4.string(), version: z4.string().nullable() });
|
|
1349
1417
|
var ImageIndexSchema = z4.object({
|
|
@@ -1758,6 +1826,8 @@ var CloudHostSchema = z4.object({
|
|
|
1758
1826
|
capacity: CapacitySchema.nullable(),
|
|
1759
1827
|
/** ISO 3166-1 alpha-2 code (`RO`), null when nobody said where the host is. */
|
|
1760
1828
|
country: z4.string().nullable(),
|
|
1829
|
+
/** The S3 region a storage made on this host answers to (`ro-west-1`); null: it takes no storage. */
|
|
1830
|
+
region: z4.string().nullable(),
|
|
1761
1831
|
/** 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
1832
|
version: z4.string().nullable()
|
|
1763
1833
|
});
|
|
@@ -1766,7 +1836,7 @@ var HostInfoSchema = z4.object({
|
|
|
1766
1836
|
health: HealthSchema.nullable(),
|
|
1767
1837
|
error: z4.string().nullable()
|
|
1768
1838
|
});
|
|
1769
|
-
var HostPatchRequest = z4.object({ country: z4.string().nullable() });
|
|
1839
|
+
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
1840
|
var CountrySchema = z4.object({ code: z4.string(), name: z4.string() });
|
|
1771
1841
|
|
|
1772
1842
|
// ../shared/src/ssh.ts
|
|
@@ -1793,7 +1863,7 @@ var isCaLine = (line) => /^cert-authority(,|\s)/.test(line.trim());
|
|
|
1793
1863
|
import { connect } from "node:net";
|
|
1794
1864
|
var AGENT_PORT = 52;
|
|
1795
1865
|
async function agentCall(udsPath, req, timeoutMs = 5e3) {
|
|
1796
|
-
const reply = await new Promise((
|
|
1866
|
+
const reply = await new Promise((resolve3, reject) => {
|
|
1797
1867
|
const sock = connect(udsPath);
|
|
1798
1868
|
let buf = "";
|
|
1799
1869
|
let handshaken = false;
|
|
@@ -1817,7 +1887,7 @@ async function agentCall(udsPath, req, timeoutMs = 5e3) {
|
|
|
1817
1887
|
sock.write(JSON.stringify(req) + "\n");
|
|
1818
1888
|
} else {
|
|
1819
1889
|
sock.end();
|
|
1820
|
-
return
|
|
1890
|
+
return resolve3(line);
|
|
1821
1891
|
}
|
|
1822
1892
|
}
|
|
1823
1893
|
});
|
|
@@ -1903,7 +1973,7 @@ async function withLock(key, fn) {
|
|
|
1903
1973
|
if (mine?.has(key)) return fn();
|
|
1904
1974
|
const previous = tails.get(key);
|
|
1905
1975
|
let release;
|
|
1906
|
-
const tail = new Promise((
|
|
1976
|
+
const tail = new Promise((resolve3) => release = resolve3);
|
|
1907
1977
|
tails.set(key, tail);
|
|
1908
1978
|
try {
|
|
1909
1979
|
await previous;
|
|
@@ -2098,11 +2168,11 @@ function spawnDetached(argv, logFile, env = process.env) {
|
|
|
2098
2168
|
if (!cmd) throw new KvboxError("spawnDetached: empty argv");
|
|
2099
2169
|
const out = openSync2(logFile, "a");
|
|
2100
2170
|
const child = spawn(cmd, args, { detached: true, stdio: ["ignore", out, out], env });
|
|
2101
|
-
return new Promise((
|
|
2171
|
+
return new Promise((resolve3, reject) => {
|
|
2102
2172
|
child.once("error", (err) => reject(new KvboxError(`${cmd} could not start: ${err.message}`)));
|
|
2103
2173
|
child.once("spawn", () => {
|
|
2104
2174
|
child.unref();
|
|
2105
|
-
|
|
2175
|
+
resolve3(child.pid ?? -1);
|
|
2106
2176
|
});
|
|
2107
2177
|
});
|
|
2108
2178
|
}
|
|
@@ -2526,6 +2596,331 @@ async function attachedBox(ref, p) {
|
|
|
2526
2596
|
|
|
2527
2597
|
// src/core/capacity.ts
|
|
2528
2598
|
import { cpus, totalmem } from "node:os";
|
|
2599
|
+
|
|
2600
|
+
// src/core/backupStore.ts
|
|
2601
|
+
import { createHash as createHash2, randomBytes as randomBytes3 } from "node:crypto";
|
|
2602
|
+
import { existsSync as existsSync4 } from "node:fs";
|
|
2603
|
+
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";
|
|
2604
|
+
import { request as httpRequest } from "node:http";
|
|
2605
|
+
import { userInfo as userInfo2 } from "node:os";
|
|
2606
|
+
import { isAbsolute, join as join2 } from "node:path";
|
|
2607
|
+
import { pipeline } from "node:stream";
|
|
2608
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
2609
|
+
import { request } from "undici";
|
|
2610
|
+
var GARAGE_VERSION = "2.5.0";
|
|
2611
|
+
var GARAGE_SHA256 = {
|
|
2612
|
+
x64: { arch: "x86_64", sha256: "2ff667286217cd73ebcb1c03af993822365000441dfe31a80cb64c5189a9dea8" },
|
|
2613
|
+
arm64: { arch: "aarch64", sha256: "69b6040cef428b993500c17dd0d0c1240acf2f3f667b9b05ceba4b9660db4e8c" }
|
|
2614
|
+
};
|
|
2615
|
+
var GARAGE_S3_PORT = 3900;
|
|
2616
|
+
var GARAGE_RPC_PORT = 3901;
|
|
2617
|
+
var KEY_NAME = "kvbox-control-plane";
|
|
2618
|
+
var START_WAIT_MS = 6e4;
|
|
2619
|
+
var WATCH_MS = 3e4;
|
|
2620
|
+
var garage = (p, args, timeoutMs = 2e4) => run([p.garage, "-c", p.backupStore.conf, ...args], { timeoutMs });
|
|
2621
|
+
var realDeps = {
|
|
2622
|
+
install: installGarage,
|
|
2623
|
+
start: (p) => spawnDetached([p.garage, "-c", p.backupStore.conf, "server"], p.backupStore.log),
|
|
2624
|
+
running: (p) => garageRunning(p),
|
|
2625
|
+
stop: stopGarage,
|
|
2626
|
+
api: async (p, operation, body) => {
|
|
2627
|
+
const { stdout } = await garage(p, ["json-api", operation, ...body === void 0 ? [] : [JSON.stringify(body)]]);
|
|
2628
|
+
const text = stdout.trim();
|
|
2629
|
+
return text === "" ? null : JSON.parse(text);
|
|
2630
|
+
},
|
|
2631
|
+
cli: async (p, args) => (await garage(p, args)).stdout,
|
|
2632
|
+
register: registerWithControlPlane,
|
|
2633
|
+
device: async (path) => (await stat2(path)).dev
|
|
2634
|
+
};
|
|
2635
|
+
var versionFile = (p) => `${p.garage}.version`;
|
|
2636
|
+
async function installGarage(p) {
|
|
2637
|
+
if (existsSync4(p.garage) && (await readFile5(versionFile(p), "utf8").catch(() => "")).trim() === GARAGE_VERSION) return false;
|
|
2638
|
+
const build = GARAGE_SHA256[process.arch];
|
|
2639
|
+
if (!build) throw new KvboxError(`there is no Garage build for this machine (${process.arch})`);
|
|
2640
|
+
const url = `https://garagehq.deuxfleurs.fr/_releases/v${GARAGE_VERSION}/${build.arch}-unknown-linux-musl/garage`;
|
|
2641
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(3e5) }).catch((err) => {
|
|
2642
|
+
throw new KvboxError(`could not download Garage from ${url} (${err.message})`);
|
|
2643
|
+
});
|
|
2644
|
+
if (!res.ok) throw new KvboxError(`could not download Garage from ${url}: HTTP ${res.status}`);
|
|
2645
|
+
const bytes = Buffer.from(await res.arrayBuffer());
|
|
2646
|
+
const got = createHash2("sha256").update(bytes).digest("hex");
|
|
2647
|
+
if (got !== build.sha256) throw new KvboxError(`the Garage download is not the expected file (sha256 ${got}); nothing was installed`);
|
|
2648
|
+
await mkdir4(p.bin, { recursive: true });
|
|
2649
|
+
const tmp = `${p.garage}.tmp`;
|
|
2650
|
+
await writeFile5(tmp, bytes, { mode: 493 });
|
|
2651
|
+
await chmod2(tmp, 493);
|
|
2652
|
+
await rename4(tmp, p.garage);
|
|
2653
|
+
await writeFile5(versionFile(p), `${GARAGE_VERSION}
|
|
2654
|
+
`);
|
|
2655
|
+
return true;
|
|
2656
|
+
}
|
|
2657
|
+
async function registerWithControlPlane(cfg, body) {
|
|
2658
|
+
const cp = cfg.controlPlane;
|
|
2659
|
+
if (!cp) throw new KvboxError("this host has not joined a control plane");
|
|
2660
|
+
const res = await request(`${cp.url}/hosts/self/backup-store`, {
|
|
2661
|
+
method: "PUT",
|
|
2662
|
+
headers: { authorization: `Bearer ${cp.secret}`, "content-type": "application/json" },
|
|
2663
|
+
body: JSON.stringify(body),
|
|
2664
|
+
headersTimeout: 1e4,
|
|
2665
|
+
bodyTimeout: 1e4
|
|
2666
|
+
}).catch((err) => {
|
|
2667
|
+
throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);
|
|
2668
|
+
});
|
|
2669
|
+
const text = await res.body.text();
|
|
2670
|
+
if (res.statusCode === 404) throw new KvboxError(`${cp.name} does not know backup stores yet: it is older than this host`);
|
|
2671
|
+
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
2672
|
+
let error;
|
|
2673
|
+
try {
|
|
2674
|
+
error = JSON.parse(text).error;
|
|
2675
|
+
} catch {
|
|
2676
|
+
}
|
|
2677
|
+
throw new KvboxError(typeof error === "string" ? error : `${cp.name} answered ${res.statusCode}`);
|
|
2678
|
+
}
|
|
2679
|
+
}
|
|
2680
|
+
function garageToml(path) {
|
|
2681
|
+
const q = (s) => JSON.stringify(s);
|
|
2682
|
+
return [
|
|
2683
|
+
"# written by kvbox-server backup setup: this host's backup store",
|
|
2684
|
+
`metadata_dir = ${q(join2(path, "meta"))}`,
|
|
2685
|
+
`data_dir = ${q(join2(path, "data"))}`,
|
|
2686
|
+
'db_engine = "lmdb"',
|
|
2687
|
+
"metadata_fsync = true",
|
|
2688
|
+
"data_fsync = true",
|
|
2689
|
+
"replication_factor = 1",
|
|
2690
|
+
`rpc_bind_addr = "127.0.0.1:${GARAGE_RPC_PORT}"`,
|
|
2691
|
+
`rpc_public_addr = "127.0.0.1:${GARAGE_RPC_PORT}"`,
|
|
2692
|
+
`rpc_secret_file = ${q(join2(path, "rpc_secret"))}`,
|
|
2693
|
+
"",
|
|
2694
|
+
"[s3_api]",
|
|
2695
|
+
`s3_region = ${q(BACKUP_STORE_REGION)}`,
|
|
2696
|
+
`api_bind_addr = "127.0.0.1:${GARAGE_S3_PORT}"`,
|
|
2697
|
+
""
|
|
2698
|
+
].join("\n");
|
|
2699
|
+
}
|
|
2700
|
+
async function readPid(p) {
|
|
2701
|
+
const n = Number((await readFile5(p.backupStore.pid, "utf8").catch(() => "")).trim());
|
|
2702
|
+
return Number.isInteger(n) && n > 0 ? n : null;
|
|
2703
|
+
}
|
|
2704
|
+
async function garageRunning(p = paths()) {
|
|
2705
|
+
const pid = await readPid(p);
|
|
2706
|
+
if (!pidAlive(pid)) return false;
|
|
2707
|
+
const cmdline = await readFile5(`/proc/${pid}/cmdline`, "utf8").catch(() => null);
|
|
2708
|
+
return cmdline === null || cmdline.split("\0")[0] === p.garage;
|
|
2709
|
+
}
|
|
2710
|
+
async function stopGarage(p) {
|
|
2711
|
+
const pid = await readPid(p);
|
|
2712
|
+
if (pid === null || !await garageRunning(p)) return;
|
|
2713
|
+
const cmdline = await readFile5(`/proc/${pid}/cmdline`, "utf8").catch(() => null);
|
|
2714
|
+
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`);
|
|
2715
|
+
process.kill(pid, "SIGTERM");
|
|
2716
|
+
const until = Date.now() + 15e3;
|
|
2717
|
+
while (pidAlive(pid)) {
|
|
2718
|
+
if (Date.now() > until) throw new KvboxError(`Garage (pid ${pid}) did not stop within 15s`);
|
|
2719
|
+
await sleep(200);
|
|
2720
|
+
}
|
|
2721
|
+
await rm2(p.backupStore.pid, { force: true });
|
|
2722
|
+
}
|
|
2723
|
+
async function ensureGarage(p, deps) {
|
|
2724
|
+
if (!await deps.running(p)) {
|
|
2725
|
+
const pid = await deps.start(p);
|
|
2726
|
+
await writeFile5(p.backupStore.pid, `${pid}
|
|
2727
|
+
`);
|
|
2728
|
+
}
|
|
2729
|
+
const until = Date.now() + START_WAIT_MS;
|
|
2730
|
+
for (; ; ) {
|
|
2731
|
+
try {
|
|
2732
|
+
await deps.cli(p, ["status"]);
|
|
2733
|
+
return;
|
|
2734
|
+
} catch (err) {
|
|
2735
|
+
if (Date.now() > until) throw new KvboxError(`Garage did not answer after ${START_WAIT_MS / 1e3}s (see ${p.backupStore.log}): ${err.message}`);
|
|
2736
|
+
await sleep(500);
|
|
2737
|
+
}
|
|
2738
|
+
}
|
|
2739
|
+
}
|
|
2740
|
+
function setupBackupStore(req, p = paths(), deps = realDeps) {
|
|
2741
|
+
return serial(() => setup(req, p, deps));
|
|
2742
|
+
}
|
|
2743
|
+
var turn = Promise.resolve();
|
|
2744
|
+
function serial(step) {
|
|
2745
|
+
const mine = turn.then(step, step);
|
|
2746
|
+
turn = mine.catch(() => void 0);
|
|
2747
|
+
return mine;
|
|
2748
|
+
}
|
|
2749
|
+
async function setup(req, p, deps) {
|
|
2750
|
+
const path = req.path.replace(/\/+$/, "") || "/";
|
|
2751
|
+
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`);
|
|
2752
|
+
const cfg = await loadConfig(p);
|
|
2753
|
+
if (!cfg.controlPlane) throw new KvboxError("this host has not joined a control plane, which is what takes backups; run kvbox-server join first");
|
|
2754
|
+
if (cfg.backupStore && cfg.backupStore.path !== path) {
|
|
2755
|
+
throw new KvboxError(`this host already is a backup store, with its data in ${cfg.backupStore.path}; a host has one store`);
|
|
2756
|
+
}
|
|
2757
|
+
const dir = await stat2(path).catch(() => null);
|
|
2758
|
+
if (!dir?.isDirectory()) throw new KvboxError(`${path} is not a directory: mount the backup disk and give a directory on it`);
|
|
2759
|
+
if (!req.force && await deps.device(path) === await deps.device(p.home)) {
|
|
2760
|
+
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`);
|
|
2761
|
+
}
|
|
2762
|
+
if (cfg.backupStore && !req.newStore && !existsSync4(join2(path, "rpc_secret"))) throw notTheStoreDisk(path);
|
|
2763
|
+
const newBinary = await deps.install(p);
|
|
2764
|
+
await mkdir4(p.backupStore.dir, { recursive: true, mode: 448 });
|
|
2765
|
+
try {
|
|
2766
|
+
for (const sub of ["meta", "data"]) await mkdir4(join2(path, sub), { recursive: true, mode: 448 });
|
|
2767
|
+
const rpcSecret = join2(path, "rpc_secret");
|
|
2768
|
+
if (!existsSync4(rpcSecret)) await writeFile5(rpcSecret, `${randomBytes3(32).toString("hex")}
|
|
2769
|
+
`, { mode: 384 });
|
|
2770
|
+
} catch (err) {
|
|
2771
|
+
const code = err.code;
|
|
2772
|
+
if (code !== "EACCES" && code !== "EPERM" && code !== "EROFS") throw err;
|
|
2773
|
+
const user = userInfo2().username;
|
|
2774
|
+
throw new KvboxError(`kvbox-server (user ${user}) cannot write in ${path}: make the directory ${user}'s (sudo chown ${user} ${path}) and run this again`);
|
|
2775
|
+
}
|
|
2776
|
+
const conf = garageToml(path);
|
|
2777
|
+
const had = await readFile5(p.backupStore.conf, "utf8").catch(() => null);
|
|
2778
|
+
await writeFile5(p.backupStore.conf, conf, { mode: 384 });
|
|
2779
|
+
if ((newBinary || had !== null && had !== conf) && await deps.running(p)) await deps.stop(p);
|
|
2780
|
+
await ensureGarage(p, deps);
|
|
2781
|
+
const layout = await deps.api(p, "GetClusterLayout");
|
|
2782
|
+
if ((layout?.version ?? 0) === 0) {
|
|
2783
|
+
const node = (await deps.cli(p, ["node", "id", "-q"])).trim().split("@")[0];
|
|
2784
|
+
const fs = await statfs2(path);
|
|
2785
|
+
await deps.cli(p, ["layout", "assign", "-z", "kvbox", "-c", String(fs.blocks * fs.bsize), node]);
|
|
2786
|
+
await deps.cli(p, ["layout", "apply", "--version", "1"]);
|
|
2787
|
+
}
|
|
2788
|
+
const bucket = await bucketInfo(p, deps).then(async (info) => info ?? await deps.api(p, "CreateBucket", { globalAlias: BACKUP_STORE_BUCKET }));
|
|
2789
|
+
let store;
|
|
2790
|
+
if (cfg.backupStore && await hasKey(p, deps, cfg.backupStore.accessKey)) {
|
|
2791
|
+
store = cfg.backupStore;
|
|
2792
|
+
} else {
|
|
2793
|
+
if (cfg.backupStore && !req.newStore) {
|
|
2794
|
+
await deps.stop(p);
|
|
2795
|
+
throw notTheStoreDisk(path);
|
|
2796
|
+
}
|
|
2797
|
+
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`);
|
|
2798
|
+
const key = await deps.api(p, "CreateKey", { name: KEY_NAME });
|
|
2799
|
+
store = { path, bucket: BACKUP_STORE_BUCKET, region: BACKUP_STORE_REGION, accessKey: key.accessKeyId, secretKey: key.secretAccessKey, registered: false };
|
|
2800
|
+
}
|
|
2801
|
+
await deps.api(p, "AllowBucketKey", { bucketId: bucket.id, accessKeyId: store.accessKey, permissions: { read: true, write: true, owner: false } });
|
|
2802
|
+
const now = await loadConfig(p);
|
|
2803
|
+
await saveConfig({ ...now, backupStore: { ...store, registered: false } }, p);
|
|
2804
|
+
log.info(`backup store: Garage keeps its data in ${path}`);
|
|
2805
|
+
try {
|
|
2806
|
+
await deps.register(now, { bucket: store.bucket, region: store.region, accessKey: store.accessKey, secretKey: store.secretKey });
|
|
2807
|
+
} catch (err) {
|
|
2808
|
+
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`);
|
|
2809
|
+
}
|
|
2810
|
+
await saveConfig({ ...await loadConfig(p), backupStore: { ...store, registered: true } }, p);
|
|
2811
|
+
log.info(`backup store: registered with ${now.controlPlane?.name ?? cfg.controlPlane.name}`);
|
|
2812
|
+
return backupStoreStatus(p, deps);
|
|
2813
|
+
}
|
|
2814
|
+
var notTheStoreDisk = (path) => new KvboxError(
|
|
2815
|
+
`${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)`
|
|
2816
|
+
);
|
|
2817
|
+
async function hasKey(p, deps, id) {
|
|
2818
|
+
const keys = await deps.api(p, "ListKeys");
|
|
2819
|
+
return (keys ?? []).some((k) => k.id === id);
|
|
2820
|
+
}
|
|
2821
|
+
async function bucketInfo(p, deps) {
|
|
2822
|
+
try {
|
|
2823
|
+
return await deps.api(p, "GetBucketInfo", { globalAlias: BACKUP_STORE_BUCKET });
|
|
2824
|
+
} catch (err) {
|
|
2825
|
+
if (/not found|nosuchbucket/i.test(err.message)) return null;
|
|
2826
|
+
throw err;
|
|
2827
|
+
}
|
|
2828
|
+
}
|
|
2829
|
+
async function backupStoreStatus(p = paths(), deps = realDeps) {
|
|
2830
|
+
const store = (await loadConfig(p)).backupStore;
|
|
2831
|
+
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>");
|
|
2832
|
+
const fs = await statfs2(store.path).catch(() => null);
|
|
2833
|
+
const running = await deps.running(p);
|
|
2834
|
+
const info = running ? await bucketInfo(p, deps).catch(() => null) : null;
|
|
2835
|
+
return {
|
|
2836
|
+
path: store.path,
|
|
2837
|
+
bucket: store.bucket,
|
|
2838
|
+
accessKey: store.accessKey,
|
|
2839
|
+
running: running && info !== null,
|
|
2840
|
+
totalBytes: fs ? fs.blocks * fs.bsize : 0,
|
|
2841
|
+
freeBytes: fs ? fs.bavail * fs.bsize : 0,
|
|
2842
|
+
...info ? { objects: info.objects ?? 0, storedBytes: info.bytes ?? 0 } : {},
|
|
2843
|
+
registered: store.registered
|
|
2844
|
+
};
|
|
2845
|
+
}
|
|
2846
|
+
async function backupStoreCapacity(p = paths(), deps = realDeps) {
|
|
2847
|
+
const store = (await loadConfig(p)).backupStore;
|
|
2848
|
+
if (!store) return void 0;
|
|
2849
|
+
const fs = await statfs2(store.path).catch(() => null);
|
|
2850
|
+
return { totalBytes: fs ? fs.blocks * fs.bsize : 0, freeBytes: fs ? fs.bavail * fs.bsize : 0, running: fs !== null && await deps.running(p) };
|
|
2851
|
+
}
|
|
2852
|
+
function reviveBackupStore(p = paths(), deps = realDeps) {
|
|
2853
|
+
return serial(() => revive(p, deps));
|
|
2854
|
+
}
|
|
2855
|
+
var upgraded = /* @__PURE__ */ new Set();
|
|
2856
|
+
var restartDue = /* @__PURE__ */ new Set();
|
|
2857
|
+
async function revive(p, deps) {
|
|
2858
|
+
const store = (await loadConfig(p)).backupStore;
|
|
2859
|
+
if (!store) return "none";
|
|
2860
|
+
if (!upgraded.has(p.home)) {
|
|
2861
|
+
upgraded.add(p.home);
|
|
2862
|
+
const fresh = await deps.install(p).catch((err) => {
|
|
2863
|
+
log.warn(`backup store: Garage ${GARAGE_VERSION} could not be installed, the one there keeps running (${err.message})`);
|
|
2864
|
+
return false;
|
|
2865
|
+
});
|
|
2866
|
+
if (fresh) restartDue.add(p.home);
|
|
2867
|
+
}
|
|
2868
|
+
if (restartDue.has(p.home) && existsSync4(join2(store.path, "rpc_secret"))) {
|
|
2869
|
+
if (await deps.running(p)) await deps.stop(p);
|
|
2870
|
+
const pid2 = await deps.start(p);
|
|
2871
|
+
await writeFile5(p.backupStore.pid, `${pid2}
|
|
2872
|
+
`);
|
|
2873
|
+
restartDue.delete(p.home);
|
|
2874
|
+
return "upgraded";
|
|
2875
|
+
}
|
|
2876
|
+
if (await deps.running(p)) return "running";
|
|
2877
|
+
if (!existsSync4(join2(store.path, "rpc_secret"))) return "no-disk";
|
|
2878
|
+
await rm2(p.backupStore.pid, { force: true });
|
|
2879
|
+
const pid = await deps.start(p);
|
|
2880
|
+
await writeFile5(p.backupStore.pid, `${pid}
|
|
2881
|
+
`);
|
|
2882
|
+
return "started";
|
|
2883
|
+
}
|
|
2884
|
+
var watch;
|
|
2885
|
+
function startBackupStoreWatch(p = paths()) {
|
|
2886
|
+
let warned = false;
|
|
2887
|
+
const tick = () => {
|
|
2888
|
+
reviveBackupStore(p).then((state) => {
|
|
2889
|
+
if (state === "started") log.info("backup store: Garage was not running; started it");
|
|
2890
|
+
if (state === "upgraded") log.info(`backup store: Garage ${GARAGE_VERSION} installed and started`);
|
|
2891
|
+
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");
|
|
2892
|
+
warned = state === "no-disk";
|
|
2893
|
+
}).catch((err) => log.warn(`backup store: Garage did not start (${err.message})`));
|
|
2894
|
+
};
|
|
2895
|
+
tick();
|
|
2896
|
+
watch ??= setInterval(tick, WATCH_MS);
|
|
2897
|
+
watch.unref();
|
|
2898
|
+
}
|
|
2899
|
+
function isStoreRequest(url) {
|
|
2900
|
+
return url !== void 0 && (url.startsWith(`/${BACKUP_STORE_BUCKET}/`) || url.startsWith(`/${BACKUP_STORE_BUCKET}?`) || url === `/${BACKUP_STORE_BUCKET}`);
|
|
2901
|
+
}
|
|
2902
|
+
function forStore(url, p = paths()) {
|
|
2903
|
+
return isStoreRequest(url) && existsSync4(p.backupStore.conf);
|
|
2904
|
+
}
|
|
2905
|
+
function storeProxy(req, res, port = GARAGE_S3_PORT) {
|
|
2906
|
+
const up = httpRequest({ host: "127.0.0.1", port, method: req.method, path: req.url, headers: req.headers }, (answer) => {
|
|
2907
|
+
res.writeHead(answer.statusCode ?? 502, answer.headers);
|
|
2908
|
+
pipeline(answer, res, (err) => {
|
|
2909
|
+
if (err) res.destroy();
|
|
2910
|
+
});
|
|
2911
|
+
});
|
|
2912
|
+
up.on("error", () => {
|
|
2913
|
+
if (res.headersSent) return res.destroy();
|
|
2914
|
+
res.writeHead(503, { "content-type": "application/json" });
|
|
2915
|
+
res.end(JSON.stringify({ error: "this host's backup store is not running" }));
|
|
2916
|
+
});
|
|
2917
|
+
res.once("close", () => {
|
|
2918
|
+
if (!res.writableFinished) up.destroy();
|
|
2919
|
+
});
|
|
2920
|
+
req.pipe(up);
|
|
2921
|
+
}
|
|
2922
|
+
|
|
2923
|
+
// src/core/capacity.ts
|
|
2529
2924
|
function hostResources() {
|
|
2530
2925
|
return { memMib: Math.floor(totalmem() / 1024 ** 2), cores: cpus().length };
|
|
2531
2926
|
}
|
|
@@ -2551,7 +2946,10 @@ async function capacity(p = paths()) {
|
|
|
2551
2946
|
running: running.length,
|
|
2552
2947
|
disk: await diskCapacity(p),
|
|
2553
2948
|
// 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)
|
|
2949
|
+
images: await listImages(await loadConfig(p), p),
|
|
2950
|
+
...await backupStoreCapacity(p).then((store) => store ? { backupStore: store } : {}),
|
|
2951
|
+
// Backups and restores here reach a store by its certificate's pin (core/storeFetch.ts).
|
|
2952
|
+
storeClient: true
|
|
2555
2953
|
};
|
|
2556
2954
|
}
|
|
2557
2955
|
function gb(mib) {
|
|
@@ -2635,11 +3033,11 @@ function ext4Usage(file) {
|
|
|
2635
3033
|
}
|
|
2636
3034
|
|
|
2637
3035
|
// src/core/snapshots.ts
|
|
2638
|
-
import { existsSync as
|
|
2639
|
-
import { link, mkdir as
|
|
3036
|
+
import { existsSync as existsSync5 } from "node:fs";
|
|
3037
|
+
import { link, mkdir as mkdir5, readdir as readdir5, rename as rename5, rm as rm3, stat as stat3 } from "node:fs/promises";
|
|
2640
3038
|
|
|
2641
3039
|
// src/core/firecracker.ts
|
|
2642
|
-
import { Agent, request } from "undici";
|
|
3040
|
+
import { Agent, request as request2 } from "undici";
|
|
2643
3041
|
var FirecrackerClient = class {
|
|
2644
3042
|
constructor(socketPath) {
|
|
2645
3043
|
this.socketPath = socketPath;
|
|
@@ -2648,7 +3046,7 @@ var FirecrackerClient = class {
|
|
|
2648
3046
|
socketPath;
|
|
2649
3047
|
agent;
|
|
2650
3048
|
async call(method, path, body) {
|
|
2651
|
-
const res = await
|
|
3049
|
+
const res = await request2(`http://localhost${path}`, {
|
|
2652
3050
|
dispatcher: this.agent,
|
|
2653
3051
|
method,
|
|
2654
3052
|
headers: body === void 0 ? {} : { "content-type": "application/json" },
|
|
@@ -2781,7 +3179,7 @@ async function listSnapshots(scope, p = paths()) {
|
|
|
2781
3179
|
async function usedBytes(dir) {
|
|
2782
3180
|
let total = 0;
|
|
2783
3181
|
for (const entry of await readdir5(dir)) {
|
|
2784
|
-
total += (await
|
|
3182
|
+
total += (await stat3(`${dir}/${entry}`)).blocks * 512;
|
|
2785
3183
|
}
|
|
2786
3184
|
return total;
|
|
2787
3185
|
}
|
|
@@ -2803,17 +3201,17 @@ async function saveSnapshot(req, owner, p = paths()) {
|
|
|
2803
3201
|
async function snapshotBox(ref, req, owner, p) {
|
|
2804
3202
|
const box = await readBox(ref, p);
|
|
2805
3203
|
if (!vmAlive(box)) {
|
|
2806
|
-
if (
|
|
3204
|
+
if (existsSync5(p.machine(box.owner, box.name).hibernateVmstate)) {
|
|
2807
3205
|
throw new KvboxError(`box ${req.box} is hibernated; a snapshot freezes a running box (kvbox wake ${req.box} first)`);
|
|
2808
3206
|
}
|
|
2809
3207
|
throw new KvboxError(`box ${req.box} is not running; a snapshot freezes a running box (kvbox start ${req.box} first)`);
|
|
2810
3208
|
}
|
|
2811
3209
|
const final = p.snapshot(owner, req.name);
|
|
2812
|
-
if (
|
|
3210
|
+
if (existsSync5(final.dir) && !req.replace) throw new KvboxError(`snapshot ${req.name} already exists (--replace retakes it)`);
|
|
2813
3211
|
const s = req.replace ? p.snapshot(owner, `.${req.name}.new-${box.id}`) : final;
|
|
2814
3212
|
const cfg = await loadConfig(p);
|
|
2815
|
-
if (s !== final) await
|
|
2816
|
-
await
|
|
3213
|
+
if (s !== final) await rm3(s.dir, { recursive: true, force: true });
|
|
3214
|
+
await mkdir5(s.dir, { recursive: true, mode: 448 });
|
|
2817
3215
|
try {
|
|
2818
3216
|
const volumes = await captureDrivesOf(box, p);
|
|
2819
3217
|
await captureBox(box, s, cfg, p);
|
|
@@ -2834,7 +3232,7 @@ async function snapshotBox(ref, req, owner, p) {
|
|
|
2834
3232
|
if (s !== final) await swapIn({ owner, name: req.name }, s.dir, box.id, p);
|
|
2835
3233
|
return toSnapshot(meta);
|
|
2836
3234
|
} catch (err) {
|
|
2837
|
-
await
|
|
3235
|
+
await rm3(s.dir, { recursive: true, force: true });
|
|
2838
3236
|
throw err;
|
|
2839
3237
|
}
|
|
2840
3238
|
}
|
|
@@ -2842,17 +3240,17 @@ async function swapIn(ref, from, boxId, p) {
|
|
|
2842
3240
|
const to = p.snapshot(ref.owner, ref.name).dir;
|
|
2843
3241
|
const old = p.snapshot(ref.owner, `.${ref.name}.old-${boxId}`).dir;
|
|
2844
3242
|
await withSnapshotLock(ref, async () => {
|
|
2845
|
-
await
|
|
2846
|
-
const hadOld =
|
|
2847
|
-
if (hadOld) await
|
|
3243
|
+
await rm3(old, { recursive: true, force: true });
|
|
3244
|
+
const hadOld = existsSync5(to);
|
|
3245
|
+
if (hadOld) await rename5(to, old);
|
|
2848
3246
|
try {
|
|
2849
|
-
await
|
|
3247
|
+
await rename5(from, to);
|
|
2850
3248
|
} catch (err) {
|
|
2851
|
-
if (hadOld) await
|
|
3249
|
+
if (hadOld) await rename5(old, to);
|
|
2852
3250
|
throw err;
|
|
2853
3251
|
}
|
|
2854
3252
|
});
|
|
2855
|
-
await
|
|
3253
|
+
await rm3(old, { recursive: true, force: true });
|
|
2856
3254
|
}
|
|
2857
3255
|
async function captureBox(box, to, cfg, p) {
|
|
2858
3256
|
const m = p.machine(box.owner, box.name);
|
|
@@ -2860,7 +3258,7 @@ async function captureBox(box, to, cfg, p) {
|
|
|
2860
3258
|
let lineageTouched = false;
|
|
2861
3259
|
try {
|
|
2862
3260
|
const since = box.memSnapshots ?? 0;
|
|
2863
|
-
const mode = since === 0 ||
|
|
3261
|
+
const mode = since === 0 || existsSync5(m.memBase) ? "Diff" : "Full";
|
|
2864
3262
|
let failure2;
|
|
2865
3263
|
await fc.pause();
|
|
2866
3264
|
try {
|
|
@@ -2881,31 +3279,31 @@ async function captureBox(box, to, cfg, p) {
|
|
|
2881
3279
|
} else if (since > 0) {
|
|
2882
3280
|
await mergeOntoPrevious(m.memBase, to.mem, cfg.snapshotEditor ?? p.snapshotEditor);
|
|
2883
3281
|
}
|
|
2884
|
-
await
|
|
3282
|
+
await rm3(m.memBase, { force: true });
|
|
2885
3283
|
await link(to.mem, m.memBase);
|
|
2886
3284
|
} catch (err) {
|
|
2887
|
-
if (lineageTouched) await
|
|
3285
|
+
if (lineageTouched) await rm3(m.memBase, { force: true }).catch(() => void 0);
|
|
2888
3286
|
throw err;
|
|
2889
3287
|
} finally {
|
|
2890
3288
|
await fc.close();
|
|
2891
3289
|
}
|
|
2892
3290
|
}
|
|
2893
3291
|
async function mergeOntoPrevious(previous, diffFile, editor) {
|
|
2894
|
-
if (!
|
|
3292
|
+
if (!existsSync5(editor)) throw new KvboxError(`snapshot-editor missing at ${editor}; rerun install-server.sh`);
|
|
2895
3293
|
const merged = `${diffFile}.merged`;
|
|
2896
3294
|
await run(["cp", "--sparse=always", "--reflink=auto", previous, merged]);
|
|
2897
3295
|
await run([editor, "edit-memory", "rebase", "--memory-path", merged, "--diff-path", diffFile]);
|
|
2898
|
-
await
|
|
3296
|
+
await rename5(merged, diffFile);
|
|
2899
3297
|
}
|
|
2900
3298
|
async function deleteSnapshot(ref, p = paths()) {
|
|
2901
3299
|
const dir = p.snapshot(ref.owner, ref.name).dir;
|
|
2902
|
-
if (ref.name.startsWith(".") || !
|
|
2903
|
-
await withSnapshotLock(ref, () =>
|
|
3300
|
+
if (ref.name.startsWith(".") || !existsSync5(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);
|
|
3301
|
+
await withSnapshotLock(ref, () => rm3(dir, { recursive: true, force: true }));
|
|
2904
3302
|
}
|
|
2905
3303
|
|
|
2906
3304
|
// src/core/network.ts
|
|
2907
3305
|
import { randomInt } from "node:crypto";
|
|
2908
|
-
import { existsSync as
|
|
3306
|
+
import { existsSync as existsSync6 } from "node:fs";
|
|
2909
3307
|
import { fileURLToPath } from "node:url";
|
|
2910
3308
|
var TAP_PREFIX = "kv-";
|
|
2911
3309
|
var PRIVILEGED_SCRIPT = "/usr/local/lib/kvbox/net-setup.sh";
|
|
@@ -2915,15 +3313,15 @@ function tapName(box) {
|
|
|
2915
3313
|
function netSetupScript() {
|
|
2916
3314
|
const override = process.env["KVBOX_NET_SETUP"];
|
|
2917
3315
|
if (override) return override;
|
|
2918
|
-
if (
|
|
3316
|
+
if (existsSync6(PRIVILEGED_SCRIPT)) return PRIVILEGED_SCRIPT;
|
|
2919
3317
|
for (const rel of ["../scripts/net-setup.sh", "../../scripts/net-setup.sh"]) {
|
|
2920
3318
|
const candidate = fileURLToPath(new URL(rel, import.meta.url));
|
|
2921
|
-
if (
|
|
3319
|
+
if (existsSync6(candidate)) return candidate;
|
|
2922
3320
|
}
|
|
2923
3321
|
throw new KvboxError("net-setup.sh not found next to kvbox-server");
|
|
2924
3322
|
}
|
|
2925
3323
|
function bridgeExists(bridge) {
|
|
2926
|
-
return
|
|
3324
|
+
return existsSync6(`/sys/class/net/${bridge}`);
|
|
2927
3325
|
}
|
|
2928
3326
|
function netRun(cfg, args) {
|
|
2929
3327
|
return run([netSetupScript(), ...args], {
|
|
@@ -3106,7 +3504,7 @@ function recordState(meta, state, by, p, at = (/* @__PURE__ */ new Date()).toISO
|
|
|
3106
3504
|
}
|
|
3107
3505
|
}
|
|
3108
3506
|
function isHibernated(meta, p) {
|
|
3109
|
-
return !vmAlive(meta) &&
|
|
3507
|
+
return !vmAlive(meta) && existsSync7(p.machine(meta.owner, meta.name).hibernateVmstate);
|
|
3110
3508
|
}
|
|
3111
3509
|
function statusOf(meta, p = paths()) {
|
|
3112
3510
|
if (vmAlive(meta)) return meta.paused ? "standby" : "running";
|
|
@@ -3208,7 +3606,7 @@ function bootArgs(name, ip, cfg, pubkeyB64) {
|
|
|
3208
3606
|
return process.arch === "arm64" ? `keep_bootcon ${args}` : args;
|
|
3209
3607
|
}
|
|
3210
3608
|
async function createOverlay(file, gib) {
|
|
3211
|
-
await
|
|
3609
|
+
await writeFile6(file, "", { mode: 384 });
|
|
3212
3610
|
await truncate2(file, gib * 1024 ** 3);
|
|
3213
3611
|
await run(["mkfs.ext4", "-q", "-F", "-m", "0", "-L", "kvbox-box", "-E", "lazy_itable_init=1,lazy_journal_init=1", file]);
|
|
3214
3612
|
}
|
|
@@ -3216,21 +3614,21 @@ async function waitFor(pred, timeoutMs, stepMs = 50) {
|
|
|
3216
3614
|
const deadline = Date.now() + timeoutMs;
|
|
3217
3615
|
while (Date.now() < deadline) {
|
|
3218
3616
|
if (pred()) return true;
|
|
3219
|
-
await
|
|
3617
|
+
await sleep2(stepMs);
|
|
3220
3618
|
}
|
|
3221
3619
|
return pred();
|
|
3222
3620
|
}
|
|
3223
3621
|
async function tailOf(file, lines = 5) {
|
|
3224
3622
|
try {
|
|
3225
|
-
return (await
|
|
3623
|
+
return (await readFile6(file, "utf8")).trim().split("\n").slice(-lines).join("\n");
|
|
3226
3624
|
} catch {
|
|
3227
3625
|
return "";
|
|
3228
3626
|
}
|
|
3229
3627
|
}
|
|
3230
3628
|
async function spawnFirecracker(ref, cfg, p) {
|
|
3231
3629
|
const m = p.machine(ref.owner, ref.name);
|
|
3232
|
-
await
|
|
3233
|
-
await
|
|
3630
|
+
await rm4(m.sock, { force: true });
|
|
3631
|
+
await rm4(m.vsock, { force: true });
|
|
3234
3632
|
const logFd = openSync4(m.log, "a");
|
|
3235
3633
|
let child;
|
|
3236
3634
|
try {
|
|
@@ -3245,7 +3643,7 @@ async function spawnFirecracker(ref, cfg, p) {
|
|
|
3245
3643
|
child.unref();
|
|
3246
3644
|
const pid = child.pid;
|
|
3247
3645
|
if (pid === void 0) throw new KvboxError("could not start firecracker");
|
|
3248
|
-
if (!await waitFor(() =>
|
|
3646
|
+
if (!await waitFor(() => existsSync7(m.sock), 3e3)) {
|
|
3249
3647
|
killQuietly(pid);
|
|
3250
3648
|
throw new KvboxError(`firecracker did not open its API socket; last log lines:
|
|
3251
3649
|
${await tailOf(m.log)}`);
|
|
@@ -3311,14 +3709,14 @@ async function currentBaseVersion(p = paths()) {
|
|
|
3311
3709
|
}
|
|
3312
3710
|
async function readHostPubkey(p) {
|
|
3313
3711
|
try {
|
|
3314
|
-
return (await
|
|
3712
|
+
return (await readFile6(`${p.sshKey}.pub`, "utf8")).trim();
|
|
3315
3713
|
} catch {
|
|
3316
3714
|
throw new KvboxError(`SSH key missing at ${p.sshKey}.pub; run install-server.sh`);
|
|
3317
3715
|
}
|
|
3318
3716
|
}
|
|
3319
3717
|
function assertAssets(cfg) {
|
|
3320
3718
|
for (const [what, file] of [["kernel", cfg.kernel], ["base image", cfg.rootfs], ["firecracker", cfg.firecracker]]) {
|
|
3321
|
-
if (!
|
|
3719
|
+
if (!existsSync7(file)) throw new KvboxError(`${what} missing at ${file}; run install-server.sh`);
|
|
3322
3720
|
}
|
|
3323
3721
|
}
|
|
3324
3722
|
async function createMachine(req, owner, p = paths()) {
|
|
@@ -3326,9 +3724,9 @@ async function createMachine(req, owner, p = paths()) {
|
|
|
3326
3724
|
if (req.from !== void 0) return restoreMachine(req.from, owner, req, cfg, p);
|
|
3327
3725
|
const sizeName = req.size ?? cfg.defaultSize;
|
|
3328
3726
|
if (!isSizeName(sizeName)) throw new KvboxError(`unknown size "${sizeName}"; use one of ${Object.keys(SIZES).join(", ")}`);
|
|
3329
|
-
const
|
|
3727
|
+
const size2 = SIZES[sizeName];
|
|
3330
3728
|
assertAssets(cfg);
|
|
3331
|
-
await assertRoomFor(
|
|
3729
|
+
await assertRoomFor(size2.vcpu, size2.memMib, req.force ?? false, { owner }, "new", p);
|
|
3332
3730
|
const sshKeys = isCloudBox(owner) && req.sshKeys !== void 0 && req.sshKeys.length > 0 ? req.sshKeys : void 0;
|
|
3333
3731
|
authorizedKeysB64(await readHostPubkey(p), sshKeys ?? []);
|
|
3334
3732
|
const existing = await readAllMeta(p);
|
|
@@ -3344,10 +3742,10 @@ async function createMachine(req, owner, p = paths()) {
|
|
|
3344
3742
|
const autoHibernateSec = autoHibernateFor(req, cfg, manifest);
|
|
3345
3743
|
const vars = env.vars.map((v) => ({ ...v, secret: env.secrets.includes(v.name), updatedAt: now }));
|
|
3346
3744
|
const machine = await bootInto(
|
|
3347
|
-
{ id, name, owner, ip, mac: macFor(ip), vcpu:
|
|
3745
|
+
{ id, name, owner, ip, mac: macFor(ip), vcpu: size2.vcpu, memMib: size2.memMib, base: base.version, image, sshKeys },
|
|
3348
3746
|
// The image is shared read-only by every box; only the box's own writes land in its overlay.
|
|
3349
3747
|
async (m) => {
|
|
3350
|
-
await createOverlay(m.overlay,
|
|
3748
|
+
await createOverlay(m.overlay, size2.diskGib);
|
|
3351
3749
|
if (vars.length > 0) await writeBoxEnv({ owner, name }, vars, p);
|
|
3352
3750
|
},
|
|
3353
3751
|
{ source: "base", autoHibernateSec, idleCheck: manifest.idle, url: maskedUrl(manifest, vars) },
|
|
@@ -3361,7 +3759,7 @@ async function bootInto(box, prepare, origin, cfg, p) {
|
|
|
3361
3759
|
const keysB64 = authorizedKeysB64(await readHostPubkey(p), box.sshKeys ?? []);
|
|
3362
3760
|
const m = p.machine(owner, name);
|
|
3363
3761
|
await ensureHostNetwork(cfg);
|
|
3364
|
-
await
|
|
3762
|
+
await mkdir6(m.dir, { recursive: true, mode: 448 });
|
|
3365
3763
|
let tapCreated = false;
|
|
3366
3764
|
let pid;
|
|
3367
3765
|
let sshPort;
|
|
@@ -3384,7 +3782,7 @@ async function bootInto(box, prepare, origin, cfg, p) {
|
|
|
3384
3782
|
if (pid !== void 0) killQuietly(pid);
|
|
3385
3783
|
await closePorts({ id, ip, sshPort }, cfg);
|
|
3386
3784
|
if (tapCreated) await deleteTap(id, cfg).catch(() => void 0);
|
|
3387
|
-
await
|
|
3785
|
+
await rm4(m.dir, { recursive: true, force: true });
|
|
3388
3786
|
boxListChanged();
|
|
3389
3787
|
throw err;
|
|
3390
3788
|
} finally {
|
|
@@ -3413,7 +3811,7 @@ async function restoreFrom(from, owner, req, cfg, p) {
|
|
|
3413
3811
|
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
3812
|
}
|
|
3415
3813
|
assertAssets(cfg);
|
|
3416
|
-
if (!
|
|
3814
|
+
if (!existsSync7(imageFile(snap.image, snap.base, p))) {
|
|
3417
3815
|
throw new KvboxError(`snapshot ${shown(from)} stacks on ${imageLabel(snap.image)} ${snap.base}, which is gone from ${p.assets}`);
|
|
3418
3816
|
}
|
|
3419
3817
|
const manifest = await imageManifest(imageFile(snap.image, snap.base, p));
|
|
@@ -3449,7 +3847,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
|
|
|
3449
3847
|
const { id, ip, owner, name } = box;
|
|
3450
3848
|
const m = p.machine(owner, name);
|
|
3451
3849
|
await ensureHostNetwork(cfg);
|
|
3452
|
-
await
|
|
3850
|
+
await mkdir6(m.dir, { recursive: true, mode: 448 });
|
|
3453
3851
|
let tapCreated = false;
|
|
3454
3852
|
let pid;
|
|
3455
3853
|
let sshPort;
|
|
@@ -3481,7 +3879,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
|
|
|
3481
3879
|
if (pid !== void 0) killQuietly(pid);
|
|
3482
3880
|
await closePorts({ id, ip, sshPort }, cfg);
|
|
3483
3881
|
if (tapCreated) await deleteTap(id, cfg).catch(() => void 0);
|
|
3484
|
-
await
|
|
3882
|
+
await rm4(m.dir, { recursive: true, force: true });
|
|
3485
3883
|
boxListChanged();
|
|
3486
3884
|
throw err;
|
|
3487
3885
|
} finally {
|
|
@@ -3549,7 +3947,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
|
|
|
3549
3947
|
// another slug. Such a fork is discarded rather than kept stale; a cold fork boots with the new line.
|
|
3550
3948
|
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
3949
|
);
|
|
3552
|
-
await
|
|
3950
|
+
await rm4(p.machine(owner, name).forkVmstate, { force: true });
|
|
3553
3951
|
return machine;
|
|
3554
3952
|
});
|
|
3555
3953
|
var AGENT_REPLY_MS = 2e4;
|
|
@@ -3564,7 +3962,7 @@ async function introduce(spec, vsock, cfg, failure2) {
|
|
|
3564
3962
|
const msg = err.message;
|
|
3565
3963
|
const transient = /unreachable|refused|before the guest accepted/.test(msg);
|
|
3566
3964
|
if (transient && Date.now() < deadline) {
|
|
3567
|
-
await
|
|
3965
|
+
await sleep2(100);
|
|
3568
3966
|
continue;
|
|
3569
3967
|
}
|
|
3570
3968
|
if (transient) throw new KvboxError(`${msg}
|
|
@@ -3623,7 +4021,7 @@ function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs: AGENT_REPLY_MS
|
|
|
3623
4021
|
} catch (err) {
|
|
3624
4022
|
if (!pidAlive(pid)) return;
|
|
3625
4023
|
if (isNoAgent(err) && Date.now() < deadline) {
|
|
3626
|
-
await
|
|
4024
|
+
await sleep2(500);
|
|
3627
4025
|
continue;
|
|
3628
4026
|
}
|
|
3629
4027
|
warnEnv(box, vars, err);
|
|
@@ -3666,8 +4064,8 @@ async function cleanupProcess(meta, cfg, p) {
|
|
|
3666
4064
|
await closePorts(meta, cfg);
|
|
3667
4065
|
await deleteTap(meta.id, cfg);
|
|
3668
4066
|
const m = p.machine(meta.owner, meta.name);
|
|
3669
|
-
await
|
|
3670
|
-
await
|
|
4067
|
+
await rm4(m.sock, { force: true });
|
|
4068
|
+
await rm4(m.vsock, { force: true });
|
|
3671
4069
|
}
|
|
3672
4070
|
var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
|
|
3673
4071
|
const meta = await readMeta(ref, p);
|
|
@@ -3676,8 +4074,8 @@ var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
|
|
|
3676
4074
|
if (!vmAlive(meta) && !isHibernated(meta, p)) throw new KvboxError(`box ${shown(ref)} is already stopped`);
|
|
3677
4075
|
await shutdown(meta, cfg, p, 1e4);
|
|
3678
4076
|
await compactDisk(m.overlay).catch((err) => log.warn(`box ${shown(ref)}: disk not compacted: ${err.message}`));
|
|
3679
|
-
await
|
|
3680
|
-
await
|
|
4077
|
+
await rm4(m.hibernateDir, { recursive: true, force: true });
|
|
4078
|
+
await rm4(m.memBase, { force: true });
|
|
3681
4079
|
const stopped = { ...meta, pid: null, memSnapshots: void 0, paused: void 0 };
|
|
3682
4080
|
await writeMachineMeta(stopped, p);
|
|
3683
4081
|
recordState(stopped, "stopped", "stop", p);
|
|
@@ -3801,15 +4199,15 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
|
|
|
3801
4199
|
if (status === "hibernated") throw new KvboxError(`${stateMessage(ref, status)} already`);
|
|
3802
4200
|
if (status === "stopped") throw new KvboxError(`${stateMessage(ref, status)}; only a running box can be hibernated (there is no memory to keep)`);
|
|
3803
4201
|
const m = p.machine(ref.owner, ref.name);
|
|
3804
|
-
await
|
|
3805
|
-
await
|
|
4202
|
+
await rm4(m.hibernateDir, { recursive: true, force: true });
|
|
4203
|
+
await mkdir6(m.hibernateDir, { recursive: true, mode: 448 });
|
|
3806
4204
|
const fc = new FirecrackerClient(m.sock);
|
|
3807
4205
|
try {
|
|
3808
4206
|
try {
|
|
3809
4207
|
await fc.pause();
|
|
3810
4208
|
await fc.snapshotCreate(m.hibernateVmstate, m.hibernateMem, "Full");
|
|
3811
4209
|
} catch (err) {
|
|
3812
|
-
await
|
|
4210
|
+
await rm4(m.hibernateDir, { recursive: true, force: true });
|
|
3813
4211
|
if (!meta.paused) await fc.resume().catch(() => void 0);
|
|
3814
4212
|
throw err;
|
|
3815
4213
|
}
|
|
@@ -3820,7 +4218,7 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
|
|
|
3820
4218
|
await waitFor(() => !pidAlive(meta.pid), 5e3, 50);
|
|
3821
4219
|
await cleanupProcess(meta, cfg, p);
|
|
3822
4220
|
await run(["fallocate", "--dig-holes", m.hibernateMem]);
|
|
3823
|
-
await
|
|
4221
|
+
await rm4(m.memBase, { force: true });
|
|
3824
4222
|
const hibernated = { ...meta, pid: null, memSnapshots: void 0, paused: void 0 };
|
|
3825
4223
|
await writeMachineMeta(hibernated, p);
|
|
3826
4224
|
recordState(hibernated, "hibernated", by, p);
|
|
@@ -3833,7 +4231,7 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths(), force = f
|
|
|
3833
4231
|
if (status === "running" || status === "standby") throw new KvboxError(`${stateMessage(ref, status)}, not hibernated`);
|
|
3834
4232
|
if (status === "stopped") throw new KvboxError(`${stateMessage(ref, status)}, not hibernated; kvbox start ${shown(ref)} boots it`);
|
|
3835
4233
|
assertAssets(cfg);
|
|
3836
|
-
if (!
|
|
4234
|
+
if (!existsSync7(imageFile(meta.image, meta.base, p))) {
|
|
3837
4235
|
throw new KvboxError(`box ${shown(ref)} stacks on ${imageLabel(meta.image)} ${meta.base}, which is gone from ${p.assets}`);
|
|
3838
4236
|
}
|
|
3839
4237
|
await assertRoomFor(meta.vcpu, meta.memMib, force, meta, "start", p);
|
|
@@ -3859,9 +4257,9 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths(), force = f
|
|
|
3859
4257
|
await deleteTap(meta.id, cfg).catch(() => void 0);
|
|
3860
4258
|
throw err;
|
|
3861
4259
|
}
|
|
3862
|
-
await
|
|
4260
|
+
await rm4(m.memBase, { force: true });
|
|
3863
4261
|
await link2(m.hibernateMem, m.memBase);
|
|
3864
|
-
await
|
|
4262
|
+
await rm4(m.hibernateDir, { recursive: true, force: true });
|
|
3865
4263
|
const running = { ...meta, pid, bootId: currentBootId(), memSnapshots: 1, paused: void 0, sshKeysStale: stale ? true : void 0 };
|
|
3866
4264
|
await writeMachineMeta(running, p);
|
|
3867
4265
|
recordState(running, "running", "wake", p);
|
|
@@ -3871,7 +4269,7 @@ async function applyAtNextBoot(meta, changes, by, cfg, p, whileStopped) {
|
|
|
3871
4269
|
const wasRunning = vmAlive(meta);
|
|
3872
4270
|
if (wasRunning) {
|
|
3873
4271
|
await shutdown(meta, cfg, p, 1e4);
|
|
3874
|
-
await
|
|
4272
|
+
await rm4(p.machine(meta.owner, meta.name).memBase, { force: true });
|
|
3875
4273
|
}
|
|
3876
4274
|
const updated = { ...meta, ...changes, pid: null, memSnapshots: void 0, paused: void 0 };
|
|
3877
4275
|
await writeMachineMeta(updated, p);
|
|
@@ -3941,9 +4339,9 @@ var replaceDisk = locked(async function replaceDisk2(ref, file, disk, p = paths(
|
|
|
3941
4339
|
const currentGib = Math.round(statSync2(m.overlay).size / 1024 ** 3);
|
|
3942
4340
|
const restoredGib = Math.round(statSync2(file).size / 1024 ** 3);
|
|
3943
4341
|
return applyAtNextBoot(meta, { base: disk.base, image: disk.image }, "restore", cfg, p, async () => {
|
|
3944
|
-
if (disk.vars === null) await
|
|
4342
|
+
if (disk.vars === null) await rm4(m.env, { force: true });
|
|
3945
4343
|
else await writeBoxEnv(ref, disk.vars, p);
|
|
3946
|
-
await
|
|
4344
|
+
await rename6(file, m.overlay);
|
|
3947
4345
|
if (currentGib > restoredGib) await growDisk(m.overlay, currentGib);
|
|
3948
4346
|
});
|
|
3949
4347
|
});
|
|
@@ -3969,7 +4367,7 @@ var detachVolume = locked(async function detachVolume2(ref, volume, p = paths())
|
|
|
3969
4367
|
if (!meta.volumes?.includes(volume.name) || volume.owner !== meta.owner) throw new KvboxError(`volume ${shown(volume)} is not attached to box ${shown(ref)}`);
|
|
3970
4368
|
assertNotHibernated(meta, p);
|
|
3971
4369
|
const kept = meta.volumes.filter((v) => v !== volume.name);
|
|
3972
|
-
return applyAtNextBoot(meta, { volumes: kept.length > 0 ? kept : void 0 }, "detach", cfg, p, () =>
|
|
4370
|
+
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
4371
|
});
|
|
3974
4372
|
async function resizeVolume(volume, sizeGib, p = paths()) {
|
|
3975
4373
|
await assertCanGrow(volume, sizeGib, p);
|
|
@@ -4127,7 +4525,7 @@ var destroyBox = locked(async function destroyBox2(ref, p = paths()) {
|
|
|
4127
4525
|
throw err;
|
|
4128
4526
|
});
|
|
4129
4527
|
recordState(meta, "stopped", "rm", p);
|
|
4130
|
-
await
|
|
4528
|
+
await rm4(p.machine(ref.owner, ref.name).dir, { recursive: true, force: true });
|
|
4131
4529
|
boxListChanged();
|
|
4132
4530
|
return meta;
|
|
4133
4531
|
});
|
|
@@ -4175,7 +4573,7 @@ async function settleDeadBoxes(p = paths()) {
|
|
|
4175
4573
|
} catch (err) {
|
|
4176
4574
|
log.warn(`usage ledger: ${err.message}`);
|
|
4177
4575
|
}
|
|
4178
|
-
await
|
|
4576
|
+
await rm4(p.machine(meta.owner, meta.name).memBase, { force: true });
|
|
4179
4577
|
if (meta.paused) {
|
|
4180
4578
|
await writeMachineMeta({ ...meta, pid: null, bootId: void 0, memSnapshots: void 0, paused: void 0 }, p);
|
|
4181
4579
|
leftStopped.push(refKey(meta));
|
|
@@ -4193,7 +4591,7 @@ async function pinRunningTaps(p = paths()) {
|
|
|
4193
4591
|
const cfg = await loadConfig(p);
|
|
4194
4592
|
if (!bridgeExists(cfg.bridge)) return;
|
|
4195
4593
|
for (const meta of await readAllMeta(p)) {
|
|
4196
|
-
if (!vmAlive(meta) || !
|
|
4594
|
+
if (!vmAlive(meta) || !existsSync7(`/sys/class/net/${tapName(meta.id)}`)) continue;
|
|
4197
4595
|
await pinTap(meta, cfg).catch((err) => log.warn(`could not pin box ${meta.name}'s tap: ${err.message}`));
|
|
4198
4596
|
}
|
|
4199
4597
|
}
|
|
@@ -4232,14 +4630,14 @@ async function bootRecovered(settled, p = paths()) {
|
|
|
4232
4630
|
}
|
|
4233
4631
|
|
|
4234
4632
|
// 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
|
|
4633
|
+
import { randomBytes as randomBytes5 } from "node:crypto";
|
|
4634
|
+
import { existsSync as existsSync8 } from "node:fs";
|
|
4635
|
+
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";
|
|
4636
|
+
import { basename as basename2, join as join3 } from "node:path";
|
|
4637
|
+
import { setTimeout as sleep3 } from "node:timers/promises";
|
|
4240
4638
|
|
|
4241
4639
|
// ../shared/src/backup.ts
|
|
4242
|
-
import { createCipheriv, createDecipheriv, createHmac, randomBytes as
|
|
4640
|
+
import { createCipheriv, createDecipheriv, createHmac, randomBytes as randomBytes4 } from "node:crypto";
|
|
4243
4641
|
import { promisify as promisify2 } from "node:util";
|
|
4244
4642
|
import { deflateRaw as deflateRawCb, inflateRaw as inflateRawCb, constants as zlib } from "node:zlib";
|
|
4245
4643
|
var deflateRaw = promisify2(deflateRawCb);
|
|
@@ -4291,7 +4689,7 @@ function openText(keys, sealedB64, label) {
|
|
|
4291
4689
|
return unseal(keys.seal, Buffer.from(sealedB64, "base64"), label, label).toString("utf8");
|
|
4292
4690
|
}
|
|
4293
4691
|
function seal(key, prefix, plain, aad) {
|
|
4294
|
-
const nonce =
|
|
4692
|
+
const nonce = randomBytes4(NONCE);
|
|
4295
4693
|
const cipher = createCipheriv("aes-256-gcm", key, nonce);
|
|
4296
4694
|
cipher.setAAD(Buffer.from(aad));
|
|
4297
4695
|
const data = Buffer.concat([cipher.update(plain), cipher.final()]);
|
|
@@ -4315,17 +4713,55 @@ function chunkCount(bytes) {
|
|
|
4315
4713
|
return Math.ceil(bytes / CHUNK_SIZE);
|
|
4316
4714
|
}
|
|
4317
4715
|
|
|
4716
|
+
// src/core/storeFetch.ts
|
|
4717
|
+
import { Agent as Agent2, buildConnector, fetch as pinnedFetch } from "undici";
|
|
4718
|
+
var dispatchers = /* @__PURE__ */ new Map();
|
|
4719
|
+
function storeDispatcher(pin, local) {
|
|
4720
|
+
const id = `${pin}|${local}`;
|
|
4721
|
+
const have = dispatchers.get(id);
|
|
4722
|
+
if (have) return have;
|
|
4723
|
+
const plain = buildConnector({ rejectUnauthorized: false, maxCachedSessions: 0, timeout: 1e4 });
|
|
4724
|
+
const connect3 = (opts, cb) => {
|
|
4725
|
+
plain(local ? { ...opts, hostname: "127.0.0.1" } : opts, (err, socket) => {
|
|
4726
|
+
if (err || !socket) return cb(err ?? new Error("no socket"), null);
|
|
4727
|
+
const tls = socket;
|
|
4728
|
+
const got = typeof tls.getPeerCertificate === "function" ? tls.getPeerCertificate().fingerprint256 : void 0;
|
|
4729
|
+
if (got !== pin) {
|
|
4730
|
+
socket.destroy();
|
|
4731
|
+
return cb(new Error("the backup store's certificate is not the one the control plane knows (fingerprint mismatch)"), null);
|
|
4732
|
+
}
|
|
4733
|
+
cb(null, socket);
|
|
4734
|
+
});
|
|
4735
|
+
};
|
|
4736
|
+
const agent = new Agent2({ connect: connect3 });
|
|
4737
|
+
dispatchers.set(id, agent);
|
|
4738
|
+
return agent;
|
|
4739
|
+
}
|
|
4740
|
+
async function chunkFetcher(pin, sampleUrl, p = paths()) {
|
|
4741
|
+
if (pin === void 0) return (url, init) => fetch(url, init);
|
|
4742
|
+
const cfg = await loadConfig(p);
|
|
4743
|
+
const cp = cfg.controlPlane;
|
|
4744
|
+
let local = false;
|
|
4745
|
+
if (cfg.backupStore && cp && sampleUrl !== void 0) {
|
|
4746
|
+
const target = new URL(sampleUrl);
|
|
4747
|
+
local = target.hostname === cp.advertise && Number(target.port || 443) === cp.port;
|
|
4748
|
+
}
|
|
4749
|
+
const dispatcher = storeDispatcher(pin, local);
|
|
4750
|
+
return (url, init) => pinnedFetch(url, { ...init, dispatcher });
|
|
4751
|
+
}
|
|
4752
|
+
|
|
4318
4753
|
// src/core/backups.ts
|
|
4319
4754
|
var PARALLEL = 4;
|
|
4320
4755
|
var TRIES = 4;
|
|
4321
4756
|
var CHUNK_TIMEOUT_MS = 12e4;
|
|
4322
4757
|
async function assertRoom(dir, bytes, what, p) {
|
|
4323
|
-
const st = await
|
|
4758
|
+
const st = await statfs3(dir);
|
|
4324
4759
|
const free = st.bavail * st.bsize;
|
|
4325
4760
|
const headroom = (await loadConfig(p)).volumeHeadroomGib * 1024 ** 3;
|
|
4326
4761
|
if (free - bytes < headroom) {
|
|
4327
4762
|
const gib = (n) => (n / 1024 ** 3).toFixed(1);
|
|
4328
|
-
|
|
4763
|
+
const needs = bytes === 0 ? "cannot be made:" : `needs ${gib(bytes)} GiB and`;
|
|
4764
|
+
throw new KvboxError(`${what} ${needs} this host has ${gib(free)} GiB free (keeping ${gib(headroom)} GiB spare); try again when it has room`);
|
|
4329
4765
|
}
|
|
4330
4766
|
}
|
|
4331
4767
|
function checkId(id) {
|
|
@@ -4340,22 +4776,22 @@ async function readBox2(ref, p) {
|
|
|
4340
4776
|
}
|
|
4341
4777
|
}
|
|
4342
4778
|
async function chunkNames(file, keys) {
|
|
4343
|
-
const { size } = await
|
|
4779
|
+
const { size: size2 } = await stat4(file);
|
|
4344
4780
|
const chunks = [];
|
|
4345
4781
|
const fh = await open(file, "r");
|
|
4346
4782
|
try {
|
|
4347
4783
|
const buf = Buffer.alloc(CHUNK_SIZE);
|
|
4348
|
-
for (let i = 0; i < chunkCount(
|
|
4349
|
-
const slot = await readSlot(fh, buf, i,
|
|
4784
|
+
for (let i = 0; i < chunkCount(size2); i++) {
|
|
4785
|
+
const slot = await readSlot(fh, buf, i, size2);
|
|
4350
4786
|
chunks.push(isZero(slot) ? null : chunkName(keys, slot));
|
|
4351
4787
|
}
|
|
4352
4788
|
} finally {
|
|
4353
4789
|
await fh.close();
|
|
4354
4790
|
}
|
|
4355
|
-
return { sizeBytes:
|
|
4791
|
+
return { sizeBytes: size2, chunks };
|
|
4356
4792
|
}
|
|
4357
|
-
async function readSlot(fh, buf, index,
|
|
4358
|
-
const length = Math.min(CHUNK_SIZE,
|
|
4793
|
+
async function readSlot(fh, buf, index, size2) {
|
|
4794
|
+
const length = Math.min(CHUNK_SIZE, size2 - index * CHUNK_SIZE);
|
|
4359
4795
|
let got = 0;
|
|
4360
4796
|
while (got < length) {
|
|
4361
4797
|
const { bytesRead } = await fh.read(buf, got, length - got, index * CHUNK_SIZE + got);
|
|
@@ -4368,13 +4804,13 @@ async function stageBackup(ref, req, p = paths()) {
|
|
|
4368
4804
|
checkId(req.id);
|
|
4369
4805
|
const keys = backupKeys(req.key);
|
|
4370
4806
|
const s = p.backup(req.id);
|
|
4371
|
-
await
|
|
4372
|
-
await
|
|
4807
|
+
await rm5(s.dir, { recursive: true, force: true });
|
|
4808
|
+
await mkdir7(s.dir, { recursive: true, mode: 448 });
|
|
4373
4809
|
try {
|
|
4374
4810
|
const { meta, envText } = await withBoxLock(ref, async () => {
|
|
4375
4811
|
const meta2 = await readBox2(ref, p);
|
|
4376
4812
|
const m = p.machine(meta2.owner, meta2.name);
|
|
4377
|
-
await assertRoom(s.dir,
|
|
4813
|
+
await assertRoom(s.dir, 0, `a backup of box ${shown(ref)}`, p);
|
|
4378
4814
|
const copy = () => run(["cp", "--sparse=always", "--reflink=auto", m.overlay, s.disk], { timeoutMs: 6e5 });
|
|
4379
4815
|
if (vmAlive(meta2) && !meta2.paused) {
|
|
4380
4816
|
const fc = new FirecrackerClient(m.sock);
|
|
@@ -4391,11 +4827,11 @@ async function stageBackup(ref, req, p = paths()) {
|
|
|
4391
4827
|
} else {
|
|
4392
4828
|
await copy();
|
|
4393
4829
|
}
|
|
4394
|
-
const envText2 =
|
|
4830
|
+
const envText2 = existsSync8(m.env) ? await readFile7(m.env, "utf8") : null;
|
|
4395
4831
|
return { meta: meta2, envText: envText2 };
|
|
4396
4832
|
});
|
|
4397
4833
|
const { sizeBytes, chunks } = await chunkNames(s.disk, keys);
|
|
4398
|
-
await
|
|
4834
|
+
await writeFile7(s.chunks, JSON.stringify({ chunks }), { mode: 384 });
|
|
4399
4835
|
return {
|
|
4400
4836
|
id: req.id,
|
|
4401
4837
|
sizeBytes,
|
|
@@ -4407,7 +4843,7 @@ async function stageBackup(ref, req, p = paths()) {
|
|
|
4407
4843
|
memMib: meta.memMib
|
|
4408
4844
|
};
|
|
4409
4845
|
} catch (err) {
|
|
4410
|
-
await
|
|
4846
|
+
await rm5(s.dir, { recursive: true, force: true });
|
|
4411
4847
|
throw err;
|
|
4412
4848
|
}
|
|
4413
4849
|
}
|
|
@@ -4441,9 +4877,9 @@ async function uploadBackup(id, req, p = paths()) {
|
|
|
4441
4877
|
}
|
|
4442
4878
|
async function uploadOnce(id, req, signal, p) {
|
|
4443
4879
|
const s = p.backup(id);
|
|
4444
|
-
if (!
|
|
4880
|
+
if (!existsSync8(s.chunks)) throw new NotFoundError(`backup ${id}`);
|
|
4445
4881
|
const keys = backupKeys(req.key);
|
|
4446
|
-
const { chunks } = JSON.parse(await
|
|
4882
|
+
const { chunks } = JSON.parse(await readFile7(s.chunks, "utf8"));
|
|
4447
4883
|
const slotOf = /* @__PURE__ */ new Map();
|
|
4448
4884
|
chunks.forEach((name, i) => {
|
|
4449
4885
|
if (name !== null && !slotOf.has(name)) slotOf.set(name, i);
|
|
@@ -4453,16 +4889,17 @@ async function uploadOnce(id, req, signal, p) {
|
|
|
4453
4889
|
if (index === void 0) throw new KvboxError(`backup ${id} has no chunk ${name.slice(0, 12)}`);
|
|
4454
4890
|
return { name, url, index };
|
|
4455
4891
|
});
|
|
4456
|
-
const { size } = await
|
|
4892
|
+
const { size: size2 } = await stat4(s.disk);
|
|
4893
|
+
const fetchChunk = await chunkFetcher(req.pin, work[0]?.url, p);
|
|
4457
4894
|
const fh = await open(s.disk, "r");
|
|
4458
4895
|
let bytes = 0;
|
|
4459
4896
|
const sizes = {};
|
|
4460
4897
|
try {
|
|
4461
4898
|
await pool(work, async ({ name, url, index }) => {
|
|
4462
|
-
const slot = Buffer.from(await readSlot(fh, Buffer.alloc(CHUNK_SIZE), index,
|
|
4899
|
+
const slot = Buffer.from(await readSlot(fh, Buffer.alloc(CHUNK_SIZE), index, size2));
|
|
4463
4900
|
const sealed = await sealChunk(keys, name, slot);
|
|
4464
4901
|
await withTries(`upload of chunk ${index}`, async () => {
|
|
4465
|
-
const res = await
|
|
4902
|
+
const res = await fetchChunk(url, { method: "PUT", body: sealed, signal: AbortSignal.any([signal, AbortSignal.timeout(CHUNK_TIMEOUT_MS)]) });
|
|
4466
4903
|
if (!res.ok) throw new Error(`storage answered ${res.status}: ${(await res.text()).slice(0, 200)}`);
|
|
4467
4904
|
}, signal);
|
|
4468
4905
|
bytes += sealed.length;
|
|
@@ -4471,36 +4908,37 @@ async function uploadOnce(id, req, signal, p) {
|
|
|
4471
4908
|
} finally {
|
|
4472
4909
|
await fh.close();
|
|
4473
4910
|
}
|
|
4474
|
-
await
|
|
4911
|
+
await rm5(s.dir, { recursive: true, force: true });
|
|
4475
4912
|
return { chunks: work.length, bytes, sizes };
|
|
4476
4913
|
}
|
|
4477
4914
|
async function dropBackup(id, p = paths()) {
|
|
4478
4915
|
checkId(id);
|
|
4479
4916
|
uploads.get(id)?.abort();
|
|
4480
|
-
await
|
|
4917
|
+
await rm5(p.backup(id).dir, { recursive: true, force: true });
|
|
4481
4918
|
}
|
|
4482
4919
|
async function clearStagedBackups(p = paths()) {
|
|
4483
|
-
await
|
|
4920
|
+
await rm5(p.backups, { recursive: true, force: true });
|
|
4484
4921
|
const prefix = basename2(p.machine("x", "x").restoring);
|
|
4485
4922
|
for (const ref of await listMachineRefs(p)) {
|
|
4486
4923
|
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
|
|
4924
|
+
for (const f of await readdir6(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await rm5(join3(dir, f), { force: true });
|
|
4488
4925
|
}
|
|
4489
4926
|
}
|
|
4490
|
-
async function downloadDisk(file, req) {
|
|
4927
|
+
async function downloadDisk(file, req, p = paths()) {
|
|
4491
4928
|
const keys = backupKeys(req.key);
|
|
4492
4929
|
const slots = chunkCount(req.sizeBytes);
|
|
4493
4930
|
for (const c of req.chunks) {
|
|
4494
4931
|
if (c.index >= slots) throw new KvboxError(`chunk ${c.index} is past the end of a ${req.sizeBytes}-byte disk`);
|
|
4495
4932
|
if (!CHUNK_HASH_RE.test(c.hash)) throw new KvboxError(`chunk ${c.index}: not a chunk name`);
|
|
4496
4933
|
}
|
|
4497
|
-
await
|
|
4934
|
+
const fetchChunk = await chunkFetcher(req.pin, req.chunks[0]?.url, p);
|
|
4935
|
+
await writeFile7(file, "", { mode: 384 });
|
|
4498
4936
|
const fh = await open(file, "r+");
|
|
4499
4937
|
try {
|
|
4500
4938
|
await fh.truncate(req.sizeBytes);
|
|
4501
4939
|
await pool(req.chunks, async ({ index, hash, url }) => {
|
|
4502
4940
|
const plain = await withTries(`download of chunk ${index}`, async () => {
|
|
4503
|
-
const res = await
|
|
4941
|
+
const res = await fetchChunk(url, { signal: AbortSignal.timeout(CHUNK_TIMEOUT_MS) });
|
|
4504
4942
|
if (!res.ok) throw new Error(`storage answered ${res.status}`);
|
|
4505
4943
|
return Buffer.from(await res.arrayBuffer());
|
|
4506
4944
|
});
|
|
@@ -4530,34 +4968,34 @@ async function restoreBackup(ref, req, p = paths()) {
|
|
|
4530
4968
|
}
|
|
4531
4969
|
async function restoreOnce(ref, req, p) {
|
|
4532
4970
|
const meta = await readBox2(ref, p);
|
|
4533
|
-
if (!vmAlive(meta) &&
|
|
4971
|
+
if (!vmAlive(meta) && existsSync8(p.machine(ref.owner, ref.name).hibernateVmstate)) {
|
|
4534
4972
|
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
4973
|
}
|
|
4536
|
-
if (!
|
|
4974
|
+
if (!existsSync8(imageFile(req.image, req.base, p))) {
|
|
4537
4975
|
throw new KvboxError(`this backup stacks on ${imageLabel(req.image)} ${req.base}, which this host does not have`);
|
|
4538
4976
|
}
|
|
4539
4977
|
const keys = backupKeys(req.key);
|
|
4540
4978
|
const m = p.machine(ref.owner, ref.name);
|
|
4541
|
-
const current = (await
|
|
4979
|
+
const current = (await stat4(m.overlay)).size;
|
|
4542
4980
|
if (req.sizeBytes > current) {
|
|
4543
4981
|
const gb2 = (n) => `${Math.ceil(n / 1024 ** 3)}GB`;
|
|
4544
4982
|
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
4983
|
}
|
|
4546
|
-
const file = `${m.restoring}.${
|
|
4984
|
+
const file = `${m.restoring}.${randomBytes5(4).toString("hex")}`;
|
|
4547
4985
|
const envFile = `${file}.env`;
|
|
4548
4986
|
try {
|
|
4549
4987
|
let vars = null;
|
|
4550
4988
|
if (req.env !== null) {
|
|
4551
|
-
await
|
|
4989
|
+
await writeFile7(envFile, openText(keys, req.env, `env:${req.id}`), { mode: 384 });
|
|
4552
4990
|
vars = await readBoxEnvFile(envFile);
|
|
4553
4991
|
checkBoxEnv(vars);
|
|
4554
4992
|
}
|
|
4555
4993
|
await assertRoom(m.dir, req.chunks.length * CHUNK_SIZE, `a restore of box ${shown(ref)}`, p);
|
|
4556
|
-
await downloadDisk(file, req);
|
|
4994
|
+
await downloadDisk(file, req, p);
|
|
4557
4995
|
return await replaceDisk(ref, file, { base: req.base, image: req.image, vars }, p);
|
|
4558
4996
|
} finally {
|
|
4559
|
-
await
|
|
4560
|
-
await
|
|
4997
|
+
await rm5(file, { force: true });
|
|
4998
|
+
await rm5(envFile, { force: true });
|
|
4561
4999
|
}
|
|
4562
5000
|
}
|
|
4563
5001
|
async function pool(items, fn) {
|
|
@@ -4585,14 +5023,14 @@ async function withTries(what, fn, signal) {
|
|
|
4585
5023
|
} catch (err) {
|
|
4586
5024
|
if (signal?.aborted) throw new KvboxError(`${what}: the backup was dropped`);
|
|
4587
5025
|
last = err;
|
|
4588
|
-
await
|
|
5026
|
+
await sleep3(250 * 2 ** i);
|
|
4589
5027
|
}
|
|
4590
5028
|
}
|
|
4591
5029
|
throw new KvboxError(`${what} failed ${TRIES} times: ${last.message}`);
|
|
4592
5030
|
}
|
|
4593
5031
|
|
|
4594
5032
|
// src/core/relay.ts
|
|
4595
|
-
import { access as access2, chmod as
|
|
5033
|
+
import { access as access2, chmod as chmod4, mkdir as mkdir9, rm as rm6, writeFile as writeFile8 } from "node:fs/promises";
|
|
4596
5034
|
|
|
4597
5035
|
// ../shared/src/relay.ts
|
|
4598
5036
|
import { z as z7 } from "zod";
|
|
@@ -4627,9 +5065,9 @@ function decodeRelayJoin(text) {
|
|
|
4627
5065
|
|
|
4628
5066
|
// src/core/controlPlane.ts
|
|
4629
5067
|
import { X509Certificate } from "node:crypto";
|
|
4630
|
-
import { chmod as
|
|
5068
|
+
import { chmod as chmod3, mkdir as mkdir8, readFile as readFile8 } from "node:fs/promises";
|
|
4631
5069
|
import { hostname as osHostname } from "node:os";
|
|
4632
|
-
import { request as
|
|
5070
|
+
import { request as request3 } from "undici";
|
|
4633
5071
|
|
|
4634
5072
|
// ../shared/src/country.ts
|
|
4635
5073
|
var names = new Intl.DisplayNames(["en"], { type: "region", fallback: "none" });
|
|
@@ -4667,10 +5105,10 @@ function parseCountry(input) {
|
|
|
4667
5105
|
// src/core/controlPlane.ts
|
|
4668
5106
|
var DEFAULT_HTTPS_PORT = 7777;
|
|
4669
5107
|
async function ensureTlsCert(p = paths()) {
|
|
4670
|
-
const have = await
|
|
4671
|
-
const haveKey = await
|
|
5108
|
+
const have = await readFile8(p.tlsCert, "utf8").catch(() => null);
|
|
5109
|
+
const haveKey = await readFile8(p.tlsKey).then(() => true, () => false);
|
|
4672
5110
|
if (have === null || !haveKey) {
|
|
4673
|
-
await
|
|
5111
|
+
await mkdir8(p.tls, { recursive: true, mode: 448 });
|
|
4674
5112
|
try {
|
|
4675
5113
|
await run([
|
|
4676
5114
|
"openssl",
|
|
@@ -4693,9 +5131,9 @@ async function ensureTlsCert(p = paths()) {
|
|
|
4693
5131
|
} catch (err) {
|
|
4694
5132
|
throw new KvboxError(`could not make the host's certificate (is openssl installed?): ${err.message}`);
|
|
4695
5133
|
}
|
|
4696
|
-
await
|
|
5134
|
+
await chmod3(p.tlsKey, 384);
|
|
4697
5135
|
}
|
|
4698
|
-
const pem = await
|
|
5136
|
+
const pem = await readFile8(p.tlsCert, "utf8");
|
|
4699
5137
|
return { fingerprint: new X509Certificate(pem).fingerprint256 };
|
|
4700
5138
|
}
|
|
4701
5139
|
function isPrivateAddress(ip) {
|
|
@@ -4734,7 +5172,7 @@ async function joinControlPlane(opts, p = paths(), guessAddress = defaultAdverti
|
|
|
4734
5172
|
const { fingerprint } = await ensureTlsCert(p);
|
|
4735
5173
|
const hostUrl = `https://${advertise}:${port}`;
|
|
4736
5174
|
const body = { token: opts.token, name, url: hostUrl, fingerprint, publicAddress: advertise, ...country !== void 0 ? { country } : {} };
|
|
4737
|
-
const res = await
|
|
5175
|
+
const res = await request3(`${url}/hosts/join`, {
|
|
4738
5176
|
method: "POST",
|
|
4739
5177
|
headers: { "content-type": "application/json" },
|
|
4740
5178
|
body: JSON.stringify(body),
|
|
@@ -4759,7 +5197,7 @@ async function fetchCloudCa(p = paths()) {
|
|
|
4759
5197
|
const cfg = await loadConfig(p);
|
|
4760
5198
|
const cp = cfg.controlPlane;
|
|
4761
5199
|
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
|
|
5200
|
+
const res = await request3(`${cp.url}/hosts/self/ssh-ca`, {
|
|
4763
5201
|
headers: { authorization: `Bearer ${cp.secret}` },
|
|
4764
5202
|
headersTimeout: 1e4,
|
|
4765
5203
|
bodyTimeout: 1e4
|
|
@@ -4778,7 +5216,7 @@ async function leaveControlPlane(p = paths()) {
|
|
|
4778
5216
|
const cfg = await loadConfig(p);
|
|
4779
5217
|
const cp = cfg.controlPlane;
|
|
4780
5218
|
if (!cp) throw new KvboxError("this host has not joined a control plane");
|
|
4781
|
-
const told = await
|
|
5219
|
+
const told = await request3(`${cp.url}/hosts/self`, {
|
|
4782
5220
|
method: "DELETE",
|
|
4783
5221
|
headers: { authorization: `Bearer ${cp.secret}` },
|
|
4784
5222
|
headersTimeout: 3e3,
|
|
@@ -4788,7 +5226,7 @@ async function leaveControlPlane(p = paths()) {
|
|
|
4788
5226
|
return res.statusCode >= 200 && res.statusCode < 300;
|
|
4789
5227
|
}).catch(() => false);
|
|
4790
5228
|
const { controlPlane: _gone, ...rest } = cfg;
|
|
4791
|
-
await saveConfig(rest, p);
|
|
5229
|
+
await saveConfig({ ...rest, ...rest.backupStore ? { backupStore: { ...rest.backupStore, registered: false } } : {} }, p);
|
|
4792
5230
|
return { controlPlane: cp.name, told };
|
|
4793
5231
|
}
|
|
4794
5232
|
function jsonOrNull(text) {
|
|
@@ -4805,16 +5243,16 @@ function errorIn(text) {
|
|
|
4805
5243
|
}
|
|
4806
5244
|
|
|
4807
5245
|
// src/core/relay.ts
|
|
4808
|
-
function relayConf(
|
|
5246
|
+
function relayConf(join4) {
|
|
4809
5247
|
return [
|
|
4810
5248
|
"# kvbox relay tunnel: made by `kvbox-server relay`, installed by net-setup.sh. Do not edit.",
|
|
4811
5249
|
"[Interface]",
|
|
4812
|
-
`PrivateKey = ${
|
|
4813
|
-
`Address = ${
|
|
5250
|
+
`PrivateKey = ${join4.privateKey}`,
|
|
5251
|
+
`Address = ${join4.tunnelIp}/32`,
|
|
4814
5252
|
"",
|
|
4815
5253
|
"[Peer]",
|
|
4816
|
-
`PublicKey = ${
|
|
4817
|
-
`Endpoint = ${
|
|
5254
|
+
`PublicKey = ${join4.relayKey}`,
|
|
5255
|
+
`Endpoint = ${join4.relay}`,
|
|
4818
5256
|
// Only the relay's own tunnel address goes through the tunnel: the host keeps its normal internet
|
|
4819
5257
|
// route, and the relay SNATs forwarded connections so their replies come back this way.
|
|
4820
5258
|
`AllowedIPs = ${RELAY_TUNNEL_GATEWAY}/32`,
|
|
@@ -4824,22 +5262,22 @@ function relayConf(join3) {
|
|
|
4824
5262
|
].join("\n");
|
|
4825
5263
|
}
|
|
4826
5264
|
async function useRelay(joinString, p = paths()) {
|
|
4827
|
-
const
|
|
4828
|
-
if (!
|
|
5265
|
+
const join4 = decodeRelayJoin(joinString);
|
|
5266
|
+
if (!join4) throw new KvboxError("that is not a relay join string; copy the whole line `kvbox-relay add` printed on the relay");
|
|
4829
5267
|
const cfg = await loadConfig(p);
|
|
4830
|
-
if (cfg.relay && cfg.relay.name !==
|
|
5268
|
+
if (cfg.relay && cfg.relay.name !== join4.name) {
|
|
4831
5269
|
throw new KvboxError(`this host already goes through relay ${cfg.relay.name} (${cfg.relay.publicIp}); run kvbox-server relay off first`);
|
|
4832
5270
|
}
|
|
4833
|
-
if (cfg.relay && cfg.relay.publicIp !==
|
|
5271
|
+
if (cfg.relay && cfg.relay.publicIp !== join4.publicIp && cfg.controlPlane?.advertise === cfg.relay.publicIp) {
|
|
4834
5272
|
throw new KvboxError(
|
|
4835
|
-
`${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${
|
|
5273
|
+
`${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${join4.publicIp}; run kvbox-server leave first, then join again`
|
|
4836
5274
|
);
|
|
4837
5275
|
}
|
|
4838
|
-
await
|
|
4839
|
-
await
|
|
4840
|
-
await
|
|
5276
|
+
await mkdir9(p.relay, { recursive: true, mode: 448 });
|
|
5277
|
+
await writeFile8(p.relayConf, relayConf(join4), { mode: 384 });
|
|
5278
|
+
await chmod4(p.relayConf, 384);
|
|
4841
5279
|
await netSetup(cfg, ["relay", "up", p.relayConf, String(cfg.controlPlane?.port ?? DEFAULT_HTTPS_PORT)]);
|
|
4842
|
-
const relay = { name:
|
|
5280
|
+
const relay = { name: join4.name, publicIp: join4.publicIp, tunnelIp: join4.tunnelIp, endpoint: join4.relay };
|
|
4843
5281
|
await saveConfig({ ...cfg, relay }, p);
|
|
4844
5282
|
return relay;
|
|
4845
5283
|
}
|
|
@@ -4858,19 +5296,19 @@ async function dropRelay(p = paths()) {
|
|
|
4858
5296
|
throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox-server leave first`);
|
|
4859
5297
|
}
|
|
4860
5298
|
await netSetup(cfg, ["relay", "down"]);
|
|
4861
|
-
await
|
|
5299
|
+
await rm6(p.relayConf, { force: true });
|
|
4862
5300
|
const { relay: _gone, ...rest } = cfg;
|
|
4863
5301
|
await saveConfig(rest, p);
|
|
4864
5302
|
return relay;
|
|
4865
5303
|
}
|
|
4866
5304
|
|
|
4867
5305
|
// src/core/idle.ts
|
|
4868
|
-
import { readFile as
|
|
5306
|
+
import { readFile as readFile9 } from "node:fs/promises";
|
|
4869
5307
|
var HIBERNATE_CONCURRENCY = 2;
|
|
4870
5308
|
async function tapTraffic(id) {
|
|
4871
5309
|
const dir = `/sys/class/net/${tapName(id)}/statistics`;
|
|
4872
5310
|
try {
|
|
4873
|
-
const [rx, tx] = await Promise.all([
|
|
5311
|
+
const [rx, tx] = await Promise.all([readFile9(`${dir}/rx_bytes`, "utf8"), readFile9(`${dir}/tx_bytes`, "utf8")]);
|
|
4874
5312
|
return Number(rx) + Number(tx);
|
|
4875
5313
|
} catch {
|
|
4876
5314
|
return null;
|
|
@@ -5034,9 +5472,9 @@ function startRelayWatch(opts = {}) {
|
|
|
5034
5472
|
// src/daemon.ts
|
|
5035
5473
|
import { spawn as spawn3 } from "node:child_process";
|
|
5036
5474
|
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
|
|
5475
|
+
import { mkdir as mkdir10, readFile as readFile10, stat as stat5 } from "node:fs/promises";
|
|
5476
|
+
import { userInfo as userInfo3 } from "node:os";
|
|
5477
|
+
import { setTimeout as sleep4 } from "node:timers/promises";
|
|
5040
5478
|
|
|
5041
5479
|
// ../shared/src/systemd.ts
|
|
5042
5480
|
import { spawnSync } from "node:child_process";
|
|
@@ -5072,11 +5510,11 @@ function startsAtBoot(p) {
|
|
|
5072
5510
|
}
|
|
5073
5511
|
|
|
5074
5512
|
// src/socketClient.ts
|
|
5075
|
-
import { Agent as
|
|
5513
|
+
import { Agent as Agent3, request as request4 } from "undici";
|
|
5076
5514
|
var SocketClient = class {
|
|
5077
5515
|
agent;
|
|
5078
5516
|
constructor(socketPath) {
|
|
5079
|
-
this.agent = new
|
|
5517
|
+
this.agent = new Agent3({ connect: { socketPath } });
|
|
5080
5518
|
}
|
|
5081
5519
|
health() {
|
|
5082
5520
|
return this.call("GET", "/health", HealthSchema);
|
|
@@ -5087,15 +5525,23 @@ var SocketClient = class {
|
|
|
5087
5525
|
trustCa(req) {
|
|
5088
5526
|
return this.call("POST", "/ssh/trust-ca", TrustCaReportSchema, req);
|
|
5089
5527
|
}
|
|
5528
|
+
backupStore() {
|
|
5529
|
+
return this.call("GET", "/backup-store", BackupStoreStatusSchema);
|
|
5530
|
+
}
|
|
5531
|
+
/** Downloads Garage the first time, so it may take minutes. */
|
|
5532
|
+
setupBackupStore(req) {
|
|
5533
|
+
return this.call("POST", "/backup-store", BackupStoreStatusSchema, req, 15 * 6e4);
|
|
5534
|
+
}
|
|
5090
5535
|
async close() {
|
|
5091
5536
|
await this.agent.close();
|
|
5092
5537
|
}
|
|
5093
|
-
async call(method, path, schema, body) {
|
|
5538
|
+
async call(method, path, schema, body, timeoutMs) {
|
|
5094
5539
|
let res;
|
|
5095
5540
|
try {
|
|
5096
|
-
res = await
|
|
5541
|
+
res = await request4(`http://kvbox-server${path}`, {
|
|
5097
5542
|
method,
|
|
5098
5543
|
dispatcher: this.agent,
|
|
5544
|
+
...timeoutMs === void 0 ? {} : { headersTimeout: timeoutMs, bodyTimeout: timeoutMs },
|
|
5099
5545
|
...body === void 0 ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }
|
|
5100
5546
|
});
|
|
5101
5547
|
} catch (err) {
|
|
@@ -5126,7 +5572,7 @@ function safeJson(text) {
|
|
|
5126
5572
|
async function runningPid(p = paths()) {
|
|
5127
5573
|
let pid;
|
|
5128
5574
|
try {
|
|
5129
|
-
pid = Number.parseInt(await
|
|
5575
|
+
pid = Number.parseInt(await readFile10(p.serverPid, "utf8"), 10);
|
|
5130
5576
|
} catch {
|
|
5131
5577
|
return null;
|
|
5132
5578
|
}
|
|
@@ -5163,11 +5609,11 @@ async function stopDaemon(pid, timeoutMs = 1e4) {
|
|
|
5163
5609
|
const deadline = Date.now() + timeoutMs;
|
|
5164
5610
|
while (alive(pid)) {
|
|
5165
5611
|
if (Date.now() > deadline) throw new KvboxError(`kvbox-server (pid ${pid}) did not stop within ${timeoutMs / 1e3}s`);
|
|
5166
|
-
await
|
|
5612
|
+
await sleep4(100);
|
|
5167
5613
|
}
|
|
5168
5614
|
}
|
|
5169
5615
|
async function answering(p = paths()) {
|
|
5170
|
-
if (!await
|
|
5616
|
+
if (!await stat5(p.serverSock).then(() => true, () => false)) return null;
|
|
5171
5617
|
const probe = new SocketClient(p.serverSock);
|
|
5172
5618
|
try {
|
|
5173
5619
|
const health = await probe.health();
|
|
@@ -5179,7 +5625,7 @@ async function answering(p = paths()) {
|
|
|
5179
5625
|
}
|
|
5180
5626
|
}
|
|
5181
5627
|
async function startDetached(p = paths(), timeoutMs = 5e3) {
|
|
5182
|
-
await
|
|
5628
|
+
await mkdir10(p.home, { recursive: true });
|
|
5183
5629
|
const running = await answering(p);
|
|
5184
5630
|
if (running) return { pid: running.pid, socketPath: p.serverSock, viaGroup: void 0, viaUnit: false, alreadyRunning: running.version };
|
|
5185
5631
|
if (hasUnitFor(p)) return startUnit(p, timeoutMs);
|
|
@@ -5205,7 +5651,7 @@ async function restartDaemon(p = paths()) {
|
|
|
5205
5651
|
return startDetached(p);
|
|
5206
5652
|
}
|
|
5207
5653
|
async function startUnit(p, timeoutMs) {
|
|
5208
|
-
const logFrom = await
|
|
5654
|
+
const logFrom = await stat5(p.serverLog).then((s) => s.size, () => 0);
|
|
5209
5655
|
const res = startUnitProcess();
|
|
5210
5656
|
if (!res.ok) {
|
|
5211
5657
|
const why = res.out || await lastErrorLine(p.serverLog, logFrom) || "systemctl start failed";
|
|
@@ -5219,14 +5665,14 @@ async function startUnit(p, timeoutMs) {
|
|
|
5219
5665
|
return { pid: await pidFile(p, -1), socketPath: p.serverSock, viaGroup: void 0, viaUnit: true };
|
|
5220
5666
|
}
|
|
5221
5667
|
async function pidFile(p, fallback) {
|
|
5222
|
-
const pid = Number.parseInt(await
|
|
5668
|
+
const pid = Number.parseInt(await readFile10(p.serverPid, "utf8").catch(() => ""), 10);
|
|
5223
5669
|
return Number.isNaN(pid) ? fallback : pid;
|
|
5224
5670
|
}
|
|
5225
5671
|
async function serving(p, timeoutMs, check) {
|
|
5226
5672
|
const deadline = Date.now() + timeoutMs;
|
|
5227
5673
|
while (Date.now() < deadline) {
|
|
5228
5674
|
await check?.();
|
|
5229
|
-
if (await
|
|
5675
|
+
if (await stat5(p.serverSock).then(() => true, () => false)) {
|
|
5230
5676
|
const probe = new SocketClient(p.serverSock);
|
|
5231
5677
|
try {
|
|
5232
5678
|
await probe.health();
|
|
@@ -5236,12 +5682,12 @@ async function serving(p, timeoutMs, check) {
|
|
|
5236
5682
|
await probe.close();
|
|
5237
5683
|
}
|
|
5238
5684
|
}
|
|
5239
|
-
await
|
|
5685
|
+
await sleep4(100);
|
|
5240
5686
|
}
|
|
5241
5687
|
throw new KvboxError(`kvbox-server did not start within ${timeoutMs / 1e3}s; see ${p.serverLog}`);
|
|
5242
5688
|
}
|
|
5243
5689
|
async function lastErrorLine(logPath, from = 0) {
|
|
5244
|
-
const text = (await
|
|
5690
|
+
const text = (await readFile10(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString("utf8");
|
|
5245
5691
|
for (const line of text.trimEnd().split("\n").slice(-20).reverse()) {
|
|
5246
5692
|
const m = /^(?:\[[^\]]*\])?\[?error\]?: (.*)$/.exec(line);
|
|
5247
5693
|
if (m?.[1] !== void 0) return m[1];
|
|
@@ -5265,7 +5711,7 @@ function selfLauncher(opts = {}) {
|
|
|
5265
5711
|
} catch {
|
|
5266
5712
|
return plain;
|
|
5267
5713
|
}
|
|
5268
|
-
const group = groupWithMember(gid, opts.user ??
|
|
5714
|
+
const group = groupWithMember(gid, opts.user ?? userInfo3().username, opts.groupFile ?? "/etc/group");
|
|
5269
5715
|
if (group === void 0) return plain;
|
|
5270
5716
|
return { cmd: "sg", args: [group, "-c", argv.map(shellQuote).join(" ")], viaGroup: group };
|
|
5271
5717
|
}
|
|
@@ -5288,7 +5734,7 @@ function groupWithMember(gid, user, groupFile) {
|
|
|
5288
5734
|
}
|
|
5289
5735
|
|
|
5290
5736
|
// src/listen.ts
|
|
5291
|
-
import { readFile as
|
|
5737
|
+
import { readFile as readFile12, rm as rm7, writeFile as writeFile10 } from "node:fs/promises";
|
|
5292
5738
|
import { createServer as createHttpsServer } from "node:https";
|
|
5293
5739
|
import { createAdaptorServer } from "@hono/node-server";
|
|
5294
5740
|
|
|
@@ -5310,7 +5756,7 @@ function edgeCredential(hostSecret) {
|
|
|
5310
5756
|
}
|
|
5311
5757
|
|
|
5312
5758
|
// src/app.ts
|
|
5313
|
-
import { Hono as
|
|
5759
|
+
import { Hono as Hono11 } from "hono";
|
|
5314
5760
|
|
|
5315
5761
|
// ../shared/src/version.ts
|
|
5316
5762
|
import { createRequire } from "node:module";
|
|
@@ -5325,10 +5771,10 @@ function versionOf(srcFileUrl, injected) {
|
|
|
5325
5771
|
}
|
|
5326
5772
|
|
|
5327
5773
|
// src/version.ts
|
|
5328
|
-
var VERSION = versionOf(import.meta.url, true ? "0.
|
|
5774
|
+
var VERSION = versionOf(import.meta.url, true ? "0.6.0" : void 0);
|
|
5329
5775
|
|
|
5330
5776
|
// src/caller.ts
|
|
5331
|
-
import { createHash as
|
|
5777
|
+
import { createHash as createHash3, timingSafeEqual } from "node:crypto";
|
|
5332
5778
|
var OWNER_HEADER = "x-kvbox-owner";
|
|
5333
5779
|
function resolveCaller(opts = {}) {
|
|
5334
5780
|
const cp = opts.controlPlane;
|
|
@@ -5377,17 +5823,17 @@ function bearerCheck(token) {
|
|
|
5377
5823
|
};
|
|
5378
5824
|
}
|
|
5379
5825
|
function digest(secret) {
|
|
5380
|
-
return
|
|
5826
|
+
return createHash3("sha256").update(secret).digest();
|
|
5381
5827
|
}
|
|
5382
5828
|
|
|
5383
5829
|
// src/core/update.ts
|
|
5384
|
-
import { mkdir as
|
|
5830
|
+
import { mkdir as mkdir11, readFile as readFile11, writeFile as writeFile9 } from "node:fs/promises";
|
|
5385
5831
|
var INSTALL_SERVER_URL = "https://kvbox.sh/install-server.sh";
|
|
5386
5832
|
var UPDATE_STALE_MS = 60 * 6e4;
|
|
5387
5833
|
async function readUpdateState(p = paths(), now = Date.now()) {
|
|
5388
5834
|
let raw;
|
|
5389
5835
|
try {
|
|
5390
|
-
raw = JSON.parse(await
|
|
5836
|
+
raw = JSON.parse(await readFile11(p.updateState, "utf8"));
|
|
5391
5837
|
} catch {
|
|
5392
5838
|
return null;
|
|
5393
5839
|
}
|
|
@@ -5407,19 +5853,19 @@ async function startUpdate(version, p = paths(), deps = {}) {
|
|
|
5407
5853
|
if (!res.ok) throw new KvboxError(`could not download ${url}: HTTP ${res.status}`);
|
|
5408
5854
|
const script = await res.text();
|
|
5409
5855
|
if (!script.startsWith("#!") || !script.includes("--update")) throw new KvboxError(`${url} is not an install-server.sh that knows --update`);
|
|
5410
|
-
await
|
|
5411
|
-
await
|
|
5856
|
+
await mkdir11(p.updateDir, { recursive: true });
|
|
5857
|
+
await writeFile9(p.updateScript, script, { mode: 448 });
|
|
5412
5858
|
const state = { state: "running", startedAt: (/* @__PURE__ */ new Date()).toISOString(), finishedAt: null, from: version, to: null, error: null, needsManual: [] };
|
|
5413
|
-
await
|
|
5859
|
+
await writeFile9(p.updateState, `${JSON.stringify(state, null, 2)}
|
|
5414
5860
|
`);
|
|
5415
|
-
await
|
|
5861
|
+
await writeFile9(p.updateLog, `--- ${state.startedAt} update from ${version}, ${url}
|
|
5416
5862
|
`, { flag: "a" });
|
|
5417
5863
|
const env = { ...process.env, KVBOX_HOME: p.home, KVBOX_YES: "1" };
|
|
5418
5864
|
try {
|
|
5419
5865
|
await (deps.spawn ?? spawnDetached)(["bash", p.updateScript, "--update"], p.updateLog, env);
|
|
5420
5866
|
} catch (err) {
|
|
5421
5867
|
const failed = { ...state, state: "failed", finishedAt: (/* @__PURE__ */ new Date()).toISOString(), error: err.message };
|
|
5422
|
-
await
|
|
5868
|
+
await writeFile9(p.updateState, `${JSON.stringify(failed, null, 2)}
|
|
5423
5869
|
`);
|
|
5424
5870
|
throw err;
|
|
5425
5871
|
}
|
|
@@ -5457,18 +5903,35 @@ function backupRoutes() {
|
|
|
5457
5903
|
return r;
|
|
5458
5904
|
}
|
|
5459
5905
|
|
|
5906
|
+
// src/routes/backupStore.ts
|
|
5907
|
+
import { Hono as Hono2 } from "hono";
|
|
5908
|
+
function backupStoreRoutes(opts = {}) {
|
|
5909
|
+
const r = new Hono2();
|
|
5910
|
+
if (opts.controlPlane) {
|
|
5911
|
+
r.all("/*", (c) => c.json({ error: "a backup store is set up on the host itself (kvbox-server backup setup there)" }, 403));
|
|
5912
|
+
return r;
|
|
5913
|
+
}
|
|
5914
|
+
r.get("/", async (c) => c.json(await backupStoreStatus()));
|
|
5915
|
+
r.post("/", async (c) => {
|
|
5916
|
+
const body = BackupStoreSetupRequest.safeParse(await c.req.json().catch(() => ({})));
|
|
5917
|
+
if (!body.success) throw new KvboxError("backup setup: expected the directory as path");
|
|
5918
|
+
return c.json(await setupBackupStore(body.data));
|
|
5919
|
+
});
|
|
5920
|
+
return r;
|
|
5921
|
+
}
|
|
5922
|
+
|
|
5460
5923
|
// src/routes/boxHttp.ts
|
|
5461
5924
|
import { connect as connect2 } from "node:net";
|
|
5462
5925
|
import { Readable } from "node:stream";
|
|
5463
|
-
import { Hono as
|
|
5464
|
-
import { request as
|
|
5926
|
+
import { Hono as Hono3 } from "hono";
|
|
5927
|
+
import { request as request5 } from "undici";
|
|
5465
5928
|
|
|
5466
5929
|
// ../shared/src/httpHead.ts
|
|
5467
5930
|
var END = "\r\n\r\n";
|
|
5468
5931
|
var HeadTimeoutError = class extends Error {
|
|
5469
5932
|
};
|
|
5470
5933
|
function readHead(socket, opts) {
|
|
5471
|
-
return new Promise((
|
|
5934
|
+
return new Promise((resolve3, reject) => {
|
|
5472
5935
|
let bytes = Buffer.alloc(0);
|
|
5473
5936
|
const done = (err) => {
|
|
5474
5937
|
clearTimeout(timer);
|
|
@@ -5477,7 +5940,7 @@ function readHead(socket, opts) {
|
|
|
5477
5940
|
socket.pause();
|
|
5478
5941
|
if (err) return reject(err);
|
|
5479
5942
|
const end = bytes.indexOf(END);
|
|
5480
|
-
|
|
5943
|
+
resolve3({ head: bytes.subarray(0, end).toString("latin1"), rest: bytes.subarray(end + END.length) });
|
|
5481
5944
|
};
|
|
5482
5945
|
const onData = (chunk) => {
|
|
5483
5946
|
bytes = Buffer.concat([bytes, chunk]);
|
|
@@ -5586,7 +6049,7 @@ function boxHeaders(incoming, target, upgrade = false) {
|
|
|
5586
6049
|
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
6050
|
var wants = (value) => value === "1";
|
|
5588
6051
|
function boxHttpRoutes(wake = wakeBox) {
|
|
5589
|
-
const r = new
|
|
6052
|
+
const r = new Hono3();
|
|
5590
6053
|
r.all("/:name/http/:port", (c) => forward(c, wake));
|
|
5591
6054
|
return r;
|
|
5592
6055
|
}
|
|
@@ -5603,7 +6066,7 @@ async function forward(c, wake) {
|
|
|
5603
6066
|
raw.headers.forEach((value, name) => pairs.push([name, value]));
|
|
5604
6067
|
let res;
|
|
5605
6068
|
try {
|
|
5606
|
-
res = await
|
|
6069
|
+
res = await request5(`http://${target.ip}:${target.port}${target.path}`, {
|
|
5607
6070
|
method: raw.method,
|
|
5608
6071
|
headers: boxHeaders(pairs, target).flat(),
|
|
5609
6072
|
body: raw.body === null ? null : Readable.fromWeb(raw.body),
|
|
@@ -5705,17 +6168,17 @@ ${lines.join("")}\r
|
|
|
5705
6168
|
}
|
|
5706
6169
|
|
|
5707
6170
|
// src/routes/capacity.ts
|
|
5708
|
-
import { Hono as
|
|
6171
|
+
import { Hono as Hono4 } from "hono";
|
|
5709
6172
|
function capacityRoutes() {
|
|
5710
|
-
const r = new
|
|
6173
|
+
const r = new Hono4();
|
|
5711
6174
|
r.get("/", async (c) => c.json({ ...await capacity(), version: VERSION }));
|
|
5712
6175
|
return r;
|
|
5713
6176
|
}
|
|
5714
6177
|
|
|
5715
6178
|
// src/routes/env.ts
|
|
5716
|
-
import { Hono as
|
|
6179
|
+
import { Hono as Hono5 } from "hono";
|
|
5717
6180
|
function envRoutes() {
|
|
5718
|
-
const r = new
|
|
6181
|
+
const r = new Hono5();
|
|
5719
6182
|
r.get("/", async (c) => c.json(await listEnvVersions(c.get("listScope"))));
|
|
5720
6183
|
r.post("/", async (c) => {
|
|
5721
6184
|
const body = HostEnvRequest.safeParse(await c.req.json().catch(() => ({})));
|
|
@@ -5726,7 +6189,7 @@ function envRoutes() {
|
|
|
5726
6189
|
}
|
|
5727
6190
|
|
|
5728
6191
|
// src/routes/machines.ts
|
|
5729
|
-
import { Hono as
|
|
6192
|
+
import { Hono as Hono6 } from "hono";
|
|
5730
6193
|
|
|
5731
6194
|
// src/core/stats.ts
|
|
5732
6195
|
var STATS_REPLY_MS = 3e3;
|
|
@@ -5781,7 +6244,7 @@ async function usageReport(scope, window, p = paths()) {
|
|
|
5781
6244
|
|
|
5782
6245
|
// src/routes/machines.ts
|
|
5783
6246
|
function machineRoutes() {
|
|
5784
|
-
const r = new
|
|
6247
|
+
const r = new Hono6();
|
|
5785
6248
|
r.get("/", async (c) => c.json(await listMachines(c.get("listScope"))));
|
|
5786
6249
|
r.post("/", async (c) => {
|
|
5787
6250
|
const body = CreateMachineRequest.parse(await c.req.json().catch(() => ({})));
|
|
@@ -5883,9 +6346,9 @@ function machineRoutes() {
|
|
|
5883
6346
|
}
|
|
5884
6347
|
|
|
5885
6348
|
// src/routes/snapshots.ts
|
|
5886
|
-
import { Hono as
|
|
6349
|
+
import { Hono as Hono7 } from "hono";
|
|
5887
6350
|
function snapshotRoutes() {
|
|
5888
|
-
const r = new
|
|
6351
|
+
const r = new Hono7();
|
|
5889
6352
|
r.get("/", async (c) => c.json(await listSnapshots(c.get("listScope"))));
|
|
5890
6353
|
r.post("/", async (c) => {
|
|
5891
6354
|
const body = CreateSnapshotRequest.parse(await c.req.json());
|
|
@@ -5899,9 +6362,9 @@ function snapshotRoutes() {
|
|
|
5899
6362
|
}
|
|
5900
6363
|
|
|
5901
6364
|
// src/routes/ssh.ts
|
|
5902
|
-
import { Hono as
|
|
6365
|
+
import { Hono as Hono8 } from "hono";
|
|
5903
6366
|
function sshRoutes(opts = {}) {
|
|
5904
|
-
const r = new
|
|
6367
|
+
const r = new Hono8();
|
|
5905
6368
|
if (opts.controlPlane) {
|
|
5906
6369
|
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
6370
|
return r;
|
|
@@ -5916,10 +6379,10 @@ function sshRoutes(opts = {}) {
|
|
|
5916
6379
|
}
|
|
5917
6380
|
|
|
5918
6381
|
// src/routes/usage.ts
|
|
5919
|
-
import { Hono as
|
|
6382
|
+
import { Hono as Hono9 } from "hono";
|
|
5920
6383
|
var PULL_LIMIT = 1e3;
|
|
5921
6384
|
function usageRoutes(opts = {}) {
|
|
5922
|
-
const r = new
|
|
6385
|
+
const r = new Hono9();
|
|
5923
6386
|
r.get("/", async (c) => {
|
|
5924
6387
|
let window;
|
|
5925
6388
|
try {
|
|
@@ -5952,9 +6415,9 @@ function whole(value, name) {
|
|
|
5952
6415
|
}
|
|
5953
6416
|
|
|
5954
6417
|
// src/routes/volumes.ts
|
|
5955
|
-
import { Hono as
|
|
6418
|
+
import { Hono as Hono10 } from "hono";
|
|
5956
6419
|
function volumeRoutes() {
|
|
5957
|
-
const r = new
|
|
6420
|
+
const r = new Hono10();
|
|
5958
6421
|
r.get("/", async (c) => c.json(await listVolumes(c.get("listScope"))));
|
|
5959
6422
|
r.post("/", async (c) => {
|
|
5960
6423
|
const body = CreateVolumeRequest.parse(await c.req.json().catch(() => ({})));
|
|
@@ -5984,7 +6447,7 @@ function volumeRoutes() {
|
|
|
5984
6447
|
|
|
5985
6448
|
// src/app.ts
|
|
5986
6449
|
function createApp(opts = {}) {
|
|
5987
|
-
const app = new
|
|
6450
|
+
const app = new Hono11();
|
|
5988
6451
|
app.use(resolveCaller(opts));
|
|
5989
6452
|
app.get("/health", async (c) => {
|
|
5990
6453
|
const cfg = await loadConfig();
|
|
@@ -6013,6 +6476,7 @@ function createApp(opts = {}) {
|
|
|
6013
6476
|
app.route("/capacity", capacityRoutes());
|
|
6014
6477
|
app.route("/env", envRoutes());
|
|
6015
6478
|
app.route("/ssh", sshRoutes(opts));
|
|
6479
|
+
app.route("/backup-store", backupStoreRoutes(opts));
|
|
6016
6480
|
app.route("/usage", usageRoutes(opts));
|
|
6017
6481
|
app.notFound((c) => c.json({ error: `no route: ${c.req.method} ${c.req.path}` }, 404));
|
|
6018
6482
|
app.onError((err, c) => {
|
|
@@ -6035,19 +6499,19 @@ async function listen(opts = {}) {
|
|
|
6035
6499
|
throw new KvboxError(`socket path too long for a Unix socket (${socketPath}); set KVBOX_HOME to a shorter path`);
|
|
6036
6500
|
}
|
|
6037
6501
|
if (socketPath === p.serverSock) await refuseSecondDaemon(p);
|
|
6038
|
-
await
|
|
6502
|
+
await rm7(socketPath, { force: true });
|
|
6039
6503
|
const server = createAdaptorServer({ fetch: createApp().fetch });
|
|
6040
|
-
await new Promise((
|
|
6504
|
+
await new Promise((resolve3, reject) => {
|
|
6041
6505
|
server.once("error", reject);
|
|
6042
|
-
server.listen(socketPath, () =>
|
|
6506
|
+
server.listen(socketPath, () => resolve3());
|
|
6043
6507
|
});
|
|
6044
|
-
await
|
|
6508
|
+
await writeFile10(p.serverPid, `${process.pid}
|
|
6045
6509
|
`);
|
|
6046
6510
|
let https;
|
|
6047
6511
|
let httpsServer;
|
|
6048
6512
|
const cp = cfg.controlPlane;
|
|
6049
6513
|
if (cp) {
|
|
6050
|
-
const [key, cert] = await Promise.all([
|
|
6514
|
+
const [key, cert] = await Promise.all([readFile12(p.tlsKey), readFile12(p.tlsCert)]).catch((err) => {
|
|
6051
6515
|
throw new KvboxError(`joined ${cp.name} but the host's certificate is missing (${err.message}); run kvbox-server leave, then join again`);
|
|
6052
6516
|
});
|
|
6053
6517
|
httpsServer = createAdaptorServer({
|
|
@@ -6056,18 +6520,24 @@ async function listen(opts = {}) {
|
|
|
6056
6520
|
// A body forwarded to a box may take long to arrive (a large upload through the edge, #182).
|
|
6057
6521
|
serverOptions: { key, cert, requestTimeout: REQUEST_TIMEOUT_MS }
|
|
6058
6522
|
});
|
|
6523
|
+
const appListeners = httpsServer.listeners("request");
|
|
6524
|
+
httpsServer.removeAllListeners("request");
|
|
6525
|
+
httpsServer.on("request", (req, res) => {
|
|
6526
|
+
if (forStore(req.url, p)) return storeProxy(req, res);
|
|
6527
|
+
for (const l of appListeners) l.call(httpsServer, req, res);
|
|
6528
|
+
});
|
|
6059
6529
|
const secret = secretCheck(cp);
|
|
6060
6530
|
const edge = edgeCheck(cp);
|
|
6061
6531
|
limitUntrusted(httpsServer, (req) => secret(req.headers.authorization) || edge(req.headers.authorization));
|
|
6062
6532
|
httpsServer.on("upgrade", boxUpgradeHandler({ name: cp.name, secret: cp.secret }));
|
|
6063
6533
|
const port = opts.httpsPort ?? cp.port;
|
|
6064
|
-
await new Promise((
|
|
6534
|
+
await new Promise((resolve3, reject) => {
|
|
6065
6535
|
httpsServer.once("error", reject);
|
|
6066
|
-
httpsServer.listen(port, "0.0.0.0", () =>
|
|
6536
|
+
httpsServer.listen(port, "0.0.0.0", () => resolve3());
|
|
6067
6537
|
}).catch(async (err) => {
|
|
6068
6538
|
server.close();
|
|
6069
|
-
await
|
|
6070
|
-
await
|
|
6539
|
+
await rm7(socketPath, { force: true });
|
|
6540
|
+
await rm7(p.serverPid, { force: true });
|
|
6071
6541
|
throw new KvboxError(`cannot listen on port ${port} for ${cp.name} (${err.message})`);
|
|
6072
6542
|
});
|
|
6073
6543
|
const bound = httpsServer.address().port;
|
|
@@ -6075,18 +6545,18 @@ async function listen(opts = {}) {
|
|
|
6075
6545
|
}
|
|
6076
6546
|
const close = async () => {
|
|
6077
6547
|
await Promise.all([
|
|
6078
|
-
new Promise((
|
|
6079
|
-
httpsServer ? new Promise((
|
|
6548
|
+
new Promise((resolve3) => server.close(() => resolve3())),
|
|
6549
|
+
httpsServer ? new Promise((resolve3) => httpsServer.close(() => resolve3())) : void 0
|
|
6080
6550
|
]);
|
|
6081
|
-
await
|
|
6082
|
-
await
|
|
6551
|
+
await rm7(socketPath, { force: true });
|
|
6552
|
+
await rm7(p.serverPid, { force: true });
|
|
6083
6553
|
};
|
|
6084
6554
|
const shutdown2 = async () => {
|
|
6085
6555
|
server.close();
|
|
6086
6556
|
httpsServer?.close();
|
|
6087
6557
|
await stopRecovery();
|
|
6088
|
-
await
|
|
6089
|
-
await
|
|
6558
|
+
await rm7(socketPath, { force: true });
|
|
6559
|
+
await rm7(p.serverPid, { force: true });
|
|
6090
6560
|
process.exit(0);
|
|
6091
6561
|
};
|
|
6092
6562
|
process.once("SIGINT", () => void shutdown2());
|
|
@@ -6158,6 +6628,7 @@ var startCommand = new Command("start").description("run the daemon in the foreg
|
|
|
6158
6628
|
bindDns();
|
|
6159
6629
|
startRelayWatch();
|
|
6160
6630
|
startIdleWatch();
|
|
6631
|
+
startBackupStoreWatch();
|
|
6161
6632
|
const recovery2 = await bootRecovered(settled, paths());
|
|
6162
6633
|
if (recovery2) {
|
|
6163
6634
|
for (const box of recovery2.booted) log.info(`box ${box} was running when it went down; booted it again`);
|
|
@@ -6167,11 +6638,66 @@ var startCommand = new Command("start").description("run the daemon in the foreg
|
|
|
6167
6638
|
});
|
|
6168
6639
|
|
|
6169
6640
|
// src/program.ts
|
|
6170
|
-
import { Command as
|
|
6641
|
+
import { Command as Command13 } from "commander";
|
|
6171
6642
|
|
|
6172
|
-
// src/commands/
|
|
6643
|
+
// src/commands/backup/index.ts
|
|
6644
|
+
import { Command as Command4 } from "commander";
|
|
6645
|
+
|
|
6646
|
+
// src/commands/backup/setup.ts
|
|
6647
|
+
import { resolve as resolve2 } from "node:path";
|
|
6173
6648
|
import { Command as Command2 } from "commander";
|
|
6174
|
-
|
|
6649
|
+
|
|
6650
|
+
// src/commands/backup/output.ts
|
|
6651
|
+
function size(bytes) {
|
|
6652
|
+
const gib = bytes / 1024 ** 3;
|
|
6653
|
+
return gib >= 1024 ? `${(gib / 1024).toFixed(1)} TB` : `${gib.toFixed(1)} GB`;
|
|
6654
|
+
}
|
|
6655
|
+
function printStore(s) {
|
|
6656
|
+
const rows = [
|
|
6657
|
+
["path", s.path],
|
|
6658
|
+
["storage", s.running ? "running" : "not running (the daemon starts it again within a minute; kvbox-server logs says why if it does not)"],
|
|
6659
|
+
["disk", `${size(s.totalBytes - s.freeBytes)} used of ${size(s.totalBytes)}, ${size(s.freeBytes)} free`]
|
|
6660
|
+
];
|
|
6661
|
+
if (s.storedBytes !== void 0) rows.push(["backups", `${size(s.storedBytes)} in ${s.objects ?? 0} chunks`]);
|
|
6662
|
+
rows.push(["key", s.accessKey]);
|
|
6663
|
+
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"]);
|
|
6664
|
+
const width = Math.max(...rows.map(([label]) => label.length));
|
|
6665
|
+
for (const [label, value] of rows) console.log(`${label.padEnd(width)} ${value}`);
|
|
6666
|
+
}
|
|
6667
|
+
|
|
6668
|
+
// src/commands/backup/setup.ts
|
|
6669
|
+
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) => {
|
|
6670
|
+
const client = new SocketClient(paths().serverSock);
|
|
6671
|
+
try {
|
|
6672
|
+
if (!opts.json) console.log("setting up the backup store (the first time downloads Garage, which can take a minute)");
|
|
6673
|
+
const store = await client.setupBackupStore({ path: resolve2(opts.path), ...opts.force ? { force: true } : {}, ...opts.newStore ? { newStore: true } : {} });
|
|
6674
|
+
if (opts.json) return console.log(JSON.stringify(store, null, 2));
|
|
6675
|
+
console.log("this host is now a backup store; new backups can be kept here");
|
|
6676
|
+
printStore(store);
|
|
6677
|
+
} finally {
|
|
6678
|
+
await client.close();
|
|
6679
|
+
}
|
|
6680
|
+
});
|
|
6681
|
+
|
|
6682
|
+
// src/commands/backup/status.ts
|
|
6683
|
+
import { Command as Command3 } from "commander";
|
|
6684
|
+
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) => {
|
|
6685
|
+
const client = new SocketClient(paths().serverSock);
|
|
6686
|
+
try {
|
|
6687
|
+
const store = await client.backupStore();
|
|
6688
|
+
if (opts.json) console.log(JSON.stringify(store, null, 2));
|
|
6689
|
+
else printStore(store);
|
|
6690
|
+
} finally {
|
|
6691
|
+
await client.close();
|
|
6692
|
+
}
|
|
6693
|
+
});
|
|
6694
|
+
|
|
6695
|
+
// src/commands/backup/index.ts
|
|
6696
|
+
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);
|
|
6697
|
+
|
|
6698
|
+
// src/commands/join.ts
|
|
6699
|
+
import { Command as Command5 } from "commander";
|
|
6700
|
+
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
6701
|
const p = paths();
|
|
6176
6702
|
const joined = await joinControlPlane({ url, ...opts }, p);
|
|
6177
6703
|
console.log(`joined ${joined.controlPlane} as host ${joined.hostName}`);
|
|
@@ -6185,8 +6711,8 @@ var joinCommand = new Command2("join").description("put this host behind a contr
|
|
|
6185
6711
|
});
|
|
6186
6712
|
|
|
6187
6713
|
// src/commands/leave.ts
|
|
6188
|
-
import { Command as
|
|
6189
|
-
var leaveCommand = new
|
|
6714
|
+
import { Command as Command6 } from "commander";
|
|
6715
|
+
var leaveCommand = new Command6("leave").description("take this host out from behind its control plane and restart the daemon").action(async () => {
|
|
6190
6716
|
const p = paths();
|
|
6191
6717
|
const left = await leaveControlPlane(p);
|
|
6192
6718
|
console.log(`left ${left.controlPlane}`);
|
|
@@ -6200,14 +6726,14 @@ var leaveCommand = new Command3("leave").description("take this host out from be
|
|
|
6200
6726
|
});
|
|
6201
6727
|
|
|
6202
6728
|
// src/commands/logs.ts
|
|
6203
|
-
import { open as open2, readFile as
|
|
6204
|
-
import { setTimeout as
|
|
6205
|
-
import { Command as
|
|
6206
|
-
var logsCommand = new
|
|
6729
|
+
import { open as open2, readFile as readFile13, stat as stat6 } from "node:fs/promises";
|
|
6730
|
+
import { setTimeout as sleep5 } from "node:timers/promises";
|
|
6731
|
+
import { Command as Command7 } from "commander";
|
|
6732
|
+
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
6733
|
const n = Number.parseInt(opts.lines, 10);
|
|
6208
6734
|
if (!Number.isInteger(n) || n < 0) throw new KvboxError(`--lines: expected a number, got ${opts.lines}`);
|
|
6209
6735
|
const p = paths();
|
|
6210
|
-
const text = await
|
|
6736
|
+
const text = await readFile13(p.serverLog, "utf8").catch((err) => {
|
|
6211
6737
|
if (err.code === "ENOENT") throw new KvboxError(`no log yet at ${p.serverLog} (the daemon writes it once it has run)`);
|
|
6212
6738
|
throw err;
|
|
6213
6739
|
});
|
|
@@ -6227,14 +6753,14 @@ function tailLines(text, n) {
|
|
|
6227
6753
|
}
|
|
6228
6754
|
async function follow(path, write, opts = {}) {
|
|
6229
6755
|
const intervalMs = opts.intervalMs ?? 250;
|
|
6230
|
-
let offset = opts.from ?? await
|
|
6756
|
+
let offset = opts.from ?? await stat6(path).then((s) => s.size, () => 0);
|
|
6231
6757
|
while (!opts.signal?.aborted) {
|
|
6232
|
-
const
|
|
6233
|
-
if (
|
|
6234
|
-
if (
|
|
6758
|
+
const size2 = await stat6(path).then((s) => s.size, () => 0);
|
|
6759
|
+
if (size2 < offset) offset = 0;
|
|
6760
|
+
if (size2 > offset) {
|
|
6235
6761
|
const fh = await open2(path, "r");
|
|
6236
6762
|
try {
|
|
6237
|
-
const buf = Buffer.alloc(
|
|
6763
|
+
const buf = Buffer.alloc(size2 - offset);
|
|
6238
6764
|
const { bytesRead } = await fh.read(buf, 0, buf.length, offset);
|
|
6239
6765
|
write(buf.subarray(0, bytesRead).toString("utf8"));
|
|
6240
6766
|
offset += bytesRead;
|
|
@@ -6242,14 +6768,14 @@ async function follow(path, write, opts = {}) {
|
|
|
6242
6768
|
await fh.close();
|
|
6243
6769
|
}
|
|
6244
6770
|
}
|
|
6245
|
-
await
|
|
6771
|
+
await sleep5(intervalMs, void 0, { signal: opts.signal }).catch(() => void 0);
|
|
6246
6772
|
}
|
|
6247
6773
|
}
|
|
6248
6774
|
|
|
6249
6775
|
// src/commands/net.ts
|
|
6250
6776
|
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
6251
|
-
import { Command as
|
|
6252
|
-
var netCommand = new
|
|
6777
|
+
import { Command as Command8 } from "commander";
|
|
6778
|
+
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
6779
|
if (!["up", "down", "status"].includes(action)) throw new KvboxError("net: expected up, down or status");
|
|
6254
6780
|
const cfg = await loadConfig(paths());
|
|
6255
6781
|
const res = spawnSync2(netSetupScript(), [action], {
|
|
@@ -6260,8 +6786,8 @@ var netCommand = new Command5("net").description("host network: up | down | stat
|
|
|
6260
6786
|
});
|
|
6261
6787
|
|
|
6262
6788
|
// src/commands/relay.ts
|
|
6263
|
-
import { Command as
|
|
6264
|
-
var relayCommand = new
|
|
6789
|
+
import { Command as Command9 } from "commander";
|
|
6790
|
+
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
6791
|
if (joinString === "off") {
|
|
6266
6792
|
const relay2 = await dropRelay(paths());
|
|
6267
6793
|
console.log(`tunnel to relay ${relay2.name} is down; this host no longer answers at ${relay2.publicIp}`);
|
|
@@ -6275,8 +6801,8 @@ var relayCommand = new Command6("relay").description("reach the internet through
|
|
|
6275
6801
|
// src/commands/status.ts
|
|
6276
6802
|
import { homedir as homedir2 } from "node:os";
|
|
6277
6803
|
import { styleText } from "node:util";
|
|
6278
|
-
import { Command as
|
|
6279
|
-
var
|
|
6804
|
+
import { Command as Command10 } from "commander";
|
|
6805
|
+
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
6806
|
const p = paths();
|
|
6281
6807
|
const atBoot = startsAtBoot(p);
|
|
6282
6808
|
const pid = await daemonPid(p);
|
|
@@ -6348,8 +6874,8 @@ function printStatus(health, atBoot, logPath) {
|
|
|
6348
6874
|
}
|
|
6349
6875
|
|
|
6350
6876
|
// src/commands/stop.ts
|
|
6351
|
-
import { Command as
|
|
6352
|
-
var stopCommand = new
|
|
6877
|
+
import { Command as Command11 } from "commander";
|
|
6878
|
+
var stopCommand = new Command11("stop").description("stop the daemon (running boxes are not affected)").action(async () => {
|
|
6353
6879
|
const pid = await daemonPid(paths());
|
|
6354
6880
|
if (pid === null) throw new KvboxError("kvbox-server is not running");
|
|
6355
6881
|
await stopDaemon(pid);
|
|
@@ -6357,8 +6883,8 @@ var stopCommand = new Command8("stop").description("stop the daemon (running box
|
|
|
6357
6883
|
});
|
|
6358
6884
|
|
|
6359
6885
|
// src/commands/trust-ca.ts
|
|
6360
|
-
import { Command as
|
|
6361
|
-
var trustCaCommand = new
|
|
6886
|
+
import { Command as Command12 } from "commander";
|
|
6887
|
+
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
6888
|
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
6889
|
if (publicKey !== void 0 && opts.fromCloud) throw new KvboxError("either a public key or --from-cloud, not both");
|
|
6364
6890
|
const client = new SocketClient(paths().serverSock);
|
|
@@ -6414,7 +6940,7 @@ function describeReport(report2) {
|
|
|
6414
6940
|
|
|
6415
6941
|
// src/program.ts
|
|
6416
6942
|
function buildProgram() {
|
|
6417
|
-
return new
|
|
6943
|
+
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
6944
|
}
|
|
6419
6945
|
|
|
6420
6946
|
// src/index.ts
|