@kvbox/server 0.5.51 → 0.6.1
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 +540 -107
- package/dist/kvbox-server.js.map +1 -1
- package/package.json +1 -1
package/dist/kvbox-server.js
CHANGED
|
@@ -135,7 +135,9 @@ function paths(home = kvboxHome()) {
|
|
|
135
135
|
dir,
|
|
136
136
|
meta: join(dir, "meta.json"),
|
|
137
137
|
/** The volume itself: a sparse ext4 the guest sees as a whole disk. */
|
|
138
|
-
disk: join(dir, "disk.ext4")
|
|
138
|
+
disk: join(dir, "disk.ext4"),
|
|
139
|
+
/** A restore's disk while it downloads (a backup's chunks), renamed over `disk` once complete. */
|
|
140
|
+
restoring: join(dir, "disk.ext4.restore")
|
|
139
141
|
};
|
|
140
142
|
},
|
|
141
143
|
/** Each owner's environment variables as the control plane last sent them (#88): env/<owner>.json, mode 600. */
|
|
@@ -579,6 +581,12 @@ function openDb(p = paths()) {
|
|
|
579
581
|
handles.set(p.db, db);
|
|
580
582
|
return db;
|
|
581
583
|
}
|
|
584
|
+
function closeDb(p = paths()) {
|
|
585
|
+
const db = handles.get(p.db);
|
|
586
|
+
if (db === void 0) return;
|
|
587
|
+
db.close();
|
|
588
|
+
handles.delete(p.db);
|
|
589
|
+
}
|
|
582
590
|
function migrate(db) {
|
|
583
591
|
db.exec("create table if not exists schema_version (version integer not null)");
|
|
584
592
|
const row = db.prepare("select version from schema_version").get();
|
|
@@ -597,6 +605,22 @@ function migrate(db) {
|
|
|
597
605
|
}
|
|
598
606
|
}
|
|
599
607
|
}
|
|
608
|
+
function renameLedgerRealm(from, to, p = paths()) {
|
|
609
|
+
const db = openDb(p);
|
|
610
|
+
let rows = 0;
|
|
611
|
+
db.exec("begin");
|
|
612
|
+
try {
|
|
613
|
+
for (const table of ["usage_events", "volume_events"]) {
|
|
614
|
+
const res = db.prepare(`update ${table} set owner = substr(owner, 1, length(owner) - length(?)) || ? where substr(owner, -length(?)) = ?`).run(`@${from}`, `@${to}`, `@${from}`, `@${from}`);
|
|
615
|
+
rows += Number(res.changes);
|
|
616
|
+
}
|
|
617
|
+
db.exec("commit");
|
|
618
|
+
} catch (err) {
|
|
619
|
+
db.exec("rollback");
|
|
620
|
+
throw err;
|
|
621
|
+
}
|
|
622
|
+
return rows;
|
|
623
|
+
}
|
|
600
624
|
var LIVE_STATES = ["running", "standby"];
|
|
601
625
|
function fromRaw(r) {
|
|
602
626
|
return { boxId: r.box_id, owner: r.owner, name: r.name, at: r.at, state: r.state, vcpu: r.vcpu, memMib: r.mem_mib, diskGib: r.disk_gib, by: r.by };
|
|
@@ -1079,6 +1103,7 @@ var WakeHookCallSchema = z4.object({
|
|
|
1079
1103
|
reason: z4.string().optional()
|
|
1080
1104
|
});
|
|
1081
1105
|
var BACKUP_STATUSES = ["running", "ready", "failed"];
|
|
1106
|
+
var BACKUP_KINDS = ["box", "volume"];
|
|
1082
1107
|
var BackupSchema = z4.object({
|
|
1083
1108
|
id: z4.string(),
|
|
1084
1109
|
owner: z4.string(),
|
|
@@ -1126,6 +1151,31 @@ var HostRestoreRequest = z4.object({
|
|
|
1126
1151
|
/** The certificate fingerprint of the store the URLs point at (see HostUploadRequest). */
|
|
1127
1152
|
pin: z4.string().optional()
|
|
1128
1153
|
});
|
|
1154
|
+
var VolumeBackupSchema = z4.object({
|
|
1155
|
+
id: z4.string(),
|
|
1156
|
+
owner: z4.string(),
|
|
1157
|
+
volume: z4.string(),
|
|
1158
|
+
status: z4.enum(BACKUP_STATUSES),
|
|
1159
|
+
/** Why it failed; null otherwise. */
|
|
1160
|
+
error: z4.string().nullable(),
|
|
1161
|
+
/** The volume's size when taken. */
|
|
1162
|
+
diskBytes: z4.number().int().nullable(),
|
|
1163
|
+
/** What it holds: the slots that are not all zeros. */
|
|
1164
|
+
dataBytes: z4.number().int().nullable(),
|
|
1165
|
+
/** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
|
|
1166
|
+
uploadedBytes: z4.number().int().nullable(),
|
|
1167
|
+
createdBy: z4.string().nullable(),
|
|
1168
|
+
createdAt: z4.string(),
|
|
1169
|
+
finishedAt: z4.string().nullable()
|
|
1170
|
+
});
|
|
1171
|
+
var HostVolumeBackupManifestSchema = z4.object({ id: z4.string(), sizeBytes: z4.number().int(), chunks: z4.array(z4.string().nullable()) });
|
|
1172
|
+
var HostVolumeRestoreRequest = z4.object({
|
|
1173
|
+
id: z4.string(),
|
|
1174
|
+
key: z4.string(),
|
|
1175
|
+
sizeBytes: z4.number().int().positive(),
|
|
1176
|
+
chunks: z4.array(z4.object({ index: z4.number().int().nonnegative(), hash: z4.string(), url: z4.string() })),
|
|
1177
|
+
pin: z4.string().optional()
|
|
1178
|
+
});
|
|
1129
1179
|
var BACKUP_STORE_BUCKET = "kvbox-backups";
|
|
1130
1180
|
var BACKUP_STORE_REGION = "kvbox";
|
|
1131
1181
|
var BackupStoreSetupRequest = z4.object({ path: z4.string().min(1), force: z4.boolean().optional(), newStore: z4.boolean().optional() });
|
|
@@ -1160,7 +1210,38 @@ var CloudBackupStoreSchema = z4.object({
|
|
|
1160
1210
|
freeBytes: z4.number().int().nullable(),
|
|
1161
1211
|
/** Ready backups kept here, and what their chunks take (encrypted, compressed). */
|
|
1162
1212
|
backups: z4.number().int(),
|
|
1163
|
-
storedBytes: z4.number().int()
|
|
1213
|
+
storedBytes: z4.number().int(),
|
|
1214
|
+
/** How many boxes have a ready backup here (a box and an earlier one of the same name count once), and how many volumes (#168). */
|
|
1215
|
+
boxes: z4.number().int(),
|
|
1216
|
+
volumes: z4.number().int(),
|
|
1217
|
+
/** When the newest ready backup kept here finished; null when it keeps none. */
|
|
1218
|
+
lastBackupAt: z4.string().nullable()
|
|
1219
|
+
});
|
|
1220
|
+
var StoredItemSchema = z4.object({
|
|
1221
|
+
kind: z4.enum(BACKUP_KINDS),
|
|
1222
|
+
owner: z4.string(),
|
|
1223
|
+
name: z4.string(),
|
|
1224
|
+
/** The host the box (or volume) is on now; null when it is gone (its backups stay). */
|
|
1225
|
+
host: z4.string().nullable(),
|
|
1226
|
+
/** It is on the store's own host: losing that host loses it and its backups together. */
|
|
1227
|
+
sameHost: z4.boolean(),
|
|
1228
|
+
/** Ready backups kept here, and what they added to the store together (encrypted, compressed). */
|
|
1229
|
+
backups: z4.number().int(),
|
|
1230
|
+
uploadedBytes: z4.number().int(),
|
|
1231
|
+
/** The newest backup sent here, whatever became of it. */
|
|
1232
|
+
latest: z4.object({ id: z4.string(), status: z4.enum(BACKUP_STATUSES), error: z4.string().nullable(), createdAt: z4.string() })
|
|
1233
|
+
});
|
|
1234
|
+
var FailedBackupSchema = z4.object({
|
|
1235
|
+
id: z4.string(),
|
|
1236
|
+
owner: z4.string(),
|
|
1237
|
+
/** What it was a backup of: a box or a volume (#168), and its name. */
|
|
1238
|
+
kind: z4.enum(BACKUP_KINDS),
|
|
1239
|
+
name: z4.string(),
|
|
1240
|
+
error: z4.string().nullable(),
|
|
1241
|
+
/** The host that took it, and the host of the store it was going to; null when gone, or when it failed before a store was picked. */
|
|
1242
|
+
host: z4.string().nullable(),
|
|
1243
|
+
store: z4.string().nullable(),
|
|
1244
|
+
createdAt: z4.string()
|
|
1164
1245
|
});
|
|
1165
1246
|
var MachineSchema = z4.object({
|
|
1166
1247
|
/** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */
|
|
@@ -1209,6 +1290,11 @@ var MachineSchema = z4.object({
|
|
|
1209
1290
|
host: z4.string().optional(),
|
|
1210
1291
|
/** The country code of that host (`RO`, `US`), when its admin gave one. Only the control plane fills it in. */
|
|
1211
1292
|
country: z4.string().optional(),
|
|
1293
|
+
/**
|
|
1294
|
+
* The kind of managed service the box runs (`postgres`, `redis`, `storage`). Only an admin's
|
|
1295
|
+
* `GET /machines?all=1` lists such boxes, so a host's boxes add up; every other listing hides them.
|
|
1296
|
+
*/
|
|
1297
|
+
managed: z4.string().optional(),
|
|
1212
1298
|
/** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
|
|
1213
1299
|
autoHibernateSec: z4.number().int().positive().optional(),
|
|
1214
1300
|
/** A script inside the box that says it is idle (#102, exit 0): auto-hibernate asks it instead of watching the traffic. */
|
|
@@ -3033,6 +3119,7 @@ import { link, mkdir as mkdir5, readdir as readdir5, rename as rename5, rm as rm
|
|
|
3033
3119
|
|
|
3034
3120
|
// src/core/firecracker.ts
|
|
3035
3121
|
import { Agent, request as request2 } from "undici";
|
|
3122
|
+
var syncFallbackLogged = false;
|
|
3036
3123
|
var FirecrackerClient = class {
|
|
3037
3124
|
constructor(socketPath) {
|
|
3038
3125
|
this.socketPath = socketPath;
|
|
@@ -3058,15 +3145,35 @@ var FirecrackerClient = class {
|
|
|
3058
3145
|
}
|
|
3059
3146
|
/** /dev/vda: the shared base image, read-only. Firecracker adds `root=/dev/vda ro` to the boot args to match. */
|
|
3060
3147
|
rootDrive(pathOnHost) {
|
|
3061
|
-
return this.drive("rootfs", pathOnHost, { root: true, readOnly: true });
|
|
3148
|
+
return this.drive("rootfs", pathOnHost, { root: true, readOnly: true, engine: "Sync" });
|
|
3062
3149
|
}
|
|
3063
3150
|
/** The box's own writable disk, /dev/vdb: the guest stacks it on the base as an overlay. */
|
|
3064
3151
|
overlayDrive(pathOnHost) {
|
|
3065
|
-
return this.
|
|
3152
|
+
return this.writableDrive("overlay", pathOnHost);
|
|
3066
3153
|
}
|
|
3067
3154
|
/** A volume (#52): /dev/vdc and up, in the order they are added; the guest mounts it by label. */
|
|
3068
3155
|
volumeDrive(id, pathOnHost) {
|
|
3069
|
-
return this.
|
|
3156
|
+
return this.writableDrive(id, pathOnHost);
|
|
3157
|
+
}
|
|
3158
|
+
/**
|
|
3159
|
+
* A drive the guest writes to gets the Async engine (io_uring, #175): with Sync, Firecracker's one
|
|
3160
|
+
* VMM thread sits in the write or the fsync and the box's network waits behind it, seconds under a
|
|
3161
|
+
* heavy write. The base image stays on Sync, which is the faster of the two for reads the host has
|
|
3162
|
+
* cached. A host that cannot do Async (kernel before 5.10.51, io_uring turned off) keeps Sync.
|
|
3163
|
+
* The engine is part of a snapshot: a box frozen on Sync wakes on Sync, until its next cold boot.
|
|
3164
|
+
*/
|
|
3165
|
+
async writableDrive(id, pathOnHost) {
|
|
3166
|
+
const opts = { root: false, readOnly: false };
|
|
3167
|
+
try {
|
|
3168
|
+
return await this.drive(id, pathOnHost, { ...opts, engine: "Async" });
|
|
3169
|
+
} catch (asyncErr) {
|
|
3170
|
+
const done = await this.drive(id, pathOnHost, { ...opts, engine: "Sync" });
|
|
3171
|
+
if (!syncFallbackLogged) {
|
|
3172
|
+
syncFallbackLogged = true;
|
|
3173
|
+
log.warn(`this host cannot give box disks the Async engine, they keep Sync (heavy writes in a box can stall its network): ${asyncErr.message}`);
|
|
3174
|
+
}
|
|
3175
|
+
return done;
|
|
3176
|
+
}
|
|
3070
3177
|
}
|
|
3071
3178
|
drive(id, pathOnHost, opts) {
|
|
3072
3179
|
return this.call("PUT", `/drives/${id}`, {
|
|
@@ -3077,7 +3184,8 @@ var FirecrackerClient = class {
|
|
|
3077
3184
|
// "Unsafe" (the default) acks guest flushes without doing anything, so the last journal
|
|
3078
3185
|
// commit of a clean shutdown can be lost when the guest resets and Firecracker exits.
|
|
3079
3186
|
// Writeback makes a guest flush a real fsync; a box's writes must survive `kvbox stop`.
|
|
3080
|
-
cache_type: "Writeback"
|
|
3187
|
+
cache_type: "Writeback",
|
|
3188
|
+
io_engine: opts.engine
|
|
3081
3189
|
});
|
|
3082
3190
|
}
|
|
3083
3191
|
/**
|
|
@@ -4386,6 +4494,34 @@ async function resizeVolume(volume, sizeGib, p = paths()) {
|
|
|
4386
4494
|
return { ...grown, attachedTo: holder };
|
|
4387
4495
|
});
|
|
4388
4496
|
}
|
|
4497
|
+
async function replaceVolumeDisk(volume, file, p = paths()) {
|
|
4498
|
+
const grow = async () => {
|
|
4499
|
+
const meta = await readVolume(volume, p);
|
|
4500
|
+
if (meta.sizeGib * 1024 ** 3 > statSync2(file).size) await growDisk(file, meta.sizeGib);
|
|
4501
|
+
};
|
|
4502
|
+
await grow();
|
|
4503
|
+
const swap = async () => {
|
|
4504
|
+
await grow();
|
|
4505
|
+
await rename6(file, p.volume(volume.owner, volume.name).disk);
|
|
4506
|
+
};
|
|
4507
|
+
const holder = await attachedBox(volume, p);
|
|
4508
|
+
if (holder === null) {
|
|
4509
|
+
await withHostLock("volumes", async () => {
|
|
4510
|
+
const now = await attachedBox(volume, p);
|
|
4511
|
+
if (now !== null) throw new KvboxError(`volume ${shown(volume)} was just attached to box ${now}; try again`);
|
|
4512
|
+
await swap();
|
|
4513
|
+
});
|
|
4514
|
+
return getVolume(volume, p);
|
|
4515
|
+
}
|
|
4516
|
+
const box = { owner: volume.owner, name: holder };
|
|
4517
|
+
await withBoxLock(box, async () => {
|
|
4518
|
+
const meta = await readMeta(box, p);
|
|
4519
|
+
if (!meta.volumes?.includes(volume.name)) throw new KvboxError(`volume ${shown(volume)} was just detached from box ${holder}; try again`);
|
|
4520
|
+
assertNotHibernated(meta, p);
|
|
4521
|
+
await applyAtNextBoot(meta, {}, "restore", await loadConfig(p), p, swap);
|
|
4522
|
+
});
|
|
4523
|
+
return getVolume(volume, p);
|
|
4524
|
+
}
|
|
4389
4525
|
var setMachine = locked(async function setMachine2(ref, req, p = paths()) {
|
|
4390
4526
|
const meta = await readMeta(ref, p);
|
|
4391
4527
|
const next = { ...meta };
|
|
@@ -4627,7 +4763,7 @@ async function bootRecovered(settled, p = paths()) {
|
|
|
4627
4763
|
// src/core/backups.ts
|
|
4628
4764
|
import { randomBytes as randomBytes5 } from "node:crypto";
|
|
4629
4765
|
import { existsSync as existsSync8 } from "node:fs";
|
|
4630
|
-
import { mkdir as mkdir7, open, readdir as readdir6, readFile as readFile7, rm as
|
|
4766
|
+
import { mkdir as mkdir7, open, readdir as readdir6, readFile as readFile7, rm as rm6, stat as stat4, statfs as statfs3, writeFile as writeFile7 } from "node:fs/promises";
|
|
4631
4767
|
import { basename as basename2, join as join3 } from "node:path";
|
|
4632
4768
|
import { setTimeout as sleep3 } from "node:timers/promises";
|
|
4633
4769
|
|
|
@@ -4708,6 +4844,26 @@ function chunkCount(bytes) {
|
|
|
4708
4844
|
return Math.ceil(bytes / CHUNK_SIZE);
|
|
4709
4845
|
}
|
|
4710
4846
|
|
|
4847
|
+
// src/core/clone.ts
|
|
4848
|
+
import { rm as rm5 } from "node:fs/promises";
|
|
4849
|
+
var CLONE_TIMEOUT_MS = 6e5;
|
|
4850
|
+
async function cloneDisk(from, to, timeoutMs = CLONE_TIMEOUT_MS) {
|
|
4851
|
+
const started = Date.now();
|
|
4852
|
+
try {
|
|
4853
|
+
await run(["cp", "--reflink=always", from, to], { timeoutMs });
|
|
4854
|
+
} catch (err) {
|
|
4855
|
+
await rm5(to, { force: true });
|
|
4856
|
+
if (Date.now() - started >= timeoutMs) {
|
|
4857
|
+
throw new KvboxError(`the instant copy of the disk took more than ${Math.round(timeoutMs / 1e3)} s and was stopped; the box was paused for that long. Try again; if it keeps happening, the host's operator should look at its disk`);
|
|
4858
|
+
}
|
|
4859
|
+
const why = err.message;
|
|
4860
|
+
if (/failed to clone|not supported|cross-device|Invalid cross/i.test(why)) {
|
|
4861
|
+
throw new KvboxError("this host cannot take backups: its disk cannot make an instant copy of a box's disk (kvbox hosts keep their boxes on XFS); the host's operator has to move it to XFS");
|
|
4862
|
+
}
|
|
4863
|
+
throw err;
|
|
4864
|
+
}
|
|
4865
|
+
}
|
|
4866
|
+
|
|
4711
4867
|
// src/core/storeFetch.ts
|
|
4712
4868
|
import { Agent as Agent2, buildConnector, fetch as pinnedFetch } from "undici";
|
|
4713
4869
|
var dispatchers = /* @__PURE__ */ new Map();
|
|
@@ -4755,7 +4911,8 @@ async function assertRoom(dir, bytes, what, p) {
|
|
|
4755
4911
|
const headroom = (await loadConfig(p)).volumeHeadroomGib * 1024 ** 3;
|
|
4756
4912
|
if (free - bytes < headroom) {
|
|
4757
4913
|
const gib = (n) => (n / 1024 ** 3).toFixed(1);
|
|
4758
|
-
|
|
4914
|
+
const needs = bytes === 0 ? "cannot be made:" : `needs ${gib(bytes)} GiB and`;
|
|
4915
|
+
throw new KvboxError(`${what} ${needs} this host has ${gib(free)} GiB free (keeping ${gib(headroom)} GiB spare); try again when it has room`);
|
|
4759
4916
|
}
|
|
4760
4917
|
}
|
|
4761
4918
|
function checkId(id) {
|
|
@@ -4798,29 +4955,14 @@ async function stageBackup(ref, req, p = paths()) {
|
|
|
4798
4955
|
checkId(req.id);
|
|
4799
4956
|
const keys = backupKeys(req.key);
|
|
4800
4957
|
const s = p.backup(req.id);
|
|
4801
|
-
await
|
|
4958
|
+
await rm6(s.dir, { recursive: true, force: true });
|
|
4802
4959
|
await mkdir7(s.dir, { recursive: true, mode: 448 });
|
|
4803
4960
|
try {
|
|
4804
4961
|
const { meta, envText } = await withBoxLock(ref, async () => {
|
|
4805
4962
|
const meta2 = await readBox2(ref, p);
|
|
4806
4963
|
const m = p.machine(meta2.owner, meta2.name);
|
|
4807
|
-
await assertRoom(s.dir,
|
|
4808
|
-
|
|
4809
|
-
if (vmAlive(meta2) && !meta2.paused) {
|
|
4810
|
-
const fc = new FirecrackerClient(m.sock);
|
|
4811
|
-
try {
|
|
4812
|
-
await fc.pause();
|
|
4813
|
-
try {
|
|
4814
|
-
await copy();
|
|
4815
|
-
} finally {
|
|
4816
|
-
await resumeAfterCopy(fc, meta2, p);
|
|
4817
|
-
}
|
|
4818
|
-
} finally {
|
|
4819
|
-
await fc.close();
|
|
4820
|
-
}
|
|
4821
|
-
} else {
|
|
4822
|
-
await copy();
|
|
4823
|
-
}
|
|
4964
|
+
await assertRoom(s.dir, 0, `a backup of box ${shown(ref)}`, p);
|
|
4965
|
+
await frozenClone(meta2, m.overlay, s.disk, p);
|
|
4824
4966
|
const envText2 = existsSync8(m.env) ? await readFile7(m.env, "utf8") : null;
|
|
4825
4967
|
return { meta: meta2, envText: envText2 };
|
|
4826
4968
|
});
|
|
@@ -4837,7 +4979,54 @@ async function stageBackup(ref, req, p = paths()) {
|
|
|
4837
4979
|
memMib: meta.memMib
|
|
4838
4980
|
};
|
|
4839
4981
|
} catch (err) {
|
|
4840
|
-
await
|
|
4982
|
+
await rm6(s.dir, { recursive: true, force: true });
|
|
4983
|
+
throw err;
|
|
4984
|
+
}
|
|
4985
|
+
}
|
|
4986
|
+
async function frozenClone(box, from, to, p) {
|
|
4987
|
+
if (!vmAlive(box) || box.paused) return cloneDisk(from, to);
|
|
4988
|
+
const fc = new FirecrackerClient(p.machine(box.owner, box.name).sock);
|
|
4989
|
+
try {
|
|
4990
|
+
await fc.pause();
|
|
4991
|
+
try {
|
|
4992
|
+
await cloneDisk(from, to);
|
|
4993
|
+
} finally {
|
|
4994
|
+
await resumeAfterCopy(fc, box, p);
|
|
4995
|
+
}
|
|
4996
|
+
} finally {
|
|
4997
|
+
await fc.close();
|
|
4998
|
+
}
|
|
4999
|
+
}
|
|
5000
|
+
async function stageVolumeBackup(ref, req, p = paths()) {
|
|
5001
|
+
checkId(req.id);
|
|
5002
|
+
const keys = backupKeys(req.key);
|
|
5003
|
+
await readVolume(ref, p);
|
|
5004
|
+
const from = p.volume(ref.owner, ref.name).disk;
|
|
5005
|
+
const s = p.backup(req.id);
|
|
5006
|
+
await rm6(s.dir, { recursive: true, force: true });
|
|
5007
|
+
await mkdir7(s.dir, { recursive: true, mode: 448 });
|
|
5008
|
+
try {
|
|
5009
|
+
await assertRoom(s.dir, 0, `a backup of volume ${shown(ref)}`, p);
|
|
5010
|
+
const holder = await attachedBox(ref, p);
|
|
5011
|
+
if (holder === null) {
|
|
5012
|
+
await withHostLock("volumes", async () => {
|
|
5013
|
+
const now = await attachedBox(ref, p);
|
|
5014
|
+
if (now !== null) throw new KvboxError(`volume ${shown(ref)} was just attached to box ${now}; try again`);
|
|
5015
|
+
await cloneDisk(from, s.disk);
|
|
5016
|
+
});
|
|
5017
|
+
} else {
|
|
5018
|
+
const box = { owner: ref.owner, name: holder };
|
|
5019
|
+
await withBoxLock(box, async () => {
|
|
5020
|
+
const meta = await readBox2(box, p);
|
|
5021
|
+
if (!meta.volumes?.includes(ref.name)) throw new KvboxError(`volume ${shown(ref)} was just detached from box ${holder}; try again`);
|
|
5022
|
+
await frozenClone(meta, from, s.disk, p);
|
|
5023
|
+
});
|
|
5024
|
+
}
|
|
5025
|
+
const { sizeBytes, chunks } = await chunkNames(s.disk, keys);
|
|
5026
|
+
await writeFile7(s.chunks, JSON.stringify({ chunks }), { mode: 384 });
|
|
5027
|
+
return { id: req.id, sizeBytes, chunks };
|
|
5028
|
+
} catch (err) {
|
|
5029
|
+
await rm6(s.dir, { recursive: true, force: true });
|
|
4841
5030
|
throw err;
|
|
4842
5031
|
}
|
|
4843
5032
|
}
|
|
@@ -4902,20 +5091,25 @@ async function uploadOnce(id, req, signal, p) {
|
|
|
4902
5091
|
} finally {
|
|
4903
5092
|
await fh.close();
|
|
4904
5093
|
}
|
|
4905
|
-
await
|
|
5094
|
+
await rm6(s.dir, { recursive: true, force: true });
|
|
4906
5095
|
return { chunks: work.length, bytes, sizes };
|
|
4907
5096
|
}
|
|
4908
5097
|
async function dropBackup(id, p = paths()) {
|
|
4909
5098
|
checkId(id);
|
|
4910
5099
|
uploads.get(id)?.abort();
|
|
4911
|
-
await
|
|
5100
|
+
await rm6(p.backup(id).dir, { recursive: true, force: true });
|
|
4912
5101
|
}
|
|
4913
5102
|
async function clearStagedBackups(p = paths()) {
|
|
4914
|
-
await
|
|
5103
|
+
await rm6(p.backups, { recursive: true, force: true });
|
|
4915
5104
|
const prefix = basename2(p.machine("x", "x").restoring);
|
|
4916
5105
|
for (const ref of await listMachineRefs(p)) {
|
|
4917
5106
|
const dir = p.machine(ref.owner, ref.name).dir;
|
|
4918
|
-
for (const f of await readdir6(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await
|
|
5107
|
+
for (const f of await readdir6(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await rm6(join3(dir, f), { force: true });
|
|
5108
|
+
}
|
|
5109
|
+
const volumePrefix = basename2(p.volume("x", "x").restoring);
|
|
5110
|
+
for (const ref of await listVolumeRefs(p)) {
|
|
5111
|
+
const dir = p.volume(ref.owner, ref.name).dir;
|
|
5112
|
+
for (const f of await readdir6(dir).catch(() => [])) if (f.startsWith(`${volumePrefix}.`)) await rm6(join3(dir, f), { force: true });
|
|
4919
5113
|
}
|
|
4920
5114
|
}
|
|
4921
5115
|
async function downloadDisk(file, req, p = paths()) {
|
|
@@ -4946,8 +5140,9 @@ async function downloadDisk(file, req, p = paths()) {
|
|
|
4946
5140
|
}
|
|
4947
5141
|
}
|
|
4948
5142
|
var restoring = /* @__PURE__ */ new Set();
|
|
5143
|
+
var holding = /* @__PURE__ */ new Map();
|
|
4949
5144
|
function restoreRunning(ref) {
|
|
4950
|
-
return restoring.has(refKey(ref));
|
|
5145
|
+
return restoring.has(refKey(ref)) || holding.has(refKey(ref));
|
|
4951
5146
|
}
|
|
4952
5147
|
async function restoreBackup(ref, req, p = paths()) {
|
|
4953
5148
|
checkId(req.id);
|
|
@@ -4988,8 +5183,44 @@ async function restoreOnce(ref, req, p) {
|
|
|
4988
5183
|
await downloadDisk(file, req, p);
|
|
4989
5184
|
return await replaceDisk(ref, file, { base: req.base, image: req.image, vars }, p);
|
|
4990
5185
|
} finally {
|
|
4991
|
-
await
|
|
4992
|
-
await
|
|
5186
|
+
await rm6(file, { force: true });
|
|
5187
|
+
await rm6(envFile, { force: true });
|
|
5188
|
+
}
|
|
5189
|
+
}
|
|
5190
|
+
async function restoreVolumeBackup(ref, req, p = paths()) {
|
|
5191
|
+
checkId(req.id);
|
|
5192
|
+
const k = `volume:${refKey(ref)}`;
|
|
5193
|
+
if (restoring.has(k)) throw new KvboxError(`a restore of volume ${shown(ref)} is already running; wait for it to finish`);
|
|
5194
|
+
restoring.add(k);
|
|
5195
|
+
const v = p.volume(ref.owner, ref.name);
|
|
5196
|
+
const file = `${v.restoring}.${randomBytes5(4).toString("hex")}`;
|
|
5197
|
+
let held2 = null;
|
|
5198
|
+
try {
|
|
5199
|
+
const meta = await readVolume(ref, p);
|
|
5200
|
+
const holder = await attachedBox(ref, p);
|
|
5201
|
+
if (holder !== null) {
|
|
5202
|
+
held2 = refKey({ owner: ref.owner, name: holder });
|
|
5203
|
+
holding.set(held2, (holding.get(held2) ?? 0) + 1);
|
|
5204
|
+
const box = await readBox2({ owner: ref.owner, name: holder }, p);
|
|
5205
|
+
if (!vmAlive(box) && existsSync8(p.machine(box.owner, box.name).hibernateVmstate)) {
|
|
5206
|
+
throw new KvboxError(`volume ${shown(ref)} is attached to box ${shown(box)}, which is hibernated; its memory belongs to the disks it has: kvbox wake ${shown(box)} or kvbox stop ${shown(box)} first`);
|
|
5207
|
+
}
|
|
5208
|
+
}
|
|
5209
|
+
if (req.sizeBytes > meta.sizeGib * 1024 ** 3) {
|
|
5210
|
+
const gib = Math.ceil(req.sizeBytes / 1024 ** 3);
|
|
5211
|
+
throw new KvboxError(`this backup's volume was ${gib} GB and volume ${shown(ref)} is ${meta.sizeGib} GB: kvbox volume grow ${shown(ref)} ${gib} first`);
|
|
5212
|
+
}
|
|
5213
|
+
await assertRoom(v.dir, req.chunks.length * CHUNK_SIZE, `a restore of volume ${shown(ref)}`, p);
|
|
5214
|
+
await downloadDisk(file, req, p);
|
|
5215
|
+
return await replaceVolumeDisk(ref, file, p);
|
|
5216
|
+
} finally {
|
|
5217
|
+
restoring.delete(k);
|
|
5218
|
+
if (held2 !== null) {
|
|
5219
|
+
const n = (holding.get(held2) ?? 1) - 1;
|
|
5220
|
+
if (n > 0) holding.set(held2, n);
|
|
5221
|
+
else holding.delete(held2);
|
|
5222
|
+
}
|
|
5223
|
+
await rm6(file, { force: true });
|
|
4993
5224
|
}
|
|
4994
5225
|
}
|
|
4995
5226
|
async function pool(items, fn) {
|
|
@@ -5024,7 +5255,7 @@ async function withTries(what, fn, signal) {
|
|
|
5024
5255
|
}
|
|
5025
5256
|
|
|
5026
5257
|
// src/core/relay.ts
|
|
5027
|
-
import { access as access2, chmod as chmod4, mkdir as mkdir9, rm as
|
|
5258
|
+
import { access as access2, chmod as chmod4, mkdir as mkdir9, rm as rm7, writeFile as writeFile8 } from "node:fs/promises";
|
|
5028
5259
|
|
|
5029
5260
|
// ../shared/src/relay.ts
|
|
5030
5261
|
import { z as z7 } from "zod";
|
|
@@ -5206,6 +5437,19 @@ async function fetchCloudCa(p = paths()) {
|
|
|
5206
5437
|
const publicKey = parseSshPublicKey(parsed.data.publicKey);
|
|
5207
5438
|
return { controlPlane: cp.name, publicKey, fingerprint: sshKeyFingerprint(publicKey) };
|
|
5208
5439
|
}
|
|
5440
|
+
async function fetchCloudName(p = paths()) {
|
|
5441
|
+
const cfg = await loadConfig(p);
|
|
5442
|
+
const cp = cfg.controlPlane;
|
|
5443
|
+
if (!cp) throw new KvboxError("this host has not joined a control plane, so there is no name to ask for; give it: kvbox-server rename-realm <name>");
|
|
5444
|
+
const res = await request3(`${cp.url}/health`, { headersTimeout: 1e4, bodyTimeout: 1e4 }).catch((err) => {
|
|
5445
|
+
throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);
|
|
5446
|
+
});
|
|
5447
|
+
const text = await res.body.text();
|
|
5448
|
+
if (res.statusCode < 200 || res.statusCode >= 300) throw new KvboxError(`${cp.url} answered ${res.statusCode}`);
|
|
5449
|
+
const name = jsonOrNull(text)?.name;
|
|
5450
|
+
if (typeof name !== "string" || !REALM_RE.test(name)) throw new KvboxError(`${cp.url} did not say its name; give it: kvbox-server rename-realm <name>`);
|
|
5451
|
+
return name;
|
|
5452
|
+
}
|
|
5209
5453
|
async function leaveControlPlane(p = paths()) {
|
|
5210
5454
|
const cfg = await loadConfig(p);
|
|
5211
5455
|
const cp = cfg.controlPlane;
|
|
@@ -5290,7 +5534,7 @@ async function dropRelay(p = paths()) {
|
|
|
5290
5534
|
throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox-server leave first`);
|
|
5291
5535
|
}
|
|
5292
5536
|
await netSetup(cfg, ["relay", "down"]);
|
|
5293
|
-
await
|
|
5537
|
+
await rm7(p.relayConf, { force: true });
|
|
5294
5538
|
const { relay: _gone, ...rest } = cfg;
|
|
5295
5539
|
await saveConfig(rest, p);
|
|
5296
5540
|
return relay;
|
|
@@ -5728,7 +5972,7 @@ function groupWithMember(gid, user, groupFile) {
|
|
|
5728
5972
|
}
|
|
5729
5973
|
|
|
5730
5974
|
// src/listen.ts
|
|
5731
|
-
import { readFile as readFile12, rm as
|
|
5975
|
+
import { readFile as readFile12, rm as rm8, writeFile as writeFile10 } from "node:fs/promises";
|
|
5732
5976
|
import { createServer as createHttpsServer } from "node:https";
|
|
5733
5977
|
import { createAdaptorServer } from "@hono/node-server";
|
|
5734
5978
|
|
|
@@ -5765,7 +6009,7 @@ function versionOf(srcFileUrl, injected) {
|
|
|
5765
6009
|
}
|
|
5766
6010
|
|
|
5767
6011
|
// src/version.ts
|
|
5768
|
-
var VERSION = versionOf(import.meta.url, true ? "0.
|
|
6012
|
+
var VERSION = versionOf(import.meta.url, true ? "0.6.1" : void 0);
|
|
5769
6013
|
|
|
5770
6014
|
// src/caller.ts
|
|
5771
6015
|
import { createHash as createHash3, timingSafeEqual } from "node:crypto";
|
|
@@ -5883,6 +6127,20 @@ function backupMachineRoutes() {
|
|
|
5883
6127
|
});
|
|
5884
6128
|
return r;
|
|
5885
6129
|
}
|
|
6130
|
+
function backupVolumeRoutes() {
|
|
6131
|
+
const r = new Hono();
|
|
6132
|
+
r.post("/:name/backup", async (c) => {
|
|
6133
|
+
const body = HostBackupRequest.safeParse(await c.req.json().catch(() => ({})));
|
|
6134
|
+
if (!body.success) throw new KvboxError("backup: expected {id, key}");
|
|
6135
|
+
return c.json(await stageVolumeBackup(parseRef(c.req.param("name"), c.get("owner")), body.data));
|
|
6136
|
+
});
|
|
6137
|
+
r.post("/:name/restore", async (c) => {
|
|
6138
|
+
const body = HostVolumeRestoreRequest.safeParse(await c.req.json().catch(() => ({})));
|
|
6139
|
+
if (!body.success) throw new KvboxError("restore: expected {id, key, sizeBytes, chunks}");
|
|
6140
|
+
return c.json(await restoreVolumeBackup(parseRef(c.req.param("name"), c.get("owner")), body.data));
|
|
6141
|
+
});
|
|
6142
|
+
return r;
|
|
6143
|
+
}
|
|
5886
6144
|
function backupRoutes() {
|
|
5887
6145
|
const r = new Hono();
|
|
5888
6146
|
r.post("/:id/upload", async (c) => {
|
|
@@ -6462,6 +6720,7 @@ function createApp(opts = {}) {
|
|
|
6462
6720
|
if (opts.controlPlane) app.route("/machines", boxHttpRoutes());
|
|
6463
6721
|
if (opts.controlPlane) {
|
|
6464
6722
|
app.route("/machines", backupMachineRoutes());
|
|
6723
|
+
app.route("/volumes", backupVolumeRoutes());
|
|
6465
6724
|
app.route("/backups", backupRoutes());
|
|
6466
6725
|
}
|
|
6467
6726
|
app.route("/machines", machineRoutes());
|
|
@@ -6493,7 +6752,7 @@ async function listen(opts = {}) {
|
|
|
6493
6752
|
throw new KvboxError(`socket path too long for a Unix socket (${socketPath}); set KVBOX_HOME to a shorter path`);
|
|
6494
6753
|
}
|
|
6495
6754
|
if (socketPath === p.serverSock) await refuseSecondDaemon(p);
|
|
6496
|
-
await
|
|
6755
|
+
await rm8(socketPath, { force: true });
|
|
6497
6756
|
const server = createAdaptorServer({ fetch: createApp().fetch });
|
|
6498
6757
|
await new Promise((resolve3, reject) => {
|
|
6499
6758
|
server.once("error", reject);
|
|
@@ -6530,8 +6789,8 @@ async function listen(opts = {}) {
|
|
|
6530
6789
|
httpsServer.listen(port, "0.0.0.0", () => resolve3());
|
|
6531
6790
|
}).catch(async (err) => {
|
|
6532
6791
|
server.close();
|
|
6533
|
-
await
|
|
6534
|
-
await
|
|
6792
|
+
await rm8(socketPath, { force: true });
|
|
6793
|
+
await rm8(p.serverPid, { force: true });
|
|
6535
6794
|
throw new KvboxError(`cannot listen on port ${port} for ${cp.name} (${err.message})`);
|
|
6536
6795
|
});
|
|
6537
6796
|
const bound = httpsServer.address().port;
|
|
@@ -6542,15 +6801,15 @@ async function listen(opts = {}) {
|
|
|
6542
6801
|
new Promise((resolve3) => server.close(() => resolve3())),
|
|
6543
6802
|
httpsServer ? new Promise((resolve3) => httpsServer.close(() => resolve3())) : void 0
|
|
6544
6803
|
]);
|
|
6545
|
-
await
|
|
6546
|
-
await
|
|
6804
|
+
await rm8(socketPath, { force: true });
|
|
6805
|
+
await rm8(p.serverPid, { force: true });
|
|
6547
6806
|
};
|
|
6548
6807
|
const shutdown2 = async () => {
|
|
6549
6808
|
server.close();
|
|
6550
6809
|
httpsServer?.close();
|
|
6551
6810
|
await stopRecovery();
|
|
6552
|
-
await
|
|
6553
|
-
await
|
|
6811
|
+
await rm8(socketPath, { force: true });
|
|
6812
|
+
await rm8(p.serverPid, { force: true });
|
|
6554
6813
|
process.exit(0);
|
|
6555
6814
|
};
|
|
6556
6815
|
process.once("SIGINT", () => void shutdown2());
|
|
@@ -6632,7 +6891,7 @@ var startCommand = new Command("start").description("run the daemon in the foreg
|
|
|
6632
6891
|
});
|
|
6633
6892
|
|
|
6634
6893
|
// src/program.ts
|
|
6635
|
-
import { Command as
|
|
6894
|
+
import { Command as Command14 } from "commander";
|
|
6636
6895
|
|
|
6637
6896
|
// src/commands/backup/index.ts
|
|
6638
6897
|
import { Command as Command4 } from "commander";
|
|
@@ -6792,11 +7051,241 @@ var relayCommand = new Command9("relay").description("reach the internet through
|
|
|
6792
7051
|
console.log(`this host is reachable at ${relay.publicIp}; kvbox-server join advertises it by default`);
|
|
6793
7052
|
});
|
|
6794
7053
|
|
|
7054
|
+
// src/commands/rename-realm.ts
|
|
7055
|
+
import { Command as Command11 } from "commander";
|
|
7056
|
+
|
|
7057
|
+
// src/core/realm.ts
|
|
7058
|
+
import { lstat as lstat2, readFile as readFile14, readdir as readdir7, readlink, rename as rename7, rm as rm9, symlink as symlink2, writeFile as writeFile11 } from "node:fs/promises";
|
|
7059
|
+
import { z as z8 } from "zod";
|
|
7060
|
+
var esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
7061
|
+
async function ownersIn(root, from, suffix = "") {
|
|
7062
|
+
const entries = await readdir7(root).catch((err) => {
|
|
7063
|
+
if (err.code === "ENOENT") return [];
|
|
7064
|
+
throw err;
|
|
7065
|
+
});
|
|
7066
|
+
const tail = `@${from}${suffix}`;
|
|
7067
|
+
return entries.filter((e) => e.endsWith(tail)).map((e) => e.slice(0, e.length - suffix.length));
|
|
7068
|
+
}
|
|
7069
|
+
async function namesIn2(dir) {
|
|
7070
|
+
return (await readdir7(dir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
|
|
7071
|
+
}
|
|
7072
|
+
async function plan(from, to, p) {
|
|
7073
|
+
if (!REALM_RE.test(to)) throw new KvboxError(`"${to}" cannot name a realm (letters, digits, '.', '-')`);
|
|
7074
|
+
if (from === to) throw new KvboxError(`this host's cloud boxes are already under ${to}`);
|
|
7075
|
+
const tail = new RegExp(`@${esc(from)}$`);
|
|
7076
|
+
const owner = (o) => o.replace(tail, `@${to}`);
|
|
7077
|
+
const source = (s) => s.replace(new RegExp(`^((?:[a-z]+:)?[^/@]+)@${esc(from)}/`), `$1@${to}/`);
|
|
7078
|
+
const caLine = (line) => isCaLine(line) ? line.replace(/principals="([^"]*)"/, (_, list) => `principals="${list.split(",").map(owner).join(",")}"`) : line;
|
|
7079
|
+
const out = { boxes: [], snapshots: [], volumes: [], envOwners: await ownersIn(p.env, from, ".json") };
|
|
7080
|
+
const clash = async (path, what) => {
|
|
7081
|
+
if (await lstat2(path).then(() => true, () => false)) throw new KvboxError(`${what} already exists under ${to} (${path}); nothing was changed`);
|
|
7082
|
+
};
|
|
7083
|
+
const read = async (file, schema, what) => {
|
|
7084
|
+
try {
|
|
7085
|
+
return schema.parse(JSON.parse(await readFile14(file, "utf8")));
|
|
7086
|
+
} catch (err) {
|
|
7087
|
+
throw new KvboxError(`${what} cannot be read (${file}: ${err.message}); nothing was changed`);
|
|
7088
|
+
}
|
|
7089
|
+
};
|
|
7090
|
+
for (const oldOwner of await ownersIn(p.machines, from)) {
|
|
7091
|
+
await clash(p.ownerMachines(owner(oldOwner)), `boxes of ${owner(oldOwner)}`);
|
|
7092
|
+
for (const name of await namesIn2(p.ownerMachines(oldOwner))) {
|
|
7093
|
+
const meta = await read(p.machine(oldOwner, name).meta, MachineMetaSchema, `box ${oldOwner}/${name}`);
|
|
7094
|
+
const status = statusOf({ ...meta, owner: oldOwner, name }, p);
|
|
7095
|
+
const sshKeys = meta.sshKeys?.map(caLine);
|
|
7096
|
+
const keysChanged = sshKeys !== void 0 && sshKeys.some((l, i) => l !== meta.sshKeys[i]);
|
|
7097
|
+
out.boxes.push({
|
|
7098
|
+
oldOwner,
|
|
7099
|
+
name,
|
|
7100
|
+
status,
|
|
7101
|
+
meta: {
|
|
7102
|
+
...meta,
|
|
7103
|
+
owner: owner(meta.owner),
|
|
7104
|
+
source: source(meta.source),
|
|
7105
|
+
...sshKeys !== void 0 ? { sshKeys } : {},
|
|
7106
|
+
// A stopped box reads its lines at boot; any other guest still holds the old ones.
|
|
7107
|
+
...keysChanged ? { sshKeysStale: status === "stopped" ? void 0 : true } : {},
|
|
7108
|
+
...meta.links !== void 0 ? { links: meta.links.map((l) => ({ ...l, owner: owner(l.owner) })) } : {}
|
|
7109
|
+
}
|
|
7110
|
+
});
|
|
7111
|
+
}
|
|
7112
|
+
}
|
|
7113
|
+
for (const oldOwner of await ownersIn(p.snapshots, from)) {
|
|
7114
|
+
await clash(p.ownerSnapshots(owner(oldOwner)), `snapshots of ${owner(oldOwner)}`);
|
|
7115
|
+
for (const name of (await namesIn2(p.ownerSnapshots(oldOwner))).filter((n) => !n.startsWith("."))) {
|
|
7116
|
+
const meta = await read(p.snapshot(oldOwner, name).meta, SnapshotMetaSchema, `snapshot ${oldOwner}/${name}`);
|
|
7117
|
+
out.snapshots.push({ oldOwner, name, meta: { ...meta, owner: owner(meta.owner), source: source(meta.source) } });
|
|
7118
|
+
}
|
|
7119
|
+
}
|
|
7120
|
+
for (const oldOwner of await ownersIn(p.volumes, from)) {
|
|
7121
|
+
await clash(p.ownerVolumes(owner(oldOwner)), `volumes of ${owner(oldOwner)}`);
|
|
7122
|
+
for (const name of await namesIn2(p.ownerVolumes(oldOwner))) {
|
|
7123
|
+
const meta = await read(p.volume(oldOwner, name).meta, VolumeMetaSchema.extend({ id: z8.string().optional() }), `volume ${oldOwner}/${name}`);
|
|
7124
|
+
out.volumes.push({ oldOwner, name, meta: { ...meta, owner: owner(meta.owner) } });
|
|
7125
|
+
}
|
|
7126
|
+
}
|
|
7127
|
+
for (const oldOwner of out.envOwners) await clash(p.ownerEnv(owner(oldOwner)), `the variables of ${owner(oldOwner)}`);
|
|
7128
|
+
return out;
|
|
7129
|
+
}
|
|
7130
|
+
async function countRealm(from, to, p = paths()) {
|
|
7131
|
+
const planned = await plan(from, to, p);
|
|
7132
|
+
return { boxes: planned.boxes.length, snapshots: planned.snapshots.length, volumes: planned.volumes.length };
|
|
7133
|
+
}
|
|
7134
|
+
async function writeJson(file, value) {
|
|
7135
|
+
const tmp = `${file}.tmp`;
|
|
7136
|
+
await writeFile11(tmp, JSON.stringify(value, null, 2) + "\n");
|
|
7137
|
+
await rename7(tmp, file);
|
|
7138
|
+
}
|
|
7139
|
+
async function move(entries, metaOf, ownerDir, owners, to) {
|
|
7140
|
+
for (const e of entries) await writeJson(metaOf(e.oldOwner, e.name), e.meta);
|
|
7141
|
+
for (const o of owners) await rename7(ownerDir(o), ownerDir(to(o)));
|
|
7142
|
+
}
|
|
7143
|
+
async function renameRealm(from, to, p = paths()) {
|
|
7144
|
+
const planned = await plan(from, to, p);
|
|
7145
|
+
const tail = new RegExp(`@${esc(from)}$`);
|
|
7146
|
+
const owner = (o) => o.replace(tail, `@${to}`);
|
|
7147
|
+
await move(planned.volumes, (o, n) => p.volume(o, n).meta, p.ownerVolumes, await ownersIn(p.volumes, from), owner);
|
|
7148
|
+
await move(planned.snapshots, (o, n) => p.snapshot(o, n).meta, p.ownerSnapshots, await ownersIn(p.snapshots, from), owner);
|
|
7149
|
+
await move(planned.boxes, (o, n) => p.machine(o, n).meta, p.ownerMachines, await ownersIn(p.machines, from), owner);
|
|
7150
|
+
for (const box of planned.boxes) {
|
|
7151
|
+
const m = p.machine(box.meta.owner, box.name);
|
|
7152
|
+
for (const volume of box.meta.volumes ?? []) {
|
|
7153
|
+
const link3 = m.volumeDrive(volume);
|
|
7154
|
+
const target = await readlink(link3).catch(() => null);
|
|
7155
|
+
if (target !== p.volume(box.oldOwner, volume).disk) continue;
|
|
7156
|
+
await rm9(link3, { force: true });
|
|
7157
|
+
await symlink2(p.volume(box.meta.owner, volume).disk, link3);
|
|
7158
|
+
}
|
|
7159
|
+
}
|
|
7160
|
+
for (const o of planned.envOwners) await rename7(p.ownerEnv(o), p.ownerEnv(owner(o)));
|
|
7161
|
+
renameLedgerRealm(from, to, p);
|
|
7162
|
+
closeDb(p);
|
|
7163
|
+
const cfg = await loadConfig(p);
|
|
7164
|
+
if (cfg.controlPlane?.name === from) await saveConfig({ ...cfg, controlPlane: { ...cfg.controlPlane, name: to } }, p);
|
|
7165
|
+
const report2 = { from, to, boxes: planned.boxes.length, snapshots: planned.snapshots.length, volumes: planned.volumes.length, keysUpdated: [], keysPending: [] };
|
|
7166
|
+
for (const box of planned.boxes) {
|
|
7167
|
+
const { meta, status } = box;
|
|
7168
|
+
if (!(meta.sshKeys ?? []).some(isCaLine)) continue;
|
|
7169
|
+
const key = `${meta.owner}/${meta.name}`;
|
|
7170
|
+
if (status === "stopped") report2.keysPending.push({ box: key, when: "start" });
|
|
7171
|
+
else if (status === "hibernated") report2.keysPending.push({ box: key, when: "wake" });
|
|
7172
|
+
else if (status === "standby") report2.keysPending.push({ box: key, when: "resume" });
|
|
7173
|
+
else if (!meta.sshKeysStale) report2.keysUpdated.push(key);
|
|
7174
|
+
else {
|
|
7175
|
+
const why = await pushAuthorizedKeys(meta, p.machine(meta.owner, meta.name).vsock, p);
|
|
7176
|
+
if (why === void 0) {
|
|
7177
|
+
await writeJson(p.machine(meta.owner, meta.name).meta, { ...meta, sshKeysStale: void 0 });
|
|
7178
|
+
report2.keysUpdated.push(key);
|
|
7179
|
+
} else report2.keysPending.push({ box: key, when: "later", why });
|
|
7180
|
+
}
|
|
7181
|
+
}
|
|
7182
|
+
return report2;
|
|
7183
|
+
}
|
|
7184
|
+
|
|
7185
|
+
// src/commands/trust-ca.ts
|
|
7186
|
+
import { Command as Command10 } from "commander";
|
|
7187
|
+
var trustCaCommand = new Command10("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) => {
|
|
7188
|
+
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");
|
|
7189
|
+
if (publicKey !== void 0 && opts.fromCloud) throw new KvboxError("either a public key or --from-cloud, not both");
|
|
7190
|
+
const client = new SocketClient(paths().serverSock);
|
|
7191
|
+
try {
|
|
7192
|
+
let key = publicKey;
|
|
7193
|
+
if (key === void 0) {
|
|
7194
|
+
const ca = await client.cloudCa();
|
|
7195
|
+
console.log(`${ca.controlPlane} says its SSH CA is ${ca.fingerprint}`);
|
|
7196
|
+
if (!await confirm("make every cloud box on this host trust it (in place of the CA it trusts now)?", opts.yes ?? false)) {
|
|
7197
|
+
throw new KvboxError("cancelled", 130);
|
|
7198
|
+
}
|
|
7199
|
+
key = ca.publicKey;
|
|
7200
|
+
}
|
|
7201
|
+
const report2 = await client.trustCa({ publicKey: key });
|
|
7202
|
+
if (opts.json) console.log(JSON.stringify(report2, null, 2));
|
|
7203
|
+
else describeReport(report2);
|
|
7204
|
+
} finally {
|
|
7205
|
+
await client.close();
|
|
7206
|
+
}
|
|
7207
|
+
});
|
|
7208
|
+
async function confirm(question, yes) {
|
|
7209
|
+
if (yes) return true;
|
|
7210
|
+
if (!process.stdin.isTTY) {
|
|
7211
|
+
console.error("refusing without -y when stdin is not a terminal");
|
|
7212
|
+
return false;
|
|
7213
|
+
}
|
|
7214
|
+
const { createInterface } = await import("node:readline/promises");
|
|
7215
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
7216
|
+
try {
|
|
7217
|
+
const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();
|
|
7218
|
+
return answer === "y" || answer === "yes";
|
|
7219
|
+
} finally {
|
|
7220
|
+
rl.close();
|
|
7221
|
+
}
|
|
7222
|
+
}
|
|
7223
|
+
var WHEN = {
|
|
7224
|
+
start: "is stopped: it trusts the CA from its next start",
|
|
7225
|
+
wake: "is hibernated: it trusts the CA from its next wake",
|
|
7226
|
+
resume: "is in standby: it trusts the CA from its next resume",
|
|
7227
|
+
later: "is running but could not take it now; it trusts the CA from its next stop and start"
|
|
7228
|
+
};
|
|
7229
|
+
function describeReport(report2) {
|
|
7230
|
+
console.log(`CA ${report2.fingerprint}`);
|
|
7231
|
+
for (const box of report2.updated) console.log(`box ${box} now trusts the CA`);
|
|
7232
|
+
for (const p of report2.pending) console.log(`box ${p.box} ${WHEN[p.when]}${p.why ? ` (${p.why})` : ""}`);
|
|
7233
|
+
for (const f of report2.failed) console.error(`box ${f.box}: ${f.error}`);
|
|
7234
|
+
const parts = [`${report2.updated.length} box(es) updated now`, `${report2.pending.length} pending`, `${report2.failed.length} failed`];
|
|
7235
|
+
const skipped = report2.skipped ?? [];
|
|
7236
|
+
if (skipped.length > 0) parts.push(`${skipped.length} cloud box(es) without a CA line untouched (managed services: no certificate opens them)`);
|
|
7237
|
+
if (report2.local > 0) parts.push(`${report2.local} local box(es) untouched (they trust this host's key only)`);
|
|
7238
|
+
console.log(parts.join(", "));
|
|
7239
|
+
}
|
|
7240
|
+
|
|
7241
|
+
// src/commands/rename-realm.ts
|
|
7242
|
+
var renameRealmCommand = new Command11("rename-realm").description("move this host's cloud boxes to the control plane's new name (after KVBOX_CLOUD_NAME changed there)").argument("[name]", "the new name; without it the control plane is asked").option("--from <old>", "the name the boxes are under now (default: the one this host joined under)").option("-y, --yes", "do not ask for confirmation").option("--json", "print the report as JSON").action(async (name, opts) => {
|
|
7243
|
+
const p = paths();
|
|
7244
|
+
const cp = (await loadConfig(p)).controlPlane;
|
|
7245
|
+
const from = opts.from ?? cp?.name;
|
|
7246
|
+
if (from === void 0) throw new KvboxError("this host has not joined a control plane; say which name the boxes are under: --from <old>");
|
|
7247
|
+
const to = name ?? await fetchCloudName(p);
|
|
7248
|
+
if (from === to) {
|
|
7249
|
+
if (!opts.json) console.log(`nothing to do: the control plane is called ${to} and this host's boxes are already under that name`);
|
|
7250
|
+
else console.log(JSON.stringify({ from, to, boxes: 0, snapshots: 0, volumes: 0, keysUpdated: [], keysPending: [] }, null, 2));
|
|
7251
|
+
return;
|
|
7252
|
+
}
|
|
7253
|
+
const count = await countRealm(from, to, p);
|
|
7254
|
+
if (!opts.json) {
|
|
7255
|
+
console.log(`${name === void 0 ? `the control plane is now called ${to}; ` : ""}this host has ${count.boxes} box(es), ${count.snapshots} snapshot(s) and ${count.volumes} volume(s) under ${from}`);
|
|
7256
|
+
}
|
|
7257
|
+
if (!await confirm(`move them to ${to}? (kvbox-server restarts; boxes keep running, a backup in progress is lost)`, opts.yes ?? false)) {
|
|
7258
|
+
throw new KvboxError("cancelled", 130);
|
|
7259
|
+
}
|
|
7260
|
+
const pid = await daemonPid(p);
|
|
7261
|
+
if (pid !== null) await stopDaemon(pid);
|
|
7262
|
+
let report2;
|
|
7263
|
+
try {
|
|
7264
|
+
report2 = await renameRealm(from, to, p);
|
|
7265
|
+
} finally {
|
|
7266
|
+
if (pid !== null) await startDetached(p);
|
|
7267
|
+
}
|
|
7268
|
+
if (opts.json) console.log(JSON.stringify(report2, null, 2));
|
|
7269
|
+
else describe(report2, pid !== null);
|
|
7270
|
+
});
|
|
7271
|
+
var WHEN2 = {
|
|
7272
|
+
start: "is stopped: it accepts them from its next start",
|
|
7273
|
+
wake: "is hibernated: it accepts them from its next wake",
|
|
7274
|
+
resume: "is in standby: it accepts them from its next resume",
|
|
7275
|
+
later: "is running but could not take the change now; it accepts them from its next stop and start"
|
|
7276
|
+
};
|
|
7277
|
+
function describe(report2, restarted) {
|
|
7278
|
+
console.log(`moved ${report2.boxes} box(es), ${report2.snapshots} snapshot(s) and ${report2.volumes} volume(s) from ${report2.from} to ${report2.to}`);
|
|
7279
|
+
for (const box of report2.keysUpdated) console.log(`box ${box} accepts SSH certificates for ${report2.to} now`);
|
|
7280
|
+
for (const k of report2.keysPending) console.log(`box ${k.box} ${WHEN2[k.when]}${k.why ? ` (${k.why})` : ""}`);
|
|
7281
|
+
console.log(restarted ? "kvbox-server restarted" : "kvbox-server was not running; start it with kvbox-server start -d");
|
|
7282
|
+
}
|
|
7283
|
+
|
|
6795
7284
|
// src/commands/status.ts
|
|
6796
7285
|
import { homedir as homedir2 } from "node:os";
|
|
6797
7286
|
import { styleText } from "node:util";
|
|
6798
|
-
import { Command as
|
|
6799
|
-
var statusCommand2 = new
|
|
7287
|
+
import { Command as Command12 } from "commander";
|
|
7288
|
+
var statusCommand2 = new Command12("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) => {
|
|
6800
7289
|
const p = paths();
|
|
6801
7290
|
const atBoot = startsAtBoot(p);
|
|
6802
7291
|
const pid = await daemonPid(p);
|
|
@@ -6868,73 +7357,17 @@ function printStatus(health, atBoot, logPath) {
|
|
|
6868
7357
|
}
|
|
6869
7358
|
|
|
6870
7359
|
// src/commands/stop.ts
|
|
6871
|
-
import { Command as
|
|
6872
|
-
var stopCommand = new
|
|
7360
|
+
import { Command as Command13 } from "commander";
|
|
7361
|
+
var stopCommand = new Command13("stop").description("stop the daemon (running boxes are not affected)").action(async () => {
|
|
6873
7362
|
const pid = await daemonPid(paths());
|
|
6874
7363
|
if (pid === null) throw new KvboxError("kvbox-server is not running");
|
|
6875
7364
|
await stopDaemon(pid);
|
|
6876
7365
|
console.log(`kvbox-server stopped (pid ${pid}); boxes keep running`);
|
|
6877
7366
|
});
|
|
6878
7367
|
|
|
6879
|
-
// src/commands/trust-ca.ts
|
|
6880
|
-
import { Command as Command12 } from "commander";
|
|
6881
|
-
var trustCaCommand = new Command12("trust-ca").description("make every cloud box on this host trust a new SSH CA (after `ca rotate` on the control plane)").argument("[public-key]", "the CA public key (or its cert-authority line); or --from-cloud").option("--from-cloud", "ask the control plane this host joined for its current CA, show the fingerprint, then ask").option("-y, --yes", "do not ask for confirmation").option("--json", "print the report as JSON").action(async (publicKey, opts) => {
|
|
6882
|
-
if (publicKey === void 0 && !opts.fromCloud) throw new KvboxError("give the CA public key, or --from-cloud to fetch it from the control plane this host joined");
|
|
6883
|
-
if (publicKey !== void 0 && opts.fromCloud) throw new KvboxError("either a public key or --from-cloud, not both");
|
|
6884
|
-
const client = new SocketClient(paths().serverSock);
|
|
6885
|
-
try {
|
|
6886
|
-
let key = publicKey;
|
|
6887
|
-
if (key === void 0) {
|
|
6888
|
-
const ca = await client.cloudCa();
|
|
6889
|
-
console.log(`${ca.controlPlane} says its SSH CA is ${ca.fingerprint}`);
|
|
6890
|
-
if (!await confirm("make every cloud box on this host trust it (in place of the CA it trusts now)?", opts.yes ?? false)) {
|
|
6891
|
-
throw new KvboxError("cancelled", 130);
|
|
6892
|
-
}
|
|
6893
|
-
key = ca.publicKey;
|
|
6894
|
-
}
|
|
6895
|
-
const report2 = await client.trustCa({ publicKey: key });
|
|
6896
|
-
if (opts.json) console.log(JSON.stringify(report2, null, 2));
|
|
6897
|
-
else describeReport(report2);
|
|
6898
|
-
} finally {
|
|
6899
|
-
await client.close();
|
|
6900
|
-
}
|
|
6901
|
-
});
|
|
6902
|
-
async function confirm(question, yes) {
|
|
6903
|
-
if (yes) return true;
|
|
6904
|
-
if (!process.stdin.isTTY) {
|
|
6905
|
-
console.error("refusing without -y when stdin is not a terminal");
|
|
6906
|
-
return false;
|
|
6907
|
-
}
|
|
6908
|
-
const { createInterface } = await import("node:readline/promises");
|
|
6909
|
-
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
6910
|
-
try {
|
|
6911
|
-
const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();
|
|
6912
|
-
return answer === "y" || answer === "yes";
|
|
6913
|
-
} finally {
|
|
6914
|
-
rl.close();
|
|
6915
|
-
}
|
|
6916
|
-
}
|
|
6917
|
-
var WHEN = {
|
|
6918
|
-
start: "is stopped: it trusts the CA from its next start",
|
|
6919
|
-
wake: "is hibernated: it trusts the CA from its next wake",
|
|
6920
|
-
resume: "is in standby: it trusts the CA from its next resume",
|
|
6921
|
-
later: "is running but could not take it now; it trusts the CA from its next stop and start"
|
|
6922
|
-
};
|
|
6923
|
-
function describeReport(report2) {
|
|
6924
|
-
console.log(`CA ${report2.fingerprint}`);
|
|
6925
|
-
for (const box of report2.updated) console.log(`box ${box} now trusts the CA`);
|
|
6926
|
-
for (const p of report2.pending) console.log(`box ${p.box} ${WHEN[p.when]}${p.why ? ` (${p.why})` : ""}`);
|
|
6927
|
-
for (const f of report2.failed) console.error(`box ${f.box}: ${f.error}`);
|
|
6928
|
-
const parts = [`${report2.updated.length} box(es) updated now`, `${report2.pending.length} pending`, `${report2.failed.length} failed`];
|
|
6929
|
-
const skipped = report2.skipped ?? [];
|
|
6930
|
-
if (skipped.length > 0) parts.push(`${skipped.length} cloud box(es) without a CA line untouched (managed services: no certificate opens them)`);
|
|
6931
|
-
if (report2.local > 0) parts.push(`${report2.local} local box(es) untouched (they trust this host's key only)`);
|
|
6932
|
-
console.log(parts.join(", "));
|
|
6933
|
-
}
|
|
6934
|
-
|
|
6935
7368
|
// src/program.ts
|
|
6936
7369
|
function buildProgram() {
|
|
6937
|
-
return new
|
|
7370
|
+
return new Command14("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(renameRealmCommand).addCommand(backupCommand).addCommand(netCommand);
|
|
6938
7371
|
}
|
|
6939
7372
|
|
|
6940
7373
|
// src/index.ts
|