@kvbox/server 0.5.36 → 0.5.38
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 +532 -54
- package/dist/kvbox-server.js.map +1 -1
- package/package.json +1 -1
package/dist/kvbox-server.js
CHANGED
|
@@ -85,6 +85,8 @@ function paths(home = kvboxHome()) {
|
|
|
85
85
|
env: join(dir, "env.json"),
|
|
86
86
|
/** The box's writable layer, stacked on the read-only base image inside the guest. */
|
|
87
87
|
overlay: join(dir, "overlay.ext4"),
|
|
88
|
+
/** A restore's disk while it downloads (a backup's chunks), renamed over `overlay` once complete. */
|
|
89
|
+
restoring: join(dir, "overlay.ext4.restore"),
|
|
88
90
|
/**
|
|
89
91
|
* The box's memory as of its last snapshot (a hard link to that snapshot's `mem`, never modified).
|
|
90
92
|
* The next snapshot is a diff of the pages dirtied since, merged onto this. Absent after a boot.
|
|
@@ -123,6 +125,16 @@ function paths(home = kvboxHome()) {
|
|
|
123
125
|
/** Each owner's environment variables as the control plane last sent them (#88): env/<owner>.json, mode 600. */
|
|
124
126
|
env: join(home, "env"),
|
|
125
127
|
ownerEnv: (owner) => join(home, "env", `${owner}.json`),
|
|
128
|
+
/**
|
|
129
|
+
* Backups in progress (decision "Backups: encrypted 4 MiB chunks in object storage"): backups/<id>/ holds the
|
|
130
|
+
* copy of the box's disk being uploaded and its chunk list, gone once the upload ends. Nothing here outlives
|
|
131
|
+
* a daemon restart.
|
|
132
|
+
*/
|
|
133
|
+
backups: join(home, "backups"),
|
|
134
|
+
backup: (id) => {
|
|
135
|
+
const dir = join(home, "backups", id);
|
|
136
|
+
return { dir, disk: join(dir, "disk.ext4"), chunks: join(dir, "chunks.json") };
|
|
137
|
+
},
|
|
126
138
|
snapshot: (owner, name) => {
|
|
127
139
|
const dir = join(home, "snapshots", owner, name);
|
|
128
140
|
return {
|
|
@@ -506,6 +518,52 @@ var WakeHookCallSchema = z3.object({
|
|
|
506
518
|
action: z3.enum(["wake", "resume", "none"]),
|
|
507
519
|
reason: z3.string().optional()
|
|
508
520
|
});
|
|
521
|
+
var BACKUP_STATUSES = ["running", "ready", "failed"];
|
|
522
|
+
var BackupSchema = z3.object({
|
|
523
|
+
id: z3.string(),
|
|
524
|
+
owner: z3.string(),
|
|
525
|
+
box: z3.string(),
|
|
526
|
+
status: z3.enum(BACKUP_STATUSES),
|
|
527
|
+
/** Why it failed; null otherwise. */
|
|
528
|
+
error: z3.string().nullable(),
|
|
529
|
+
/** The image version the disk stacks on (a restore needs it on the host), and the image (absent: base). */
|
|
530
|
+
base: z3.string().nullable(),
|
|
531
|
+
image: z3.string().optional(),
|
|
532
|
+
vcpu: z3.number().int().nullable(),
|
|
533
|
+
memMib: z3.number().int().nullable(),
|
|
534
|
+
/** The disk's size. */
|
|
535
|
+
diskBytes: z3.number().int().nullable(),
|
|
536
|
+
/** What it holds: the slots that are not all zeros. */
|
|
537
|
+
dataBytes: z3.number().int().nullable(),
|
|
538
|
+
/** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
|
|
539
|
+
uploadedBytes: z3.number().int().nullable(),
|
|
540
|
+
createdBy: z3.string().nullable(),
|
|
541
|
+
createdAt: z3.string(),
|
|
542
|
+
finishedAt: z3.string().nullable()
|
|
543
|
+
});
|
|
544
|
+
var HostBackupRequest = z3.object({ id: z3.string(), key: z3.string() });
|
|
545
|
+
var HostBackupManifestSchema = z3.object({
|
|
546
|
+
id: z3.string(),
|
|
547
|
+
sizeBytes: z3.number().int(),
|
|
548
|
+
chunks: z3.array(z3.string().nullable()),
|
|
549
|
+
env: z3.string().nullable(),
|
|
550
|
+
base: z3.string(),
|
|
551
|
+
image: z3.string().optional(),
|
|
552
|
+
vcpu: z3.number().int(),
|
|
553
|
+
memMib: z3.number().int()
|
|
554
|
+
});
|
|
555
|
+
var HostUploadRequest = z3.object({ key: z3.string(), urls: z3.record(z3.string(), z3.string()) });
|
|
556
|
+
var HostUploadResultSchema = z3.object({ chunks: z3.number().int(), bytes: z3.number().int(), sizes: z3.record(z3.string(), z3.number().int()) });
|
|
557
|
+
var HostRestoreRequest = z3.object({
|
|
558
|
+
/** The backup's id: its variables were sealed under it. */
|
|
559
|
+
id: z3.string(),
|
|
560
|
+
key: z3.string(),
|
|
561
|
+
sizeBytes: z3.number().int().positive(),
|
|
562
|
+
base: z3.string(),
|
|
563
|
+
image: z3.string().optional(),
|
|
564
|
+
env: z3.string().nullable(),
|
|
565
|
+
chunks: z3.array(z3.object({ index: z3.number().int().nonnegative(), hash: z3.string(), url: z3.string() }))
|
|
566
|
+
});
|
|
509
567
|
var MachineSchema = z3.object({
|
|
510
568
|
/** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */
|
|
511
569
|
id: z3.string(),
|
|
@@ -544,6 +602,11 @@ var MachineSchema = z3.object({
|
|
|
544
602
|
ports: z3.array(PortForwardSchema).optional(),
|
|
545
603
|
/** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /machines`. */
|
|
546
604
|
ownerKind: z3.enum(["user", "org"]).optional(),
|
|
605
|
+
/**
|
|
606
|
+
* The name of the host the box runs on. Only the control plane fills it in, on `GET /machines`: a box
|
|
607
|
+
* links to, and a volume attaches to, only a box on the same host.
|
|
608
|
+
*/
|
|
609
|
+
host: z3.string().optional(),
|
|
547
610
|
/** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
|
|
548
611
|
autoHibernateSec: z3.number().int().positive().optional(),
|
|
549
612
|
/** A script inside the box that says it is idle (#102, exit 0): auto-hibernate asks it instead of watching the traffic. */
|
|
@@ -571,7 +634,9 @@ var VolumeSchema = z3.object({
|
|
|
571
634
|
attachedTo: z3.string().nullable(),
|
|
572
635
|
createdAt: z3.string(),
|
|
573
636
|
/** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /volumes`. */
|
|
574
|
-
ownerKind: z3.enum(["user", "org"]).optional()
|
|
637
|
+
ownerKind: z3.enum(["user", "org"]).optional(),
|
|
638
|
+
/** The name of the host the volume lives on; only the control plane fills it in. It attaches only to a box there. */
|
|
639
|
+
host: z3.string().optional()
|
|
575
640
|
});
|
|
576
641
|
var MAX_VOLUME_GIB = 4096;
|
|
577
642
|
var VOLUME_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
|
|
@@ -720,6 +785,7 @@ var CapacitySchema = z3.object({
|
|
|
720
785
|
*/
|
|
721
786
|
images: z3.array(z3.object({ name: z3.string(), version: z3.string() })).optional()
|
|
722
787
|
});
|
|
788
|
+
var ImageSchema = z3.object({ name: z3.string(), version: z3.string().nullable() });
|
|
723
789
|
var RecoveryReportSchema = z3.object({
|
|
724
790
|
at: z3.string(),
|
|
725
791
|
booted: z3.array(z3.string()),
|
|
@@ -1725,7 +1791,7 @@ async function startDns(opts) {
|
|
|
1725
1791
|
// src/core/machines.ts
|
|
1726
1792
|
import { spawn } from "node:child_process";
|
|
1727
1793
|
import { closeSync as closeSync2, existsSync as existsSync6, openSync as openSync2, statSync as statSync2 } from "node:fs";
|
|
1728
|
-
import { link as link2, mkdir as mkdir6, readFile as readFile6, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
|
|
1794
|
+
import { link as link2, mkdir as mkdir6, readFile as readFile6, rename as rename5, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
|
|
1729
1795
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
1730
1796
|
|
|
1731
1797
|
// ../shared/src/duration.ts
|
|
@@ -1905,7 +1971,7 @@ async function readBoxEnvFile(file) {
|
|
|
1905
1971
|
throw err;
|
|
1906
1972
|
}
|
|
1907
1973
|
}
|
|
1908
|
-
|
|
1974
|
+
function checkBoxEnv(vars) {
|
|
1909
1975
|
if (vars.length > ENV_MAX_VARS) throw new KvboxError(`at most ${ENV_MAX_VARS} variables`);
|
|
1910
1976
|
const seen = /* @__PURE__ */ new Set();
|
|
1911
1977
|
for (const v of vars) {
|
|
@@ -1914,6 +1980,9 @@ async function writeBoxEnv(box, vars, p = paths()) {
|
|
|
1914
1980
|
if (seen.has(v.name)) throw new KvboxError(`${v.name} is given twice`);
|
|
1915
1981
|
seen.add(v.name);
|
|
1916
1982
|
}
|
|
1983
|
+
}
|
|
1984
|
+
async function writeBoxEnv(box, vars, p = paths()) {
|
|
1985
|
+
checkBoxEnv(vars);
|
|
1917
1986
|
const file = p.machine(box.owner, box.name).env;
|
|
1918
1987
|
const tmp = `${file}.tmp`;
|
|
1919
1988
|
await writeFile3(tmp, JSON.stringify({ vars }, null, 2) + "\n", { mode: 384 });
|
|
@@ -3508,7 +3577,7 @@ var startMachine = locked(async function startMachine2(ref, p = paths(), force =
|
|
|
3508
3577
|
pid = await launch(meta, tap, cfg, keysB64, p);
|
|
3509
3578
|
await openPorts(meta, cfg, p);
|
|
3510
3579
|
void pushEnvAfterBoot(meta, pid, p.machine(meta.owner, meta.name).vsock, p);
|
|
3511
|
-
const started = { ...meta, pid, bootId: currentBootId(), sshKeysStale: void 0 };
|
|
3580
|
+
const started = { ...meta, pid, bootId: currentBootId(), sshKeysStale: void 0, paused: void 0 };
|
|
3512
3581
|
await writeMachineMeta(started, p);
|
|
3513
3582
|
recordState(started, "running", "start", p);
|
|
3514
3583
|
return toMachine(started, p);
|
|
@@ -3723,6 +3792,20 @@ var rescaleMachine = locked(async function rescaleMachine2(ref, req, p = paths()
|
|
|
3723
3792
|
}
|
|
3724
3793
|
return applyAtNextBoot(meta, changes, "rescale", cfg, p, growTo === void 0 ? void 0 : () => growDisk(disk, growTo));
|
|
3725
3794
|
});
|
|
3795
|
+
var replaceDisk = locked(async function replaceDisk2(ref, file, disk, p = paths()) {
|
|
3796
|
+
const meta = await readMeta(ref, p);
|
|
3797
|
+
const cfg = await loadConfig(p);
|
|
3798
|
+
assertNotHibernated(meta, p);
|
|
3799
|
+
const m = p.machine(ref.owner, ref.name);
|
|
3800
|
+
const currentGib = Math.round(statSync2(m.overlay).size / 1024 ** 3);
|
|
3801
|
+
const restoredGib = Math.round(statSync2(file).size / 1024 ** 3);
|
|
3802
|
+
return applyAtNextBoot(meta, { base: disk.base, image: disk.image }, "restore", cfg, p, async () => {
|
|
3803
|
+
if (disk.vars === null) await rm3(m.env, { force: true });
|
|
3804
|
+
else await writeBoxEnv(ref, disk.vars, p);
|
|
3805
|
+
await rename5(file, m.overlay);
|
|
3806
|
+
if (currentGib > restoredGib) await growDisk(m.overlay, currentGib);
|
|
3807
|
+
});
|
|
3808
|
+
});
|
|
3726
3809
|
var attachVolume = locked(async function attachVolume2(ref, volume, p = paths()) {
|
|
3727
3810
|
const cfg = await loadConfig(p);
|
|
3728
3811
|
const claimed = await withHostLock("volumes", async () => {
|
|
@@ -3980,8 +4063,368 @@ async function bootRecovered(settled, p = paths()) {
|
|
|
3980
4063
|
return recovery;
|
|
3981
4064
|
}
|
|
3982
4065
|
|
|
4066
|
+
// src/core/backups.ts
|
|
4067
|
+
import { randomBytes as randomBytes4 } from "node:crypto";
|
|
4068
|
+
import { existsSync as existsSync7 } from "node:fs";
|
|
4069
|
+
import { mkdir as mkdir7, open, readdir as readdir6, readFile as readFile7, rm as rm4, stat as stat3, statfs as statfs2, writeFile as writeFile6 } from "node:fs/promises";
|
|
4070
|
+
import { basename as basename2, join as join2 } from "node:path";
|
|
4071
|
+
import { setTimeout as sleep2 } from "node:timers/promises";
|
|
4072
|
+
|
|
4073
|
+
// ../shared/src/backup.ts
|
|
4074
|
+
import { createCipheriv, createDecipheriv, createHmac, randomBytes as randomBytes3 } from "node:crypto";
|
|
4075
|
+
import { promisify as promisify2 } from "node:util";
|
|
4076
|
+
import { deflateRaw as deflateRawCb, inflateRaw as inflateRawCb, constants as zlib } from "node:zlib";
|
|
4077
|
+
var deflateRaw = promisify2(deflateRawCb);
|
|
4078
|
+
var inflateRaw = promisify2(inflateRawCb);
|
|
4079
|
+
var CHUNK_SIZE = 4 * 1024 * 1024;
|
|
4080
|
+
var BACKUP_ID_RE = /^bk_[A-Za-z0-9_-]{12}$/;
|
|
4081
|
+
var CHUNK_HASH_RE = /^[0-9a-f]{64}$/;
|
|
4082
|
+
var FLAG_RAW = 1;
|
|
4083
|
+
var FLAG_DEFLATE = 2;
|
|
4084
|
+
var NONCE = 12;
|
|
4085
|
+
var TAG = 16;
|
|
4086
|
+
function backupKeys(dataKeyB64) {
|
|
4087
|
+
const dk = Buffer.from(dataKeyB64, "base64");
|
|
4088
|
+
if (dk.length !== 32) throw new Error("backup key: expected 32 bytes");
|
|
4089
|
+
return {
|
|
4090
|
+
name: createHmac("sha256", dk).update("kvbox-backup chunk-name v1").digest(),
|
|
4091
|
+
seal: createHmac("sha256", dk).update("kvbox-backup chunk-seal v1").digest()
|
|
4092
|
+
};
|
|
4093
|
+
}
|
|
4094
|
+
function isZero(buf) {
|
|
4095
|
+
return buf.equals(zeros(buf.length));
|
|
4096
|
+
}
|
|
4097
|
+
var zeroBuf = Buffer.alloc(0);
|
|
4098
|
+
function zeros(n) {
|
|
4099
|
+
if (zeroBuf.length < n) zeroBuf = Buffer.alloc(n);
|
|
4100
|
+
return zeroBuf.subarray(0, n);
|
|
4101
|
+
}
|
|
4102
|
+
function chunkName(keys, plain) {
|
|
4103
|
+
return createHmac("sha256", keys.name).update(plain).digest("hex");
|
|
4104
|
+
}
|
|
4105
|
+
async function sealChunk(keys, name, plain) {
|
|
4106
|
+
const packed = await deflateRaw(plain, { level: zlib.Z_BEST_SPEED });
|
|
4107
|
+
const [flag, body] = packed.length < plain.length ? [FLAG_DEFLATE, packed] : [FLAG_RAW, plain];
|
|
4108
|
+
return seal(keys.seal, Buffer.from([flag]), body, `${name}:${flag}`);
|
|
4109
|
+
}
|
|
4110
|
+
async function openChunk(keys, name, stored) {
|
|
4111
|
+
if (stored.length < 1 + NONCE + TAG) throw new Error(`chunk ${name.slice(0, 12)}: too short to be one`);
|
|
4112
|
+
const flag = stored[0];
|
|
4113
|
+
if (flag !== FLAG_RAW && flag !== FLAG_DEFLATE) throw new Error(`chunk ${name.slice(0, 12)}: unknown format ${flag}`);
|
|
4114
|
+
const body = unseal(keys.seal, stored.subarray(1), `${name}:${flag}`, `chunk ${name.slice(0, 12)}`);
|
|
4115
|
+
const plain = flag === FLAG_DEFLATE ? await inflateRaw(body, { maxOutputLength: CHUNK_SIZE }) : body;
|
|
4116
|
+
if (chunkName(keys, plain) !== name) throw new Error(`chunk ${name.slice(0, 12)}: contents do not match its name`);
|
|
4117
|
+
return plain;
|
|
4118
|
+
}
|
|
4119
|
+
function sealText(keys, text, label) {
|
|
4120
|
+
return seal(keys.seal, Buffer.alloc(0), Buffer.from(text, "utf8"), label).toString("base64");
|
|
4121
|
+
}
|
|
4122
|
+
function openText(keys, sealedB64, label) {
|
|
4123
|
+
return unseal(keys.seal, Buffer.from(sealedB64, "base64"), label, label).toString("utf8");
|
|
4124
|
+
}
|
|
4125
|
+
function seal(key, prefix, plain, aad) {
|
|
4126
|
+
const nonce = randomBytes3(NONCE);
|
|
4127
|
+
const cipher = createCipheriv("aes-256-gcm", key, nonce);
|
|
4128
|
+
cipher.setAAD(Buffer.from(aad));
|
|
4129
|
+
const data = Buffer.concat([cipher.update(plain), cipher.final()]);
|
|
4130
|
+
return Buffer.concat([prefix, nonce, data, cipher.getAuthTag()]);
|
|
4131
|
+
}
|
|
4132
|
+
function unseal(key, sealed, aad, what) {
|
|
4133
|
+
if (sealed.length < NONCE + TAG) throw new Error(`${what}: too short`);
|
|
4134
|
+
const nonce = sealed.subarray(0, NONCE);
|
|
4135
|
+
const tag = sealed.subarray(sealed.length - TAG);
|
|
4136
|
+
const data = sealed.subarray(NONCE, sealed.length - TAG);
|
|
4137
|
+
try {
|
|
4138
|
+
const decipher = createDecipheriv("aes-256-gcm", key, nonce);
|
|
4139
|
+
decipher.setAAD(Buffer.from(aad));
|
|
4140
|
+
decipher.setAuthTag(tag);
|
|
4141
|
+
return Buffer.concat([decipher.update(data), decipher.final()]);
|
|
4142
|
+
} catch {
|
|
4143
|
+
throw new Error(`${what}: does not open with this slug's backup key (changed or not this slug's)`);
|
|
4144
|
+
}
|
|
4145
|
+
}
|
|
4146
|
+
function chunkCount(bytes) {
|
|
4147
|
+
return Math.ceil(bytes / CHUNK_SIZE);
|
|
4148
|
+
}
|
|
4149
|
+
|
|
4150
|
+
// src/core/backups.ts
|
|
4151
|
+
var PARALLEL = 4;
|
|
4152
|
+
var TRIES = 4;
|
|
4153
|
+
var CHUNK_TIMEOUT_MS = 12e4;
|
|
4154
|
+
async function assertRoom(dir, bytes, what, p) {
|
|
4155
|
+
const st = await statfs2(dir);
|
|
4156
|
+
const free = st.bavail * st.bsize;
|
|
4157
|
+
const headroom = (await loadConfig(p)).volumeHeadroomGib * 1024 ** 3;
|
|
4158
|
+
if (free - bytes < headroom) {
|
|
4159
|
+
const gib = (n) => (n / 1024 ** 3).toFixed(1);
|
|
4160
|
+
throw new KvboxError(`${what} needs ${gib(bytes)} GiB and this host has ${gib(free)} GiB free (keeping ${gib(headroom)} GiB spare); try again when it has room`);
|
|
4161
|
+
}
|
|
4162
|
+
}
|
|
4163
|
+
function checkId(id) {
|
|
4164
|
+
if (!BACKUP_ID_RE.test(id)) throw new KvboxError(`not a backup id: ${id}`);
|
|
4165
|
+
}
|
|
4166
|
+
async function readBox2(ref, p) {
|
|
4167
|
+
try {
|
|
4168
|
+
return await readMachineMeta(ref, p);
|
|
4169
|
+
} catch (err) {
|
|
4170
|
+
if (err.code === "ENOENT") throw new NotFoundError(`box ${shown(ref)}`);
|
|
4171
|
+
throw err;
|
|
4172
|
+
}
|
|
4173
|
+
}
|
|
4174
|
+
async function chunkNames(file, keys) {
|
|
4175
|
+
const { size } = await stat3(file);
|
|
4176
|
+
const chunks = [];
|
|
4177
|
+
const fh = await open(file, "r");
|
|
4178
|
+
try {
|
|
4179
|
+
const buf = Buffer.alloc(CHUNK_SIZE);
|
|
4180
|
+
for (let i = 0; i < chunkCount(size); i++) {
|
|
4181
|
+
const slot = await readSlot(fh, buf, i, size);
|
|
4182
|
+
chunks.push(isZero(slot) ? null : chunkName(keys, slot));
|
|
4183
|
+
}
|
|
4184
|
+
} finally {
|
|
4185
|
+
await fh.close();
|
|
4186
|
+
}
|
|
4187
|
+
return { sizeBytes: size, chunks };
|
|
4188
|
+
}
|
|
4189
|
+
async function readSlot(fh, buf, index, size) {
|
|
4190
|
+
const length = Math.min(CHUNK_SIZE, size - index * CHUNK_SIZE);
|
|
4191
|
+
let got = 0;
|
|
4192
|
+
while (got < length) {
|
|
4193
|
+
const { bytesRead } = await fh.read(buf, got, length - got, index * CHUNK_SIZE + got);
|
|
4194
|
+
if (bytesRead === 0) break;
|
|
4195
|
+
got += bytesRead;
|
|
4196
|
+
}
|
|
4197
|
+
return buf.subarray(0, length);
|
|
4198
|
+
}
|
|
4199
|
+
async function stageBackup(ref, req, p = paths()) {
|
|
4200
|
+
checkId(req.id);
|
|
4201
|
+
const keys = backupKeys(req.key);
|
|
4202
|
+
const s = p.backup(req.id);
|
|
4203
|
+
await rm4(s.dir, { recursive: true, force: true });
|
|
4204
|
+
await mkdir7(s.dir, { recursive: true, mode: 448 });
|
|
4205
|
+
try {
|
|
4206
|
+
const { meta, envText } = await withBoxLock(ref, async () => {
|
|
4207
|
+
const meta2 = await readBox2(ref, p);
|
|
4208
|
+
const m = p.machine(meta2.owner, meta2.name);
|
|
4209
|
+
await assertRoom(s.dir, (await stat3(m.overlay)).blocks * 512, `a backup of box ${shown(ref)}`, p);
|
|
4210
|
+
const copy = () => run(["cp", "--sparse=always", "--reflink=auto", m.overlay, s.disk], { timeoutMs: 6e5 });
|
|
4211
|
+
if (vmAlive(meta2) && !meta2.paused) {
|
|
4212
|
+
const fc = new FirecrackerClient(m.sock);
|
|
4213
|
+
try {
|
|
4214
|
+
await fc.pause();
|
|
4215
|
+
try {
|
|
4216
|
+
await copy();
|
|
4217
|
+
} finally {
|
|
4218
|
+
await resumeAfterCopy(fc, meta2, p);
|
|
4219
|
+
}
|
|
4220
|
+
} finally {
|
|
4221
|
+
await fc.close();
|
|
4222
|
+
}
|
|
4223
|
+
} else {
|
|
4224
|
+
await copy();
|
|
4225
|
+
}
|
|
4226
|
+
const envText2 = existsSync7(m.env) ? await readFile7(m.env, "utf8") : null;
|
|
4227
|
+
return { meta: meta2, envText: envText2 };
|
|
4228
|
+
});
|
|
4229
|
+
const { sizeBytes, chunks } = await chunkNames(s.disk, keys);
|
|
4230
|
+
await writeFile6(s.chunks, JSON.stringify({ chunks }), { mode: 384 });
|
|
4231
|
+
return {
|
|
4232
|
+
id: req.id,
|
|
4233
|
+
sizeBytes,
|
|
4234
|
+
chunks,
|
|
4235
|
+
env: envText === null ? null : sealText(keys, envText, `env:${req.id}`),
|
|
4236
|
+
base: meta.base,
|
|
4237
|
+
...meta.image !== void 0 ? { image: meta.image } : {},
|
|
4238
|
+
vcpu: meta.vcpu,
|
|
4239
|
+
memMib: meta.memMib
|
|
4240
|
+
};
|
|
4241
|
+
} catch (err) {
|
|
4242
|
+
await rm4(s.dir, { recursive: true, force: true });
|
|
4243
|
+
throw err;
|
|
4244
|
+
}
|
|
4245
|
+
}
|
|
4246
|
+
async function resumeAfterCopy(fc, meta, p) {
|
|
4247
|
+
try {
|
|
4248
|
+
await fc.resume();
|
|
4249
|
+
} catch {
|
|
4250
|
+
try {
|
|
4251
|
+
await fc.resume();
|
|
4252
|
+
} catch (err) {
|
|
4253
|
+
const why = err.message;
|
|
4254
|
+
if (!vmAlive(meta)) throw new KvboxError(`box ${shown(meta)} stopped while its disk was copied for the backup (${why}); kvbox start ${shown(meta)}`);
|
|
4255
|
+
const paused = { ...meta, paused: true };
|
|
4256
|
+
await writeMachineMeta(paused, p);
|
|
4257
|
+
recordState(paused, "standby", "backup", p);
|
|
4258
|
+
throw new KvboxError(`box ${shown(meta)} was paused for its backup and did not resume (${why}); kvbox resume ${shown(meta)}`);
|
|
4259
|
+
}
|
|
4260
|
+
}
|
|
4261
|
+
}
|
|
4262
|
+
var uploads = /* @__PURE__ */ new Map();
|
|
4263
|
+
async function uploadBackup(id, req, p = paths()) {
|
|
4264
|
+
checkId(id);
|
|
4265
|
+
const abort = new AbortController();
|
|
4266
|
+
uploads.get(id)?.abort();
|
|
4267
|
+
uploads.set(id, abort);
|
|
4268
|
+
try {
|
|
4269
|
+
return await uploadOnce(id, req, abort.signal, p);
|
|
4270
|
+
} finally {
|
|
4271
|
+
if (uploads.get(id) === abort) uploads.delete(id);
|
|
4272
|
+
}
|
|
4273
|
+
}
|
|
4274
|
+
async function uploadOnce(id, req, signal, p) {
|
|
4275
|
+
const s = p.backup(id);
|
|
4276
|
+
if (!existsSync7(s.chunks)) throw new NotFoundError(`backup ${id}`);
|
|
4277
|
+
const keys = backupKeys(req.key);
|
|
4278
|
+
const { chunks } = JSON.parse(await readFile7(s.chunks, "utf8"));
|
|
4279
|
+
const slotOf = /* @__PURE__ */ new Map();
|
|
4280
|
+
chunks.forEach((name, i) => {
|
|
4281
|
+
if (name !== null && !slotOf.has(name)) slotOf.set(name, i);
|
|
4282
|
+
});
|
|
4283
|
+
const work = Object.entries(req.urls).map(([name, url]) => {
|
|
4284
|
+
const index = slotOf.get(name);
|
|
4285
|
+
if (index === void 0) throw new KvboxError(`backup ${id} has no chunk ${name.slice(0, 12)}`);
|
|
4286
|
+
return { name, url, index };
|
|
4287
|
+
});
|
|
4288
|
+
const { size } = await stat3(s.disk);
|
|
4289
|
+
const fh = await open(s.disk, "r");
|
|
4290
|
+
let bytes = 0;
|
|
4291
|
+
const sizes = {};
|
|
4292
|
+
try {
|
|
4293
|
+
await pool(work, async ({ name, url, index }) => {
|
|
4294
|
+
const slot = Buffer.from(await readSlot(fh, Buffer.alloc(CHUNK_SIZE), index, size));
|
|
4295
|
+
const sealed = await sealChunk(keys, name, slot);
|
|
4296
|
+
await withTries(`upload of chunk ${index}`, async () => {
|
|
4297
|
+
const res = await fetch(url, { method: "PUT", body: sealed, signal: AbortSignal.any([signal, AbortSignal.timeout(CHUNK_TIMEOUT_MS)]) });
|
|
4298
|
+
if (!res.ok) throw new Error(`storage answered ${res.status}: ${(await res.text()).slice(0, 200)}`);
|
|
4299
|
+
}, signal);
|
|
4300
|
+
bytes += sealed.length;
|
|
4301
|
+
sizes[name] = sealed.length;
|
|
4302
|
+
});
|
|
4303
|
+
} finally {
|
|
4304
|
+
await fh.close();
|
|
4305
|
+
}
|
|
4306
|
+
await rm4(s.dir, { recursive: true, force: true });
|
|
4307
|
+
return { chunks: work.length, bytes, sizes };
|
|
4308
|
+
}
|
|
4309
|
+
async function dropBackup(id, p = paths()) {
|
|
4310
|
+
checkId(id);
|
|
4311
|
+
uploads.get(id)?.abort();
|
|
4312
|
+
await rm4(p.backup(id).dir, { recursive: true, force: true });
|
|
4313
|
+
}
|
|
4314
|
+
async function clearStagedBackups(p = paths()) {
|
|
4315
|
+
await rm4(p.backups, { recursive: true, force: true });
|
|
4316
|
+
const prefix = basename2(p.machine("x", "x").restoring);
|
|
4317
|
+
for (const ref of await listMachineRefs(p)) {
|
|
4318
|
+
const dir = p.machine(ref.owner, ref.name).dir;
|
|
4319
|
+
for (const f of await readdir6(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await rm4(join2(dir, f), { force: true });
|
|
4320
|
+
}
|
|
4321
|
+
}
|
|
4322
|
+
async function downloadDisk(file, req) {
|
|
4323
|
+
const keys = backupKeys(req.key);
|
|
4324
|
+
const slots = chunkCount(req.sizeBytes);
|
|
4325
|
+
for (const c of req.chunks) {
|
|
4326
|
+
if (c.index >= slots) throw new KvboxError(`chunk ${c.index} is past the end of a ${req.sizeBytes}-byte disk`);
|
|
4327
|
+
if (!CHUNK_HASH_RE.test(c.hash)) throw new KvboxError(`chunk ${c.index}: not a chunk name`);
|
|
4328
|
+
}
|
|
4329
|
+
await writeFile6(file, "", { mode: 384 });
|
|
4330
|
+
const fh = await open(file, "r+");
|
|
4331
|
+
try {
|
|
4332
|
+
await fh.truncate(req.sizeBytes);
|
|
4333
|
+
await pool(req.chunks, async ({ index, hash, url }) => {
|
|
4334
|
+
const plain = await withTries(`download of chunk ${index}`, async () => {
|
|
4335
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(CHUNK_TIMEOUT_MS) });
|
|
4336
|
+
if (!res.ok) throw new Error(`storage answered ${res.status}`);
|
|
4337
|
+
return Buffer.from(await res.arrayBuffer());
|
|
4338
|
+
});
|
|
4339
|
+
const slot = await openChunk(keys, hash, plain);
|
|
4340
|
+
const want = Math.min(CHUNK_SIZE, req.sizeBytes - index * CHUNK_SIZE);
|
|
4341
|
+
if (slot.length !== want) throw new KvboxError(`chunk ${index}: ${slot.length} bytes where the disk has room for ${want}`);
|
|
4342
|
+
await fh.write(slot, 0, slot.length, index * CHUNK_SIZE);
|
|
4343
|
+
});
|
|
4344
|
+
} finally {
|
|
4345
|
+
await fh.close();
|
|
4346
|
+
}
|
|
4347
|
+
}
|
|
4348
|
+
var restoring = /* @__PURE__ */ new Set();
|
|
4349
|
+
function restoreRunning(ref) {
|
|
4350
|
+
return restoring.has(refKey(ref));
|
|
4351
|
+
}
|
|
4352
|
+
async function restoreBackup(ref, req, p = paths()) {
|
|
4353
|
+
checkId(req.id);
|
|
4354
|
+
const k = refKey(ref);
|
|
4355
|
+
if (restoring.has(k)) throw new KvboxError(`a restore of box ${shown(ref)} is already running; wait for it to finish`);
|
|
4356
|
+
restoring.add(k);
|
|
4357
|
+
try {
|
|
4358
|
+
return await restoreOnce(ref, req, p);
|
|
4359
|
+
} finally {
|
|
4360
|
+
restoring.delete(k);
|
|
4361
|
+
}
|
|
4362
|
+
}
|
|
4363
|
+
async function restoreOnce(ref, req, p) {
|
|
4364
|
+
const meta = await readBox2(ref, p);
|
|
4365
|
+
if (!vmAlive(meta) && existsSync7(p.machine(ref.owner, ref.name).hibernateVmstate)) {
|
|
4366
|
+
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`);
|
|
4367
|
+
}
|
|
4368
|
+
if (!existsSync7(imageFile(req.image, req.base, p))) {
|
|
4369
|
+
throw new KvboxError(`this backup stacks on ${imageLabel(req.image)} ${req.base}, which this host does not have`);
|
|
4370
|
+
}
|
|
4371
|
+
const keys = backupKeys(req.key);
|
|
4372
|
+
const m = p.machine(ref.owner, ref.name);
|
|
4373
|
+
const current = (await stat3(m.overlay)).size;
|
|
4374
|
+
if (req.sizeBytes > current) {
|
|
4375
|
+
const gb2 = (n) => `${Math.ceil(n / 1024 ** 3)}GB`;
|
|
4376
|
+
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`);
|
|
4377
|
+
}
|
|
4378
|
+
const file = `${m.restoring}.${randomBytes4(4).toString("hex")}`;
|
|
4379
|
+
const envFile = `${file}.env`;
|
|
4380
|
+
try {
|
|
4381
|
+
let vars = null;
|
|
4382
|
+
if (req.env !== null) {
|
|
4383
|
+
await writeFile6(envFile, openText(keys, req.env, `env:${req.id}`), { mode: 384 });
|
|
4384
|
+
vars = await readBoxEnvFile(envFile);
|
|
4385
|
+
checkBoxEnv(vars);
|
|
4386
|
+
}
|
|
4387
|
+
await assertRoom(m.dir, req.chunks.length * CHUNK_SIZE, `a restore of box ${shown(ref)}`, p);
|
|
4388
|
+
await downloadDisk(file, req);
|
|
4389
|
+
return await replaceDisk(ref, file, { base: req.base, image: req.image, vars }, p);
|
|
4390
|
+
} finally {
|
|
4391
|
+
await rm4(file, { force: true });
|
|
4392
|
+
await rm4(envFile, { force: true });
|
|
4393
|
+
}
|
|
4394
|
+
}
|
|
4395
|
+
async function pool(items, fn) {
|
|
4396
|
+
let next = 0;
|
|
4397
|
+
let failed;
|
|
4398
|
+
const worker = async () => {
|
|
4399
|
+
while (failed === void 0 && next < items.length) {
|
|
4400
|
+
const item = items[next++];
|
|
4401
|
+
try {
|
|
4402
|
+
await fn(item);
|
|
4403
|
+
} catch (err) {
|
|
4404
|
+
failed ??= err;
|
|
4405
|
+
}
|
|
4406
|
+
}
|
|
4407
|
+
};
|
|
4408
|
+
await Promise.all(Array.from({ length: Math.min(PARALLEL, items.length) }, worker));
|
|
4409
|
+
if (failed !== void 0) throw failed;
|
|
4410
|
+
}
|
|
4411
|
+
async function withTries(what, fn, signal) {
|
|
4412
|
+
let last;
|
|
4413
|
+
for (let i = 0; i < TRIES; i++) {
|
|
4414
|
+
if (signal?.aborted) throw new KvboxError(`${what}: the backup was dropped`);
|
|
4415
|
+
try {
|
|
4416
|
+
return await fn();
|
|
4417
|
+
} catch (err) {
|
|
4418
|
+
if (signal?.aborted) throw new KvboxError(`${what}: the backup was dropped`);
|
|
4419
|
+
last = err;
|
|
4420
|
+
await sleep2(250 * 2 ** i);
|
|
4421
|
+
}
|
|
4422
|
+
}
|
|
4423
|
+
throw new KvboxError(`${what} failed ${TRIES} times: ${last.message}`);
|
|
4424
|
+
}
|
|
4425
|
+
|
|
3983
4426
|
// src/core/relay.ts
|
|
3984
|
-
import { chmod as chmod3, mkdir as
|
|
4427
|
+
import { chmod as chmod3, mkdir as mkdir8, rm as rm5, writeFile as writeFile7 } from "node:fs/promises";
|
|
3985
4428
|
|
|
3986
4429
|
// ../shared/src/relay.ts
|
|
3987
4430
|
import { z as z7 } from "zod";
|
|
@@ -4015,16 +4458,16 @@ function decodeRelayJoin(text) {
|
|
|
4015
4458
|
}
|
|
4016
4459
|
|
|
4017
4460
|
// src/core/relay.ts
|
|
4018
|
-
function relayConf(
|
|
4461
|
+
function relayConf(join3) {
|
|
4019
4462
|
return [
|
|
4020
4463
|
"# kvbox relay tunnel: made by `kvbox server relay`, installed by net-setup.sh. Do not edit.",
|
|
4021
4464
|
"[Interface]",
|
|
4022
|
-
`PrivateKey = ${
|
|
4023
|
-
`Address = ${
|
|
4465
|
+
`PrivateKey = ${join3.privateKey}`,
|
|
4466
|
+
`Address = ${join3.tunnelIp}/32`,
|
|
4024
4467
|
"",
|
|
4025
4468
|
"[Peer]",
|
|
4026
|
-
`PublicKey = ${
|
|
4027
|
-
`Endpoint = ${
|
|
4469
|
+
`PublicKey = ${join3.relayKey}`,
|
|
4470
|
+
`Endpoint = ${join3.relay}`,
|
|
4028
4471
|
// Only the relay's own tunnel address goes through the tunnel: the host keeps its normal internet
|
|
4029
4472
|
// route, and the relay SNATs forwarded connections so their replies come back this way.
|
|
4030
4473
|
`AllowedIPs = ${RELAY_TUNNEL_GATEWAY}/32`,
|
|
@@ -4034,22 +4477,22 @@ function relayConf(join2) {
|
|
|
4034
4477
|
].join("\n");
|
|
4035
4478
|
}
|
|
4036
4479
|
async function useRelay(joinString, p = paths()) {
|
|
4037
|
-
const
|
|
4038
|
-
if (!
|
|
4480
|
+
const join3 = decodeRelayJoin(joinString);
|
|
4481
|
+
if (!join3) throw new KvboxError("that is not a relay join string; copy the whole line `kvbox-relay add` printed on the relay");
|
|
4039
4482
|
const cfg = await loadConfig(p);
|
|
4040
|
-
if (cfg.relay && cfg.relay.name !==
|
|
4483
|
+
if (cfg.relay && cfg.relay.name !== join3.name) {
|
|
4041
4484
|
throw new KvboxError(`this host already goes through relay ${cfg.relay.name} (${cfg.relay.publicIp}); run kvbox server relay off first`);
|
|
4042
4485
|
}
|
|
4043
|
-
if (cfg.relay && cfg.relay.publicIp !==
|
|
4486
|
+
if (cfg.relay && cfg.relay.publicIp !== join3.publicIp && cfg.controlPlane?.advertise === cfg.relay.publicIp) {
|
|
4044
4487
|
throw new KvboxError(
|
|
4045
|
-
`${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${
|
|
4488
|
+
`${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${join3.publicIp}; run kvbox server leave first, then join again`
|
|
4046
4489
|
);
|
|
4047
4490
|
}
|
|
4048
|
-
await
|
|
4049
|
-
await
|
|
4491
|
+
await mkdir8(p.relay, { recursive: true, mode: 448 });
|
|
4492
|
+
await writeFile7(p.relayConf, relayConf(join3), { mode: 384 });
|
|
4050
4493
|
await chmod3(p.relayConf, 384);
|
|
4051
4494
|
await netSetup(cfg, ["relay", "up", p.relayConf, String(cfg.controlPlane?.port ?? DEFAULT_HTTPS_PORT)]);
|
|
4052
|
-
const relay = { name:
|
|
4495
|
+
const relay = { name: join3.name, publicIp: join3.publicIp, tunnelIp: join3.tunnelIp, endpoint: join3.relay };
|
|
4053
4496
|
await saveConfig({ ...cfg, relay }, p);
|
|
4054
4497
|
return relay;
|
|
4055
4498
|
}
|
|
@@ -4061,19 +4504,19 @@ async function dropRelay(p = paths()) {
|
|
|
4061
4504
|
throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox server leave first`);
|
|
4062
4505
|
}
|
|
4063
4506
|
await netSetup(cfg, ["relay", "down"]);
|
|
4064
|
-
await
|
|
4507
|
+
await rm5(p.relayConf, { force: true });
|
|
4065
4508
|
const { relay: _gone, ...rest } = cfg;
|
|
4066
4509
|
await saveConfig(rest, p);
|
|
4067
4510
|
return relay;
|
|
4068
4511
|
}
|
|
4069
4512
|
|
|
4070
4513
|
// src/core/idle.ts
|
|
4071
|
-
import { readFile as
|
|
4514
|
+
import { readFile as readFile8 } from "node:fs/promises";
|
|
4072
4515
|
var HIBERNATE_CONCURRENCY = 2;
|
|
4073
4516
|
async function tapTraffic(id) {
|
|
4074
4517
|
const dir = `/sys/class/net/${tapName(id)}/statistics`;
|
|
4075
4518
|
try {
|
|
4076
|
-
const [rx, tx] = await Promise.all([
|
|
4519
|
+
const [rx, tx] = await Promise.all([readFile8(`${dir}/rx_bytes`, "utf8"), readFile8(`${dir}/tx_bytes`, "utf8")]);
|
|
4077
4520
|
return Number(rx) + Number(tx);
|
|
4078
4521
|
} catch {
|
|
4079
4522
|
return null;
|
|
@@ -4086,7 +4529,7 @@ async function boxIdle(box, p) {
|
|
|
4086
4529
|
async function hibernateIfRunning(box, p) {
|
|
4087
4530
|
const ref = { owner: box.owner, name: box.name };
|
|
4088
4531
|
return withBoxLock(ref, async () => {
|
|
4089
|
-
if ((await getMachine(ref, p)).status !== "running") return false;
|
|
4532
|
+
if ((await getMachine(ref, p)).status !== "running" || restoreRunning(ref)) return false;
|
|
4090
4533
|
await hibernateMachine(ref, p, "auto-hibernate");
|
|
4091
4534
|
return true;
|
|
4092
4535
|
});
|
|
@@ -4098,7 +4541,7 @@ function startIdleWatch(opts = {}) {
|
|
|
4098
4541
|
const traffic = opts.traffic ?? tapTraffic;
|
|
4099
4542
|
const guestIdle = opts.guestIdle ?? ((box) => boxIdle(box, p));
|
|
4100
4543
|
const hibernate = opts.hibernate ?? ((box) => hibernateIfRunning(box, p));
|
|
4101
|
-
const busy = opts.busy ?? ((box) => boxBusy(box));
|
|
4544
|
+
const busy = opts.busy ?? ((box) => boxBusy(box) || restoreRunning(box));
|
|
4102
4545
|
const now = opts.now ?? Date.now;
|
|
4103
4546
|
const log = opts.log ?? ((line) => console.log(line));
|
|
4104
4547
|
const seen = /* @__PURE__ */ new Map();
|
|
@@ -4235,12 +4678,12 @@ function startRelayWatch(opts = {}) {
|
|
|
4235
4678
|
}
|
|
4236
4679
|
|
|
4237
4680
|
// src/listen.ts
|
|
4238
|
-
import { readFile as
|
|
4681
|
+
import { readFile as readFile9, rm as rm6, writeFile as writeFile8 } from "node:fs/promises";
|
|
4239
4682
|
import { createServer as createHttpsServer } from "node:https";
|
|
4240
4683
|
import { createAdaptorServer } from "@hono/node-server";
|
|
4241
4684
|
|
|
4242
4685
|
// src/app.ts
|
|
4243
|
-
import { Hono as
|
|
4686
|
+
import { Hono as Hono10 } from "hono";
|
|
4244
4687
|
|
|
4245
4688
|
// ../shared/src/version.ts
|
|
4246
4689
|
import { createRequire } from "node:module";
|
|
@@ -4255,13 +4698,13 @@ function versionOf(srcFileUrl, injected) {
|
|
|
4255
4698
|
}
|
|
4256
4699
|
|
|
4257
4700
|
// src/version.ts
|
|
4258
|
-
var VERSION = versionOf(import.meta.url, true ? "0.5.
|
|
4701
|
+
var VERSION = versionOf(import.meta.url, true ? "0.5.38" : void 0);
|
|
4259
4702
|
|
|
4260
4703
|
// src/caller.ts
|
|
4261
4704
|
import { createHash as createHash2, timingSafeEqual } from "node:crypto";
|
|
4262
4705
|
|
|
4263
4706
|
// ../shared/src/names.ts
|
|
4264
|
-
import { createHmac } from "node:crypto";
|
|
4707
|
+
import { createHmac as createHmac2 } from "node:crypto";
|
|
4265
4708
|
var PROXY_ERROR_HEADER = "x-kvbox-proxy-error";
|
|
4266
4709
|
var PROXIED_HEADER = "x-kvbox-proxied";
|
|
4267
4710
|
var VISITOR_PATH_HEADER = "x-kvbox-path";
|
|
@@ -4273,7 +4716,7 @@ var NOT_FORWARDED = /* @__PURE__ */ new Set(["expect"]);
|
|
|
4273
4716
|
var HOP_BY_HOP = /* @__PURE__ */ new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade"]);
|
|
4274
4717
|
var BOX_HTTP_PATH_RE = /^\/machines\/([^/]+)\/http\/(\d{1,5})\/?$/;
|
|
4275
4718
|
function edgeCredential(hostSecret) {
|
|
4276
|
-
return
|
|
4719
|
+
return createHmac2("sha256", hostSecret).update("kvbox-edge-v1").digest("base64url");
|
|
4277
4720
|
}
|
|
4278
4721
|
|
|
4279
4722
|
// src/caller.ts
|
|
@@ -4328,10 +4771,40 @@ function digest(secret) {
|
|
|
4328
4771
|
return createHash2("sha256").update(secret).digest();
|
|
4329
4772
|
}
|
|
4330
4773
|
|
|
4774
|
+
// src/routes/backups.ts
|
|
4775
|
+
import { Hono } from "hono";
|
|
4776
|
+
function backupMachineRoutes() {
|
|
4777
|
+
const r = new Hono();
|
|
4778
|
+
r.post("/:name/backup", async (c) => {
|
|
4779
|
+
const body = HostBackupRequest.safeParse(await c.req.json().catch(() => ({})));
|
|
4780
|
+
if (!body.success) throw new KvboxError("backup: expected {id, key}");
|
|
4781
|
+
return c.json(await stageBackup(parseRef(c.req.param("name"), c.get("owner")), body.data));
|
|
4782
|
+
});
|
|
4783
|
+
r.post("/:name/restore", async (c) => {
|
|
4784
|
+
const body = HostRestoreRequest.safeParse(await c.req.json().catch(() => ({})));
|
|
4785
|
+
if (!body.success) throw new KvboxError("restore: expected {id, key, sizeBytes, base, env, chunks}");
|
|
4786
|
+
return c.json(await restoreBackup(parseRef(c.req.param("name"), c.get("owner")), body.data));
|
|
4787
|
+
});
|
|
4788
|
+
return r;
|
|
4789
|
+
}
|
|
4790
|
+
function backupRoutes() {
|
|
4791
|
+
const r = new Hono();
|
|
4792
|
+
r.post("/:id/upload", async (c) => {
|
|
4793
|
+
const body = HostUploadRequest.safeParse(await c.req.json().catch(() => ({})));
|
|
4794
|
+
if (!body.success) throw new KvboxError("upload: expected {key, urls}");
|
|
4795
|
+
return c.json(await uploadBackup(c.req.param("id"), body.data));
|
|
4796
|
+
});
|
|
4797
|
+
r.delete("/:id", async (c) => {
|
|
4798
|
+
await dropBackup(c.req.param("id"));
|
|
4799
|
+
return c.body(null, 204);
|
|
4800
|
+
});
|
|
4801
|
+
return r;
|
|
4802
|
+
}
|
|
4803
|
+
|
|
4331
4804
|
// src/routes/boxHttp.ts
|
|
4332
4805
|
import { connect as connect2 } from "node:net";
|
|
4333
4806
|
import { Readable } from "node:stream";
|
|
4334
|
-
import { Hono } from "hono";
|
|
4807
|
+
import { Hono as Hono2 } from "hono";
|
|
4335
4808
|
import { request as request3 } from "undici";
|
|
4336
4809
|
|
|
4337
4810
|
// ../shared/src/httpHead.ts
|
|
@@ -4457,7 +4930,7 @@ function boxHeaders(incoming, target, upgrade = false) {
|
|
|
4457
4930
|
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" } : {} } });
|
|
4458
4931
|
var wants = (value) => value === "1";
|
|
4459
4932
|
function boxHttpRoutes(wake = wakeBox) {
|
|
4460
|
-
const r = new
|
|
4933
|
+
const r = new Hono2();
|
|
4461
4934
|
r.all("/:name/http/:port", (c) => forward(c, wake));
|
|
4462
4935
|
return r;
|
|
4463
4936
|
}
|
|
@@ -4576,17 +5049,17 @@ ${lines.join("")}\r
|
|
|
4576
5049
|
}
|
|
4577
5050
|
|
|
4578
5051
|
// src/routes/capacity.ts
|
|
4579
|
-
import { Hono as
|
|
5052
|
+
import { Hono as Hono3 } from "hono";
|
|
4580
5053
|
function capacityRoutes() {
|
|
4581
|
-
const r = new
|
|
5054
|
+
const r = new Hono3();
|
|
4582
5055
|
r.get("/", async (c) => c.json(await capacity()));
|
|
4583
5056
|
return r;
|
|
4584
5057
|
}
|
|
4585
5058
|
|
|
4586
5059
|
// src/routes/env.ts
|
|
4587
|
-
import { Hono as
|
|
5060
|
+
import { Hono as Hono4 } from "hono";
|
|
4588
5061
|
function envRoutes() {
|
|
4589
|
-
const r = new
|
|
5062
|
+
const r = new Hono4();
|
|
4590
5063
|
r.get("/", async (c) => c.json(await listEnvVersions(c.get("listScope"))));
|
|
4591
5064
|
r.post("/", async (c) => {
|
|
4592
5065
|
const body = HostEnvRequest.safeParse(await c.req.json().catch(() => ({})));
|
|
@@ -4597,7 +5070,7 @@ function envRoutes() {
|
|
|
4597
5070
|
}
|
|
4598
5071
|
|
|
4599
5072
|
// src/routes/machines.ts
|
|
4600
|
-
import { Hono as
|
|
5073
|
+
import { Hono as Hono5 } from "hono";
|
|
4601
5074
|
|
|
4602
5075
|
// src/core/stats.ts
|
|
4603
5076
|
var STATS_REPLY_MS = 3e3;
|
|
@@ -4631,7 +5104,7 @@ async function usageReport(scope, window, p = paths()) {
|
|
|
4631
5104
|
|
|
4632
5105
|
// src/routes/machines.ts
|
|
4633
5106
|
function machineRoutes() {
|
|
4634
|
-
const r = new
|
|
5107
|
+
const r = new Hono5();
|
|
4635
5108
|
r.get("/", async (c) => c.json(await listMachines(c.get("listScope"))));
|
|
4636
5109
|
r.post("/", async (c) => {
|
|
4637
5110
|
const body = CreateMachineRequest.parse(await c.req.json().catch(() => ({})));
|
|
@@ -4729,9 +5202,9 @@ function machineRoutes() {
|
|
|
4729
5202
|
}
|
|
4730
5203
|
|
|
4731
5204
|
// src/routes/snapshots.ts
|
|
4732
|
-
import { Hono as
|
|
5205
|
+
import { Hono as Hono6 } from "hono";
|
|
4733
5206
|
function snapshotRoutes() {
|
|
4734
|
-
const r = new
|
|
5207
|
+
const r = new Hono6();
|
|
4735
5208
|
r.get("/", async (c) => c.json(await listSnapshots(c.get("listScope"))));
|
|
4736
5209
|
r.post("/", async (c) => {
|
|
4737
5210
|
const body = CreateSnapshotRequest.parse(await c.req.json());
|
|
@@ -4745,9 +5218,9 @@ function snapshotRoutes() {
|
|
|
4745
5218
|
}
|
|
4746
5219
|
|
|
4747
5220
|
// src/routes/ssh.ts
|
|
4748
|
-
import { Hono as
|
|
5221
|
+
import { Hono as Hono7 } from "hono";
|
|
4749
5222
|
function sshRoutes(opts = {}) {
|
|
4750
|
-
const r = new
|
|
5223
|
+
const r = new Hono7();
|
|
4751
5224
|
if (opts.controlPlane) {
|
|
4752
5225
|
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));
|
|
4753
5226
|
return r;
|
|
@@ -4762,10 +5235,10 @@ function sshRoutes(opts = {}) {
|
|
|
4762
5235
|
}
|
|
4763
5236
|
|
|
4764
5237
|
// src/routes/usage.ts
|
|
4765
|
-
import { Hono as
|
|
5238
|
+
import { Hono as Hono8 } from "hono";
|
|
4766
5239
|
var PULL_LIMIT = 1e3;
|
|
4767
5240
|
function usageRoutes(opts = {}) {
|
|
4768
|
-
const r = new
|
|
5241
|
+
const r = new Hono8();
|
|
4769
5242
|
r.get("/", async (c) => {
|
|
4770
5243
|
let window;
|
|
4771
5244
|
try {
|
|
@@ -4798,9 +5271,9 @@ function whole(value, name) {
|
|
|
4798
5271
|
}
|
|
4799
5272
|
|
|
4800
5273
|
// src/routes/volumes.ts
|
|
4801
|
-
import { Hono as
|
|
5274
|
+
import { Hono as Hono9 } from "hono";
|
|
4802
5275
|
function volumeRoutes() {
|
|
4803
|
-
const r = new
|
|
5276
|
+
const r = new Hono9();
|
|
4804
5277
|
r.get("/", async (c) => c.json(await listVolumes(c.get("listScope"))));
|
|
4805
5278
|
r.post("/", async (c) => {
|
|
4806
5279
|
const body = CreateVolumeRequest.parse(await c.req.json().catch(() => ({})));
|
|
@@ -4826,7 +5299,7 @@ function volumeRoutes() {
|
|
|
4826
5299
|
|
|
4827
5300
|
// src/app.ts
|
|
4828
5301
|
function createApp(opts = {}) {
|
|
4829
|
-
const app = new
|
|
5302
|
+
const app = new Hono10();
|
|
4830
5303
|
app.use(resolveCaller(opts));
|
|
4831
5304
|
app.get("/health", async (c) => {
|
|
4832
5305
|
const cfg = await loadConfig();
|
|
@@ -4843,6 +5316,10 @@ function createApp(opts = {}) {
|
|
|
4843
5316
|
});
|
|
4844
5317
|
});
|
|
4845
5318
|
if (opts.controlPlane) app.route("/machines", boxHttpRoutes());
|
|
5319
|
+
if (opts.controlPlane) {
|
|
5320
|
+
app.route("/machines", backupMachineRoutes());
|
|
5321
|
+
app.route("/backups", backupRoutes());
|
|
5322
|
+
}
|
|
4846
5323
|
app.route("/machines", machineRoutes());
|
|
4847
5324
|
app.route("/snapshots", snapshotRoutes());
|
|
4848
5325
|
app.route("/volumes", volumeRoutes());
|
|
@@ -4870,19 +5347,19 @@ async function listen(opts = {}) {
|
|
|
4870
5347
|
if (Buffer.byteLength(socketPath) > 100) {
|
|
4871
5348
|
throw new KvboxError(`socket path too long for a Unix socket (${socketPath}); set KVBOX_HOME to a shorter path`);
|
|
4872
5349
|
}
|
|
4873
|
-
await
|
|
5350
|
+
await rm6(socketPath, { force: true });
|
|
4874
5351
|
const server = createAdaptorServer({ fetch: createApp().fetch });
|
|
4875
5352
|
await new Promise((resolve, reject) => {
|
|
4876
5353
|
server.once("error", reject);
|
|
4877
5354
|
server.listen(socketPath, () => resolve());
|
|
4878
5355
|
});
|
|
4879
|
-
await
|
|
5356
|
+
await writeFile8(p.serverPid, `${process.pid}
|
|
4880
5357
|
`);
|
|
4881
5358
|
let https;
|
|
4882
5359
|
let httpsServer;
|
|
4883
5360
|
const cp = cfg.controlPlane;
|
|
4884
5361
|
if (cp) {
|
|
4885
|
-
const [key, cert] = await Promise.all([
|
|
5362
|
+
const [key, cert] = await Promise.all([readFile9(p.tlsKey), readFile9(p.tlsCert)]).catch((err) => {
|
|
4886
5363
|
throw new KvboxError(`joined ${cp.name} but the host's certificate is missing (${err.message}); run kvbox-server leave, then join again`);
|
|
4887
5364
|
});
|
|
4888
5365
|
httpsServer = createAdaptorServer({
|
|
@@ -4897,8 +5374,8 @@ async function listen(opts = {}) {
|
|
|
4897
5374
|
httpsServer.listen(port, "0.0.0.0", () => resolve());
|
|
4898
5375
|
}).catch(async (err) => {
|
|
4899
5376
|
server.close();
|
|
4900
|
-
await
|
|
4901
|
-
await
|
|
5377
|
+
await rm6(socketPath, { force: true });
|
|
5378
|
+
await rm6(p.serverPid, { force: true });
|
|
4902
5379
|
throw new KvboxError(`cannot listen on port ${port} for ${cp.name} (${err.message})`);
|
|
4903
5380
|
});
|
|
4904
5381
|
const bound = httpsServer.address().port;
|
|
@@ -4909,15 +5386,15 @@ async function listen(opts = {}) {
|
|
|
4909
5386
|
new Promise((resolve) => server.close(() => resolve())),
|
|
4910
5387
|
httpsServer ? new Promise((resolve) => httpsServer.close(() => resolve())) : void 0
|
|
4911
5388
|
]);
|
|
4912
|
-
await
|
|
4913
|
-
await
|
|
5389
|
+
await rm6(socketPath, { force: true });
|
|
5390
|
+
await rm6(p.serverPid, { force: true });
|
|
4914
5391
|
};
|
|
4915
5392
|
const shutdown2 = async () => {
|
|
4916
5393
|
server.close();
|
|
4917
5394
|
httpsServer?.close();
|
|
4918
5395
|
await stopRecovery();
|
|
4919
|
-
await
|
|
4920
|
-
await
|
|
5396
|
+
await rm6(socketPath, { force: true });
|
|
5397
|
+
await rm6(p.serverPid, { force: true });
|
|
4921
5398
|
process.exit(0);
|
|
4922
5399
|
};
|
|
4923
5400
|
process.once("SIGINT", () => void shutdown2());
|
|
@@ -4930,6 +5407,7 @@ var program = new Command("kvbox-server").description("kvbox host daemon: owns F
|
|
|
4930
5407
|
program.command("start", { isDefault: true }).description("serve the API on the local Unix socket (foreground)").option("--socket <path>", "socket to listen on (default: $KVBOX_HOME/server.sock)").action(async (opts) => {
|
|
4931
5408
|
await requireKvm();
|
|
4932
5409
|
const settled = await settleDeadBoxes(paths());
|
|
5410
|
+
await clearStagedBackups(paths()).catch((err) => console.error(`warning: ${err.message}`));
|
|
4933
5411
|
const { socketPath, https } = await listen(opts.socket ? { socketPath: opts.socket } : {});
|
|
4934
5412
|
console.log(`kvbox-server ${VERSION} listening on ${socketPath} (pid ${process.pid})`);
|
|
4935
5413
|
if (https) {
|