@kvbox/server 0.5.21 → 0.5.23
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 +763 -225
- package/dist/kvbox-server.js.map +1 -1
- package/package.json +1 -1
package/dist/kvbox-server.js
CHANGED
|
@@ -85,7 +85,25 @@ function paths(home = kvboxHome()) {
|
|
|
85
85
|
sock: join(dir, "fc.sock"),
|
|
86
86
|
/** Firecracker's vsock endpoint: the host connects here to reach kvbox-agent inside the box (core/agent.ts). */
|
|
87
87
|
vsock: join(dir, "vsock.sock"),
|
|
88
|
-
log: join(dir, "fc.log")
|
|
88
|
+
log: join(dir, "fc.log"),
|
|
89
|
+
/**
|
|
90
|
+
* An attached volume's drive as Firecracker sees it (#52): a symlink in the box dir to the volume's
|
|
91
|
+
* disk, given to Firecracker by its relative name (`volumeDriveRel`), so a snapshot's vmstate names
|
|
92
|
+
* it relative to whichever box dir it is restored into. There it is a same-size empty placeholder.
|
|
93
|
+
*/
|
|
94
|
+
volumeDrive: (volume) => join(dir, volumeDriveRel(volume))
|
|
95
|
+
};
|
|
96
|
+
},
|
|
97
|
+
/** Volumes are filed like boxes, by owner: volumes/<owner>/<name> (#52). */
|
|
98
|
+
volumes: join(home, "volumes"),
|
|
99
|
+
ownerVolumes: (owner) => join(home, "volumes", owner),
|
|
100
|
+
volume: (owner, name) => {
|
|
101
|
+
const dir = join(home, "volumes", owner, name);
|
|
102
|
+
return {
|
|
103
|
+
dir,
|
|
104
|
+
meta: join(dir, "meta.json"),
|
|
105
|
+
/** The volume itself: a sparse ext4 the guest sees as a whole disk. */
|
|
106
|
+
disk: join(dir, "disk.ext4")
|
|
89
107
|
};
|
|
90
108
|
},
|
|
91
109
|
snapshot: (owner, name) => {
|
|
@@ -101,6 +119,12 @@ function paths(home = kvboxHome()) {
|
|
|
101
119
|
}
|
|
102
120
|
};
|
|
103
121
|
}
|
|
122
|
+
function volumeDriveRel(volume) {
|
|
123
|
+
return `volume-${volume}.ext4`;
|
|
124
|
+
}
|
|
125
|
+
function volumeMountPath(volume) {
|
|
126
|
+
return `/mnt/${volume}`;
|
|
127
|
+
}
|
|
104
128
|
|
|
105
129
|
// src/core/config.ts
|
|
106
130
|
import { chmod, readFile, rename, writeFile } from "node:fs/promises";
|
|
@@ -125,7 +149,9 @@ var PricingSchema = z.object({
|
|
|
125
149
|
currency: z.string().min(1),
|
|
126
150
|
vcpuHour: z.number().nonnegative(),
|
|
127
151
|
ramGibHour: z.number().nonnegative(),
|
|
128
|
-
diskGibHour: z.number().nonnegative()
|
|
152
|
+
diskGibHour: z.number().nonnegative(),
|
|
153
|
+
volumeHour: z.number().nonnegative().default(0),
|
|
154
|
+
volumeGibHour: z.number().nonnegative().default(0)
|
|
129
155
|
});
|
|
130
156
|
var HOUR_MS = 36e5;
|
|
131
157
|
var round = (n, places) => Math.round(n * 10 ** places) / 10 ** places;
|
|
@@ -220,6 +246,57 @@ function groupUsage(rows, window, pricing, live = /* @__PURE__ */ new Map()) {
|
|
|
220
246
|
return out.sort(usageOrder);
|
|
221
247
|
}
|
|
222
248
|
var usageOrder = (a, b) => a.owner.localeCompare(b.owner) || a.name.localeCompare(b.name) || (a.historyFrom ?? "").localeCompare(b.historyFrom ?? "");
|
|
249
|
+
function computeVolumeUsage(events, w) {
|
|
250
|
+
const sorted = [...events].sort((a, b) => a.at < b.at ? -1 : a.at > b.at ? 1 : 0);
|
|
251
|
+
const from = Date.parse(w.from);
|
|
252
|
+
const to = Date.parse(w.to);
|
|
253
|
+
let hours = 0;
|
|
254
|
+
let gibHours = 0;
|
|
255
|
+
sorted.forEach((e, i) => {
|
|
256
|
+
if (e.by === "rm") return;
|
|
257
|
+
const start = Math.max(Date.parse(e.at), from);
|
|
258
|
+
const next = sorted[i + 1];
|
|
259
|
+
const end = Math.min(next === void 0 ? to : Date.parse(next.at), to);
|
|
260
|
+
if (end <= start) return;
|
|
261
|
+
const h = (end - start) / HOUR_MS;
|
|
262
|
+
hours += h;
|
|
263
|
+
gibHours += h * e.sizeGib;
|
|
264
|
+
});
|
|
265
|
+
const totals = { volumeHours: round(hours, 3), volumeGibHours: round(gibHours, 3) };
|
|
266
|
+
if (w.pricing !== void 0) totals.cost = { amount: round(volumeCostOf(totals, w.pricing), 4), currency: w.pricing.currency };
|
|
267
|
+
return totals;
|
|
268
|
+
}
|
|
269
|
+
function volumeCostOf(t, pricing) {
|
|
270
|
+
return t.volumeHours * pricing.volumeHour + t.volumeGibHours * pricing.volumeGibHour;
|
|
271
|
+
}
|
|
272
|
+
function groupVolumeUsage(rows, window, pricing) {
|
|
273
|
+
const byVolume = /* @__PURE__ */ new Map();
|
|
274
|
+
for (const r of rows) {
|
|
275
|
+
const key = r.ledger === void 0 ? r.volumeId : `${r.ledger}:${r.volumeId}`;
|
|
276
|
+
const list = byVolume.get(key);
|
|
277
|
+
if (list === void 0) byVolume.set(key, [r]);
|
|
278
|
+
else list.push(r);
|
|
279
|
+
}
|
|
280
|
+
const out = [];
|
|
281
|
+
for (const events of byVolume.values()) {
|
|
282
|
+
events.sort((a, b) => a.at < b.at ? -1 : a.at > b.at ? 1 : 0);
|
|
283
|
+
const first = events[0];
|
|
284
|
+
const last = events[events.length - 1];
|
|
285
|
+
const removed = last.by === "rm";
|
|
286
|
+
const to = removed && last.at < window.to ? last.at : window.to;
|
|
287
|
+
if (first.at >= to || removed && last.at <= window.from) continue;
|
|
288
|
+
const totals = computeVolumeUsage(events, { from: window.from, to, pricing });
|
|
289
|
+
out.push({ id: last.volumeId, name: last.name, owner: last.owner, sizeGib: last.sizeGib, status: removed ? "removed" : "present", ...totals, historyFrom: first.at });
|
|
290
|
+
}
|
|
291
|
+
return out.sort(usageOrder);
|
|
292
|
+
}
|
|
293
|
+
function reportTotals(boxes, volumes, pricing) {
|
|
294
|
+
const { cost: _boxes, ...sum } = sumUsage(boxes);
|
|
295
|
+
const vol = { volumeHours: round(volumes.reduce((n, v) => n + v.volumeHours, 0), 3), volumeGibHours: round(volumes.reduce((n, v) => n + v.volumeGibHours, 0), 3) };
|
|
296
|
+
const out = { ...sum, ...vol };
|
|
297
|
+
if (pricing !== void 0) return { ...out, cost: { amount: round(costOf(sum, pricing) + volumeCostOf(vol, pricing), 4), currency: pricing.currency } };
|
|
298
|
+
return out;
|
|
299
|
+
}
|
|
223
300
|
|
|
224
301
|
// src/core/refs.ts
|
|
225
302
|
import { userInfo } from "node:os";
|
|
@@ -303,6 +380,11 @@ var ConfigSchema = z2.object({
|
|
|
303
380
|
pricing: PricingSchema.optional(),
|
|
304
381
|
/** What a new box gets when `new` does not say (#47): seconds without network traffic before it is hibernated; 0: never. */
|
|
305
382
|
autoHibernateSec: z2.number().int().min(0).default(0),
|
|
383
|
+
/**
|
|
384
|
+
* GiB of disk `kvbox volume create` leaves free for the boxes' overlays and snapshots (#52): a volume is
|
|
385
|
+
* refused when it could not fill up with that much still free. 0 only on a host whose disk is for tests.
|
|
386
|
+
*/
|
|
387
|
+
volumeHeadroomGib: z2.number().int().min(0).default(20),
|
|
306
388
|
/** Absent until the host joins a control plane; then the server also listens on HTTPS. */
|
|
307
389
|
controlPlane: ControlPlaneSchema.optional(),
|
|
308
390
|
/** Absent unless the host sits behind a relay. */
|
|
@@ -409,7 +491,36 @@ var MachineSchema = z3.object({
|
|
|
409
491
|
/** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /machines`. */
|
|
410
492
|
ownerKind: z3.enum(["user", "org"]).optional(),
|
|
411
493
|
/** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
|
|
412
|
-
autoHibernateSec: z3.number().int().positive().optional()
|
|
494
|
+
autoHibernateSec: z3.number().int().positive().optional(),
|
|
495
|
+
/** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */
|
|
496
|
+
volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int(), mountPath: z3.string() })).optional()
|
|
497
|
+
});
|
|
498
|
+
var VolumeSchema = z3.object({
|
|
499
|
+
/** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */
|
|
500
|
+
id: z3.string(),
|
|
501
|
+
name: z3.string(),
|
|
502
|
+
owner: z3.string(),
|
|
503
|
+
sizeGib: z3.number().int(),
|
|
504
|
+
/** What the sparse file really occupies on the host. */
|
|
505
|
+
usedBytes: z3.number().int(),
|
|
506
|
+
attachedTo: z3.string().nullable(),
|
|
507
|
+
createdAt: z3.string(),
|
|
508
|
+
/** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /volumes`. */
|
|
509
|
+
ownerKind: z3.enum(["user", "org"]).optional()
|
|
510
|
+
});
|
|
511
|
+
var MAX_VOLUME_GIB = 4096;
|
|
512
|
+
var CreateVolumeRequest = z3.object({
|
|
513
|
+
name: z3.string(),
|
|
514
|
+
sizeGib: z3.number().int().min(1).max(MAX_VOLUME_GIB),
|
|
515
|
+
/**
|
|
516
|
+
* Through a control plane (#91): the box this volume is for, so it is made on that box's host. A
|
|
517
|
+
* volume attaches only to a box on its own host. Absent: the host with the most room for volumes.
|
|
518
|
+
* A host ignores it.
|
|
519
|
+
*/
|
|
520
|
+
box: z3.string().optional()
|
|
521
|
+
});
|
|
522
|
+
var AttachVolumeRequest = z3.object({
|
|
523
|
+
box: z3.string()
|
|
413
524
|
});
|
|
414
525
|
var CreateMachineRequest = z3.object({
|
|
415
526
|
name: z3.string().optional(),
|
|
@@ -471,12 +582,21 @@ var CreateSnapshotRequest = z3.object({
|
|
|
471
582
|
box: z3.string(),
|
|
472
583
|
name: z3.string()
|
|
473
584
|
});
|
|
585
|
+
var DiskCapacitySchema = z3.object({
|
|
586
|
+
totalGib: z3.number().int(),
|
|
587
|
+
freeGib: z3.number().int(),
|
|
588
|
+
volumesGib: z3.number().int(),
|
|
589
|
+
volumesUsedGib: z3.number().int(),
|
|
590
|
+
headroomGib: z3.number().int()
|
|
591
|
+
});
|
|
474
592
|
var CapacitySchema = z3.object({
|
|
475
593
|
hostMemMib: z3.number().int(),
|
|
476
594
|
hostCores: z3.number().int(),
|
|
477
595
|
reservedMemMib: z3.number().int(),
|
|
478
596
|
reservedVcpu: z3.number().int(),
|
|
479
|
-
running: z3.number().int()
|
|
597
|
+
running: z3.number().int(),
|
|
598
|
+
/** Absent on a host from before volumes (#91): it cannot take one. */
|
|
599
|
+
disk: DiskCapacitySchema.optional()
|
|
480
600
|
});
|
|
481
601
|
var RecoveryReportSchema = z3.object({
|
|
482
602
|
at: z3.string(),
|
|
@@ -563,14 +683,33 @@ var BoxUsageSchema = MachineUsageSchema.omit({ window: true, status: true }).ext
|
|
|
563
683
|
*/
|
|
564
684
|
createdBy: z3.string().optional()
|
|
565
685
|
});
|
|
686
|
+
var VolumeUsageSchema = z3.object({
|
|
687
|
+
/** The host's volume id; a name removed and made again appears twice, with two ids. */
|
|
688
|
+
id: z3.string(),
|
|
689
|
+
name: z3.string(),
|
|
690
|
+
owner: z3.string(),
|
|
691
|
+
ownerKind: z3.enum(["user", "org"]).optional(),
|
|
692
|
+
/** The size at the end of the window (or when removed). */
|
|
693
|
+
sizeGib: z3.number().int(),
|
|
694
|
+
status: z3.enum(["present", "removed"]),
|
|
695
|
+
volumeHours: z3.number(),
|
|
696
|
+
volumeGibHours: z3.number(),
|
|
697
|
+
cost: z3.object({ amount: z3.number(), currency: z3.string() }).optional(),
|
|
698
|
+
historyFrom: z3.string().nullable()
|
|
699
|
+
});
|
|
566
700
|
var UsageReportSchema = z3.object({
|
|
567
701
|
window: z3.object({ from: z3.string(), to: z3.string() }),
|
|
568
702
|
boxes: z3.array(BoxUsageSchema),
|
|
703
|
+
/** Absent from a side older than #91. */
|
|
704
|
+
volumes: z3.array(VolumeUsageSchema).optional(),
|
|
569
705
|
totals: z3.object({
|
|
570
706
|
seconds: MachineUsageSchema.shape.seconds,
|
|
571
707
|
vcpuHours: z3.number(),
|
|
572
708
|
ramGibHours: z3.number(),
|
|
573
709
|
diskGibHours: z3.number(),
|
|
710
|
+
volumeHours: z3.number().optional(),
|
|
711
|
+
volumeGibHours: z3.number().optional(),
|
|
712
|
+
/** Boxes and volumes together. */
|
|
574
713
|
cost: z3.object({ amount: z3.number(), currency: z3.string() }).optional()
|
|
575
714
|
})
|
|
576
715
|
});
|
|
@@ -591,6 +730,20 @@ var UsageEventsResponseSchema = z3.object({
|
|
|
591
730
|
events: z3.array(UsageEventRowSchema),
|
|
592
731
|
next: z3.number().int()
|
|
593
732
|
});
|
|
733
|
+
var VolumeEventRowSchema = z3.object({
|
|
734
|
+
id: z3.number().int(),
|
|
735
|
+
volumeId: z3.string(),
|
|
736
|
+
owner: z3.string(),
|
|
737
|
+
name: z3.string(),
|
|
738
|
+
at: z3.string(),
|
|
739
|
+
sizeGib: z3.number().int(),
|
|
740
|
+
by: z3.enum(["create", "resize", "rm"])
|
|
741
|
+
});
|
|
742
|
+
var VolumeEventsResponseSchema = z3.object({
|
|
743
|
+
ledger: z3.string().min(1),
|
|
744
|
+
events: z3.array(VolumeEventRowSchema),
|
|
745
|
+
next: z3.number().int()
|
|
746
|
+
});
|
|
594
747
|
var ApiErrorSchema = z3.object({
|
|
595
748
|
error: z3.string()
|
|
596
749
|
});
|
|
@@ -957,8 +1110,8 @@ async function requireKvm(device = KVM_DEVICE, groupFile = "/etc/group") {
|
|
|
957
1110
|
|
|
958
1111
|
// src/core/machines.ts
|
|
959
1112
|
import { spawn } from "node:child_process";
|
|
960
|
-
import { closeSync as closeSync2, existsSync as
|
|
961
|
-
import { link as link2, mkdir as
|
|
1113
|
+
import { closeSync as closeSync2, existsSync as existsSync4, openSync as openSync2, statSync as statSync2 } from "node:fs";
|
|
1114
|
+
import { link as link2, mkdir as mkdir5, readFile as readFile5, realpath, rm as rm3, truncate as truncate2, writeFile as writeFile4 } from "node:fs/promises";
|
|
962
1115
|
import { basename } from "node:path";
|
|
963
1116
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
964
1117
|
|
|
@@ -1019,20 +1172,200 @@ async function stats(udsPath, timeoutMs) {
|
|
|
1019
1172
|
if (!reply.success) throw new KvboxError(`kvbox-agent sent stats kvbox does not understand: ${reply.error.issues[0]?.message ?? "invalid"}`);
|
|
1020
1173
|
return reply.data;
|
|
1021
1174
|
}
|
|
1175
|
+
async function dropVolumes(udsPath, timeoutMs) {
|
|
1176
|
+
const reply = await agentCall(udsPath, { op: "dropVolumes" }, timeoutMs);
|
|
1177
|
+
return Array.isArray(reply["dropped"]) ? reply["dropped"].map(String) : [];
|
|
1178
|
+
}
|
|
1022
1179
|
var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
|
|
1023
1180
|
var isNoAgent = (err) => /vsock connect refused|vsock connection closed before the guest accepted|kvbox-agent unreachable: connect (ENOENT|ECONNREFUSED)/.test(err.message ?? "");
|
|
1024
1181
|
|
|
1025
|
-
// src/core/
|
|
1026
|
-
import {
|
|
1182
|
+
// src/core/volumes.ts
|
|
1183
|
+
import { existsSync, statSync } from "node:fs";
|
|
1184
|
+
import { lstat, mkdir as mkdir3, readdir as readdir2, rm, statfs, symlink, truncate, writeFile as writeFile3 } from "node:fs/promises";
|
|
1027
1185
|
|
|
1028
1186
|
// ../shared/src/capacity.ts
|
|
1029
1187
|
var MEM_HEADROOM_MIB = 2048;
|
|
1188
|
+
function sellableGib(d) {
|
|
1189
|
+
return Math.max(0, d.freeGib + d.volumesUsedGib - d.headroomGib);
|
|
1190
|
+
}
|
|
1191
|
+
function volumeRoomGib(d) {
|
|
1192
|
+
return Math.max(0, sellableGib(d) - d.volumesGib);
|
|
1193
|
+
}
|
|
1194
|
+
function hasDiskRoom(d, sizeGib) {
|
|
1195
|
+
return sizeGib <= volumeRoomGib(d);
|
|
1196
|
+
}
|
|
1030
1197
|
var VCPU_OVERSUBSCRIPTION = 2;
|
|
1031
1198
|
|
|
1199
|
+
// src/core/db.ts
|
|
1200
|
+
import { chmodSync, closeSync, mkdirSync, openSync } from "node:fs";
|
|
1201
|
+
import { dirname } from "node:path";
|
|
1202
|
+
import { DatabaseSync } from "node:sqlite";
|
|
1203
|
+
var MIGRATIONS = [
|
|
1204
|
+
`create table usage_events (
|
|
1205
|
+
id integer primary key,
|
|
1206
|
+
box_id text not null,
|
|
1207
|
+
owner text not null,
|
|
1208
|
+
name text not null,
|
|
1209
|
+
at text not null,
|
|
1210
|
+
state text not null,
|
|
1211
|
+
vcpu integer not null,
|
|
1212
|
+
mem_mib integer not null,
|
|
1213
|
+
disk_gib integer not null,
|
|
1214
|
+
by text not null
|
|
1215
|
+
);
|
|
1216
|
+
create index usage_events_box_at on usage_events (box_id, at);`,
|
|
1217
|
+
// The ledger's identity (#42): a control plane keys pulled rows by it, so a re-join is recognised
|
|
1218
|
+
// and a fresh ledger (KVBOX_HOME wiped) restarts its cursor instead of waiting for ids it already saw.
|
|
1219
|
+
`create table ledger (id text not null);
|
|
1220
|
+
insert into ledger (id) values (lower(hex(randomblob(16))));
|
|
1221
|
+
create index usage_events_at on usage_events (at);`,
|
|
1222
|
+
// Volumes (#91): a row per create, resize and rm, the size from that moment on. Its own table and
|
|
1223
|
+
// ids, pulled by the control plane like usage_events, in the same ledger.
|
|
1224
|
+
`create table volume_events (
|
|
1225
|
+
id integer primary key,
|
|
1226
|
+
volume_id text not null,
|
|
1227
|
+
owner text not null,
|
|
1228
|
+
name text not null,
|
|
1229
|
+
at text not null,
|
|
1230
|
+
size_gib integer not null,
|
|
1231
|
+
by text not null
|
|
1232
|
+
);
|
|
1233
|
+
create index volume_events_volume_at on volume_events (volume_id, at);`
|
|
1234
|
+
];
|
|
1235
|
+
var handles = /* @__PURE__ */ new Map();
|
|
1236
|
+
function openDb(p = paths()) {
|
|
1237
|
+
const have = handles.get(p.db);
|
|
1238
|
+
if (have !== void 0) return have;
|
|
1239
|
+
mkdirSync(dirname(p.db), { recursive: true, mode: 448 });
|
|
1240
|
+
closeSync(openSync(p.db, "a", 384));
|
|
1241
|
+
chmodSync(p.db, 384);
|
|
1242
|
+
const db = new DatabaseSync(p.db);
|
|
1243
|
+
db.exec("pragma journal_mode = wal");
|
|
1244
|
+
db.exec("pragma busy_timeout = 5000");
|
|
1245
|
+
migrate(db);
|
|
1246
|
+
handles.set(p.db, db);
|
|
1247
|
+
return db;
|
|
1248
|
+
}
|
|
1249
|
+
function migrate(db) {
|
|
1250
|
+
db.exec("create table if not exists schema_version (version integer not null)");
|
|
1251
|
+
const row = db.prepare("select version from schema_version").get();
|
|
1252
|
+
let version = row?.version ?? 0;
|
|
1253
|
+
if (row === void 0) db.prepare("insert into schema_version (version) values (0)").run();
|
|
1254
|
+
while (version < MIGRATIONS.length) {
|
|
1255
|
+
db.exec("begin");
|
|
1256
|
+
try {
|
|
1257
|
+
db.exec(MIGRATIONS[version]);
|
|
1258
|
+
version += 1;
|
|
1259
|
+
db.prepare("update schema_version set version = ?").run(version);
|
|
1260
|
+
db.exec("commit");
|
|
1261
|
+
} catch (err) {
|
|
1262
|
+
db.exec("rollback");
|
|
1263
|
+
throw err;
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
var LIVE_STATES = ["running", "standby"];
|
|
1268
|
+
function fromRaw(r) {
|
|
1269
|
+
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 };
|
|
1270
|
+
}
|
|
1271
|
+
function lastEvent(boxId, db) {
|
|
1272
|
+
const raw = db.prepare("select * from usage_events where box_id = ? order by at desc, id desc limit 1").get(boxId);
|
|
1273
|
+
return raw === void 0 ? void 0 : fromRaw(raw);
|
|
1274
|
+
}
|
|
1275
|
+
function insertRaw(e, db) {
|
|
1276
|
+
db.prepare(
|
|
1277
|
+
"insert into usage_events (box_id, owner, name, at, state, vcpu, mem_mib, disk_gib, by) values (?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
|
1278
|
+
).run(e.boxId, e.owner, e.name, e.at, e.state, e.vcpu, e.memMib, e.diskGib, e.by);
|
|
1279
|
+
}
|
|
1280
|
+
function insertUsageEvent(e, p = paths()) {
|
|
1281
|
+
const db = openDb(p);
|
|
1282
|
+
if (e.state === "running" && e.by !== "resume") closeOpenRun(e.boxId, e.at, p);
|
|
1283
|
+
insertRaw(e, db);
|
|
1284
|
+
}
|
|
1285
|
+
function closeOpenRun(boxId, at, p = paths()) {
|
|
1286
|
+
const db = openDb(p);
|
|
1287
|
+
const last = lastEvent(boxId, db);
|
|
1288
|
+
if (last === void 0 || !LIVE_STATES.includes(last.state)) return false;
|
|
1289
|
+
insertRaw({ ...last, at, state: "stopped", by: "server" }, db);
|
|
1290
|
+
return true;
|
|
1291
|
+
}
|
|
1292
|
+
function closeRunCutByBoot(boxId, bootAt, now, p = paths()) {
|
|
1293
|
+
const last = lastEvent(boxId, openDb(p));
|
|
1294
|
+
return closeOpenRun(boxId, last !== void 0 && last.at < bootAt ? bootAt : now, p);
|
|
1295
|
+
}
|
|
1296
|
+
function usageEventsFor(boxId, since, p = paths()) {
|
|
1297
|
+
const rows = openDb(p).prepare("select * from usage_events where box_id = ? and at >= ? order by at, id").all(boxId, since);
|
|
1298
|
+
return rows.map(fromRaw);
|
|
1299
|
+
}
|
|
1300
|
+
var withId = (r) => ({ ...fromRaw(r), id: r.id });
|
|
1301
|
+
function ledgerId(p = paths()) {
|
|
1302
|
+
return openDb(p).prepare("select id from ledger").get().id;
|
|
1303
|
+
}
|
|
1304
|
+
function usageEventsAfter(after, limit, scope, p = paths()) {
|
|
1305
|
+
const db = openDb(p);
|
|
1306
|
+
const rows = scope === null ? db.prepare("select * from usage_events where id > ? order by id limit ?").all(after, limit) : typeof scope === "string" ? db.prepare("select * from usage_events where id > ? and owner = ? order by id limit ?").all(after, scope, limit) : db.prepare("select * from usage_events where id > ? and substr(owner, -length(?)) = ? order by id limit ?").all(after, `@${scope.realm}`, `@${scope.realm}`, limit);
|
|
1307
|
+
return rows.map(withId);
|
|
1308
|
+
}
|
|
1309
|
+
function usageEventsInScope(scope, window, p = paths()) {
|
|
1310
|
+
const rows = openDb(p).prepare(
|
|
1311
|
+
`select * from usage_events where at < ? and (at >= ? or id in (select max(id) from usage_events where at < ? group by box_id))
|
|
1312
|
+
order by at, id`
|
|
1313
|
+
).all(window.to, window.from, window.from);
|
|
1314
|
+
return rows.filter((r) => inScope(r.owner, scope)).map(withId);
|
|
1315
|
+
}
|
|
1316
|
+
var volumeWithId = (r) => ({ id: r.id, volumeId: r.volume_id, owner: r.owner, name: r.name, at: r.at, sizeGib: r.size_gib, by: r.by });
|
|
1317
|
+
function insertVolumeEvent(e, p = paths()) {
|
|
1318
|
+
openDb(p).prepare("insert into volume_events (volume_id, owner, name, at, size_gib, by) values (?, ?, ?, ?, ?, ?)").run(e.volumeId, e.owner, e.name, e.at, e.sizeGib, e.by);
|
|
1319
|
+
}
|
|
1320
|
+
function volumeEventsAfter(after, limit, scope, p = paths()) {
|
|
1321
|
+
const db = openDb(p);
|
|
1322
|
+
const rows = scope === null ? db.prepare("select * from volume_events where id > ? order by id limit ?").all(after, limit) : typeof scope === "string" ? db.prepare("select * from volume_events where id > ? and owner = ? order by id limit ?").all(after, scope, limit) : db.prepare("select * from volume_events where id > ? and substr(owner, -length(?)) = ? order by id limit ?").all(after, `@${scope.realm}`, `@${scope.realm}`, limit);
|
|
1323
|
+
return rows.map(volumeWithId);
|
|
1324
|
+
}
|
|
1325
|
+
function volumeEventsInScope(scope, window, p = paths()) {
|
|
1326
|
+
const rows = openDb(p).prepare(
|
|
1327
|
+
`select * from volume_events where at < ? and (at >= ? or id in (select max(id) from volume_events where at < ? group by volume_id))
|
|
1328
|
+
order by at, id`
|
|
1329
|
+
).all(window.to, window.from, window.from);
|
|
1330
|
+
return rows.filter((r) => inScope(r.owner, scope)).map(volumeWithId);
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
// src/core/locks.ts
|
|
1334
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
1335
|
+
var tails = /* @__PURE__ */ new Map();
|
|
1336
|
+
var held = new AsyncLocalStorage();
|
|
1337
|
+
function withBoxLock(ref, fn) {
|
|
1338
|
+
return withLock(refKey(ref), fn);
|
|
1339
|
+
}
|
|
1340
|
+
function withHostLock(name, fn) {
|
|
1341
|
+
return withLock(`host:${name}`, fn);
|
|
1342
|
+
}
|
|
1343
|
+
async function withLock(key, fn) {
|
|
1344
|
+
const mine = held.getStore();
|
|
1345
|
+
if (mine?.has(key)) return fn();
|
|
1346
|
+
const previous = tails.get(key);
|
|
1347
|
+
let release;
|
|
1348
|
+
const tail = new Promise((resolve) => release = resolve);
|
|
1349
|
+
tails.set(key, tail);
|
|
1350
|
+
try {
|
|
1351
|
+
await previous;
|
|
1352
|
+
return await held.run(/* @__PURE__ */ new Set([...mine ?? [], key]), fn);
|
|
1353
|
+
} finally {
|
|
1354
|
+
release();
|
|
1355
|
+
if (tails.get(key) === tail) tails.delete(key);
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
function boxBusy(ref) {
|
|
1359
|
+
return tails.has(refKey(ref));
|
|
1360
|
+
}
|
|
1361
|
+
function locked(fn) {
|
|
1362
|
+
return (...args) => withBoxLock(args[0], () => fn(...args));
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1032
1365
|
// src/core/state.ts
|
|
1033
1366
|
import { randomBytes } from "node:crypto";
|
|
1034
1367
|
import { readFileSync } from "node:fs";
|
|
1035
|
-
import { mkdir as mkdir2, readFile as readFile4, readdir, writeFile as writeFile2 } from "node:fs/promises";
|
|
1368
|
+
import { mkdir as mkdir2, readFile as readFile4, readdir, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
|
|
1036
1369
|
import { z as z4 } from "zod";
|
|
1037
1370
|
var MachineMetaSchema = z4.object({
|
|
1038
1371
|
/** Host-unique, minted at `kvbox new` (fresh or restored) and kept for the box's life; the tap is `kv-<id>`. */
|
|
@@ -1084,7 +1417,21 @@ var MachineMetaSchema = z4.object({
|
|
|
1084
1417
|
*/
|
|
1085
1418
|
ports: z4.array(z4.object({ guestPort: z4.number().int(), hostPort: z4.number().int(), proto: z4.enum(["tcp", "udp"]) })).optional(),
|
|
1086
1419
|
/** Seconds without traffic on the box's tap before the server hibernates it (#47, core/idle.ts). Absent: never. */
|
|
1087
|
-
autoHibernateSec: z4.number().int().positive().optional()
|
|
1420
|
+
autoHibernateSec: z4.number().int().positive().optional(),
|
|
1421
|
+
/**
|
|
1422
|
+
* Names of the owner's volumes attached to the box (#52), in the order they were attached, which is
|
|
1423
|
+
* their drive order (/dev/vdc, /dev/vdd, …). This list is the one truth about what is attached: a
|
|
1424
|
+
* volume's meta.json does not say. Absent: none.
|
|
1425
|
+
*/
|
|
1426
|
+
volumes: z4.array(z4.string()).optional()
|
|
1427
|
+
});
|
|
1428
|
+
var VolumeMetaSchema = z4.object({
|
|
1429
|
+
/** Host-unique like a box id (#91): the ledger's key, so a name removed and made again is two volumes. */
|
|
1430
|
+
id: z4.string(),
|
|
1431
|
+
name: z4.string(),
|
|
1432
|
+
owner: z4.string(),
|
|
1433
|
+
sizeGib: z4.number().int(),
|
|
1434
|
+
createdAt: z4.string()
|
|
1088
1435
|
});
|
|
1089
1436
|
function newBoxId(taken) {
|
|
1090
1437
|
for (; ; ) {
|
|
@@ -1101,10 +1448,16 @@ var SnapshotMetaSchema = z4.object({
|
|
|
1101
1448
|
vcpu: z4.number().int(),
|
|
1102
1449
|
memMib: z4.number().int(),
|
|
1103
1450
|
sizeBytes: z4.number().int(),
|
|
1104
|
-
createdAt: z4.string()
|
|
1451
|
+
createdAt: z4.string(),
|
|
1452
|
+
/**
|
|
1453
|
+
* The volumes the source box had attached when it was frozen (#52): their drives are in the vmstate
|
|
1454
|
+
* and their mounts in the memory image, but their data is not here. A box restored from the snapshot
|
|
1455
|
+
* gets an empty placeholder of each size at the drive's path and drops the mounts through kvbox-agent.
|
|
1456
|
+
*/
|
|
1457
|
+
volumes: z4.array(z4.object({ name: z4.string(), sizeGib: z4.number().int() })).optional()
|
|
1105
1458
|
});
|
|
1106
1459
|
async function ensureLayout(p = paths()) {
|
|
1107
|
-
for (const dir of [p.home, p.ssh, p.bin, p.assets, p.machines, p.snapshots]) {
|
|
1460
|
+
for (const dir of [p.home, p.ssh, p.bin, p.assets, p.machines, p.snapshots, p.volumes]) {
|
|
1108
1461
|
await mkdir2(dir, { recursive: true, mode: 448 });
|
|
1109
1462
|
}
|
|
1110
1463
|
return p;
|
|
@@ -1127,7 +1480,9 @@ async function readMachineMeta(ref, p = paths()) {
|
|
|
1127
1480
|
async function writeMachineMeta(meta, p = paths()) {
|
|
1128
1481
|
const m = p.machine(meta.owner, meta.name);
|
|
1129
1482
|
await mkdir2(m.dir, { recursive: true });
|
|
1130
|
-
|
|
1483
|
+
const tmp = `${m.meta}.tmp`;
|
|
1484
|
+
await writeFile2(tmp, JSON.stringify(meta, null, 2) + "\n");
|
|
1485
|
+
await rename2(tmp, m.meta);
|
|
1131
1486
|
}
|
|
1132
1487
|
async function listMachineRefs(p = paths()) {
|
|
1133
1488
|
return listRefs(p.machines);
|
|
@@ -1143,6 +1498,30 @@ async function writeSnapshotMeta(meta, p = paths()) {
|
|
|
1143
1498
|
async function listSnapshotRefs(p = paths()) {
|
|
1144
1499
|
return listRefs(p.snapshots);
|
|
1145
1500
|
}
|
|
1501
|
+
async function readVolumeMeta(ref, p = paths()) {
|
|
1502
|
+
const raw = await readJson(p.volume(ref.owner, ref.name).meta, VolumeMetaSchema.extend({ id: z4.string().optional() }));
|
|
1503
|
+
if (raw.id !== void 0) return { ...raw, id: raw.id };
|
|
1504
|
+
const taken = /* @__PURE__ */ new Set();
|
|
1505
|
+
for (const other of await listVolumeRefs(p)) {
|
|
1506
|
+
try {
|
|
1507
|
+
const j = JSON.parse(await readFile4(p.volume(other.owner, other.name).meta, "utf8"));
|
|
1508
|
+
if (typeof j.id === "string") taken.add(j.id);
|
|
1509
|
+
} catch {
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
const meta = { ...raw, id: newBoxId(taken) };
|
|
1513
|
+
await writeVolumeMeta(meta, p);
|
|
1514
|
+
insertVolumeEvent({ volumeId: meta.id, owner: meta.owner, name: meta.name, at: meta.createdAt, sizeGib: meta.sizeGib, by: "create" }, p);
|
|
1515
|
+
return meta;
|
|
1516
|
+
}
|
|
1517
|
+
async function writeVolumeMeta(meta, p = paths()) {
|
|
1518
|
+
const v = p.volume(meta.owner, meta.name);
|
|
1519
|
+
await mkdir2(v.dir, { recursive: true, mode: 448 });
|
|
1520
|
+
await writeFile2(v.meta, JSON.stringify(meta, null, 2) + "\n");
|
|
1521
|
+
}
|
|
1522
|
+
async function listVolumeRefs(p = paths()) {
|
|
1523
|
+
return listRefs(p.volumes);
|
|
1524
|
+
}
|
|
1146
1525
|
async function listRefs(root) {
|
|
1147
1526
|
const out = [];
|
|
1148
1527
|
for (const owner of await listDirs(root)) {
|
|
@@ -1185,7 +1564,222 @@ function hostBootTime() {
|
|
|
1185
1564
|
}
|
|
1186
1565
|
}
|
|
1187
1566
|
|
|
1567
|
+
// src/core/volumes.ts
|
|
1568
|
+
var VOLUME_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
|
|
1569
|
+
var volumeLabel = (name) => `kv:${name}`;
|
|
1570
|
+
function toVolume(meta, attachedTo, p) {
|
|
1571
|
+
let usedBytes2 = 0;
|
|
1572
|
+
try {
|
|
1573
|
+
usedBytes2 = statSync(p.volume(meta.owner, meta.name).disk).blocks * 512;
|
|
1574
|
+
} catch {
|
|
1575
|
+
}
|
|
1576
|
+
return { id: meta.id, name: meta.name, owner: meta.owner, sizeGib: meta.sizeGib, usedBytes: usedBytes2, attachedTo, createdAt: meta.createdAt };
|
|
1577
|
+
}
|
|
1578
|
+
function recordVolume(meta, by, p, at = (/* @__PURE__ */ new Date()).toISOString()) {
|
|
1579
|
+
try {
|
|
1580
|
+
insertVolumeEvent({ volumeId: meta.id, owner: meta.owner, name: meta.name, at, sizeGib: meta.sizeGib, by }, p);
|
|
1581
|
+
} catch (err) {
|
|
1582
|
+
console.error(`warning: volume ledger: ${err.message}`);
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
async function attachments(owner, p) {
|
|
1586
|
+
const out = /* @__PURE__ */ new Map();
|
|
1587
|
+
for (const ref of await listMachineRefs(p)) {
|
|
1588
|
+
if (ref.owner !== owner) continue;
|
|
1589
|
+
try {
|
|
1590
|
+
const meta = await readMachineMeta(ref, p);
|
|
1591
|
+
for (const v of meta.volumes ?? []) out.set(v, meta.name);
|
|
1592
|
+
} catch {
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1595
|
+
return out;
|
|
1596
|
+
}
|
|
1597
|
+
async function readVolume(ref, p) {
|
|
1598
|
+
try {
|
|
1599
|
+
return await readVolumeMeta(ref, p);
|
|
1600
|
+
} catch (err) {
|
|
1601
|
+
if (err.code === "ENOENT") throw new NotFoundError(`volume ${shown(ref)}`);
|
|
1602
|
+
throw err;
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
async function getVolume(ref, p = paths()) {
|
|
1606
|
+
const meta = await readVolume(ref, p);
|
|
1607
|
+
return toVolume(meta, (await attachments(ref.owner, p)).get(ref.name) ?? null, p);
|
|
1608
|
+
}
|
|
1609
|
+
async function listVolumes(scope, p = paths()) {
|
|
1610
|
+
const out = [];
|
|
1611
|
+
const byOwner = /* @__PURE__ */ new Map();
|
|
1612
|
+
for (const ref of await listVolumeRefs(p)) {
|
|
1613
|
+
if (!inScope(ref.owner, scope)) continue;
|
|
1614
|
+
try {
|
|
1615
|
+
const meta = await readVolumeMeta(ref, p);
|
|
1616
|
+
let attached = byOwner.get(ref.owner);
|
|
1617
|
+
if (attached === void 0) {
|
|
1618
|
+
attached = await attachments(ref.owner, p);
|
|
1619
|
+
byOwner.set(ref.owner, attached);
|
|
1620
|
+
}
|
|
1621
|
+
out.push(toVolume(meta, attached.get(meta.name) ?? null, p));
|
|
1622
|
+
} catch (err) {
|
|
1623
|
+
console.error(`warning: skipping volumes/${ref.owner}/${ref.name}: ${err.message}`);
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
return out.sort((a, b) => a.owner.localeCompare(b.owner) || a.name.localeCompare(b.name));
|
|
1627
|
+
}
|
|
1628
|
+
async function diskCapacity(p = paths()) {
|
|
1629
|
+
const st = await statfs(existsSync(p.volumes) ? p.volumes : p.home);
|
|
1630
|
+
let volumesGib = 0;
|
|
1631
|
+
let usedBytes2 = 0;
|
|
1632
|
+
for (const ref of await listVolumeRefs(p)) {
|
|
1633
|
+
try {
|
|
1634
|
+
volumesGib += (await readVolumeMeta(ref, p)).sizeGib;
|
|
1635
|
+
usedBytes2 += statSync(p.volume(ref.owner, ref.name).disk).blocks * 512;
|
|
1636
|
+
} catch {
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
return {
|
|
1640
|
+
totalGib: Math.floor(st.blocks * st.bsize / 1024 ** 3),
|
|
1641
|
+
freeGib: Math.floor(st.bavail * st.bsize / 1024 ** 3),
|
|
1642
|
+
volumesGib,
|
|
1643
|
+
volumesUsedGib: Math.floor(usedBytes2 / 1024 ** 3),
|
|
1644
|
+
headroomGib: (await loadConfig(p)).volumeHeadroomGib
|
|
1645
|
+
};
|
|
1646
|
+
}
|
|
1647
|
+
async function createVolume(req, owner, p = paths()) {
|
|
1648
|
+
if (!VOLUME_NAME_RE.test(req.name)) {
|
|
1649
|
+
throw new KvboxError(`invalid volume name "${req.name}": 1-12 chars, lowercase letters, digits and '-', starting with a letter or digit`);
|
|
1650
|
+
}
|
|
1651
|
+
if (!Number.isInteger(req.sizeGib) || req.sizeGib < 1 || req.sizeGib > MAX_VOLUME_GIB) {
|
|
1652
|
+
throw new KvboxError(`volume size: whole GB between 1 and ${MAX_VOLUME_GIB}`);
|
|
1653
|
+
}
|
|
1654
|
+
return withHostLock("volumes", () => makeVolume(req, owner, p));
|
|
1655
|
+
}
|
|
1656
|
+
async function makeVolume(req, owner, p) {
|
|
1657
|
+
const v = p.volume(owner, req.name);
|
|
1658
|
+
if (existsSync(v.dir)) throw new KvboxError(`volume ${req.name} already exists`);
|
|
1659
|
+
await mkdir3(p.ownerVolumes(owner), { recursive: true, mode: 448 });
|
|
1660
|
+
const disk = await diskCapacity(p);
|
|
1661
|
+
if (!hasDiskRoom(disk, req.sizeGib)) {
|
|
1662
|
+
throw new KvboxError(
|
|
1663
|
+
`not enough disk on this host for a ${req.sizeGib} GB volume: it can still promise ${volumeRoomGib(disk)} GB (${disk.freeGib} GB free, ${disk.volumesGib} GB promised to ${disk.volumesGib === 0 ? "no volume yet" : "its volumes"}, ${disk.headroomGib} GB kept for its boxes)`
|
|
1664
|
+
);
|
|
1665
|
+
}
|
|
1666
|
+
const taken = /* @__PURE__ */ new Set();
|
|
1667
|
+
for (const ref of await listVolumeRefs(p)) {
|
|
1668
|
+
try {
|
|
1669
|
+
taken.add((await readVolumeMeta(ref, p)).id);
|
|
1670
|
+
} catch {
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
try {
|
|
1674
|
+
await mkdir3(v.dir, { mode: 448 });
|
|
1675
|
+
} catch (err) {
|
|
1676
|
+
if (err.code === "EEXIST") throw new KvboxError(`volume ${req.name} already exists`);
|
|
1677
|
+
throw err;
|
|
1678
|
+
}
|
|
1679
|
+
try {
|
|
1680
|
+
await writeFile3(v.disk, "", { mode: 384 });
|
|
1681
|
+
await truncate(v.disk, req.sizeGib * 1024 ** 3);
|
|
1682
|
+
await run(["mkfs.ext4", "-q", "-F", "-m", "0", "-L", volumeLabel(req.name), "-E", "lazy_itable_init=1,lazy_journal_init=1", v.disk]);
|
|
1683
|
+
const meta = { id: newBoxId(taken), name: req.name, owner, sizeGib: req.sizeGib, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
1684
|
+
await writeVolumeMeta(meta, p);
|
|
1685
|
+
recordVolume(meta, "create", p, meta.createdAt);
|
|
1686
|
+
return toVolume(meta, null, p);
|
|
1687
|
+
} catch (err) {
|
|
1688
|
+
await rm(v.dir, { recursive: true, force: true });
|
|
1689
|
+
throw err;
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
async function deleteVolume(ref, p = paths()) {
|
|
1693
|
+
await withHostLock("volumes", async () => {
|
|
1694
|
+
const meta = await readVolume(ref, p);
|
|
1695
|
+
const box = (await attachments(ref.owner, p)).get(ref.name);
|
|
1696
|
+
if (box !== void 0) throw new KvboxError(`volume ${shown(ref)} is attached to box ${box}; kvbox volume detach ${shown(ref)} first`);
|
|
1697
|
+
try {
|
|
1698
|
+
insertVolumeEvent({ volumeId: meta.id, owner: meta.owner, name: meta.name, at: (/* @__PURE__ */ new Date()).toISOString(), sizeGib: meta.sizeGib, by: "rm" }, p);
|
|
1699
|
+
} catch (err) {
|
|
1700
|
+
throw new KvboxError(`volume ${shown(ref)} was not removed: its ledger row could not be written (${err.message}); try again`);
|
|
1701
|
+
}
|
|
1702
|
+
try {
|
|
1703
|
+
await rm(p.volume(ref.owner, ref.name).dir, { recursive: true, force: true });
|
|
1704
|
+
} catch (err) {
|
|
1705
|
+
throw new KvboxError(`volume ${shown(ref)}: its files could not be removed (${err.message}); it is no longer billed, run kvbox volume rm ${shown(ref)} again`);
|
|
1706
|
+
}
|
|
1707
|
+
});
|
|
1708
|
+
}
|
|
1709
|
+
function volumeRef(box, name) {
|
|
1710
|
+
return parseRef(name, box.owner);
|
|
1711
|
+
}
|
|
1712
|
+
async function volumeDrivesOf(box, p) {
|
|
1713
|
+
const out = [];
|
|
1714
|
+
for (const name of box.volumes ?? []) {
|
|
1715
|
+
const ref = volumeRef(box, name);
|
|
1716
|
+
let meta;
|
|
1717
|
+
try {
|
|
1718
|
+
meta = await readVolume(ref, p);
|
|
1719
|
+
} catch (err) {
|
|
1720
|
+
if (err instanceof NotFoundError) throw new KvboxError(`box ${shown(box)} has volume ${name} attached, but the volume is gone from ${p.volumes}`);
|
|
1721
|
+
throw err;
|
|
1722
|
+
}
|
|
1723
|
+
out.push({ name, sizeGib: meta.sizeGib });
|
|
1724
|
+
}
|
|
1725
|
+
return out;
|
|
1726
|
+
}
|
|
1727
|
+
async function captureDrivesOf(box, p) {
|
|
1728
|
+
const drives = await volumeDrivesOf(box, p);
|
|
1729
|
+
const named = new Set(drives.map((d) => d.name));
|
|
1730
|
+
const dir = p.machine(box.owner, box.name).dir;
|
|
1731
|
+
for (const entry of (await readdir2(dir).catch(() => [])).sort()) {
|
|
1732
|
+
const m = /^volume-(.+)\.ext4$/.exec(entry);
|
|
1733
|
+
if (!m || named.has(m[1])) continue;
|
|
1734
|
+
const st = await lstat(`${dir}/${entry}`);
|
|
1735
|
+
if (!st.isFile()) continue;
|
|
1736
|
+
drives.push({ name: m[1], sizeGib: Math.round(st.size / 1024 ** 3) });
|
|
1737
|
+
}
|
|
1738
|
+
return drives;
|
|
1739
|
+
}
|
|
1740
|
+
function volumeSummaries(box, p) {
|
|
1741
|
+
if (!box.volumes?.length) return void 0;
|
|
1742
|
+
return box.volumes.map((name) => {
|
|
1743
|
+
let sizeGib = 0;
|
|
1744
|
+
try {
|
|
1745
|
+
sizeGib = Math.round(statSync(p.volume(box.owner, name).disk).size / 1024 ** 3);
|
|
1746
|
+
} catch {
|
|
1747
|
+
}
|
|
1748
|
+
return { name, sizeGib, mountPath: volumeMountPath(name) };
|
|
1749
|
+
});
|
|
1750
|
+
}
|
|
1751
|
+
async function placeVolumeDrives(box, p) {
|
|
1752
|
+
const m = p.machine(box.owner, box.name);
|
|
1753
|
+
const drives = await volumeDrivesOf(box, p);
|
|
1754
|
+
await removeVolumeDrives(m.dir, new Set(drives.map((d) => d.name)));
|
|
1755
|
+
for (const d of drives) {
|
|
1756
|
+
const link3 = m.volumeDrive(d.name);
|
|
1757
|
+
await rm(link3, { force: true });
|
|
1758
|
+
await symlink(p.volume(box.owner, d.name).disk, link3);
|
|
1759
|
+
}
|
|
1760
|
+
return drives;
|
|
1761
|
+
}
|
|
1762
|
+
async function removeVolumeDrives(boxDir, keep) {
|
|
1763
|
+
for (const entry of await readdir2(boxDir).catch(() => [])) {
|
|
1764
|
+
const m = /^volume-(.+)\.ext4$/.exec(entry);
|
|
1765
|
+
if (m && !keep.has(m[1])) await rm(`${boxDir}/${entry}`, { force: true });
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1768
|
+
async function placeholderDrives(boxDir, volumes) {
|
|
1769
|
+
for (const v of volumes) {
|
|
1770
|
+
const file = `${boxDir}/${volumeDriveRel(v.name)}`;
|
|
1771
|
+
await rm(file, { force: true });
|
|
1772
|
+
await writeFile3(file, "", { mode: 384 });
|
|
1773
|
+
await truncate(file, v.sizeGib * 1024 ** 3);
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
var volumeDriveId = (name) => `vol-${name}`;
|
|
1777
|
+
async function attachedBox(ref, p) {
|
|
1778
|
+
return (await attachments(ref.owner, p)).get(ref.name) ?? null;
|
|
1779
|
+
}
|
|
1780
|
+
|
|
1188
1781
|
// src/core/capacity.ts
|
|
1782
|
+
import { cpus, totalmem } from "node:os";
|
|
1189
1783
|
function hostResources() {
|
|
1190
1784
|
return { memMib: Math.floor(totalmem() / 1024 ** 2), cores: cpus().length };
|
|
1191
1785
|
}
|
|
@@ -1208,7 +1802,8 @@ async function capacity(p = paths()) {
|
|
|
1208
1802
|
hostCores: host.cores,
|
|
1209
1803
|
reservedMemMib: running.reduce((n, r) => n + r.memMib, 0),
|
|
1210
1804
|
reservedVcpu: running.reduce((n, r) => n + r.vcpu, 0),
|
|
1211
|
-
running: running.length
|
|
1805
|
+
running: running.length,
|
|
1806
|
+
disk: await diskCapacity(p)
|
|
1212
1807
|
};
|
|
1213
1808
|
}
|
|
1214
1809
|
function gb(mib) {
|
|
@@ -1242,147 +1837,9 @@ async function assertRoomFor(vcpu, memMib, force, p = paths()) {
|
|
|
1242
1837
|
if (reason !== void 0) throw new KvboxError(reason);
|
|
1243
1838
|
}
|
|
1244
1839
|
|
|
1245
|
-
// src/core/db.ts
|
|
1246
|
-
import { chmodSync, closeSync, mkdirSync, openSync } from "node:fs";
|
|
1247
|
-
import { dirname } from "node:path";
|
|
1248
|
-
import { DatabaseSync } from "node:sqlite";
|
|
1249
|
-
var MIGRATIONS = [
|
|
1250
|
-
`create table usage_events (
|
|
1251
|
-
id integer primary key,
|
|
1252
|
-
box_id text not null,
|
|
1253
|
-
owner text not null,
|
|
1254
|
-
name text not null,
|
|
1255
|
-
at text not null,
|
|
1256
|
-
state text not null,
|
|
1257
|
-
vcpu integer not null,
|
|
1258
|
-
mem_mib integer not null,
|
|
1259
|
-
disk_gib integer not null,
|
|
1260
|
-
by text not null
|
|
1261
|
-
);
|
|
1262
|
-
create index usage_events_box_at on usage_events (box_id, at);`,
|
|
1263
|
-
// The ledger's identity (#42): a control plane keys pulled rows by it, so a re-join is recognised
|
|
1264
|
-
// and a fresh ledger (KVBOX_HOME wiped) restarts its cursor instead of waiting for ids it already saw.
|
|
1265
|
-
`create table ledger (id text not null);
|
|
1266
|
-
insert into ledger (id) values (lower(hex(randomblob(16))));
|
|
1267
|
-
create index usage_events_at on usage_events (at);`
|
|
1268
|
-
];
|
|
1269
|
-
var handles = /* @__PURE__ */ new Map();
|
|
1270
|
-
function openDb(p = paths()) {
|
|
1271
|
-
const have = handles.get(p.db);
|
|
1272
|
-
if (have !== void 0) return have;
|
|
1273
|
-
mkdirSync(dirname(p.db), { recursive: true, mode: 448 });
|
|
1274
|
-
closeSync(openSync(p.db, "a", 384));
|
|
1275
|
-
chmodSync(p.db, 384);
|
|
1276
|
-
const db = new DatabaseSync(p.db);
|
|
1277
|
-
db.exec("pragma journal_mode = wal");
|
|
1278
|
-
db.exec("pragma busy_timeout = 5000");
|
|
1279
|
-
migrate(db);
|
|
1280
|
-
handles.set(p.db, db);
|
|
1281
|
-
return db;
|
|
1282
|
-
}
|
|
1283
|
-
function migrate(db) {
|
|
1284
|
-
db.exec("create table if not exists schema_version (version integer not null)");
|
|
1285
|
-
const row = db.prepare("select version from schema_version").get();
|
|
1286
|
-
let version = row?.version ?? 0;
|
|
1287
|
-
if (row === void 0) db.prepare("insert into schema_version (version) values (0)").run();
|
|
1288
|
-
while (version < MIGRATIONS.length) {
|
|
1289
|
-
db.exec("begin");
|
|
1290
|
-
try {
|
|
1291
|
-
db.exec(MIGRATIONS[version]);
|
|
1292
|
-
version += 1;
|
|
1293
|
-
db.prepare("update schema_version set version = ?").run(version);
|
|
1294
|
-
db.exec("commit");
|
|
1295
|
-
} catch (err) {
|
|
1296
|
-
db.exec("rollback");
|
|
1297
|
-
throw err;
|
|
1298
|
-
}
|
|
1299
|
-
}
|
|
1300
|
-
}
|
|
1301
|
-
var LIVE_STATES = ["running", "standby"];
|
|
1302
|
-
function fromRaw(r) {
|
|
1303
|
-
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 };
|
|
1304
|
-
}
|
|
1305
|
-
function lastEvent(boxId, db) {
|
|
1306
|
-
const raw = db.prepare("select * from usage_events where box_id = ? order by at desc, id desc limit 1").get(boxId);
|
|
1307
|
-
return raw === void 0 ? void 0 : fromRaw(raw);
|
|
1308
|
-
}
|
|
1309
|
-
function insertRaw(e, db) {
|
|
1310
|
-
db.prepare(
|
|
1311
|
-
"insert into usage_events (box_id, owner, name, at, state, vcpu, mem_mib, disk_gib, by) values (?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
|
1312
|
-
).run(e.boxId, e.owner, e.name, e.at, e.state, e.vcpu, e.memMib, e.diskGib, e.by);
|
|
1313
|
-
}
|
|
1314
|
-
function insertUsageEvent(e, p = paths()) {
|
|
1315
|
-
const db = openDb(p);
|
|
1316
|
-
if (e.state === "running" && e.by !== "resume") closeOpenRun(e.boxId, e.at, p);
|
|
1317
|
-
insertRaw(e, db);
|
|
1318
|
-
}
|
|
1319
|
-
function closeOpenRun(boxId, at, p = paths()) {
|
|
1320
|
-
const db = openDb(p);
|
|
1321
|
-
const last = lastEvent(boxId, db);
|
|
1322
|
-
if (last === void 0 || !LIVE_STATES.includes(last.state)) return false;
|
|
1323
|
-
insertRaw({ ...last, at, state: "stopped", by: "server" }, db);
|
|
1324
|
-
return true;
|
|
1325
|
-
}
|
|
1326
|
-
function closeRunCutByBoot(boxId, bootAt, now, p = paths()) {
|
|
1327
|
-
const last = lastEvent(boxId, openDb(p));
|
|
1328
|
-
return closeOpenRun(boxId, last !== void 0 && last.at < bootAt ? bootAt : now, p);
|
|
1329
|
-
}
|
|
1330
|
-
function usageEventsFor(boxId, since, p = paths()) {
|
|
1331
|
-
const rows = openDb(p).prepare("select * from usage_events where box_id = ? and at >= ? order by at, id").all(boxId, since);
|
|
1332
|
-
return rows.map(fromRaw);
|
|
1333
|
-
}
|
|
1334
|
-
var withId = (r) => ({ ...fromRaw(r), id: r.id });
|
|
1335
|
-
function ledgerId(p = paths()) {
|
|
1336
|
-
return openDb(p).prepare("select id from ledger").get().id;
|
|
1337
|
-
}
|
|
1338
|
-
function usageEventsAfter(after, limit, scope, p = paths()) {
|
|
1339
|
-
const db = openDb(p);
|
|
1340
|
-
const rows = scope === null ? db.prepare("select * from usage_events where id > ? order by id limit ?").all(after, limit) : typeof scope === "string" ? db.prepare("select * from usage_events where id > ? and owner = ? order by id limit ?").all(after, scope, limit) : db.prepare("select * from usage_events where id > ? and substr(owner, -length(?)) = ? order by id limit ?").all(after, `@${scope.realm}`, `@${scope.realm}`, limit);
|
|
1341
|
-
return rows.map(withId);
|
|
1342
|
-
}
|
|
1343
|
-
function usageEventsInScope(scope, window, p = paths()) {
|
|
1344
|
-
const rows = openDb(p).prepare(
|
|
1345
|
-
`select * from usage_events where at < ? and (at >= ? or id in (select max(id) from usage_events where at < ? group by box_id))
|
|
1346
|
-
order by at, id`
|
|
1347
|
-
).all(window.to, window.from, window.from);
|
|
1348
|
-
return rows.filter((r) => inScope(r.owner, scope)).map(withId);
|
|
1349
|
-
}
|
|
1350
|
-
|
|
1351
|
-
// src/core/locks.ts
|
|
1352
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
1353
|
-
var tails = /* @__PURE__ */ new Map();
|
|
1354
|
-
var held = new AsyncLocalStorage();
|
|
1355
|
-
function withBoxLock(ref, fn) {
|
|
1356
|
-
return withLock(refKey(ref), fn);
|
|
1357
|
-
}
|
|
1358
|
-
function withHostLock(name, fn) {
|
|
1359
|
-
return withLock(`host:${name}`, fn);
|
|
1360
|
-
}
|
|
1361
|
-
async function withLock(key, fn) {
|
|
1362
|
-
const mine = held.getStore();
|
|
1363
|
-
if (mine?.has(key)) return fn();
|
|
1364
|
-
const previous = tails.get(key);
|
|
1365
|
-
let release;
|
|
1366
|
-
const tail = new Promise((resolve) => release = resolve);
|
|
1367
|
-
tails.set(key, tail);
|
|
1368
|
-
try {
|
|
1369
|
-
await previous;
|
|
1370
|
-
return await held.run(/* @__PURE__ */ new Set([...mine ?? [], key]), fn);
|
|
1371
|
-
} finally {
|
|
1372
|
-
release();
|
|
1373
|
-
if (tails.get(key) === tail) tails.delete(key);
|
|
1374
|
-
}
|
|
1375
|
-
}
|
|
1376
|
-
function boxBusy(ref) {
|
|
1377
|
-
return tails.has(refKey(ref));
|
|
1378
|
-
}
|
|
1379
|
-
function locked(fn) {
|
|
1380
|
-
return (...args) => withBoxLock(args[0], () => fn(...args));
|
|
1381
|
-
}
|
|
1382
|
-
|
|
1383
1840
|
// src/core/snapshots.ts
|
|
1384
|
-
import { existsSync } from "node:fs";
|
|
1385
|
-
import { link, mkdir as
|
|
1841
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
1842
|
+
import { link, mkdir as mkdir4, readdir as readdir3, rename as rename3, rm as rm2, stat as stat2 } from "node:fs/promises";
|
|
1386
1843
|
|
|
1387
1844
|
// src/core/firecracker.ts
|
|
1388
1845
|
import { Agent, request as request2 } from "undici";
|
|
@@ -1417,6 +1874,10 @@ var FirecrackerClient = class {
|
|
|
1417
1874
|
overlayDrive(pathOnHost) {
|
|
1418
1875
|
return this.drive("overlay", pathOnHost, { root: false, readOnly: false });
|
|
1419
1876
|
}
|
|
1877
|
+
/** A volume (#52): /dev/vdc and up, in the order they are added; the guest mounts it by label. */
|
|
1878
|
+
volumeDrive(id, pathOnHost) {
|
|
1879
|
+
return this.drive(id, pathOnHost, { root: false, readOnly: false });
|
|
1880
|
+
}
|
|
1420
1881
|
drive(id, pathOnHost, opts) {
|
|
1421
1882
|
return this.call("PUT", `/drives/${id}`, {
|
|
1422
1883
|
drive_id: id,
|
|
@@ -1521,7 +1982,7 @@ async function listSnapshots(scope, p = paths()) {
|
|
|
1521
1982
|
}
|
|
1522
1983
|
async function usedBytes(dir) {
|
|
1523
1984
|
let total = 0;
|
|
1524
|
-
for (const entry of await
|
|
1985
|
+
for (const entry of await readdir3(dir)) {
|
|
1525
1986
|
total += (await stat2(`${dir}/${entry}`)).blocks * 512;
|
|
1526
1987
|
}
|
|
1527
1988
|
return total;
|
|
@@ -1544,18 +2005,20 @@ async function saveSnapshot(req, owner, p = paths()) {
|
|
|
1544
2005
|
async function snapshotBox(ref, req, owner, p) {
|
|
1545
2006
|
const box = await readBox(ref, p);
|
|
1546
2007
|
if (!vmAlive(box)) {
|
|
1547
|
-
if (
|
|
2008
|
+
if (existsSync2(p.machine(box.owner, box.name).hibernateVmstate)) {
|
|
1548
2009
|
throw new KvboxError(`box ${req.box} is hibernated; a snapshot freezes a running box (kvbox wake ${req.box} first)`);
|
|
1549
2010
|
}
|
|
1550
2011
|
throw new KvboxError(`box ${req.box} is not running; a snapshot freezes a running box (kvbox start ${req.box} first)`);
|
|
1551
2012
|
}
|
|
1552
2013
|
const s = p.snapshot(owner, req.name);
|
|
1553
|
-
if (
|
|
2014
|
+
if (existsSync2(s.dir)) throw new KvboxError(`snapshot ${req.name} already exists`);
|
|
1554
2015
|
const cfg = await loadConfig(p);
|
|
1555
|
-
await
|
|
2016
|
+
await mkdir4(s.dir, { recursive: true, mode: 448 });
|
|
1556
2017
|
try {
|
|
2018
|
+
const volumes = await captureDrivesOf(box, p);
|
|
1557
2019
|
await captureBox(box, s, cfg, p);
|
|
1558
2020
|
const meta = {
|
|
2021
|
+
...volumes.length > 0 ? { volumes } : {},
|
|
1559
2022
|
name: req.name,
|
|
1560
2023
|
owner,
|
|
1561
2024
|
source: refKey(box),
|
|
@@ -1568,7 +2031,7 @@ async function snapshotBox(ref, req, owner, p) {
|
|
|
1568
2031
|
await writeSnapshotMeta(meta, p);
|
|
1569
2032
|
return toSnapshot(meta);
|
|
1570
2033
|
} catch (err) {
|
|
1571
|
-
await
|
|
2034
|
+
await rm2(s.dir, { recursive: true, force: true });
|
|
1572
2035
|
throw err;
|
|
1573
2036
|
}
|
|
1574
2037
|
}
|
|
@@ -1578,7 +2041,7 @@ async function captureBox(box, to, cfg, p) {
|
|
|
1578
2041
|
let lineageTouched = false;
|
|
1579
2042
|
try {
|
|
1580
2043
|
const since = box.memSnapshots ?? 0;
|
|
1581
|
-
const mode = since === 0 ||
|
|
2044
|
+
const mode = since === 0 || existsSync2(m.memBase) ? "Diff" : "Full";
|
|
1582
2045
|
let failure2;
|
|
1583
2046
|
await fc.pause();
|
|
1584
2047
|
try {
|
|
@@ -1599,31 +2062,31 @@ async function captureBox(box, to, cfg, p) {
|
|
|
1599
2062
|
} else if (since > 0) {
|
|
1600
2063
|
await mergeOntoPrevious(m.memBase, to.mem, cfg.snapshotEditor ?? p.snapshotEditor);
|
|
1601
2064
|
}
|
|
1602
|
-
await
|
|
2065
|
+
await rm2(m.memBase, { force: true });
|
|
1603
2066
|
await link(to.mem, m.memBase);
|
|
1604
2067
|
} catch (err) {
|
|
1605
|
-
if (lineageTouched) await
|
|
2068
|
+
if (lineageTouched) await rm2(m.memBase, { force: true }).catch(() => void 0);
|
|
1606
2069
|
throw err;
|
|
1607
2070
|
} finally {
|
|
1608
2071
|
await fc.close();
|
|
1609
2072
|
}
|
|
1610
2073
|
}
|
|
1611
2074
|
async function mergeOntoPrevious(previous, diffFile, editor) {
|
|
1612
|
-
if (!
|
|
2075
|
+
if (!existsSync2(editor)) throw new KvboxError(`snapshot-editor missing at ${editor}; rerun install-server.sh`);
|
|
1613
2076
|
const merged = `${diffFile}.merged`;
|
|
1614
2077
|
await run(["cp", "--sparse=always", "--reflink=auto", previous, merged]);
|
|
1615
2078
|
await run([editor, "edit-memory", "rebase", "--memory-path", merged, "--diff-path", diffFile]);
|
|
1616
|
-
await
|
|
2079
|
+
await rename3(merged, diffFile);
|
|
1617
2080
|
}
|
|
1618
2081
|
async function deleteSnapshot(ref, p = paths()) {
|
|
1619
2082
|
const dir = p.snapshot(ref.owner, ref.name).dir;
|
|
1620
|
-
if (!
|
|
1621
|
-
await
|
|
2083
|
+
if (!existsSync2(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);
|
|
2084
|
+
await rm2(dir, { recursive: true, force: true });
|
|
1622
2085
|
}
|
|
1623
2086
|
|
|
1624
2087
|
// src/core/network.ts
|
|
1625
2088
|
import { randomInt } from "node:crypto";
|
|
1626
|
-
import { existsSync as
|
|
2089
|
+
import { existsSync as existsSync3 } from "node:fs";
|
|
1627
2090
|
import { fileURLToPath } from "node:url";
|
|
1628
2091
|
var TAP_PREFIX = "kv-";
|
|
1629
2092
|
var PRIVILEGED_SCRIPT = "/usr/local/lib/kvbox/net-setup.sh";
|
|
@@ -1633,15 +2096,15 @@ function tapName(box) {
|
|
|
1633
2096
|
function netSetupScript() {
|
|
1634
2097
|
const override = process.env["KVBOX_NET_SETUP"];
|
|
1635
2098
|
if (override) return override;
|
|
1636
|
-
if (
|
|
2099
|
+
if (existsSync3(PRIVILEGED_SCRIPT)) return PRIVILEGED_SCRIPT;
|
|
1637
2100
|
for (const rel of ["../scripts/net-setup.sh", "../../scripts/net-setup.sh"]) {
|
|
1638
2101
|
const candidate = fileURLToPath(new URL(rel, import.meta.url));
|
|
1639
|
-
if (
|
|
2102
|
+
if (existsSync3(candidate)) return candidate;
|
|
1640
2103
|
}
|
|
1641
2104
|
throw new KvboxError("net-setup.sh not found next to kvbox-server");
|
|
1642
2105
|
}
|
|
1643
2106
|
function bridgeExists(bridge) {
|
|
1644
|
-
return
|
|
2107
|
+
return existsSync3(`/sys/class/net/${bridge}`);
|
|
1645
2108
|
}
|
|
1646
2109
|
function netRun(cfg, args) {
|
|
1647
2110
|
return run([netSetupScript(), ...args], {
|
|
@@ -1772,7 +2235,7 @@ async function drawPorts(count, p) {
|
|
|
1772
2235
|
}
|
|
1773
2236
|
function diskStats(disk) {
|
|
1774
2237
|
try {
|
|
1775
|
-
const st =
|
|
2238
|
+
const st = statSync2(disk);
|
|
1776
2239
|
return { diskBytes: st.size, diskUsedBytes: st.blocks * 512 };
|
|
1777
2240
|
} catch {
|
|
1778
2241
|
return { diskBytes: 0, diskUsedBytes: 0 };
|
|
@@ -1780,7 +2243,7 @@ function diskStats(disk) {
|
|
|
1780
2243
|
}
|
|
1781
2244
|
function diskGibOf(meta, p) {
|
|
1782
2245
|
try {
|
|
1783
|
-
return Math.round(
|
|
2246
|
+
return Math.round(statSync2(p.machine(meta.owner, meta.name).overlay).size / 1024 ** 3);
|
|
1784
2247
|
} catch {
|
|
1785
2248
|
return 0;
|
|
1786
2249
|
}
|
|
@@ -1793,7 +2256,7 @@ function recordState(meta, state, by, p, at = (/* @__PURE__ */ new Date()).toISO
|
|
|
1793
2256
|
}
|
|
1794
2257
|
}
|
|
1795
2258
|
function isHibernated(meta, p) {
|
|
1796
|
-
return !vmAlive(meta) &&
|
|
2259
|
+
return !vmAlive(meta) && existsSync4(p.machine(meta.owner, meta.name).hibernateVmstate);
|
|
1797
2260
|
}
|
|
1798
2261
|
function statusOf(meta, p = paths()) {
|
|
1799
2262
|
if (vmAlive(meta)) return meta.paused ? "standby" : "running";
|
|
@@ -1827,7 +2290,8 @@ function toMachine(meta, p = paths()) {
|
|
|
1827
2290
|
status: statusOf(meta, p),
|
|
1828
2291
|
...meta.sshPort === void 0 ? {} : { sshPort: meta.sshPort },
|
|
1829
2292
|
...meta.ports?.length ? { ports: meta.ports.map((f) => ({ ...f })) } : {},
|
|
1830
|
-
...meta.autoHibernateSec ? { autoHibernateSec: meta.autoHibernateSec } : {}
|
|
2293
|
+
...meta.autoHibernateSec ? { autoHibernateSec: meta.autoHibernateSec } : {},
|
|
2294
|
+
...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {}
|
|
1831
2295
|
};
|
|
1832
2296
|
}
|
|
1833
2297
|
function autoHibernateFor(req, cfg) {
|
|
@@ -1899,7 +2363,7 @@ async function currentBase(cfg, p) {
|
|
|
1899
2363
|
}
|
|
1900
2364
|
function baseFileFor(meta, p) {
|
|
1901
2365
|
const file = p.baseImage(meta.base);
|
|
1902
|
-
if (!
|
|
2366
|
+
if (!existsSync4(file)) throw new KvboxError(`box ${meta.name} runs on base image ${meta.base}, which is gone from ${p.assets}`);
|
|
1903
2367
|
return file;
|
|
1904
2368
|
}
|
|
1905
2369
|
var overlayCapable = /* @__PURE__ */ new Map();
|
|
@@ -1913,8 +2377,8 @@ async function assertOverlayCapable(baseFile, version) {
|
|
|
1913
2377
|
if (!ok) throw new KvboxError(`base image ${version} is not a kvbox base image (no /sbin/overlay-init); rerun install-server.sh`);
|
|
1914
2378
|
}
|
|
1915
2379
|
async function createOverlay(file, gib) {
|
|
1916
|
-
await
|
|
1917
|
-
await
|
|
2380
|
+
await writeFile4(file, "", { mode: 384 });
|
|
2381
|
+
await truncate2(file, gib * 1024 ** 3);
|
|
1918
2382
|
await run(["mkfs.ext4", "-q", "-F", "-m", "0", "-L", "kvbox-box", "-E", "lazy_itable_init=1,lazy_journal_init=1", file]);
|
|
1919
2383
|
}
|
|
1920
2384
|
async function waitFor(pred, timeoutMs, stepMs = 50) {
|
|
@@ -1934,8 +2398,8 @@ async function tailOf(file, lines = 5) {
|
|
|
1934
2398
|
}
|
|
1935
2399
|
async function spawnFirecracker(ref, cfg, p) {
|
|
1936
2400
|
const m = p.machine(ref.owner, ref.name);
|
|
1937
|
-
await
|
|
1938
|
-
await
|
|
2401
|
+
await rm3(m.sock, { force: true });
|
|
2402
|
+
await rm3(m.vsock, { force: true });
|
|
1939
2403
|
const logFd = openSync2(m.log, "a");
|
|
1940
2404
|
let child;
|
|
1941
2405
|
try {
|
|
@@ -1950,7 +2414,7 @@ async function spawnFirecracker(ref, cfg, p) {
|
|
|
1950
2414
|
child.unref();
|
|
1951
2415
|
const pid = child.pid;
|
|
1952
2416
|
if (pid === void 0) throw new KvboxError("could not start firecracker");
|
|
1953
|
-
if (!await waitFor(() =>
|
|
2417
|
+
if (!await waitFor(() => existsSync4(m.sock), 3e3)) {
|
|
1954
2418
|
killQuietly(pid);
|
|
1955
2419
|
throw new KvboxError(`firecracker did not open its API socket; last log lines:
|
|
1956
2420
|
${await tailOf(m.log)}`);
|
|
@@ -1966,6 +2430,7 @@ function killQuietly(pid) {
|
|
|
1966
2430
|
async function launch(spec, tap, cfg, pubkeyB64, p) {
|
|
1967
2431
|
const m = p.machine(spec.owner, spec.name);
|
|
1968
2432
|
const baseFile = baseFileFor(spec, p);
|
|
2433
|
+
const volumes = await placeVolumeDrives(spec, p);
|
|
1969
2434
|
const pid = await spawnFirecracker(spec, cfg, p);
|
|
1970
2435
|
try {
|
|
1971
2436
|
const fc = new FirecrackerClient(m.sock);
|
|
@@ -1973,6 +2438,7 @@ async function launch(spec, tap, cfg, pubkeyB64, p) {
|
|
|
1973
2438
|
await fc.bootSource(cfg.kernel, bootArgs(spec.name, spec.ip, cfg, pubkeyB64));
|
|
1974
2439
|
await fc.rootDrive(baseFile);
|
|
1975
2440
|
await fc.overlayDrive(OVERLAY_REL);
|
|
2441
|
+
for (const v of volumes) await fc.volumeDrive(volumeDriveId(v.name), volumeDriveRel(v.name));
|
|
1976
2442
|
await fc.machineConfig(spec.vcpu, spec.memMib);
|
|
1977
2443
|
await fc.networkInterface("eth0", tap, spec.mac);
|
|
1978
2444
|
await fc.vsock(GUEST_CID, m.vsock);
|
|
@@ -2021,7 +2487,7 @@ async function readHostPubkey(p) {
|
|
|
2021
2487
|
}
|
|
2022
2488
|
function assertAssets(cfg) {
|
|
2023
2489
|
for (const [what, file] of [["kernel", cfg.kernel], ["base image", cfg.rootfs], ["firecracker", cfg.firecracker]]) {
|
|
2024
|
-
if (!
|
|
2490
|
+
if (!existsSync4(file)) throw new KvboxError(`${what} missing at ${file}; run install-server.sh`);
|
|
2025
2491
|
}
|
|
2026
2492
|
}
|
|
2027
2493
|
async function createMachine(req, owner, p = paths()) {
|
|
@@ -2054,7 +2520,7 @@ async function bootInto(box, prepare, origin, cfg, p) {
|
|
|
2054
2520
|
const keysB64 = authorizedKeysB64(await readHostPubkey(p), box.sshKeys ?? []);
|
|
2055
2521
|
const m = p.machine(owner, name);
|
|
2056
2522
|
await ensureHostNetwork(cfg);
|
|
2057
|
-
await
|
|
2523
|
+
await mkdir5(m.dir, { recursive: true, mode: 448 });
|
|
2058
2524
|
let tapCreated = false;
|
|
2059
2525
|
let pid;
|
|
2060
2526
|
let sshPort;
|
|
@@ -2076,7 +2542,7 @@ async function bootInto(box, prepare, origin, cfg, p) {
|
|
|
2076
2542
|
if (pid !== void 0) killQuietly(pid);
|
|
2077
2543
|
await closePorts({ id, ip, sshPort }, cfg);
|
|
2078
2544
|
if (tapCreated) await deleteTap(id, cfg).catch(() => void 0);
|
|
2079
|
-
await
|
|
2545
|
+
await rm3(m.dir, { recursive: true, force: true });
|
|
2080
2546
|
throw err;
|
|
2081
2547
|
} finally {
|
|
2082
2548
|
drawn?.release();
|
|
@@ -2100,7 +2566,7 @@ async function restoreMachine(fromText, owner, req, cfg, p) {
|
|
|
2100
2566
|
throw new KvboxError(`--size cannot be combined with --from: a restored box has the snapshot's size (${shown(from)}: ${snap.vcpu} vCPU, ${snap.memMib} MiB)`);
|
|
2101
2567
|
}
|
|
2102
2568
|
assertAssets(cfg);
|
|
2103
|
-
if (!
|
|
2569
|
+
if (!existsSync4(p.baseImage(snap.base))) {
|
|
2104
2570
|
throw new KvboxError(`snapshot ${shown(from)} stacks on base image ${snap.base}, which is gone from ${p.assets}`);
|
|
2105
2571
|
}
|
|
2106
2572
|
await assertRoomFor(snap.vcpu, snap.memMib, req.force ?? false, p);
|
|
@@ -2116,7 +2582,8 @@ async function restoreMachine(fromText, owner, req, cfg, p) {
|
|
|
2116
2582
|
async (m) => {
|
|
2117
2583
|
await run(["cp", "--sparse=always", "--reflink=auto", s.overlay, m.overlay]);
|
|
2118
2584
|
await link2(s.mem, m.memBase);
|
|
2119
|
-
|
|
2585
|
+
await placeholderDrives(m.dir, snap.volumes ?? []);
|
|
2586
|
+
return { vmstate: s.vmstate, mem: s.mem, label: shown(from), volumes: snap.volumes };
|
|
2120
2587
|
},
|
|
2121
2588
|
{ source: `snapshot:${refKey(from)}`, autoHibernateSec: autoHibernateFor(req, cfg) },
|
|
2122
2589
|
cfg,
|
|
@@ -2127,7 +2594,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
|
|
|
2127
2594
|
const { id, ip, owner, name } = box;
|
|
2128
2595
|
const m = p.machine(owner, name);
|
|
2129
2596
|
await ensureHostNetwork(cfg);
|
|
2130
|
-
await
|
|
2597
|
+
await mkdir5(m.dir, { recursive: true, mode: 448 });
|
|
2131
2598
|
let tapCreated = false;
|
|
2132
2599
|
let pid;
|
|
2133
2600
|
let sshPort;
|
|
@@ -2147,6 +2614,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
|
|
|
2147
2614
|
});
|
|
2148
2615
|
const stale = await pushAuthorizedKeys(box, m.vsock, p);
|
|
2149
2616
|
if (stale && keysOrFail) throw new KvboxError(`${keysOrFail}: ${stale}`);
|
|
2617
|
+
if (image.volumes?.length) await dropGuestVolumes(box, m.vsock);
|
|
2150
2618
|
await attachTap(id, cfg);
|
|
2151
2619
|
await openPorts(spec, cfg);
|
|
2152
2620
|
const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin, memSnapshots: 1, sshKeysStale: stale ? true : void 0 };
|
|
@@ -2157,7 +2625,7 @@ async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
|
|
|
2157
2625
|
if (pid !== void 0) killQuietly(pid);
|
|
2158
2626
|
await closePorts({ id, ip, sshPort }, cfg);
|
|
2159
2627
|
if (tapCreated) await deleteTap(id, cfg).catch(() => void 0);
|
|
2160
|
-
await
|
|
2628
|
+
await rm3(m.dir, { recursive: true, force: true });
|
|
2161
2629
|
throw err;
|
|
2162
2630
|
} finally {
|
|
2163
2631
|
drawn?.release();
|
|
@@ -2178,7 +2646,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
|
|
|
2178
2646
|
}
|
|
2179
2647
|
if (!isSizeName(req.size)) throw new KvboxError(`unknown size "${req.size}"; use one of ${Object.keys(SIZES).join(", ")}`);
|
|
2180
2648
|
const preset = SIZES[req.size];
|
|
2181
|
-
const diskGib = Math.round(
|
|
2649
|
+
const diskGib = Math.round(statSync2(srcDisk).size / 1024 ** 3);
|
|
2182
2650
|
if (preset.diskGib < diskGib) throw new KvboxError(`box ${shown(ref)} has a ${diskGib} GB disk and a disk cannot shrink; size ${req.size} has ${preset.diskGib} GB`);
|
|
2183
2651
|
shape = { vcpu: preset.vcpu, memMib: preset.memMib };
|
|
2184
2652
|
growTo = preset.diskGib > diskGib ? preset.diskGib : void 0;
|
|
@@ -2206,11 +2674,13 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
|
|
|
2206
2674
|
p
|
|
2207
2675
|
);
|
|
2208
2676
|
}
|
|
2677
|
+
const srcVolumes = await captureDrivesOf(src, p);
|
|
2209
2678
|
const machine = await restoreInto(
|
|
2210
2679
|
box,
|
|
2211
2680
|
async (m) => {
|
|
2212
2681
|
await captureBox(src, { vmstate: m.forkVmstate, mem: m.memBase, overlay: m.overlay }, cfg, p);
|
|
2213
|
-
|
|
2682
|
+
await placeholderDrives(m.dir, srcVolumes);
|
|
2683
|
+
return { vmstate: m.forkVmstate, mem: m.memBase, label: `box ${shown(ref)}`, volumes: srcVolumes };
|
|
2214
2684
|
},
|
|
2215
2685
|
origin,
|
|
2216
2686
|
cfg,
|
|
@@ -2219,7 +2689,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
|
|
|
2219
2689
|
// another slug. Such a fork is discarded rather than kept stale; a cold fork boots with the new line.
|
|
2220
2690
|
owner === src.owner ? void 0 : `box ${shown(ref)} was not forked into ${owner}: the copy would still let ${src.owner} in (stop the box and fork it cold, which boots with ${owner}'s keys)`
|
|
2221
2691
|
);
|
|
2222
|
-
await
|
|
2692
|
+
await rm3(p.machine(owner, name).forkVmstate, { force: true });
|
|
2223
2693
|
return machine;
|
|
2224
2694
|
});
|
|
2225
2695
|
var AGENT_REPLY_MS = 2e4;
|
|
@@ -2254,6 +2724,14 @@ async function pushAuthorizedKeys(box, vsock, p) {
|
|
|
2254
2724
|
return why;
|
|
2255
2725
|
}
|
|
2256
2726
|
}
|
|
2727
|
+
async function dropGuestVolumes(box, vsock) {
|
|
2728
|
+
try {
|
|
2729
|
+
await dropVolumes(vsock, AGENT_REPLY_MS);
|
|
2730
|
+
} catch (err) {
|
|
2731
|
+
const why = isUnknownOp(err) ? `its image predates base v0.9.0, whose kvbox-agent can unmount them (kvbox vm update ${shown(box)} moves it onto the current base)` : err.message;
|
|
2732
|
+
console.error(`warning: box ${shown(box)} keeps the volume mounts it was frozen with, over empty disks now: ${why}`);
|
|
2733
|
+
}
|
|
2734
|
+
}
|
|
2257
2735
|
async function resumeVm(sock) {
|
|
2258
2736
|
const fc = new FirecrackerClient(sock);
|
|
2259
2737
|
try {
|
|
@@ -2288,8 +2766,8 @@ async function cleanupProcess(meta, cfg, p) {
|
|
|
2288
2766
|
await closePorts(meta, cfg);
|
|
2289
2767
|
await deleteTap(meta.id, cfg);
|
|
2290
2768
|
const m = p.machine(meta.owner, meta.name);
|
|
2291
|
-
await
|
|
2292
|
-
await
|
|
2769
|
+
await rm3(m.sock, { force: true });
|
|
2770
|
+
await rm3(m.vsock, { force: true });
|
|
2293
2771
|
}
|
|
2294
2772
|
var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
|
|
2295
2773
|
const meta = await readMeta(ref, p);
|
|
@@ -2297,8 +2775,8 @@ var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
|
|
|
2297
2775
|
const m = p.machine(ref.owner, ref.name);
|
|
2298
2776
|
if (!vmAlive(meta) && !isHibernated(meta, p)) throw new KvboxError(`box ${shown(ref)} is already stopped`);
|
|
2299
2777
|
await shutdown(meta, cfg, p, 1e4);
|
|
2300
|
-
await
|
|
2301
|
-
await
|
|
2778
|
+
await rm3(m.hibernateDir, { recursive: true, force: true });
|
|
2779
|
+
await rm3(m.memBase, { force: true });
|
|
2302
2780
|
const stopped = { ...meta, pid: null, memSnapshots: void 0, paused: void 0 };
|
|
2303
2781
|
await writeMachineMeta(stopped, p);
|
|
2304
2782
|
recordState(stopped, "stopped", "stop", p);
|
|
@@ -2416,15 +2894,15 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
|
|
|
2416
2894
|
if (status === "hibernated") throw new KvboxError(`${stateMessage(ref, status)} already`);
|
|
2417
2895
|
if (status === "stopped") throw new KvboxError(`${stateMessage(ref, status)}; only a running box can be hibernated (there is no memory to keep)`);
|
|
2418
2896
|
const m = p.machine(ref.owner, ref.name);
|
|
2419
|
-
await
|
|
2420
|
-
await
|
|
2897
|
+
await rm3(m.hibernateDir, { recursive: true, force: true });
|
|
2898
|
+
await mkdir5(m.hibernateDir, { recursive: true, mode: 448 });
|
|
2421
2899
|
const fc = new FirecrackerClient(m.sock);
|
|
2422
2900
|
try {
|
|
2423
2901
|
try {
|
|
2424
2902
|
await fc.pause();
|
|
2425
2903
|
await fc.snapshotCreate(m.hibernateVmstate, m.hibernateMem, "Full");
|
|
2426
2904
|
} catch (err) {
|
|
2427
|
-
await
|
|
2905
|
+
await rm3(m.hibernateDir, { recursive: true, force: true });
|
|
2428
2906
|
if (!meta.paused) await fc.resume().catch(() => void 0);
|
|
2429
2907
|
throw err;
|
|
2430
2908
|
}
|
|
@@ -2435,7 +2913,7 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
|
|
|
2435
2913
|
await waitFor(() => !pidAlive(meta.pid), 5e3, 50);
|
|
2436
2914
|
await cleanupProcess(meta, cfg, p);
|
|
2437
2915
|
await run(["fallocate", "--dig-holes", m.hibernateMem]);
|
|
2438
|
-
await
|
|
2916
|
+
await rm3(m.memBase, { force: true });
|
|
2439
2917
|
const hibernated = { ...meta, pid: null, memSnapshots: void 0, paused: void 0 };
|
|
2440
2918
|
await writeMachineMeta(hibernated, p);
|
|
2441
2919
|
recordState(hibernated, "hibernated", by, p);
|
|
@@ -2448,7 +2926,7 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths()) {
|
|
|
2448
2926
|
if (status === "running" || status === "standby") throw new KvboxError(`${stateMessage(ref, status)}, not hibernated`);
|
|
2449
2927
|
if (status === "stopped") throw new KvboxError(`${stateMessage(ref, status)}, not hibernated; kvbox start ${shown(ref)} boots it`);
|
|
2450
2928
|
assertAssets(cfg);
|
|
2451
|
-
if (!
|
|
2929
|
+
if (!existsSync4(p.baseImage(meta.base))) {
|
|
2452
2930
|
throw new KvboxError(`box ${shown(ref)} stacks on base image ${meta.base}, which is gone from ${p.assets}`);
|
|
2453
2931
|
}
|
|
2454
2932
|
const m = p.machine(ref.owner, ref.name);
|
|
@@ -2473,9 +2951,9 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths()) {
|
|
|
2473
2951
|
await deleteTap(meta.id, cfg).catch(() => void 0);
|
|
2474
2952
|
throw err;
|
|
2475
2953
|
}
|
|
2476
|
-
await
|
|
2954
|
+
await rm3(m.memBase, { force: true });
|
|
2477
2955
|
await link2(m.hibernateMem, m.memBase);
|
|
2478
|
-
await
|
|
2956
|
+
await rm3(m.hibernateDir, { recursive: true, force: true });
|
|
2479
2957
|
const running = { ...meta, pid, bootId: currentBootId(), memSnapshots: 1, paused: void 0, sshKeysStale: stale ? true : void 0 };
|
|
2480
2958
|
await writeMachineMeta(running, p);
|
|
2481
2959
|
recordState(running, "running", "wake", p);
|
|
@@ -2485,7 +2963,7 @@ async function applyAtNextBoot(meta, changes, by, cfg, p, whileStopped) {
|
|
|
2485
2963
|
const wasRunning = vmAlive(meta);
|
|
2486
2964
|
if (wasRunning) {
|
|
2487
2965
|
await shutdown(meta, cfg, p, 1e4);
|
|
2488
|
-
await
|
|
2966
|
+
await rm3(p.machine(meta.owner, meta.name).memBase, { force: true });
|
|
2489
2967
|
}
|
|
2490
2968
|
const updated = { ...meta, ...changes, pid: null, memSnapshots: void 0, paused: void 0 };
|
|
2491
2969
|
await writeMachineMeta(updated, p);
|
|
@@ -2513,7 +2991,7 @@ var rescaleMachine = locked(async function rescaleMachine2(ref, req, p = paths()
|
|
|
2513
2991
|
const cfg = await loadConfig(p);
|
|
2514
2992
|
assertNotHibernated(meta, p);
|
|
2515
2993
|
const disk = p.machine(ref.owner, ref.name).overlay;
|
|
2516
|
-
const currentDiskGib = Math.round(
|
|
2994
|
+
const currentDiskGib = Math.round(statSync2(disk).size / 1024 ** 3);
|
|
2517
2995
|
const preset = req.size !== void 0 && isSizeName(req.size) ? SIZES[req.size] : void 0;
|
|
2518
2996
|
const target = {
|
|
2519
2997
|
vcpu: req.vcpu ?? preset?.vcpu ?? meta.vcpu,
|
|
@@ -2530,6 +3008,30 @@ var rescaleMachine = locked(async function rescaleMachine2(ref, req, p = paths()
|
|
|
2530
3008
|
if (Object.keys(changes).length === 0 && growTo === void 0) return toMachine(meta, p);
|
|
2531
3009
|
return applyAtNextBoot(meta, changes, "rescale", cfg, p, growTo === void 0 ? void 0 : () => growDisk(disk, growTo));
|
|
2532
3010
|
});
|
|
3011
|
+
var attachVolume = locked(async function attachVolume2(ref, volume, p = paths()) {
|
|
3012
|
+
const cfg = await loadConfig(p);
|
|
3013
|
+
const claimed = await withHostLock("volumes", async () => {
|
|
3014
|
+
const meta = await readMeta(ref, p);
|
|
3015
|
+
if (volume.owner !== meta.owner) throw new KvboxError(`volume ${shown(volume)} is ${volume.owner}'s; a box only takes its own owner's volumes`);
|
|
3016
|
+
await readVolume(volume, p);
|
|
3017
|
+
const holder = await attachedBox(volume, p);
|
|
3018
|
+
if (holder === meta.name) throw new KvboxError(`volume ${shown(volume)} is already attached to box ${shown(ref)}`);
|
|
3019
|
+
if (holder !== null) throw new KvboxError(`volume ${shown(volume)} is attached to box ${holder}; a volume attaches to one box at a time (kvbox volume detach ${shown(volume)} first)`);
|
|
3020
|
+
assertNotHibernated(meta, p);
|
|
3021
|
+
const updated = { ...meta, volumes: [...meta.volumes ?? [], volume.name] };
|
|
3022
|
+
await writeMachineMeta(updated, p);
|
|
3023
|
+
return updated;
|
|
3024
|
+
});
|
|
3025
|
+
return applyAtNextBoot(claimed, {}, "attach", cfg, p);
|
|
3026
|
+
});
|
|
3027
|
+
var detachVolume = locked(async function detachVolume2(ref, volume, p = paths()) {
|
|
3028
|
+
const meta = await readMeta(ref, p);
|
|
3029
|
+
const cfg = await loadConfig(p);
|
|
3030
|
+
if (!meta.volumes?.includes(volume.name) || volume.owner !== meta.owner) throw new KvboxError(`volume ${shown(volume)} is not attached to box ${shown(ref)}`);
|
|
3031
|
+
assertNotHibernated(meta, p);
|
|
3032
|
+
const kept = meta.volumes.filter((v) => v !== volume.name);
|
|
3033
|
+
return applyAtNextBoot(meta, { volumes: kept.length > 0 ? kept : void 0 }, "detach", cfg, p, () => rm3(p.machine(ref.owner, ref.name).volumeDrive(volume.name), { force: true }));
|
|
3034
|
+
});
|
|
2533
3035
|
var setMachine = locked(async function setMachine2(ref, req, p = paths()) {
|
|
2534
3036
|
const meta = await readMeta(ref, p);
|
|
2535
3037
|
const next = { ...meta };
|
|
@@ -2590,7 +3092,7 @@ var removePorts = locked(async function removePorts2(ref, req, p = paths()) {
|
|
|
2590
3092
|
return toMachine(next, p);
|
|
2591
3093
|
});
|
|
2592
3094
|
async function growDisk(file, gib) {
|
|
2593
|
-
await
|
|
3095
|
+
await truncate2(file, gib * 1024 ** 3);
|
|
2594
3096
|
await run(["e2fsck", "-f", "-p", file], { okExitCodes: [1] });
|
|
2595
3097
|
await run(["resize2fs", file]);
|
|
2596
3098
|
}
|
|
@@ -2607,7 +3109,7 @@ var destroyMachine = locked(async function destroyMachine2(ref, p = paths()) {
|
|
|
2607
3109
|
const cfg = await loadConfig(p);
|
|
2608
3110
|
await shutdown(meta, cfg, p, 2e3);
|
|
2609
3111
|
recordState(meta, "stopped", "rm", p);
|
|
2610
|
-
await
|
|
3112
|
+
await rm3(p.machine(ref.owner, ref.name).dir, { recursive: true, force: true });
|
|
2611
3113
|
});
|
|
2612
3114
|
var RECOVERY_CONCURRENCY = 2;
|
|
2613
3115
|
async function settleDeadBoxes(p = paths()) {
|
|
@@ -2622,7 +3124,7 @@ async function settleDeadBoxes(p = paths()) {
|
|
|
2622
3124
|
} catch (err) {
|
|
2623
3125
|
console.error(`warning: usage ledger: ${err.message}`);
|
|
2624
3126
|
}
|
|
2625
|
-
await
|
|
3127
|
+
await rm3(p.machine(meta.owner, meta.name).memBase, { force: true });
|
|
2626
3128
|
if (meta.paused) {
|
|
2627
3129
|
await writeMachineMeta({ ...meta, pid: null, bootId: void 0, memSnapshots: void 0, paused: void 0 }, p);
|
|
2628
3130
|
leftStopped.push(refKey(meta));
|
|
@@ -2671,7 +3173,7 @@ async function bootRecovered(settled, p = paths()) {
|
|
|
2671
3173
|
}
|
|
2672
3174
|
|
|
2673
3175
|
// src/core/relay.ts
|
|
2674
|
-
import { chmod as chmod3, mkdir as
|
|
3176
|
+
import { chmod as chmod3, mkdir as mkdir6, rm as rm4, writeFile as writeFile5 } from "node:fs/promises";
|
|
2675
3177
|
|
|
2676
3178
|
// ../shared/src/relay.ts
|
|
2677
3179
|
import { z as z5 } from "zod";
|
|
@@ -2735,8 +3237,8 @@ async function useRelay(joinString, p = paths()) {
|
|
|
2735
3237
|
`${cfg.controlPlane.name} reaches this host at ${cfg.relay.publicIp}, not ${join2.publicIp}; run kvbox server leave first, then join again`
|
|
2736
3238
|
);
|
|
2737
3239
|
}
|
|
2738
|
-
await
|
|
2739
|
-
await
|
|
3240
|
+
await mkdir6(p.relay, { recursive: true, mode: 448 });
|
|
3241
|
+
await writeFile5(p.relayConf, relayConf(join2), { mode: 384 });
|
|
2740
3242
|
await chmod3(p.relayConf, 384);
|
|
2741
3243
|
await netSetup(cfg, ["relay", "up", p.relayConf, String(cfg.controlPlane?.port ?? DEFAULT_HTTPS_PORT)]);
|
|
2742
3244
|
const relay = { name: join2.name, publicIp: join2.publicIp, tunnelIp: join2.tunnelIp, endpoint: join2.relay };
|
|
@@ -2751,7 +3253,7 @@ async function dropRelay(p = paths()) {
|
|
|
2751
3253
|
throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox server leave first`);
|
|
2752
3254
|
}
|
|
2753
3255
|
await netSetup(cfg, ["relay", "down"]);
|
|
2754
|
-
await
|
|
3256
|
+
await rm4(p.relayConf, { force: true });
|
|
2755
3257
|
const { relay: _gone, ...rest } = cfg;
|
|
2756
3258
|
await saveConfig(rest, p);
|
|
2757
3259
|
return relay;
|
|
@@ -2906,12 +3408,12 @@ function startRelayWatch(opts = {}) {
|
|
|
2906
3408
|
}
|
|
2907
3409
|
|
|
2908
3410
|
// src/listen.ts
|
|
2909
|
-
import { readFile as readFile7, rm as
|
|
3411
|
+
import { readFile as readFile7, rm as rm5, writeFile as writeFile6 } from "node:fs/promises";
|
|
2910
3412
|
import { createServer as createHttpsServer } from "node:https";
|
|
2911
3413
|
import { createAdaptorServer } from "@hono/node-server";
|
|
2912
3414
|
|
|
2913
3415
|
// src/app.ts
|
|
2914
|
-
import { Hono as
|
|
3416
|
+
import { Hono as Hono8 } from "hono";
|
|
2915
3417
|
|
|
2916
3418
|
// ../shared/src/version.ts
|
|
2917
3419
|
import { createRequire } from "node:module";
|
|
@@ -2926,7 +3428,7 @@ function versionOf(srcFileUrl, injected) {
|
|
|
2926
3428
|
}
|
|
2927
3429
|
|
|
2928
3430
|
// src/version.ts
|
|
2929
|
-
var VERSION = versionOf(import.meta.url, true ? "0.5.
|
|
3431
|
+
var VERSION = versionOf(import.meta.url, true ? "0.5.23" : void 0);
|
|
2930
3432
|
|
|
2931
3433
|
// src/caller.ts
|
|
2932
3434
|
import { createHash as createHash2, timingSafeEqual } from "node:crypto";
|
|
@@ -2967,8 +3469,8 @@ function resolveCaller(opts = {}) {
|
|
|
2967
3469
|
const user = c.req.header(OWNER_HEADER);
|
|
2968
3470
|
if (user === void 0) {
|
|
2969
3471
|
const path = c.req.path.replace(/\/$/, "");
|
|
2970
|
-
const realmListing = c.req.method === "GET" && (path === "/machines" || path === "/snapshots");
|
|
2971
|
-
if (!realmListing && /^\/(machines|snapshots)(\/|$)/.test(c.req.path)) {
|
|
3472
|
+
const realmListing = c.req.method === "GET" && (path === "/machines" || path === "/snapshots" || path === "/volumes");
|
|
3473
|
+
if (!realmListing && /^\/(machines|snapshots|volumes)(\/|$)/.test(c.req.path)) {
|
|
2972
3474
|
return c.json({ error: "X-Kvbox-Owner header required" }, 400);
|
|
2973
3475
|
}
|
|
2974
3476
|
c.set("owner", "");
|
|
@@ -3283,7 +3785,8 @@ async function usageReport(scope, window, p = paths()) {
|
|
|
3283
3785
|
const cfg = await loadConfig(p);
|
|
3284
3786
|
const live = new Map((await listMachines(scope, p)).map((m) => [m.id, m.status]));
|
|
3285
3787
|
const boxes = groupUsage(usageEventsInScope(scope, window, p), window, cfg.pricing, live);
|
|
3286
|
-
|
|
3788
|
+
const volumes = groupVolumeUsage(volumeEventsInScope(scope, window, p), window, cfg.pricing);
|
|
3789
|
+
return { window, boxes, volumes, totals: reportTotals(boxes, volumes, cfg.pricing) };
|
|
3287
3790
|
}
|
|
3288
3791
|
|
|
3289
3792
|
// src/routes/machines.ts
|
|
@@ -3403,6 +3906,13 @@ function usageRoutes(opts = {}) {
|
|
|
3403
3906
|
const events = usageEventsAfter(after, limit, scope);
|
|
3404
3907
|
return c.json({ ledger: ledgerId(), events, next: events.length === 0 ? after : events[events.length - 1].id });
|
|
3405
3908
|
});
|
|
3909
|
+
r.get("/volume-events", async (c) => {
|
|
3910
|
+
const after = whole(c.req.query("after") ?? "0", "after");
|
|
3911
|
+
const limit = Math.min(whole(c.req.query("limit") ?? String(PULL_LIMIT), "limit") || PULL_LIMIT, PULL_LIMIT);
|
|
3912
|
+
const scope = opts.controlPlane === void 0 ? null : c.get("listScope");
|
|
3913
|
+
const events = volumeEventsAfter(after, limit, scope);
|
|
3914
|
+
return c.json({ ledger: ledgerId(), events, next: events.length === 0 ? after : events[events.length - 1].id });
|
|
3915
|
+
});
|
|
3406
3916
|
return r;
|
|
3407
3917
|
}
|
|
3408
3918
|
function whole(value, name) {
|
|
@@ -3411,9 +3921,36 @@ function whole(value, name) {
|
|
|
3411
3921
|
return n;
|
|
3412
3922
|
}
|
|
3413
3923
|
|
|
3924
|
+
// src/routes/volumes.ts
|
|
3925
|
+
import { Hono as Hono7 } from "hono";
|
|
3926
|
+
function volumeRoutes() {
|
|
3927
|
+
const r = new Hono7();
|
|
3928
|
+
r.get("/", async (c) => c.json(await listVolumes(c.get("listScope"))));
|
|
3929
|
+
r.post("/", async (c) => {
|
|
3930
|
+
const body = CreateVolumeRequest.parse(await c.req.json().catch(() => ({})));
|
|
3931
|
+
return c.json(await createVolume(body, c.get("owner")), 201);
|
|
3932
|
+
});
|
|
3933
|
+
r.get("/:name", async (c) => c.json(await getVolume(parseRef(c.req.param("name"), c.get("owner")))));
|
|
3934
|
+
r.delete("/:name", async (c) => {
|
|
3935
|
+
await deleteVolume(parseRef(c.req.param("name"), c.get("owner")));
|
|
3936
|
+
return c.body(null, 204);
|
|
3937
|
+
});
|
|
3938
|
+
r.post("/:name/attach", async (c) => {
|
|
3939
|
+
const body = AttachVolumeRequest.parse(await c.req.json().catch(() => ({})));
|
|
3940
|
+
const owner = c.get("owner");
|
|
3941
|
+
return c.json(await attachVolume(parseRef(body.box, owner), parseRef(c.req.param("name"), owner)));
|
|
3942
|
+
});
|
|
3943
|
+
r.post("/:name/detach", async (c) => {
|
|
3944
|
+
const body = AttachVolumeRequest.parse(await c.req.json().catch(() => ({})));
|
|
3945
|
+
const owner = c.get("owner");
|
|
3946
|
+
return c.json(await detachVolume(parseRef(body.box, owner), parseRef(c.req.param("name"), owner)));
|
|
3947
|
+
});
|
|
3948
|
+
return r;
|
|
3949
|
+
}
|
|
3950
|
+
|
|
3414
3951
|
// src/app.ts
|
|
3415
3952
|
function createApp(opts = {}) {
|
|
3416
|
-
const app = new
|
|
3953
|
+
const app = new Hono8();
|
|
3417
3954
|
app.use(resolveCaller(opts));
|
|
3418
3955
|
app.get("/health", async (c) => {
|
|
3419
3956
|
const cfg = await loadConfig();
|
|
@@ -3432,6 +3969,7 @@ function createApp(opts = {}) {
|
|
|
3432
3969
|
if (opts.controlPlane) app.route("/machines", boxHttpRoutes());
|
|
3433
3970
|
app.route("/machines", machineRoutes());
|
|
3434
3971
|
app.route("/snapshots", snapshotRoutes());
|
|
3972
|
+
app.route("/volumes", volumeRoutes());
|
|
3435
3973
|
app.route("/capacity", capacityRoutes());
|
|
3436
3974
|
app.route("/ssh", sshRoutes(opts));
|
|
3437
3975
|
app.route("/usage", usageRoutes(opts));
|
|
@@ -3455,13 +3993,13 @@ async function listen(opts = {}) {
|
|
|
3455
3993
|
if (Buffer.byteLength(socketPath) > 100) {
|
|
3456
3994
|
throw new KvboxError(`socket path too long for a Unix socket (${socketPath}); set KVBOX_HOME to a shorter path`);
|
|
3457
3995
|
}
|
|
3458
|
-
await
|
|
3996
|
+
await rm5(socketPath, { force: true });
|
|
3459
3997
|
const server = createAdaptorServer({ fetch: createApp().fetch });
|
|
3460
3998
|
await new Promise((resolve, reject) => {
|
|
3461
3999
|
server.once("error", reject);
|
|
3462
4000
|
server.listen(socketPath, () => resolve());
|
|
3463
4001
|
});
|
|
3464
|
-
await
|
|
4002
|
+
await writeFile6(p.serverPid, `${process.pid}
|
|
3465
4003
|
`);
|
|
3466
4004
|
let https;
|
|
3467
4005
|
let httpsServer;
|
|
@@ -3482,8 +4020,8 @@ async function listen(opts = {}) {
|
|
|
3482
4020
|
httpsServer.listen(port, "0.0.0.0", () => resolve());
|
|
3483
4021
|
}).catch(async (err) => {
|
|
3484
4022
|
server.close();
|
|
3485
|
-
await
|
|
3486
|
-
await
|
|
4023
|
+
await rm5(socketPath, { force: true });
|
|
4024
|
+
await rm5(p.serverPid, { force: true });
|
|
3487
4025
|
throw new KvboxError(`cannot listen on port ${port} for ${cp.name} (${err.message})`);
|
|
3488
4026
|
});
|
|
3489
4027
|
const bound = httpsServer.address().port;
|
|
@@ -3494,15 +4032,15 @@ async function listen(opts = {}) {
|
|
|
3494
4032
|
new Promise((resolve) => server.close(() => resolve())),
|
|
3495
4033
|
httpsServer ? new Promise((resolve) => httpsServer.close(() => resolve())) : void 0
|
|
3496
4034
|
]);
|
|
3497
|
-
await
|
|
3498
|
-
await
|
|
4035
|
+
await rm5(socketPath, { force: true });
|
|
4036
|
+
await rm5(p.serverPid, { force: true });
|
|
3499
4037
|
};
|
|
3500
4038
|
const shutdown2 = async () => {
|
|
3501
4039
|
server.close();
|
|
3502
4040
|
httpsServer?.close();
|
|
3503
4041
|
await stopRecovery();
|
|
3504
|
-
await
|
|
3505
|
-
await
|
|
4042
|
+
await rm5(socketPath, { force: true });
|
|
4043
|
+
await rm5(p.serverPid, { force: true });
|
|
3506
4044
|
process.exit(0);
|
|
3507
4045
|
};
|
|
3508
4046
|
process.once("SIGINT", () => void shutdown2());
|