@kvbox/server 0.6.10 → 0.6.12
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 +142 -44
- package/dist/kvbox-server.js.map +1 -1
- package/package.json +1 -1
- package/scripts/net-setup.sh +18 -0
package/dist/kvbox-server.js
CHANGED
|
@@ -466,6 +466,12 @@ var ConfigSchema = z2.object({
|
|
|
466
466
|
* refused when it could not fill up with that much still free. 0 only on a host whose disk is for tests.
|
|
467
467
|
*/
|
|
468
468
|
volumeHeadroomGib: z2.number().int().min(0).default(20),
|
|
469
|
+
/**
|
|
470
|
+
* MiB of RAM the host keeps back from its boxes: they may reserve the host's RAM less this. 0 by default
|
|
471
|
+
* (boxes rarely touch all they are sized at); raise it on a host whose boxes do fill their memory. Read at
|
|
472
|
+
* every check, so an edit needs no restart; reported in `/capacity`, which is what placement goes by.
|
|
473
|
+
*/
|
|
474
|
+
memHeadroomMib: z2.number().int().min(0).default(0),
|
|
469
475
|
/** Absent until the host joins a control plane; then the server also listens on HTTPS. */
|
|
470
476
|
controlPlane: ControlPlaneSchema.optional(),
|
|
471
477
|
/** Absent unless the host sits behind a relay. */
|
|
@@ -1744,7 +1750,6 @@ import { rename as rename5, rm as rm6 } from "node:fs/promises";
|
|
|
1744
1750
|
import { cpus, totalmem } from "node:os";
|
|
1745
1751
|
|
|
1746
1752
|
// ../shared/src/capacity.ts
|
|
1747
|
-
var MEM_HEADROOM_MIB = 2048;
|
|
1748
1753
|
function sellableGib(d) {
|
|
1749
1754
|
return Math.max(0, d.freeGib + d.volumesUsedGib - d.headroomGib);
|
|
1750
1755
|
}
|
|
@@ -1832,6 +1837,12 @@ var BackupSchema = z5.object({
|
|
|
1832
1837
|
id: z5.string(),
|
|
1833
1838
|
owner: z5.string(),
|
|
1834
1839
|
box: z5.string(),
|
|
1840
|
+
/**
|
|
1841
|
+
* The box it was taken of has been removed (#141): a box called `box` now is another box, which this backup
|
|
1842
|
+
* never restores into; `kvbox new <name> --from-backup <id>` makes a box from it. Absent from a control plane
|
|
1843
|
+
* before #141.
|
|
1844
|
+
*/
|
|
1845
|
+
boxRemoved: z5.boolean().optional(),
|
|
1835
1846
|
status: z5.enum(BACKUP_STATUSES),
|
|
1836
1847
|
/** Why it failed; null otherwise. */
|
|
1837
1848
|
error: z5.string().nullable(),
|
|
@@ -2012,7 +2023,7 @@ var MachineSchema = z5.object({
|
|
|
2012
2023
|
image: z5.string().optional(),
|
|
2013
2024
|
createdAt: z5.string(),
|
|
2014
2025
|
source: z5.string(),
|
|
2015
|
-
// "base", "snapshot:<owner/name>"
|
|
2026
|
+
// "base", "snapshot:<owner/name>", "fork:<owner/name>" (#79) or "backup:<id>" (#141)
|
|
2016
2027
|
status: BoxStatusSchema,
|
|
2017
2028
|
/**
|
|
2018
2029
|
* Public TCP port on the host that reaches the box's SSH while it runs (#49). Only boxes made
|
|
@@ -2221,8 +2232,14 @@ var CreateMachineRequest = z5.object({
|
|
|
2221
2232
|
/** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */
|
|
2222
2233
|
image: z5.string().optional(),
|
|
2223
2234
|
/** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
|
|
2224
|
-
env: z5.array(z5.object({ name: z5.string(), value: z5.string() })).optional()
|
|
2235
|
+
env: z5.array(z5.object({ name: z5.string(), value: z5.string() })).optional(),
|
|
2236
|
+
/**
|
|
2237
|
+
* Start the box on this backup's disk (#141, `kvbox new --from-backup <id>`), a removed box's too: its image,
|
|
2238
|
+
* version and variables come from the backup, its size too unless given. Only the control plane reads it.
|
|
2239
|
+
*/
|
|
2240
|
+
fromBackup: z5.string().optional()
|
|
2225
2241
|
});
|
|
2242
|
+
var HostFromBackupRequest = CreateMachineRequest.omit({ from: true, fromBackup: true, image: true, env: true }).extend({ backup: HostRestoreRequest });
|
|
2226
2243
|
var ForkMachineRequest = z5.object({
|
|
2227
2244
|
name: z5.string().optional(),
|
|
2228
2245
|
/**
|
|
@@ -2291,6 +2308,11 @@ var CapacitySchema = z5.object({
|
|
|
2291
2308
|
reservedMemMib: z5.number().int(),
|
|
2292
2309
|
reservedVcpu: z5.number().int(),
|
|
2293
2310
|
running: z5.number().int(),
|
|
2311
|
+
/**
|
|
2312
|
+
* MiB of RAM the host keeps back from its boxes (config.json `memHeadroomMib`). Absent on a kvbox-server
|
|
2313
|
+
* from before the setting, which keeps 2 GB (`OLD_HOST_MEM_HEADROOM_MIB`).
|
|
2314
|
+
*/
|
|
2315
|
+
memHeadroomMib: z5.number().int().optional(),
|
|
2294
2316
|
/** Absent on a host from before volumes (#91): it cannot take one. */
|
|
2295
2317
|
disk: DiskCapacitySchema.optional(),
|
|
2296
2318
|
/**
|
|
@@ -2303,7 +2325,9 @@ var CapacitySchema = z5.object({
|
|
|
2303
2325
|
/** Present on a host set up as a backup store: the disk its Garage keeps chunks on, and whether Garage runs. */
|
|
2304
2326
|
backupStore: z5.object({ totalBytes: z5.number().int(), freeBytes: z5.number().int(), running: z5.boolean() }).optional(),
|
|
2305
2327
|
/** True on a kvbox-server that reaches a backup store by its certificate's `pin`; older ones omit it and cannot back up to a store. */
|
|
2306
|
-
storeClient: z5.boolean().optional()
|
|
2328
|
+
storeClient: z5.boolean().optional(),
|
|
2329
|
+
/** True on a kvbox-server with `POST /machines/from-backup` (#141, `kvbox new --from-backup`); older ones omit it. */
|
|
2330
|
+
fromBackup: z5.boolean().optional()
|
|
2307
2331
|
});
|
|
2308
2332
|
var ImageSchema = z5.object({ name: z5.string(), version: z5.string().nullable() });
|
|
2309
2333
|
var ImageIndexSchema = z5.object({
|
|
@@ -3415,18 +3439,22 @@ async function runningReservations(p = paths()) {
|
|
|
3415
3439
|
async function capacity(p = paths()) {
|
|
3416
3440
|
const host = hostResources();
|
|
3417
3441
|
const running = await runningReservations(p);
|
|
3442
|
+
const cfg = await loadConfig(p);
|
|
3418
3443
|
return {
|
|
3419
3444
|
hostMemMib: host.memMib,
|
|
3445
|
+
memHeadroomMib: cfg.memHeadroomMib,
|
|
3420
3446
|
hostCores: host.cores,
|
|
3421
3447
|
reservedMemMib: running.reduce((n, r) => n + r.memMib, 0),
|
|
3422
3448
|
reservedVcpu: running.reduce((n, r) => n + r.vcpu, 0),
|
|
3423
3449
|
running: running.length,
|
|
3424
3450
|
disk: await diskCapacity(p),
|
|
3425
3451
|
// What a box can be made from here (#87): the control plane places `--base postgres` by it.
|
|
3426
|
-
images: await listImages(
|
|
3452
|
+
images: await listImages(cfg, p),
|
|
3427
3453
|
...await backupStoreCapacity(p).then((store) => store ? { backupStore: store } : {}),
|
|
3428
3454
|
// Backups and restores here reach a store by its certificate's pin (core/storeFetch.ts).
|
|
3429
|
-
storeClient: true
|
|
3455
|
+
storeClient: true,
|
|
3456
|
+
// A new box on a backup's disk (#141): the control plane places `new --from-backup` only here.
|
|
3457
|
+
fromBackup: true
|
|
3430
3458
|
};
|
|
3431
3459
|
}
|
|
3432
3460
|
function gb(mib) {
|
|
@@ -3453,11 +3481,12 @@ function roomFor(host, running, want, opts = {}) {
|
|
|
3453
3481
|
const { viewer, by = "new" } = opts;
|
|
3454
3482
|
const reservedMem = running.reduce((n, r) => n + r.memMib, 0);
|
|
3455
3483
|
const reservedVcpu = running.reduce((n, r) => n + r.vcpu, 0);
|
|
3456
|
-
const
|
|
3484
|
+
const headroom = host.headroomMib ?? 0;
|
|
3485
|
+
const memLimit = host.memMib - headroom;
|
|
3457
3486
|
const vcpuLimit = host.cores * VCPU_OVERSUBSCRIPTION;
|
|
3458
3487
|
const hint = HINTS[by];
|
|
3459
3488
|
if (reservedMem + want.memMib > memLimit) {
|
|
3460
|
-
return `not enough memory for a ${gb(want.memMib)} box: ${describeRunning(running, viewer)}; this host has ${gb(host.memMib)} and keeps ${gb(
|
|
3489
|
+
return `not enough memory for a ${gb(want.memMib)} box: ${describeRunning(running, viewer)}; ` + (headroom > 0 ? `this host has ${gb(host.memMib)} and keeps ${gb(headroom)} for itself, so boxes may reserve ${gb(memLimit)} in total. ` : `this host has ${gb(host.memMib)}, all of it for its boxes. `) + hint;
|
|
3461
3490
|
}
|
|
3462
3491
|
if (reservedVcpu + want.vcpu > vcpuLimit) {
|
|
3463
3492
|
return `too many vCPUs for a ${want.vcpu} vCPU box: ${describeRunning(running, viewer)}; this host has ${host.cores} cores and allows ${vcpuLimit} vCPUs in total (${VCPU_OVERSUBSCRIPTION}x). ` + hint;
|
|
@@ -3467,7 +3496,8 @@ function roomFor(host, running, want, opts = {}) {
|
|
|
3467
3496
|
async function assertRoomFor(vcpu, memMib, force, box, by, p = paths()) {
|
|
3468
3497
|
if (force) return;
|
|
3469
3498
|
const running = (await runningReservations(p)).filter((r) => box.name === void 0 || !(r.owner === box.owner && r.name === box.name));
|
|
3470
|
-
const
|
|
3499
|
+
const host = { ...hostResources(), headroomMib: (await loadConfig(p)).memHeadroomMib };
|
|
3500
|
+
const reason = roomFor(host, running, { vcpu, memMib }, { viewer: box.owner, by });
|
|
3471
3501
|
if (reason !== void 0) throw new KvboxError(reason);
|
|
3472
3502
|
}
|
|
3473
3503
|
|
|
@@ -4455,6 +4485,9 @@ var setMachine = locked(async function setMachine2(ref, req, p = paths()) {
|
|
|
4455
4485
|
return toMachine(next, p);
|
|
4456
4486
|
});
|
|
4457
4487
|
|
|
4488
|
+
// src/core/machines/create.ts
|
|
4489
|
+
import { rename as rename6, stat as stat3 } from "node:fs/promises";
|
|
4490
|
+
|
|
4458
4491
|
// src/core/machines/newbox.ts
|
|
4459
4492
|
import { mkdir as mkdir5, rm as rm7 } from "node:fs/promises";
|
|
4460
4493
|
var NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
|
|
@@ -4616,12 +4649,27 @@ async function restoreFrom(from, owner, req, cfg, p) {
|
|
|
4616
4649
|
async function currentBaseVersion(p = paths()) {
|
|
4617
4650
|
return (await currentImage(void 0, await loadConfig(p), p)).version;
|
|
4618
4651
|
}
|
|
4619
|
-
|
|
4620
|
-
const
|
|
4621
|
-
if (req.from !== void 0) return restoreMachine(req.from, owner, req, cfg, p);
|
|
4622
|
-
const sizeName = req.size ?? cfg.defaultSize;
|
|
4652
|
+
function sizeOf(req, defaultSize, diskBytes) {
|
|
4653
|
+
const sizeName = req.size ?? defaultSize;
|
|
4623
4654
|
if (!isSizeName(sizeName)) throw new KvboxError(`unknown size "${sizeName}"; use one of ${Object.keys(SIZES).join(", ")}`);
|
|
4624
4655
|
const size2 = SIZES[sizeName];
|
|
4656
|
+
if (diskBytes !== void 0 && diskBytes > size2.diskGib * 1024 ** 3) {
|
|
4657
|
+
const fits = SIZE_NAMES.find((n) => diskBytes <= SIZES[n].diskGib * 1024 ** 3);
|
|
4658
|
+
throw new KvboxError(`this backup's disk is ${Math.ceil(diskBytes / 1024 ** 3)} GB, more than a ${sizeName} box's ${size2.diskGib} GB${fits ? `; use --size ${fits}` : ""}`);
|
|
4659
|
+
}
|
|
4660
|
+
return size2;
|
|
4661
|
+
}
|
|
4662
|
+
async function checkNewBox(req, owner, diskBytes, p = paths()) {
|
|
4663
|
+
const cfg = await loadConfig(p);
|
|
4664
|
+
const size2 = sizeOf(req, cfg.defaultSize, diskBytes);
|
|
4665
|
+
assertAssets(cfg);
|
|
4666
|
+
await assertRoomFor(size2.vcpu, size2.memMib, req.force ?? false, { owner }, "new", p);
|
|
4667
|
+
if (req.name !== void 0) pickName(req.name, new Set((await readAllMeta(p)).filter((m) => m.owner === owner).map((m) => m.name)));
|
|
4668
|
+
}
|
|
4669
|
+
async function createMachine(req, owner, p = paths(), from) {
|
|
4670
|
+
const cfg = await loadConfig(p);
|
|
4671
|
+
if (req.from !== void 0) return restoreMachine(req.from, owner, req, cfg, p);
|
|
4672
|
+
const size2 = sizeOf(req, cfg.defaultSize, from ? (await stat3(from.disk)).size : void 0);
|
|
4625
4673
|
assertAssets(cfg);
|
|
4626
4674
|
await assertRoomFor(size2.vcpu, size2.memMib, req.force ?? false, { owner }, "new", p);
|
|
4627
4675
|
const sshKeys = isCloudBox(owner) && req.sshKeys !== void 0 && req.sshKeys.length > 0 ? req.sshKeys : void 0;
|
|
@@ -4630,26 +4678,29 @@ async function createMachine(req, owner, p = paths()) {
|
|
|
4630
4678
|
const name = pickName(req.name, new Set(existing.filter((m) => m.owner === owner).map((m) => m.name)));
|
|
4631
4679
|
const id = newBoxId(idsInUse(existing));
|
|
4632
4680
|
const { ip, mac } = driver().net.allocate(cfg, existing.map((m) => m.ip));
|
|
4633
|
-
const image = imageKey(req.image);
|
|
4634
|
-
const base = await currentImage(image, cfg, p);
|
|
4681
|
+
const image = imageKey(from ? from.image : req.image);
|
|
4682
|
+
const base = from ? { version: from.base, file: imageFile(image, from.base, p) } : await currentImage(image, cfg, p);
|
|
4635
4683
|
await assertOverlayCapable(base.file, image, base.version);
|
|
4636
4684
|
const manifest = await imageManifest(base.file);
|
|
4637
|
-
const env = imageEnv(manifest, name, req.env ?? [], (await readOwnerEnv(owner, p).catch(() => null))?.vars ?? []);
|
|
4685
|
+
const env = from ? null : imageEnv(manifest, name, req.env ?? [], (await readOwnerEnv(owner, p).catch(() => null))?.vars ?? []);
|
|
4638
4686
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4639
4687
|
const autoHibernateSec = autoHibernateFor(req, cfg, manifest);
|
|
4640
|
-
const vars = env.vars.map((v) => ({ ...v, secret: env.secrets.includes(v.name), updatedAt: now }));
|
|
4688
|
+
const vars = env === null ? from?.vars ?? [] : env.vars.map((v) => ({ ...v, secret: env.secrets.includes(v.name), updatedAt: now }));
|
|
4641
4689
|
const machine = await bootInto(
|
|
4642
4690
|
{ id, name, owner, ip, mac, vcpu: size2.vcpu, memMib: size2.memMib, base: base.version, image, sshKeys },
|
|
4643
4691
|
// The image is shared read-only by every box; only the box's own writes land in its overlay.
|
|
4644
4692
|
async (m) => {
|
|
4645
|
-
|
|
4693
|
+
if (from) {
|
|
4694
|
+
await rename6(from.disk, m.overlay);
|
|
4695
|
+
if ((await stat3(m.overlay)).size < size2.diskGib * 1024 ** 3) await growDisk(m.overlay, size2.diskGib);
|
|
4696
|
+
} else await createOverlay(m.overlay, size2.diskGib);
|
|
4646
4697
|
if (vars.length > 0) await writeBoxEnv({ owner, name }, vars, p);
|
|
4647
4698
|
},
|
|
4648
|
-
{ source: "base", autoHibernateSec, idleCheck: manifest.idle, url: maskedUrl(manifest, vars) },
|
|
4699
|
+
{ source: from ? `backup:${from.id}` : "base", autoHibernateSec, idleCheck: manifest.idle, url: maskedUrl(manifest, vars) },
|
|
4649
4700
|
cfg,
|
|
4650
4701
|
p
|
|
4651
4702
|
);
|
|
4652
|
-
return env
|
|
4703
|
+
return env?.connect === void 0 ? machine : { ...machine, connect: env.connect };
|
|
4653
4704
|
}
|
|
4654
4705
|
|
|
4655
4706
|
// src/core/machines/fork.ts
|
|
@@ -4658,7 +4709,7 @@ import { rm as rm9 } from "node:fs/promises";
|
|
|
4658
4709
|
|
|
4659
4710
|
// src/core/snapshots.ts
|
|
4660
4711
|
import { existsSync as existsSync11 } from "node:fs";
|
|
4661
|
-
import { link as link2, mkdir as mkdir6, readdir as readdir5, rename as
|
|
4712
|
+
import { link as link2, mkdir as mkdir6, readdir as readdir5, rename as rename7, rm as rm8, stat as stat4 } from "node:fs/promises";
|
|
4662
4713
|
var NAME_RE2 = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
4663
4714
|
function toSnapshot(meta) {
|
|
4664
4715
|
return {
|
|
@@ -4688,7 +4739,7 @@ async function listSnapshots(scope, p = paths()) {
|
|
|
4688
4739
|
async function usedBytes(dir) {
|
|
4689
4740
|
let total = 0;
|
|
4690
4741
|
for (const entry of await readdir5(dir)) {
|
|
4691
|
-
total += (await
|
|
4742
|
+
total += (await stat4(`${dir}/${entry}`)).blocks * 512;
|
|
4692
4743
|
}
|
|
4693
4744
|
return total;
|
|
4694
4745
|
}
|
|
@@ -4751,11 +4802,11 @@ async function swapIn(ref, from, boxId, p) {
|
|
|
4751
4802
|
await withSnapshotLock(ref, async () => {
|
|
4752
4803
|
await rm8(old, { recursive: true, force: true });
|
|
4753
4804
|
const hadOld = existsSync11(to);
|
|
4754
|
-
if (hadOld) await
|
|
4805
|
+
if (hadOld) await rename7(to, old);
|
|
4755
4806
|
try {
|
|
4756
|
-
await
|
|
4807
|
+
await rename7(from, to);
|
|
4757
4808
|
} catch (err) {
|
|
4758
|
-
if (hadOld) await
|
|
4809
|
+
if (hadOld) await rename7(old, to);
|
|
4759
4810
|
throw err;
|
|
4760
4811
|
}
|
|
4761
4812
|
});
|
|
@@ -4800,7 +4851,7 @@ async function mergeOntoPrevious(previous, diffFile, editor) {
|
|
|
4800
4851
|
const merged = `${diffFile}.merged`;
|
|
4801
4852
|
await run(["cp", "--sparse=always", "--reflink=auto", previous, merged]);
|
|
4802
4853
|
await run([editor, "edit-memory", "rebase", "--memory-path", merged, "--diff-path", diffFile]);
|
|
4803
|
-
await
|
|
4854
|
+
await rename7(merged, diffFile);
|
|
4804
4855
|
}
|
|
4805
4856
|
async function deleteSnapshot(ref, p = paths()) {
|
|
4806
4857
|
const dir = p.snapshot(ref.owner, ref.name).dir;
|
|
@@ -5045,7 +5096,7 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths(), force = f
|
|
|
5045
5096
|
|
|
5046
5097
|
// src/core/machines/volumes.ts
|
|
5047
5098
|
import { statSync as statSync5 } from "node:fs";
|
|
5048
|
-
import { rename as
|
|
5099
|
+
import { rename as rename8, rm as rm12 } from "node:fs/promises";
|
|
5049
5100
|
var attachVolume = locked(async function attachVolume2(ref, volume, p = paths()) {
|
|
5050
5101
|
const cfg = await loadConfig(p);
|
|
5051
5102
|
const claimed = await withHostLock("volumes", async () => {
|
|
@@ -5100,7 +5151,7 @@ async function replaceVolumeDisk(volume, file, p = paths()) {
|
|
|
5100
5151
|
await grow();
|
|
5101
5152
|
const swap = async () => {
|
|
5102
5153
|
await grow();
|
|
5103
|
-
await
|
|
5154
|
+
await rename8(file, p.volume(volume.owner, volume.name).disk);
|
|
5104
5155
|
};
|
|
5105
5156
|
const holder = await attachedBox(volume, p);
|
|
5106
5157
|
if (holder === null) {
|
|
@@ -5124,7 +5175,7 @@ async function replaceVolumeDisk(volume, file, p = paths()) {
|
|
|
5124
5175
|
// src/core/backups.ts
|
|
5125
5176
|
import { randomBytes as randomBytes5 } from "node:crypto";
|
|
5126
5177
|
import { existsSync as existsSync13 } from "node:fs";
|
|
5127
|
-
import { mkdir as mkdir8, open, readdir as readdir6, readFile as readFile9, rm as rm13, stat as
|
|
5178
|
+
import { mkdir as mkdir8, open, readdir as readdir6, readFile as readFile9, rm as rm13, stat as stat5, statfs as statfs3, writeFile as writeFile7 } from "node:fs/promises";
|
|
5128
5179
|
import { basename as basename2, join as join3 } from "node:path";
|
|
5129
5180
|
import { setTimeout as sleep4 } from "node:timers/promises";
|
|
5130
5181
|
|
|
@@ -5268,7 +5319,7 @@ async function readBox2(ref, p) {
|
|
|
5268
5319
|
}
|
|
5269
5320
|
}
|
|
5270
5321
|
async function chunkNames(file, keys) {
|
|
5271
|
-
const { size: size2 } = await
|
|
5322
|
+
const { size: size2 } = await stat5(file);
|
|
5272
5323
|
const chunks = [];
|
|
5273
5324
|
const fh = await open(file, "r");
|
|
5274
5325
|
try {
|
|
@@ -5408,7 +5459,7 @@ async function uploadOnce(id, req, signal, p) {
|
|
|
5408
5459
|
if (index === void 0) throw new KvboxError(`backup ${id} has no chunk ${name.slice(0, 12)}`);
|
|
5409
5460
|
return { name, url, index };
|
|
5410
5461
|
});
|
|
5411
|
-
const { size: size2 } = await
|
|
5462
|
+
const { size: size2 } = await stat5(s.disk);
|
|
5412
5463
|
const fetchChunk = await chunkFetcher(req.pin, work[0]?.url, p);
|
|
5413
5464
|
const fh = await open(s.disk, "r");
|
|
5414
5465
|
let bytes = 0;
|
|
@@ -5501,7 +5552,7 @@ async function restoreOnce(ref, req, p) {
|
|
|
5501
5552
|
}
|
|
5502
5553
|
const keys = backupKeys(req.key);
|
|
5503
5554
|
const m = p.machine(ref.owner, ref.name);
|
|
5504
|
-
const current2 = (await
|
|
5555
|
+
const current2 = (await stat5(m.overlay)).size;
|
|
5505
5556
|
if (req.sizeBytes > current2) {
|
|
5506
5557
|
const gb2 = (n) => `${Math.ceil(n / 1024 ** 3)}GB`;
|
|
5507
5558
|
throw new KvboxError(`this backup's disk is ${gb2(req.sizeBytes)} and box ${shown(ref)}'s is ${gb2(current2)}: kvbox vm rescale ${shown(ref)} --disk ${gb2(req.sizeBytes)} first`);
|
|
@@ -5523,6 +5574,48 @@ async function restoreOnce(ref, req, p) {
|
|
|
5523
5574
|
await rm13(envFile, { force: true });
|
|
5524
5575
|
}
|
|
5525
5576
|
}
|
|
5577
|
+
async function createFromBackup(req, owner, p = paths()) {
|
|
5578
|
+
const { backup, ...create } = req;
|
|
5579
|
+
checkId(backup.id);
|
|
5580
|
+
const base = await baseFor(backup, p);
|
|
5581
|
+
await checkNewBox(create, owner, backup.sizeBytes, p);
|
|
5582
|
+
const keys = backupKeys(backup.key);
|
|
5583
|
+
const dir = join3(p.backups, `new-${randomBytes5(4).toString("hex")}`);
|
|
5584
|
+
await mkdir8(dir, { recursive: true, mode: 448 });
|
|
5585
|
+
try {
|
|
5586
|
+
let vars = null;
|
|
5587
|
+
if (backup.env !== null) {
|
|
5588
|
+
const envFile = join3(dir, "env.json");
|
|
5589
|
+
await writeFile7(envFile, openText(keys, backup.env, `env:${backup.id}`), { mode: 384 });
|
|
5590
|
+
vars = await readBoxEnvFile(envFile);
|
|
5591
|
+
checkBoxEnv(vars);
|
|
5592
|
+
}
|
|
5593
|
+
await assertRoom(dir, backup.chunks.length * CHUNK_SIZE, `a box from backup ${backup.id}`, p);
|
|
5594
|
+
const disk = join3(dir, "disk.ext4");
|
|
5595
|
+
await downloadDisk(disk, backup, p);
|
|
5596
|
+
const sent = create;
|
|
5597
|
+
return await createMachine(sent, owner, p, { disk, base, image: backup.image, vars, id: backup.id });
|
|
5598
|
+
} finally {
|
|
5599
|
+
await rm13(dir, { recursive: true, force: true });
|
|
5600
|
+
}
|
|
5601
|
+
}
|
|
5602
|
+
async function baseFor(backup, p) {
|
|
5603
|
+
if (existsSync13(imageFile(backup.image, backup.base, p))) return backup.base;
|
|
5604
|
+
const current2 = (await currentImage(imageKey(backup.image), await loadConfig(p), p)).version;
|
|
5605
|
+
if (compareVersions(current2, backup.base) < 0) {
|
|
5606
|
+
throw new KvboxError(`this backup stacks on ${imageLabel(backup.image)} ${backup.base}, newer than this host's ${current2}; the host needs updating first`);
|
|
5607
|
+
}
|
|
5608
|
+
return current2;
|
|
5609
|
+
}
|
|
5610
|
+
function compareVersions(a, b) {
|
|
5611
|
+
const parts = (v) => v.replace(/^v/, "").split(/[.-]/).map((x2) => Number.parseInt(x2, 10) || 0);
|
|
5612
|
+
const [x, y] = [parts(a), parts(b)];
|
|
5613
|
+
for (let i = 0; i < Math.max(x.length, y.length); i++) {
|
|
5614
|
+
const d = (x[i] ?? 0) - (y[i] ?? 0);
|
|
5615
|
+
if (d !== 0) return d;
|
|
5616
|
+
}
|
|
5617
|
+
return 0;
|
|
5618
|
+
}
|
|
5526
5619
|
async function restoreVolumeBackup(ref, req, p = paths()) {
|
|
5527
5620
|
checkId(req.id);
|
|
5528
5621
|
const k = `volume:${refKey(ref)}`;
|
|
@@ -6108,7 +6201,7 @@ function startRelayWatch(opts = {}) {
|
|
|
6108
6201
|
// src/daemon.ts
|
|
6109
6202
|
import { spawn as spawn3 } from "node:child_process";
|
|
6110
6203
|
import { accessSync, constants as constants2, openSync as openSync5, readFileSync as readFileSync3, statSync as statSync6 } from "node:fs";
|
|
6111
|
-
import { mkdir as mkdir11, readFile as readFile11, stat as
|
|
6204
|
+
import { mkdir as mkdir11, readFile as readFile11, stat as stat6 } from "node:fs/promises";
|
|
6112
6205
|
import { userInfo as userInfo3 } from "node:os";
|
|
6113
6206
|
import { setTimeout as sleep5 } from "node:timers/promises";
|
|
6114
6207
|
|
|
@@ -6249,7 +6342,7 @@ async function stopDaemon(pid, timeoutMs = 1e4) {
|
|
|
6249
6342
|
}
|
|
6250
6343
|
}
|
|
6251
6344
|
async function answering(p = paths()) {
|
|
6252
|
-
if (!await
|
|
6345
|
+
if (!await stat6(p.serverSock).then(() => true, () => false)) return null;
|
|
6253
6346
|
const probe = new SocketClient(p.serverSock);
|
|
6254
6347
|
try {
|
|
6255
6348
|
const health = await probe.health();
|
|
@@ -6287,7 +6380,7 @@ async function restartDaemon(p = paths()) {
|
|
|
6287
6380
|
return startDetached(p);
|
|
6288
6381
|
}
|
|
6289
6382
|
async function startUnit(p, timeoutMs) {
|
|
6290
|
-
const logFrom = await
|
|
6383
|
+
const logFrom = await stat6(p.serverLog).then((s) => s.size, () => 0);
|
|
6291
6384
|
const res = startUnitProcess();
|
|
6292
6385
|
if (!res.ok) {
|
|
6293
6386
|
const why = res.out || await lastErrorLine(p.serverLog, logFrom) || "systemctl start failed";
|
|
@@ -6308,7 +6401,7 @@ async function serving(p, timeoutMs, check) {
|
|
|
6308
6401
|
const deadline = Date.now() + timeoutMs;
|
|
6309
6402
|
while (Date.now() < deadline) {
|
|
6310
6403
|
await check?.();
|
|
6311
|
-
if (await
|
|
6404
|
+
if (await stat6(p.serverSock).then(() => true, () => false)) {
|
|
6312
6405
|
const probe = new SocketClient(p.serverSock);
|
|
6313
6406
|
try {
|
|
6314
6407
|
await probe.health();
|
|
@@ -6412,7 +6505,7 @@ function versionOf(srcFileUrl, injected) {
|
|
|
6412
6505
|
}
|
|
6413
6506
|
|
|
6414
6507
|
// src/version.ts
|
|
6415
|
-
var VERSION = versionOf(import.meta.url, true ? "0.6.
|
|
6508
|
+
var VERSION = versionOf(import.meta.url, true ? "0.6.12" : void 0);
|
|
6416
6509
|
|
|
6417
6510
|
// src/caller.ts
|
|
6418
6511
|
import { createHash as createHash3, timingSafeEqual } from "node:crypto";
|
|
@@ -6523,6 +6616,11 @@ async function startUpdate(version, p = paths(), deps = {}) {
|
|
|
6523
6616
|
import { Hono } from "hono";
|
|
6524
6617
|
function backupMachineRoutes() {
|
|
6525
6618
|
const r = new Hono();
|
|
6619
|
+
r.post("/from-backup", async (c) => {
|
|
6620
|
+
const body = HostFromBackupRequest.safeParse(await c.req.json().catch(() => ({})));
|
|
6621
|
+
if (!body.success) throw new KvboxError("from-backup: expected a new box's fields and {backup: {id, key, sizeBytes, base, env, chunks}}");
|
|
6622
|
+
return c.json(await createFromBackup(body.data, c.get("owner")), 201);
|
|
6623
|
+
});
|
|
6526
6624
|
r.post("/:name/backup", async (c) => {
|
|
6527
6625
|
const body = HostBackupRequest.safeParse(await c.req.json().catch(() => ({})));
|
|
6528
6626
|
if (!body.success) throw new KvboxError("backup: expected {id, key}");
|
|
@@ -7443,7 +7541,7 @@ var leaveCommand = new Command6("leave").description("take this host out from be
|
|
|
7443
7541
|
});
|
|
7444
7542
|
|
|
7445
7543
|
// src/commands/logs.ts
|
|
7446
|
-
import { open as open2, readFile as readFile14, stat as
|
|
7544
|
+
import { open as open2, readFile as readFile14, stat as stat7 } from "node:fs/promises";
|
|
7447
7545
|
import { setTimeout as sleep6 } from "node:timers/promises";
|
|
7448
7546
|
import { Command as Command7 } from "commander";
|
|
7449
7547
|
var logsCommand = new Command7("logs").description("show the daemon's log ($KVBOX_HOME/server.log); -f keeps printing as it grows").option("-n, --lines <n>", "how many lines to show from the end", "50").option("-f, --follow", "keep printing new lines until Ctrl-C").action(async (opts) => {
|
|
@@ -7470,9 +7568,9 @@ function tailLines(text, n) {
|
|
|
7470
7568
|
}
|
|
7471
7569
|
async function follow(path, write, opts = {}) {
|
|
7472
7570
|
const intervalMs = opts.intervalMs ?? 250;
|
|
7473
|
-
let offset = opts.from ?? await
|
|
7571
|
+
let offset = opts.from ?? await stat7(path).then((s) => s.size, () => 0);
|
|
7474
7572
|
while (!opts.signal?.aborted) {
|
|
7475
|
-
const size2 = await
|
|
7573
|
+
const size2 = await stat7(path).then((s) => s.size, () => 0);
|
|
7476
7574
|
if (size2 < offset) offset = 0;
|
|
7477
7575
|
if (size2 > offset) {
|
|
7478
7576
|
const fh = await open2(path, "r");
|
|
@@ -7519,7 +7617,7 @@ var relayCommand = new Command9("relay").description("reach the internet through
|
|
|
7519
7617
|
import { Command as Command11 } from "commander";
|
|
7520
7618
|
|
|
7521
7619
|
// src/core/realm.ts
|
|
7522
|
-
import { lstat as lstat2, readFile as readFile15, readdir as readdir7, readlink, rename as
|
|
7620
|
+
import { lstat as lstat2, readFile as readFile15, readdir as readdir7, readlink, rename as rename9, rm as rm16, symlink as symlink2, writeFile as writeFile11 } from "node:fs/promises";
|
|
7523
7621
|
import { z as z9 } from "zod";
|
|
7524
7622
|
var esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
7525
7623
|
async function ownersIn(root, from, suffix = "") {
|
|
@@ -7598,11 +7696,11 @@ async function countRealm(from, to, p = paths()) {
|
|
|
7598
7696
|
async function writeJson(file, value) {
|
|
7599
7697
|
const tmp = `${file}.tmp`;
|
|
7600
7698
|
await writeFile11(tmp, JSON.stringify(value, null, 2) + "\n");
|
|
7601
|
-
await
|
|
7699
|
+
await rename9(tmp, file);
|
|
7602
7700
|
}
|
|
7603
7701
|
async function move(entries, metaOf, ownerDir, owners, to) {
|
|
7604
7702
|
for (const e of entries) await writeJson(metaOf(e.oldOwner, e.name), e.meta);
|
|
7605
|
-
for (const o of owners) await
|
|
7703
|
+
for (const o of owners) await rename9(ownerDir(o), ownerDir(to(o)));
|
|
7606
7704
|
}
|
|
7607
7705
|
async function renameRealm(from, to, p = paths()) {
|
|
7608
7706
|
const planned = await plan(from, to, p);
|
|
@@ -7621,7 +7719,7 @@ async function renameRealm(from, to, p = paths()) {
|
|
|
7621
7719
|
await symlink2(p.volume(box.meta.owner, volume).disk, link4);
|
|
7622
7720
|
}
|
|
7623
7721
|
}
|
|
7624
|
-
for (const o of planned.envOwners) await
|
|
7722
|
+
for (const o of planned.envOwners) await rename9(p.ownerEnv(o), p.ownerEnv(owner(o)));
|
|
7625
7723
|
renameLedgerRealm(from, to, p);
|
|
7626
7724
|
closeDb(p);
|
|
7627
7725
|
const cfg = await loadConfig(p);
|