@kvbox/server 0.6.12 → 0.6.13
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 +1478 -1028
- package/dist/kvbox-server.js.map +1 -1
- package/package.json +1 -1
package/dist/kvbox-server.js
CHANGED
|
@@ -9,6 +9,12 @@ var KvboxError = class extends Error {
|
|
|
9
9
|
}
|
|
10
10
|
exitCode;
|
|
11
11
|
};
|
|
12
|
+
var NotImplementedError = class extends KvboxError {
|
|
13
|
+
constructor(what) {
|
|
14
|
+
super(`${what}: not implemented yet`, 2);
|
|
15
|
+
this.name = "NotImplementedError";
|
|
16
|
+
}
|
|
17
|
+
};
|
|
12
18
|
var NotFoundError = class extends KvboxError {
|
|
13
19
|
constructor(what) {
|
|
14
20
|
super(`${what}: not found`, 1);
|
|
@@ -734,6 +740,7 @@ function macFor(ip) {
|
|
|
734
740
|
import { spawn as spawn2 } from "node:child_process";
|
|
735
741
|
import { closeSync, existsSync as existsSync2, openSync as openSync2 } from "node:fs";
|
|
736
742
|
import { readFile as readFile3, rm as rm2 } from "node:fs/promises";
|
|
743
|
+
import { relative } from "node:path";
|
|
737
744
|
|
|
738
745
|
// src/core/proc.ts
|
|
739
746
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
@@ -890,6 +897,7 @@ var FirecrackerClient = class {
|
|
|
890
897
|
// src/core/drivers/firecracker/vm.ts
|
|
891
898
|
var GUEST_CID = 3;
|
|
892
899
|
var OVERLAY_REL = "overlay.ext4";
|
|
900
|
+
var vsockRel = (m) => relative(m.dir, m.vsock);
|
|
893
901
|
function bootArgs(name, ip, cfg, pubkeyB64) {
|
|
894
902
|
const args = `console=ttyS0 reboot=k panic=1 init=/sbin/overlay-init kvbox.overlay=/dev/vdb ip=${ip}::${cfg.gateway}:255.255.255.0:${name}:eth0:off kvbox.name=${name} kvbox.sshkey=${pubkeyB64}`;
|
|
895
903
|
return process.arch === "arm64" ? `keep_bootcon ${args}` : args;
|
|
@@ -945,7 +953,7 @@ async function boot(spec, disks, tap, cfg, p) {
|
|
|
945
953
|
for (const v of disks.volumes) await fc.volumeDrive(v.id, v.path);
|
|
946
954
|
await fc.machineConfig(spec.vcpu, spec.memMib);
|
|
947
955
|
await fc.networkInterface("eth0", tap, spec.mac);
|
|
948
|
-
await fc.vsock(GUEST_CID, m
|
|
956
|
+
await fc.vsock(GUEST_CID, vsockRel(m));
|
|
949
957
|
await fc.start();
|
|
950
958
|
});
|
|
951
959
|
return pid;
|
|
@@ -965,7 +973,7 @@ async function restore(box, state, tap, cfg, p) {
|
|
|
965
973
|
snapshotPath: state.vmstate,
|
|
966
974
|
memFilePath: state.mem,
|
|
967
975
|
tap: { ifaceId: "eth0", hostDevName: tap },
|
|
968
|
-
vsockPath: m
|
|
976
|
+
vsockPath: vsockRel(m),
|
|
969
977
|
trackDirtyPages: true,
|
|
970
978
|
resume: false
|
|
971
979
|
})
|
|
@@ -996,6 +1004,9 @@ async function cleanup(box, p) {
|
|
|
996
1004
|
await rm2(m.sock, { force: true });
|
|
997
1005
|
await rm2(m.vsock, { force: true });
|
|
998
1006
|
}
|
|
1007
|
+
function guestSocket(box, port, p) {
|
|
1008
|
+
return `${p.machine(box.owner, box.name).vsock}_${port}`;
|
|
1009
|
+
}
|
|
999
1010
|
|
|
1000
1011
|
// src/core/drivers/firecracker/index.ts
|
|
1001
1012
|
var firecrackerDriver = {
|
|
@@ -1012,7 +1023,8 @@ var firecrackerDriver = {
|
|
|
1012
1023
|
resume,
|
|
1013
1024
|
shutdown,
|
|
1014
1025
|
saveState,
|
|
1015
|
-
cleanup
|
|
1026
|
+
cleanup,
|
|
1027
|
+
guestSocket
|
|
1016
1028
|
},
|
|
1017
1029
|
net: {
|
|
1018
1030
|
prepare: ensureHostNetwork,
|
|
@@ -1295,7 +1307,13 @@ var MachineMetaSchema = z3.object({
|
|
|
1295
1307
|
* was removed but the rule would not close; kept only so this box's next stop closes it, never opened
|
|
1296
1308
|
* again, never listed (a new box of the same name may get the same IP). Absent: none.
|
|
1297
1309
|
*/
|
|
1298
|
-
links: z3.array(z3.object({ owner: z3.string(), name: z3.string(), ip: z3.string(), port: z3.number().int(), stale: z3.literal(true).optional() })).optional()
|
|
1310
|
+
links: z3.array(z3.object({ owner: z3.string(), name: z3.string(), ip: z3.string(), port: z3.number().int(), stale: z3.literal(true).optional() })).optional(),
|
|
1311
|
+
/**
|
|
1312
|
+
* The integrations turned on for the box (#205): names only (`github`), never a credential. The box asks
|
|
1313
|
+
* for one each time it needs it (core/machines/integrations.ts) and is answered only for a name in this
|
|
1314
|
+
* list. Plain strings, so a name a newer server wrote still reads. Absent: none.
|
|
1315
|
+
*/
|
|
1316
|
+
integrations: z3.array(z3.string()).optional()
|
|
1299
1317
|
});
|
|
1300
1318
|
var VolumeMetaSchema = z3.object({
|
|
1301
1319
|
/** Host-unique like a box id (#91): the ledger's key, so a name removed and made again is two volumes. */
|
|
@@ -1328,7 +1346,9 @@ var SnapshotMetaSchema = z3.object({
|
|
|
1328
1346
|
* and their mounts in the memory image, but their data is not here. A box restored from the snapshot
|
|
1329
1347
|
* gets an empty placeholder of each size at the drive's path and drops the mounts through kvbox-agent.
|
|
1330
1348
|
*/
|
|
1331
|
-
volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int() })).optional()
|
|
1349
|
+
volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int() })).optional(),
|
|
1350
|
+
/** The source box's integrations when it was frozen (#205): a box restored from the snapshot has them on too. */
|
|
1351
|
+
integrations: z3.array(z3.string()).optional()
|
|
1332
1352
|
});
|
|
1333
1353
|
async function ensureLayout(p = paths()) {
|
|
1334
1354
|
for (const dir of [p.home, p.ssh, p.bin, p.assets, p.machines, p.snapshots, p.volumes]) {
|
|
@@ -1744,7 +1764,7 @@ function namesIn(text) {
|
|
|
1744
1764
|
|
|
1745
1765
|
// src/core/machines/change.ts
|
|
1746
1766
|
import { statSync as statSync3 } from "node:fs";
|
|
1747
|
-
import { rename as rename5, rm as
|
|
1767
|
+
import { rename as rename5, rm as rm8 } from "node:fs/promises";
|
|
1748
1768
|
|
|
1749
1769
|
// src/core/capacity.ts
|
|
1750
1770
|
import { cpus, totalmem } from "node:os";
|
|
@@ -1766,1062 +1786,1158 @@ import { existsSync as existsSync5, statSync } from "node:fs";
|
|
|
1766
1786
|
import { lstat, mkdir as mkdir2, readdir as readdir3, rm as rm3, statfs, symlink, truncate, writeFile as writeFile3 } from "node:fs/promises";
|
|
1767
1787
|
|
|
1768
1788
|
// ../shared/src/api.ts
|
|
1789
|
+
import { z as z6 } from "zod";
|
|
1790
|
+
|
|
1791
|
+
// ../shared/src/integrations.ts
|
|
1769
1792
|
import { z as z5 } from "zod";
|
|
1770
|
-
var
|
|
1771
|
-
var
|
|
1772
|
-
var
|
|
1793
|
+
var INTEGRATION_IDS = ["github"];
|
|
1794
|
+
var IntegrationIdSchema = z5.enum(INTEGRATION_IDS);
|
|
1795
|
+
var INTEGRATION_KINDS = ["oauth", "app", "api-key", "subscription"];
|
|
1796
|
+
var IntegrationKindSchema = z5.enum(INTEGRATION_KINDS);
|
|
1797
|
+
var INTEGRATION_STATUSES = ["ok", "needs-reconnect"];
|
|
1798
|
+
var IntegrationStatusSchema = z5.enum(INTEGRATION_STATUSES);
|
|
1799
|
+
var IntegrationListSchema = z5.array(z5.string().min(1).max(40)).max(20).transform((list) => [...new Set(list)]);
|
|
1800
|
+
function assertKnownIntegrations(list, who, hint = `the integrations are: ${INTEGRATION_IDS.join(", ")}`) {
|
|
1801
|
+
const unknown = (list ?? []).filter((n) => !INTEGRATION_IDS.includes(n));
|
|
1802
|
+
if (unknown.length > 0) throw new KvboxError(`${who} does not know the integration ${unknown.join(", ")} (${hint})`);
|
|
1803
|
+
}
|
|
1804
|
+
var IntegrationCatalogEntrySchema = z5.object({
|
|
1805
|
+
/** A plain string, like `integration` in a listing row: a reader may be older than the control plane. */
|
|
1806
|
+
id: z5.string(),
|
|
1807
|
+
title: z5.string(),
|
|
1808
|
+
description: z5.string(),
|
|
1809
|
+
/** How Connect works: `oauth` sends the browser to the provider's consent screen. */
|
|
1810
|
+
connect: z5.enum(["oauth"]),
|
|
1811
|
+
/** What a user's slug and an org's may hold; an empty list: that kind of slug cannot connect it yet. */
|
|
1812
|
+
kinds: z5.object({ user: z5.array(IntegrationKindSchema), org: z5.array(IntegrationKindSchema) }),
|
|
1813
|
+
/** Whether this control plane is set up for it (a self-hosted one without a GitHub app is not). */
|
|
1814
|
+
available: z5.boolean(),
|
|
1815
|
+
/** Its guide, as a URL. */
|
|
1816
|
+
docs: z5.string().optional(),
|
|
1817
|
+
/** Where it is connected and disconnected: this control plane's web app, when it has one. */
|
|
1818
|
+
page: z5.string().optional()
|
|
1819
|
+
});
|
|
1820
|
+
var IntegrationSchema = z5.object({
|
|
1821
|
+
/** The slug it belongs to: a user's or an org's. */
|
|
1822
|
+
owner: z5.string(),
|
|
1823
|
+
/**
|
|
1824
|
+
* Which one (`github`). A plain string, not the ids above: this is an answer, read by every released CLI
|
|
1825
|
+
* and SDK, and one from before a new integration must still read the listing that has it.
|
|
1826
|
+
*/
|
|
1827
|
+
integration: z5.string(),
|
|
1828
|
+
connected: z5.boolean(),
|
|
1829
|
+
/** The rest is null while not connected. */
|
|
1830
|
+
kind: IntegrationKindSchema.nullable(),
|
|
1831
|
+
/** Whose account, as shown: the GitHub login. Never a secret. */
|
|
1832
|
+
account: z5.string().nullable(),
|
|
1833
|
+
status: IntegrationStatusSchema.nullable(),
|
|
1834
|
+
connectedBy: z5.string().nullable(),
|
|
1835
|
+
connectedAt: z5.string().nullable(),
|
|
1836
|
+
/** The last time a box was handed the credential (to the minute). */
|
|
1837
|
+
lastUsedAt: z5.string().nullable(),
|
|
1838
|
+
/** Whether the caller may connect or disconnect it: the slug's own user, an org's owners. */
|
|
1839
|
+
canManage: z5.boolean()
|
|
1840
|
+
});
|
|
1841
|
+
var IntegrationConnectSchema = z5.object({ url: z5.string() });
|
|
1842
|
+
var IntegrationCompleteRequestSchema = z5.object({ code: z5.string().min(1), state: z5.string().min(1) });
|
|
1843
|
+
var IntegrationIdentitySchema = z5.object({ name: z5.string(), email: z5.string() });
|
|
1844
|
+
var CREDENTIAL_REFUSALS = ["off", "not-connected", "needs-reconnect", "unavailable"];
|
|
1845
|
+
var CredentialAnswerSchema = z5.discriminatedUnion("ok", [
|
|
1846
|
+
z5.object({
|
|
1847
|
+
ok: z5.literal(true),
|
|
1848
|
+
kind: IntegrationKindSchema,
|
|
1849
|
+
token: z5.string(),
|
|
1850
|
+
/** When the token ends (ISO), for one that does (a GitHub App's hour). */
|
|
1851
|
+
expiresAt: z5.string().optional(),
|
|
1852
|
+
identity: IntegrationIdentitySchema.optional()
|
|
1853
|
+
}),
|
|
1854
|
+
z5.object({
|
|
1855
|
+
ok: z5.literal(false),
|
|
1856
|
+
code: z5.enum(CREDENTIAL_REFUSALS),
|
|
1857
|
+
message: z5.string(),
|
|
1858
|
+
/** With `off`: whether the slug has it connected, so the box can say how to turn it on. */
|
|
1859
|
+
connected: z5.boolean().optional()
|
|
1860
|
+
})
|
|
1861
|
+
]);
|
|
1862
|
+
var HostCredentialRequestSchema = z5.object({ owner: z5.string().min(1), box: z5.string().min(1), integration: IntegrationIdSchema, probe: z5.boolean().optional() });
|
|
1863
|
+
var ConnectedAnswerSchema = z5.object({ connected: z5.boolean(), identity: IntegrationIdentitySchema.optional() });
|
|
1864
|
+
var GUEST_REQUEST_PORT = 53;
|
|
1865
|
+
var GuestRequestSchema = z5.object({ op: z5.literal("credential"), integration: IntegrationIdSchema });
|
|
1866
|
+
var INTEGRATIONS_BASE = "0.17.0";
|
|
1867
|
+
var GUEST_REQUESTS_PER_MINUTE = 60;
|
|
1868
|
+
|
|
1869
|
+
// ../shared/src/api.ts
|
|
1870
|
+
var SizeSchema = z6.enum(SIZE_NAMES);
|
|
1871
|
+
var BoxStatusSchema = z6.enum(["running", "standby", "hibernated", "stopped", "unknown"]);
|
|
1872
|
+
var PortProtoSchema = z6.enum(["tcp", "udp"]);
|
|
1773
1873
|
var MAX_BOX_PORTS = 16;
|
|
1774
|
-
var PortForwardSchema =
|
|
1775
|
-
guestPort:
|
|
1776
|
-
hostPort:
|
|
1874
|
+
var PortForwardSchema = z6.object({
|
|
1875
|
+
guestPort: z6.number().int().min(1).max(65535),
|
|
1876
|
+
hostPort: z6.number().int(),
|
|
1777
1877
|
proto: PortProtoSchema,
|
|
1778
1878
|
/** The host's public address; only the control plane fills it in, as for `ssh`. */
|
|
1779
|
-
address:
|
|
1879
|
+
address: z6.string().optional(),
|
|
1780
1880
|
/**
|
|
1781
1881
|
* Closed but kept (#173): nothing reaches the box through it, and the host port stays the box's, so
|
|
1782
1882
|
* publishing the same box port again opens the same number. Absent: open while the box runs.
|
|
1783
1883
|
*/
|
|
1784
|
-
closed:
|
|
1884
|
+
closed: z6.literal(true).optional()
|
|
1785
1885
|
});
|
|
1786
|
-
var PortsRequest =
|
|
1787
|
-
ports:
|
|
1886
|
+
var PortsRequest = z6.object({
|
|
1887
|
+
ports: z6.array(z6.object({ guestPort: z6.number().int().min(1).max(65535), proto: PortProtoSchema.optional() })).min(1).max(MAX_BOX_PORTS),
|
|
1788
1888
|
/** `DELETE` only (#173): close the ports but keep their host ports for the box (`closed`). */
|
|
1789
|
-
keep:
|
|
1889
|
+
keep: z6.boolean().optional()
|
|
1790
1890
|
});
|
|
1791
|
-
var BoxPortSchema =
|
|
1891
|
+
var BoxPortSchema = z6.number().int().min(1).max(65535);
|
|
1792
1892
|
var MAX_BOX_LINKS = 32;
|
|
1793
|
-
var BoxLinkSchema =
|
|
1794
|
-
var LinkRequest =
|
|
1795
|
-
var ClaimSubdomainRequest =
|
|
1796
|
-
var SubdomainPortRequest =
|
|
1797
|
-
var SubdomainRouteRequest =
|
|
1798
|
-
var SubdomainSchema =
|
|
1799
|
-
owner:
|
|
1800
|
-
box:
|
|
1801
|
-
subdomain:
|
|
1893
|
+
var BoxLinkSchema = z6.object({ from: z6.string(), port: BoxPortSchema });
|
|
1894
|
+
var LinkRequest = z6.object({ from: z6.string().min(1), fromOwner: z6.string().optional(), port: BoxPortSchema });
|
|
1895
|
+
var ClaimSubdomainRequest = z6.object({ name: z6.string(), port: BoxPortSchema });
|
|
1896
|
+
var SubdomainPortRequest = z6.object({ port: BoxPortSchema });
|
|
1897
|
+
var SubdomainRouteRequest = z6.object({ name: z6.string(), port: BoxPortSchema });
|
|
1898
|
+
var SubdomainSchema = z6.object({
|
|
1899
|
+
owner: z6.string(),
|
|
1900
|
+
box: z6.string(),
|
|
1901
|
+
subdomain: z6.string(),
|
|
1802
1902
|
port: BoxPortSchema,
|
|
1803
|
-
url:
|
|
1804
|
-
routes:
|
|
1805
|
-
});
|
|
1806
|
-
var AddDomainRequest =
|
|
1807
|
-
var DomainSchema =
|
|
1808
|
-
owner:
|
|
1809
|
-
box:
|
|
1810
|
-
domain:
|
|
1903
|
+
url: z6.string(),
|
|
1904
|
+
routes: z6.array(z6.object({ name: z6.string(), port: BoxPortSchema, url: z6.string() }))
|
|
1905
|
+
});
|
|
1906
|
+
var AddDomainRequest = z6.object({ domain: z6.string(), port: BoxPortSchema.optional() });
|
|
1907
|
+
var DomainSchema = z6.object({
|
|
1908
|
+
owner: z6.string(),
|
|
1909
|
+
box: z6.string(),
|
|
1910
|
+
domain: z6.string(),
|
|
1811
1911
|
port: BoxPortSchema,
|
|
1812
|
-
status:
|
|
1813
|
-
www:
|
|
1814
|
-
url:
|
|
1815
|
-
error:
|
|
1816
|
-
records:
|
|
1817
|
-
createdAt:
|
|
1818
|
-
});
|
|
1819
|
-
var WakeHookSchema =
|
|
1820
|
-
id:
|
|
1821
|
-
owner:
|
|
1822
|
-
box:
|
|
1823
|
-
url:
|
|
1824
|
-
createdBy:
|
|
1825
|
-
createdAt:
|
|
1826
|
-
lastCalledAt:
|
|
1827
|
-
});
|
|
1828
|
-
var CreatedWakeHookSchema = WakeHookSchema.extend({ secret:
|
|
1829
|
-
var WakeHookCallSchema =
|
|
1830
|
-
box:
|
|
1831
|
-
action:
|
|
1832
|
-
reason:
|
|
1912
|
+
status: z6.enum(["pending", "live"]),
|
|
1913
|
+
www: z6.boolean(),
|
|
1914
|
+
url: z6.string(),
|
|
1915
|
+
error: z6.string().nullable(),
|
|
1916
|
+
records: z6.array(z6.object({ type: z6.enum(["A", "TXT", "CNAME"]), name: z6.string(), value: z6.string() })),
|
|
1917
|
+
createdAt: z6.string()
|
|
1918
|
+
});
|
|
1919
|
+
var WakeHookSchema = z6.object({
|
|
1920
|
+
id: z6.string(),
|
|
1921
|
+
owner: z6.string(),
|
|
1922
|
+
box: z6.string(),
|
|
1923
|
+
url: z6.string(),
|
|
1924
|
+
createdBy: z6.string().nullable(),
|
|
1925
|
+
createdAt: z6.string(),
|
|
1926
|
+
lastCalledAt: z6.string().nullable()
|
|
1927
|
+
});
|
|
1928
|
+
var CreatedWakeHookSchema = WakeHookSchema.extend({ secret: z6.string() });
|
|
1929
|
+
var WakeHookCallSchema = z6.object({
|
|
1930
|
+
box: z6.string(),
|
|
1931
|
+
action: z6.enum(["wake", "resume", "none"]),
|
|
1932
|
+
reason: z6.string().optional()
|
|
1833
1933
|
});
|
|
1834
1934
|
var BACKUP_STATUSES = ["running", "ready", "failed"];
|
|
1835
1935
|
var BACKUP_KINDS = ["box", "volume"];
|
|
1836
|
-
var BackupSchema =
|
|
1837
|
-
id:
|
|
1838
|
-
owner:
|
|
1839
|
-
box:
|
|
1936
|
+
var BackupSchema = z6.object({
|
|
1937
|
+
id: z6.string(),
|
|
1938
|
+
owner: z6.string(),
|
|
1939
|
+
box: z6.string(),
|
|
1840
1940
|
/**
|
|
1841
1941
|
* The box it was taken of has been removed (#141): a box called `box` now is another box, which this backup
|
|
1842
1942
|
* never restores into; `kvbox new <name> --from-backup <id>` makes a box from it. Absent from a control plane
|
|
1843
1943
|
* before #141.
|
|
1844
1944
|
*/
|
|
1845
|
-
boxRemoved:
|
|
1846
|
-
status:
|
|
1945
|
+
boxRemoved: z6.boolean().optional(),
|
|
1946
|
+
status: z6.enum(BACKUP_STATUSES),
|
|
1847
1947
|
/** Why it failed; null otherwise. */
|
|
1848
|
-
error:
|
|
1948
|
+
error: z6.string().nullable(),
|
|
1849
1949
|
/** The image version the disk stacks on (a restore needs it on the host), and the image (absent: base). */
|
|
1850
|
-
base:
|
|
1851
|
-
image:
|
|
1852
|
-
vcpu:
|
|
1853
|
-
memMib:
|
|
1950
|
+
base: z6.string().nullable(),
|
|
1951
|
+
image: z6.string().optional(),
|
|
1952
|
+
vcpu: z6.number().int().nullable(),
|
|
1953
|
+
memMib: z6.number().int().nullable(),
|
|
1854
1954
|
/** The disk's size. */
|
|
1855
|
-
diskBytes:
|
|
1955
|
+
diskBytes: z6.number().int().nullable(),
|
|
1856
1956
|
/** What it holds: the slots that are not all zeros. */
|
|
1857
|
-
dataBytes:
|
|
1957
|
+
dataBytes: z6.number().int().nullable(),
|
|
1858
1958
|
/** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
|
|
1859
|
-
uploadedBytes:
|
|
1860
|
-
createdBy:
|
|
1861
|
-
createdAt:
|
|
1862
|
-
finishedAt:
|
|
1863
|
-
});
|
|
1864
|
-
var BackupLimitSchema =
|
|
1865
|
-
perDay:
|
|
1866
|
-
used:
|
|
1867
|
-
nextAt:
|
|
1868
|
-
});
|
|
1869
|
-
var NamedBackupLimitSchema = BackupLimitSchema.extend({ owner:
|
|
1870
|
-
var HostBackupRequest =
|
|
1871
|
-
var HostBackupManifestSchema =
|
|
1872
|
-
id:
|
|
1873
|
-
sizeBytes:
|
|
1874
|
-
chunks:
|
|
1875
|
-
env:
|
|
1876
|
-
base:
|
|
1877
|
-
image:
|
|
1878
|
-
vcpu:
|
|
1879
|
-
memMib:
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
var
|
|
1959
|
+
uploadedBytes: z6.number().int().nullable(),
|
|
1960
|
+
createdBy: z6.string().nullable(),
|
|
1961
|
+
createdAt: z6.string(),
|
|
1962
|
+
finishedAt: z6.string().nullable()
|
|
1963
|
+
});
|
|
1964
|
+
var BackupLimitSchema = z6.object({
|
|
1965
|
+
perDay: z6.number().int(),
|
|
1966
|
+
used: z6.number().int(),
|
|
1967
|
+
nextAt: z6.string().nullable()
|
|
1968
|
+
});
|
|
1969
|
+
var NamedBackupLimitSchema = BackupLimitSchema.extend({ owner: z6.string(), name: z6.string() });
|
|
1970
|
+
var HostBackupRequest = z6.object({ id: z6.string(), key: z6.string() });
|
|
1971
|
+
var HostBackupManifestSchema = z6.object({
|
|
1972
|
+
id: z6.string(),
|
|
1973
|
+
sizeBytes: z6.number().int(),
|
|
1974
|
+
chunks: z6.array(z6.string().nullable()),
|
|
1975
|
+
env: z6.string().nullable(),
|
|
1976
|
+
base: z6.string(),
|
|
1977
|
+
image: z6.string().optional(),
|
|
1978
|
+
vcpu: z6.number().int(),
|
|
1979
|
+
memMib: z6.number().int(),
|
|
1980
|
+
/** The box's integrations (#205), so a box made from the backup has them again. Absent: none, or an older host. */
|
|
1981
|
+
integrations: z6.array(z6.string()).optional()
|
|
1982
|
+
});
|
|
1983
|
+
var HostUploadRequest = z6.object({ key: z6.string(), urls: z6.record(z6.string(), z6.string()), pin: z6.string().optional() });
|
|
1984
|
+
var HostUploadResultSchema = z6.object({ chunks: z6.number().int(), bytes: z6.number().int(), sizes: z6.record(z6.string(), z6.number().int()) });
|
|
1985
|
+
var HostRestoreRequest = z6.object({
|
|
1884
1986
|
/** The backup's id: its variables were sealed under it. */
|
|
1885
|
-
id:
|
|
1886
|
-
key:
|
|
1887
|
-
sizeBytes:
|
|
1888
|
-
base:
|
|
1889
|
-
image:
|
|
1890
|
-
env:
|
|
1891
|
-
chunks:
|
|
1987
|
+
id: z6.string(),
|
|
1988
|
+
key: z6.string(),
|
|
1989
|
+
sizeBytes: z6.number().int().positive(),
|
|
1990
|
+
base: z6.string(),
|
|
1991
|
+
image: z6.string().optional(),
|
|
1992
|
+
env: z6.string().nullable(),
|
|
1993
|
+
chunks: z6.array(z6.object({ index: z6.number().int().nonnegative(), hash: z6.string(), url: z6.string() })),
|
|
1892
1994
|
/** The certificate fingerprint of the store the URLs point at (see HostUploadRequest). */
|
|
1893
|
-
pin:
|
|
1995
|
+
pin: z6.string().optional()
|
|
1894
1996
|
});
|
|
1895
|
-
var VolumeBackupSchema =
|
|
1896
|
-
id:
|
|
1897
|
-
owner:
|
|
1898
|
-
volume:
|
|
1899
|
-
status:
|
|
1997
|
+
var VolumeBackupSchema = z6.object({
|
|
1998
|
+
id: z6.string(),
|
|
1999
|
+
owner: z6.string(),
|
|
2000
|
+
volume: z6.string(),
|
|
2001
|
+
status: z6.enum(BACKUP_STATUSES),
|
|
1900
2002
|
/** Why it failed; null otherwise. */
|
|
1901
|
-
error:
|
|
2003
|
+
error: z6.string().nullable(),
|
|
1902
2004
|
/** The volume's size when taken. */
|
|
1903
|
-
diskBytes:
|
|
2005
|
+
diskBytes: z6.number().int().nullable(),
|
|
1904
2006
|
/** What it holds: the slots that are not all zeros. */
|
|
1905
|
-
dataBytes:
|
|
2007
|
+
dataBytes: z6.number().int().nullable(),
|
|
1906
2008
|
/** What this backup added to storage (encrypted, compressed): the chunks no earlier backup had. */
|
|
1907
|
-
uploadedBytes:
|
|
1908
|
-
createdBy:
|
|
1909
|
-
createdAt:
|
|
1910
|
-
finishedAt:
|
|
2009
|
+
uploadedBytes: z6.number().int().nullable(),
|
|
2010
|
+
createdBy: z6.string().nullable(),
|
|
2011
|
+
createdAt: z6.string(),
|
|
2012
|
+
finishedAt: z6.string().nullable()
|
|
1911
2013
|
});
|
|
1912
|
-
var BackupScheduleSchema =
|
|
1913
|
-
enabled:
|
|
2014
|
+
var BackupScheduleSchema = z6.object({
|
|
2015
|
+
enabled: z6.boolean(),
|
|
1914
2016
|
/** 0-23, UTC. Kept while it is off, so turning it on again keeps the hour. */
|
|
1915
|
-
hour:
|
|
1916
|
-
nextAt:
|
|
1917
|
-
lastAt:
|
|
1918
|
-
lastBackup:
|
|
1919
|
-
lastError:
|
|
1920
|
-
});
|
|
1921
|
-
var SetBackupScheduleRequest =
|
|
1922
|
-
var HostVolumeBackupManifestSchema =
|
|
1923
|
-
var HostVolumeRestoreRequest =
|
|
1924
|
-
id:
|
|
1925
|
-
key:
|
|
1926
|
-
sizeBytes:
|
|
1927
|
-
chunks:
|
|
1928
|
-
pin:
|
|
2017
|
+
hour: z6.number().int().min(0).max(23),
|
|
2018
|
+
nextAt: z6.string().nullable(),
|
|
2019
|
+
lastAt: z6.string().nullable(),
|
|
2020
|
+
lastBackup: z6.string().nullable(),
|
|
2021
|
+
lastError: z6.string().nullable()
|
|
2022
|
+
});
|
|
2023
|
+
var SetBackupScheduleRequest = z6.object({ enabled: z6.boolean().optional(), hour: z6.number().int().min(0).max(23).optional() });
|
|
2024
|
+
var HostVolumeBackupManifestSchema = z6.object({ id: z6.string(), sizeBytes: z6.number().int(), chunks: z6.array(z6.string().nullable()) });
|
|
2025
|
+
var HostVolumeRestoreRequest = z6.object({
|
|
2026
|
+
id: z6.string(),
|
|
2027
|
+
key: z6.string(),
|
|
2028
|
+
sizeBytes: z6.number().int().positive(),
|
|
2029
|
+
chunks: z6.array(z6.object({ index: z6.number().int().nonnegative(), hash: z6.string(), url: z6.string() })),
|
|
2030
|
+
pin: z6.string().optional()
|
|
1929
2031
|
});
|
|
1930
2032
|
var BACKUP_STORE_BUCKET = "kvbox-backups";
|
|
1931
2033
|
var BACKUP_STORE_REGION = "kvbox";
|
|
1932
|
-
var BackupStoreSetupRequest =
|
|
1933
|
-
var BackupStoreStatusSchema =
|
|
1934
|
-
path:
|
|
1935
|
-
bucket:
|
|
1936
|
-
accessKey:
|
|
2034
|
+
var BackupStoreSetupRequest = z6.object({ path: z6.string().min(1), force: z6.boolean().optional(), newStore: z6.boolean().optional() });
|
|
2035
|
+
var BackupStoreStatusSchema = z6.object({
|
|
2036
|
+
path: z6.string(),
|
|
2037
|
+
bucket: z6.string(),
|
|
2038
|
+
accessKey: z6.string(),
|
|
1937
2039
|
/** Whether Garage is running and can store. */
|
|
1938
|
-
running:
|
|
2040
|
+
running: z6.boolean(),
|
|
1939
2041
|
/** The filesystem the path is on. */
|
|
1940
|
-
totalBytes:
|
|
1941
|
-
freeBytes:
|
|
2042
|
+
totalBytes: z6.number().int(),
|
|
2043
|
+
freeBytes: z6.number().int(),
|
|
1942
2044
|
/** What the bucket holds, when Garage answers. */
|
|
1943
|
-
objects:
|
|
1944
|
-
storedBytes:
|
|
2045
|
+
objects: z6.number().int().optional(),
|
|
2046
|
+
storedBytes: z6.number().int().optional(),
|
|
1945
2047
|
/** Whether the control plane took the store's registration at setup. */
|
|
1946
|
-
registered:
|
|
2048
|
+
registered: z6.boolean().optional()
|
|
1947
2049
|
});
|
|
1948
|
-
var BackupStoreRegistration =
|
|
1949
|
-
var CloudBackupStoreSchema =
|
|
1950
|
-
id:
|
|
2050
|
+
var BackupStoreRegistration = z6.object({ bucket: z6.string().min(1), region: z6.string().min(1), accessKey: z6.string().min(1), secretKey: z6.string().min(1) });
|
|
2051
|
+
var CloudBackupStoreSchema = z6.object({
|
|
2052
|
+
id: z6.string(),
|
|
1951
2053
|
/** Null while no host serves it (its host left; it comes back when a host registers its key and secret again). */
|
|
1952
|
-
host:
|
|
1953
|
-
endpoint:
|
|
1954
|
-
bucket:
|
|
1955
|
-
accessKey:
|
|
1956
|
-
createdAt:
|
|
2054
|
+
host: z6.string().nullable(),
|
|
2055
|
+
endpoint: z6.string().nullable(),
|
|
2056
|
+
bucket: z6.string(),
|
|
2057
|
+
accessKey: z6.string(),
|
|
2058
|
+
createdAt: z6.string(),
|
|
1957
2059
|
/** The host answered a poll in the last minute and its Garage runs. */
|
|
1958
|
-
live:
|
|
2060
|
+
live: z6.boolean(),
|
|
1959
2061
|
/** From the host's last poll; null when it never reported a store. */
|
|
1960
|
-
totalBytes:
|
|
1961
|
-
freeBytes:
|
|
2062
|
+
totalBytes: z6.number().int().nullable(),
|
|
2063
|
+
freeBytes: z6.number().int().nullable(),
|
|
1962
2064
|
/** Ready backups kept here, and what their chunks take (encrypted, compressed). */
|
|
1963
|
-
backups:
|
|
1964
|
-
storedBytes:
|
|
2065
|
+
backups: z6.number().int(),
|
|
2066
|
+
storedBytes: z6.number().int(),
|
|
1965
2067
|
/** How many boxes have a ready backup here (a box and an earlier one of the same name count once), how many volumes (#168) and managed databases (#186). */
|
|
1966
|
-
boxes:
|
|
1967
|
-
volumes:
|
|
1968
|
-
databases:
|
|
2068
|
+
boxes: z6.number().int(),
|
|
2069
|
+
volumes: z6.number().int(),
|
|
2070
|
+
databases: z6.number().int(),
|
|
1969
2071
|
/** When the newest ready backup kept here finished; null when it keeps none. */
|
|
1970
|
-
lastBackupAt:
|
|
2072
|
+
lastBackupAt: z6.string().nullable()
|
|
1971
2073
|
});
|
|
1972
|
-
var StoredItemSchema =
|
|
1973
|
-
kind:
|
|
1974
|
-
owner:
|
|
2074
|
+
var StoredItemSchema = z6.object({
|
|
2075
|
+
kind: z6.enum(BACKUP_KINDS),
|
|
2076
|
+
owner: z6.string(),
|
|
1975
2077
|
/** The box's or volume's name; a managed database's (#186) for its hidden volume. */
|
|
1976
|
-
name:
|
|
2078
|
+
name: z6.string(),
|
|
1977
2079
|
/** The managed database's kind (`postgres`) when the volume is one's (#186); null otherwise. */
|
|
1978
|
-
managed:
|
|
2080
|
+
managed: z6.string().nullable(),
|
|
1979
2081
|
/** The host the box (or volume) is on now; null when it is gone (its backups stay). */
|
|
1980
|
-
host:
|
|
2082
|
+
host: z6.string().nullable(),
|
|
1981
2083
|
/** It is on the store's own host: losing that host loses it and its backups together. */
|
|
1982
|
-
sameHost:
|
|
2084
|
+
sameHost: z6.boolean(),
|
|
1983
2085
|
/** Ready backups kept here, and what they added to the store together (encrypted, compressed). */
|
|
1984
|
-
backups:
|
|
1985
|
-
uploadedBytes:
|
|
2086
|
+
backups: z6.number().int(),
|
|
2087
|
+
uploadedBytes: z6.number().int(),
|
|
1986
2088
|
/** The newest backup sent here, whatever became of it. */
|
|
1987
|
-
latest:
|
|
2089
|
+
latest: z6.object({ id: z6.string(), status: z6.enum(BACKUP_STATUSES), error: z6.string().nullable(), createdAt: z6.string() })
|
|
1988
2090
|
});
|
|
1989
|
-
var FailedBackupSchema =
|
|
1990
|
-
id:
|
|
1991
|
-
owner:
|
|
2091
|
+
var FailedBackupSchema = z6.object({
|
|
2092
|
+
id: z6.string(),
|
|
2093
|
+
owner: z6.string(),
|
|
1992
2094
|
/** What it was a backup of: a box or a volume (#168), and its name; a managed database's (#186) for its hidden volume. */
|
|
1993
|
-
kind:
|
|
1994
|
-
name:
|
|
2095
|
+
kind: z6.enum(BACKUP_KINDS),
|
|
2096
|
+
name: z6.string(),
|
|
1995
2097
|
/** The managed database's kind (`postgres`) when the volume is one's; null otherwise. */
|
|
1996
|
-
managed:
|
|
1997
|
-
error:
|
|
2098
|
+
managed: z6.string().nullable(),
|
|
2099
|
+
error: z6.string().nullable(),
|
|
1998
2100
|
/** The host that took it, and the host of the store it was going to; null when gone, or when it failed before a store was picked. */
|
|
1999
|
-
host:
|
|
2000
|
-
store:
|
|
2001
|
-
createdAt:
|
|
2101
|
+
host: z6.string().nullable(),
|
|
2102
|
+
store: z6.string().nullable(),
|
|
2103
|
+
createdAt: z6.string()
|
|
2002
2104
|
});
|
|
2003
|
-
var MachineSchema =
|
|
2105
|
+
var MachineSchema = z6.object({
|
|
2004
2106
|
/** Host-unique short id (the tap is `kv-<id>`). Missing only on a box made before ids that has not restarted since. */
|
|
2005
|
-
id:
|
|
2006
|
-
name:
|
|
2107
|
+
id: z6.string(),
|
|
2108
|
+
name: z6.string(),
|
|
2007
2109
|
/** Who the box belongs to; names are unique per owner. A bare name is local to the host, `user@control-plane` later. */
|
|
2008
|
-
owner:
|
|
2009
|
-
ip:
|
|
2010
|
-
mac:
|
|
2011
|
-
pid:
|
|
2012
|
-
vcpu:
|
|
2013
|
-
memMib:
|
|
2014
|
-
diskBytes:
|
|
2110
|
+
owner: z6.string(),
|
|
2111
|
+
ip: z6.string(),
|
|
2112
|
+
mac: z6.string(),
|
|
2113
|
+
pid: z6.number().int().nullable(),
|
|
2114
|
+
vcpu: z6.number().int(),
|
|
2115
|
+
memMib: z6.number().int(),
|
|
2116
|
+
diskBytes: z6.number().int(),
|
|
2015
2117
|
// the box's own writable disk, as the guest sees it
|
|
2016
|
-
diskUsedBytes:
|
|
2118
|
+
diskUsedBytes: z6.number().int(),
|
|
2017
2119
|
// what the box uses of it: the filesystem's own count, like the guest's `df` (#115)
|
|
2018
2120
|
/** What the disk's sparse file occupies on the host. Grows while the box runs, `kvbox stop` trims it back. Hosts before 0.5.42 do not send it. */
|
|
2019
|
-
diskHostBytes:
|
|
2020
|
-
base:
|
|
2121
|
+
diskHostBytes: z6.number().int().optional(),
|
|
2122
|
+
base: z6.string(),
|
|
2021
2123
|
// version of the image the box's overlay stacks on
|
|
2022
2124
|
/** The image (#87) when it is not the base one: `postgres`. `base` is then that image's version. */
|
|
2023
|
-
image:
|
|
2024
|
-
createdAt:
|
|
2025
|
-
source:
|
|
2125
|
+
image: z6.string().optional(),
|
|
2126
|
+
createdAt: z6.string(),
|
|
2127
|
+
source: z6.string(),
|
|
2026
2128
|
// "base", "snapshot:<owner/name>", "fork:<owner/name>" (#79) or "backup:<id>" (#141)
|
|
2027
2129
|
status: BoxStatusSchema,
|
|
2028
2130
|
/**
|
|
2029
2131
|
* Public TCP port on the host that reaches the box's SSH while it runs (#49). Only boxes made
|
|
2030
2132
|
* through a control plane have one; the control plane adds the host's address for `connect` (#21).
|
|
2031
2133
|
*/
|
|
2032
|
-
sshPort:
|
|
2134
|
+
sshPort: z6.number().int().optional(),
|
|
2033
2135
|
/**
|
|
2034
2136
|
* Where `ssh` reaches the box from outside: the host's public address and that port (#21). Only
|
|
2035
2137
|
* the control plane fills it in (a host does not know its own public address); absent for a box
|
|
2036
2138
|
* whose host reported no port or did not answer.
|
|
2037
2139
|
*/
|
|
2038
|
-
ssh:
|
|
2140
|
+
ssh: z6.object({ host: z6.string(), port: z6.number().int(), user: z6.string() }).optional(),
|
|
2039
2141
|
/** Box ports published on the host (#30). Absent: none. */
|
|
2040
|
-
ports:
|
|
2142
|
+
ports: z6.array(PortForwardSchema).optional(),
|
|
2041
2143
|
/** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /machines`. */
|
|
2042
|
-
ownerKind:
|
|
2144
|
+
ownerKind: z6.enum(["user", "org"]).optional(),
|
|
2043
2145
|
/**
|
|
2044
2146
|
* The name of the host the box runs on. Only the control plane fills it in, on `GET /machines`: a box
|
|
2045
2147
|
* links to, and a volume attaches to, only a box on the same host.
|
|
2046
2148
|
*/
|
|
2047
|
-
host:
|
|
2149
|
+
host: z6.string().optional(),
|
|
2048
2150
|
/** The country code of that host (`RO`, `US`), when its admin gave one. Only the control plane fills it in. */
|
|
2049
|
-
country:
|
|
2151
|
+
country: z6.string().optional(),
|
|
2050
2152
|
/**
|
|
2051
2153
|
* The kind of managed service the box runs (`postgres`, `redis`, `storage`). Only an admin's
|
|
2052
2154
|
* `GET /machines?all=1` lists such boxes, so a host's boxes add up; every other listing hides them.
|
|
2053
2155
|
*/
|
|
2054
|
-
managed:
|
|
2156
|
+
managed: z6.string().optional(),
|
|
2055
2157
|
/** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
|
|
2056
|
-
autoHibernateSec:
|
|
2158
|
+
autoHibernateSec: z6.number().int().positive().optional(),
|
|
2057
2159
|
/** A script inside the box that says it is idle (#102, exit 0): auto-hibernate asks it instead of watching the traffic. */
|
|
2058
|
-
idleCheck:
|
|
2160
|
+
idleCheck: z6.string().optional(),
|
|
2059
2161
|
/** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */
|
|
2060
|
-
volumes:
|
|
2162
|
+
volumes: z6.array(z6.object({ name: z6.string(), sizeGib: z6.number().int(), mountPath: z6.string() })).optional(),
|
|
2061
2163
|
/** Boxes that may reach this one, each on one port (#98). Absent: none. */
|
|
2062
|
-
links:
|
|
2164
|
+
links: z6.array(BoxLinkSchema).optional(),
|
|
2165
|
+
/**
|
|
2166
|
+
* The integrations turned on for the box (#205, `github`): names only, the credential is fetched by the box
|
|
2167
|
+
* each time it is needed. Absent: none. A host before integrations never sends it.
|
|
2168
|
+
*/
|
|
2169
|
+
integrations: z6.array(z6.string()).optional(),
|
|
2063
2170
|
/** How to reach what the box serves, its secrets masked (#87): `postgres://postgres:****@db.kvbox:5432/postgres`. */
|
|
2064
|
-
url:
|
|
2171
|
+
url: z6.string().optional(),
|
|
2065
2172
|
/**
|
|
2066
2173
|
* Only in what `POST /machines` answers, for an image that declares one (#87): how to reach what it
|
|
2067
2174
|
* serves, e.g. `postgres://postgres:<password>@db.kvbox:5432/postgres`. Holds the box's variables.
|
|
2068
2175
|
*/
|
|
2069
|
-
connect:
|
|
2176
|
+
connect: z6.string().optional()
|
|
2070
2177
|
});
|
|
2071
|
-
var VolumeSchema =
|
|
2178
|
+
var VolumeSchema = z6.object({
|
|
2072
2179
|
/** The host's 6-hex volume id (#91): the ledger's key, so a name removed and made again is two volumes. */
|
|
2073
|
-
id:
|
|
2074
|
-
name:
|
|
2075
|
-
owner:
|
|
2076
|
-
sizeGib:
|
|
2180
|
+
id: z6.string(),
|
|
2181
|
+
name: z6.string(),
|
|
2182
|
+
owner: z6.string(),
|
|
2183
|
+
sizeGib: z6.number().int(),
|
|
2077
2184
|
/** What the sparse file really occupies on the host. */
|
|
2078
|
-
usedBytes:
|
|
2079
|
-
attachedTo:
|
|
2080
|
-
createdAt:
|
|
2185
|
+
usedBytes: z6.number().int(),
|
|
2186
|
+
attachedTo: z6.string().nullable(),
|
|
2187
|
+
createdAt: z6.string(),
|
|
2081
2188
|
/** Whether the owner slug is a user or an org. Only the control plane knows; it fills it in on `GET /volumes`. */
|
|
2082
|
-
ownerKind:
|
|
2189
|
+
ownerKind: z6.enum(["user", "org"]).optional(),
|
|
2083
2190
|
/** The name of the host the volume lives on; only the control plane fills it in. It attaches only to a box there. */
|
|
2084
|
-
host:
|
|
2191
|
+
host: z6.string().optional()
|
|
2085
2192
|
});
|
|
2086
2193
|
var MAX_VOLUME_GIB = 4096;
|
|
2087
2194
|
var VOLUME_NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
|
|
2088
2195
|
var VOLUME_NAME_RULE = "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit";
|
|
2089
|
-
var CreateVolumeRequest =
|
|
2090
|
-
name:
|
|
2091
|
-
sizeGib:
|
|
2196
|
+
var CreateVolumeRequest = z6.object({
|
|
2197
|
+
name: z6.string(),
|
|
2198
|
+
sizeGib: z6.number().int().min(1).max(MAX_VOLUME_GIB),
|
|
2092
2199
|
/**
|
|
2093
2200
|
* Through a control plane (#91): the box this volume is for, so it is made on that box's host; the
|
|
2094
2201
|
* control plane requires it (a volume attaches only to a box on its own host, so one made for no box
|
|
2095
2202
|
* could never attach) and the CLI attaches right after. A host ignores it.
|
|
2096
2203
|
*/
|
|
2097
|
-
box:
|
|
2204
|
+
box: z6.string().optional()
|
|
2098
2205
|
});
|
|
2099
|
-
var AttachVolumeRequest =
|
|
2100
|
-
box:
|
|
2206
|
+
var AttachVolumeRequest = z6.object({
|
|
2207
|
+
box: z6.string()
|
|
2101
2208
|
});
|
|
2102
|
-
var ResizeVolumeRequest =
|
|
2103
|
-
sizeGib:
|
|
2209
|
+
var ResizeVolumeRequest = z6.object({
|
|
2210
|
+
sizeGib: z6.number().int().min(1).max(MAX_VOLUME_GIB)
|
|
2104
2211
|
});
|
|
2105
|
-
var RunScriptRequest =
|
|
2106
|
-
var ScriptOutputSchema =
|
|
2212
|
+
var RunScriptRequest = z6.object({ input: z6.unknown().optional() });
|
|
2213
|
+
var ScriptOutputSchema = z6.object({ output: z6.unknown() });
|
|
2107
2214
|
var BOX_RUN_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
2108
|
-
var StartRunRequest =
|
|
2109
|
-
id:
|
|
2110
|
-
command:
|
|
2215
|
+
var StartRunRequest = z6.object({
|
|
2216
|
+
id: z6.string().regex(BOX_RUN_ID_RE),
|
|
2217
|
+
command: z6.string().min(1).max(8192),
|
|
2111
2218
|
/** The command and everything it started are killed after this long. */
|
|
2112
|
-
timeoutSec:
|
|
2219
|
+
timeoutSec: z6.number().int().min(1).max(86400),
|
|
2113
2220
|
/**
|
|
2114
2221
|
* The caller will read the output back (`exec`, #188): the box's kvbox-agent must know `runOutput`
|
|
2115
2222
|
* (base v0.16.0+), which the host checks before the command starts, so an older box is `box-outdated`
|
|
2116
2223
|
* without having run anything.
|
|
2117
2224
|
*/
|
|
2118
|
-
output:
|
|
2225
|
+
output: z6.boolean().optional()
|
|
2119
2226
|
});
|
|
2120
|
-
var StartRunAnswerSchema =
|
|
2121
|
-
id:
|
|
2227
|
+
var StartRunAnswerSchema = z6.object({
|
|
2228
|
+
id: z6.string(),
|
|
2122
2229
|
/** False: a run of this id was already there. */
|
|
2123
|
-
started:
|
|
2230
|
+
started: z6.boolean(),
|
|
2124
2231
|
/** The box was asleep and this request woke it. */
|
|
2125
|
-
woke:
|
|
2232
|
+
woke: z6.boolean()
|
|
2126
2233
|
});
|
|
2127
2234
|
var BOX_RUN_STATES = ["running", "exited", "timeout", "unknown"];
|
|
2128
|
-
var BoxRunSchema =
|
|
2129
|
-
id:
|
|
2130
|
-
state:
|
|
2235
|
+
var BoxRunSchema = z6.object({
|
|
2236
|
+
id: z6.string(),
|
|
2237
|
+
state: z6.enum(BOX_RUN_STATES),
|
|
2131
2238
|
/** With `exited`; 128 + the signal for a command a signal ended. */
|
|
2132
|
-
exitCode:
|
|
2239
|
+
exitCode: z6.number().int().optional(),
|
|
2133
2240
|
/**
|
|
2134
2241
|
* With `exited` and `timeout`: how long the command itself ran, by the box's own clock (base v0.15.1
|
|
2135
2242
|
* and later). The asker learns of the end seconds late, so its own count is too long.
|
|
2136
2243
|
*/
|
|
2137
|
-
durationMs:
|
|
2244
|
+
durationMs: z6.number().int().nonnegative().optional()
|
|
2138
2245
|
});
|
|
2139
|
-
var RunRefusalSchema =
|
|
2246
|
+
var RunRefusalSchema = z6.object({ error: z6.string(), code: z6.string().optional() });
|
|
2140
2247
|
var RUN_OUTPUT_MAX_BYTES = 1 << 20;
|
|
2141
2248
|
var RUN_STREAMS = ["stdout", "stderr"];
|
|
2142
|
-
var RunOutputSchema =
|
|
2143
|
-
id:
|
|
2144
|
-
stream:
|
|
2145
|
-
offset:
|
|
2146
|
-
size:
|
|
2147
|
-
data:
|
|
2148
|
-
});
|
|
2149
|
-
var ExecRequest =
|
|
2150
|
-
command:
|
|
2249
|
+
var RunOutputSchema = z6.object({
|
|
2250
|
+
id: z6.string(),
|
|
2251
|
+
stream: z6.enum(RUN_STREAMS),
|
|
2252
|
+
offset: z6.number().int().nonnegative(),
|
|
2253
|
+
size: z6.number().int().nonnegative(),
|
|
2254
|
+
data: z6.string()
|
|
2255
|
+
});
|
|
2256
|
+
var ExecRequest = z6.object({
|
|
2257
|
+
command: z6.string().min(1).max(8192),
|
|
2151
2258
|
/** The command and everything it started are killed after this long (default DEFAULT_EXEC_TIMEOUT_SEC). */
|
|
2152
|
-
timeoutSec:
|
|
2259
|
+
timeoutSec: z6.number().int().min(1).max(86400).optional()
|
|
2153
2260
|
});
|
|
2154
|
-
var ExecStartSchema =
|
|
2155
|
-
id:
|
|
2261
|
+
var ExecStartSchema = z6.object({
|
|
2262
|
+
id: z6.string(),
|
|
2156
2263
|
/** The box was asleep and this request woke it. */
|
|
2157
|
-
woke:
|
|
2264
|
+
woke: z6.boolean()
|
|
2158
2265
|
});
|
|
2159
|
-
var ExecSchema =
|
|
2160
|
-
id:
|
|
2161
|
-
state:
|
|
2266
|
+
var ExecSchema = z6.object({
|
|
2267
|
+
id: z6.string(),
|
|
2268
|
+
state: z6.enum(BOX_RUN_STATES),
|
|
2162
2269
|
/** With `exited`; 128 + the signal for a command a signal ended. */
|
|
2163
|
-
exitCode:
|
|
2270
|
+
exitCode: z6.number().int().optional(),
|
|
2164
2271
|
/** With `exited` and `timeout`: how long the command itself ran. */
|
|
2165
|
-
durationMs:
|
|
2166
|
-
stdout:
|
|
2167
|
-
stderr:
|
|
2168
|
-
stdoutBytes:
|
|
2169
|
-
stderrBytes:
|
|
2170
|
-
truncated:
|
|
2171
|
-
});
|
|
2172
|
-
var EnvVarSchema =
|
|
2173
|
-
name:
|
|
2174
|
-
value:
|
|
2175
|
-
secret:
|
|
2176
|
-
updatedAt:
|
|
2177
|
-
});
|
|
2178
|
-
var BoxEnvSchema =
|
|
2179
|
-
box:
|
|
2180
|
-
vars:
|
|
2181
|
-
});
|
|
2182
|
-
var BoxEnvChangeSchema =
|
|
2183
|
-
box:
|
|
2184
|
-
name:
|
|
2272
|
+
durationMs: z6.number().int().nonnegative().optional(),
|
|
2273
|
+
stdout: z6.string().optional(),
|
|
2274
|
+
stderr: z6.string().optional(),
|
|
2275
|
+
stdoutBytes: z6.number().int().nonnegative().optional(),
|
|
2276
|
+
stderrBytes: z6.number().int().nonnegative().optional(),
|
|
2277
|
+
truncated: z6.boolean().optional()
|
|
2278
|
+
});
|
|
2279
|
+
var EnvVarSchema = z6.object({
|
|
2280
|
+
name: z6.string(),
|
|
2281
|
+
value: z6.string().optional(),
|
|
2282
|
+
secret: z6.boolean(),
|
|
2283
|
+
updatedAt: z6.string()
|
|
2284
|
+
});
|
|
2285
|
+
var BoxEnvSchema = z6.object({
|
|
2286
|
+
box: z6.string(),
|
|
2287
|
+
vars: z6.array(EnvVarSchema)
|
|
2288
|
+
});
|
|
2289
|
+
var BoxEnvChangeSchema = z6.object({
|
|
2290
|
+
box: z6.string(),
|
|
2291
|
+
name: z6.string(),
|
|
2185
2292
|
/** Whether the box is running now: the change waits for its next start. */
|
|
2186
|
-
running:
|
|
2293
|
+
running: z6.boolean()
|
|
2187
2294
|
});
|
|
2188
|
-
var SetEnvRequest =
|
|
2189
|
-
value:
|
|
2190
|
-
secret:
|
|
2295
|
+
var SetEnvRequest = z6.object({
|
|
2296
|
+
value: z6.string(),
|
|
2297
|
+
secret: z6.boolean().optional()
|
|
2191
2298
|
});
|
|
2192
|
-
var EnvChangeSchema =
|
|
2193
|
-
owner:
|
|
2194
|
-
name:
|
|
2195
|
-
boxes:
|
|
2299
|
+
var EnvChangeSchema = z6.object({
|
|
2300
|
+
owner: z6.string(),
|
|
2301
|
+
name: z6.string(),
|
|
2302
|
+
boxes: z6.number().int()
|
|
2196
2303
|
});
|
|
2197
|
-
var HostEnvRequest =
|
|
2198
|
-
version:
|
|
2199
|
-
vars:
|
|
2304
|
+
var HostEnvRequest = z6.object({
|
|
2305
|
+
version: z6.number().int().min(0),
|
|
2306
|
+
vars: z6.array(z6.object({ name: z6.string(), value: z6.string() }))
|
|
2200
2307
|
});
|
|
2201
|
-
var HostEnvVersionsSchema =
|
|
2202
|
-
var CreateMachineRequest =
|
|
2203
|
-
name:
|
|
2308
|
+
var HostEnvVersionsSchema = z6.array(z6.object({ owner: z6.string(), version: z6.number().int() }));
|
|
2309
|
+
var CreateMachineRequest = z6.object({
|
|
2310
|
+
name: z6.string().optional(),
|
|
2204
2311
|
/** Ignored over the local socket (the caller is the host owner); the control plane sets it over HTTPS. */
|
|
2205
|
-
owner:
|
|
2312
|
+
owner: z6.string().optional(),
|
|
2206
2313
|
size: SizeSchema.optional(),
|
|
2207
|
-
from:
|
|
2208
|
-
force:
|
|
2314
|
+
from: z6.string().optional(),
|
|
2315
|
+
force: z6.boolean().optional(),
|
|
2209
2316
|
/**
|
|
2210
2317
|
* Extra authorized_keys lines for the box, on top of the host's own key: the control plane sends
|
|
2211
2318
|
* its SSH CA as one `cert-authority …` line (#51). Written into the box's authorized_keys at every
|
|
2212
2319
|
* boot (#49); a host older than that ignores them.
|
|
2213
2320
|
*/
|
|
2214
|
-
sshKeys:
|
|
2321
|
+
sshKeys: z6.array(z6.string()).optional(),
|
|
2215
2322
|
/** Seconds without network traffic before the box is hibernated (#47); 0: never. Absent: the host's default. */
|
|
2216
|
-
autoHibernateSec:
|
|
2323
|
+
autoHibernateSec: z6.number().int().min(0).optional(),
|
|
2217
2324
|
/**
|
|
2218
2325
|
* Place the box on the host of this box (#98, `kvbox new --near`), so the two can be linked. Only the
|
|
2219
2326
|
* control plane reads it; a host has one place to put a box.
|
|
2220
2327
|
*/
|
|
2221
|
-
near:
|
|
2328
|
+
near: z6.string().optional(),
|
|
2222
2329
|
/**
|
|
2223
2330
|
* Place the box on a host in this country (`kvbox new --country romania`): a code or an English name,
|
|
2224
2331
|
* `@kvbox/shared/country`. Only the control plane reads it.
|
|
2225
2332
|
*/
|
|
2226
|
-
country:
|
|
2333
|
+
country: z6.string().optional(),
|
|
2227
2334
|
/**
|
|
2228
2335
|
* Place the box on the host of this name and nowhere else (`kvbox new --host kvbox2`, a hidden flag):
|
|
2229
2336
|
* an admin's, to try a host out. Only the control plane reads it, and refuses it from anyone else.
|
|
2230
2337
|
*/
|
|
2231
|
-
host:
|
|
2338
|
+
host: z6.string().optional(),
|
|
2232
2339
|
/** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */
|
|
2233
|
-
image:
|
|
2340
|
+
image: z6.string().optional(),
|
|
2234
2341
|
/** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
|
|
2235
|
-
env:
|
|
2342
|
+
env: z6.array(z6.object({ name: z6.string(), value: z6.string() })).optional(),
|
|
2236
2343
|
/**
|
|
2237
2344
|
* Start the box on this backup's disk (#141, `kvbox new --from-backup <id>`), a removed box's too: its image,
|
|
2238
2345
|
* version and variables come from the backup, its size too unless given. Only the control plane reads it.
|
|
2239
2346
|
*/
|
|
2240
|
-
fromBackup:
|
|
2347
|
+
fromBackup: z6.string().optional(),
|
|
2348
|
+
/**
|
|
2349
|
+
* The integrations turned on for the box (#205, `kvbox new --integration github`). Absent: none, or with
|
|
2350
|
+
* `from` / `fromBackup` the list the snapshot or the backup was taken with.
|
|
2351
|
+
*/
|
|
2352
|
+
integrations: IntegrationListSchema.optional()
|
|
2241
2353
|
});
|
|
2242
2354
|
var HostFromBackupRequest = CreateMachineRequest.omit({ from: true, fromBackup: true, image: true, env: true }).extend({ backup: HostRestoreRequest });
|
|
2243
|
-
var ForkMachineRequest =
|
|
2244
|
-
name:
|
|
2355
|
+
var ForkMachineRequest = z6.object({
|
|
2356
|
+
name: z6.string().optional(),
|
|
2245
2357
|
/**
|
|
2246
2358
|
* The new box's slug, bare (`acme`): the control plane sends the target of `--org` here; the host
|
|
2247
2359
|
* qualifies it with the caller's realm. Absent: the source's owner. A CLI leaves it out.
|
|
2248
2360
|
*/
|
|
2249
|
-
owner:
|
|
2361
|
+
owner: z6.string().optional(),
|
|
2250
2362
|
/** A cold fork only: a warm one keeps the source's vCPU and memory. */
|
|
2251
2363
|
size: SizeSchema.optional(),
|
|
2252
|
-
force:
|
|
2364
|
+
force: z6.boolean().optional(),
|
|
2253
2365
|
/** As in CreateMachineRequest: the control plane's CA line for the new box's owner. */
|
|
2254
|
-
sshKeys:
|
|
2255
|
-
autoHibernateSec:
|
|
2366
|
+
sshKeys: z6.array(z6.string()).optional(),
|
|
2367
|
+
autoHibernateSec: z6.number().int().min(0).optional()
|
|
2256
2368
|
});
|
|
2257
|
-
var SetSshKeysRequest =
|
|
2258
|
-
sshKeys:
|
|
2369
|
+
var SetSshKeysRequest = z6.object({
|
|
2370
|
+
sshKeys: z6.array(z6.string())
|
|
2259
2371
|
});
|
|
2260
|
-
var RescaleMachineRequest =
|
|
2372
|
+
var RescaleMachineRequest = z6.object({
|
|
2261
2373
|
size: SizeSchema.optional(),
|
|
2262
|
-
vcpu:
|
|
2263
|
-
memMib:
|
|
2264
|
-
diskGib:
|
|
2374
|
+
vcpu: z6.number().int().min(1).max(64).optional(),
|
|
2375
|
+
memMib: z6.number().int().min(256).optional(),
|
|
2376
|
+
diskGib: z6.number().int().min(1).optional(),
|
|
2265
2377
|
/** Skip the capacity guard when a running box grows (#37). */
|
|
2266
|
-
force:
|
|
2378
|
+
force: z6.boolean().optional()
|
|
2267
2379
|
});
|
|
2268
|
-
var StartMachineRequest =
|
|
2269
|
-
force:
|
|
2380
|
+
var StartMachineRequest = z6.object({
|
|
2381
|
+
force: z6.boolean().optional()
|
|
2270
2382
|
});
|
|
2271
|
-
var SetMachineRequest =
|
|
2383
|
+
var SetMachineRequest = z6.object({
|
|
2272
2384
|
/** Seconds without network traffic before the box is hibernated (#47); 0: never. */
|
|
2273
|
-
autoHibernateSec:
|
|
2385
|
+
autoHibernateSec: z6.number().int().min(0).optional(),
|
|
2274
2386
|
/** The box's idle check (#102): an absolute path to a script inside the box, exit 0 = idle; "": none, back to network traffic. */
|
|
2275
|
-
idleCheck:
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2387
|
+
idleCheck: z6.union([z6.literal(""), z6.string().max(255).regex(/^\/[^\0\n]*$/, "an absolute path inside the box")]).optional(),
|
|
2388
|
+
/** The box's integrations (#205), the whole list: `[]` turns every one off. Applies at once, in any state. */
|
|
2389
|
+
integrations: IntegrationListSchema.optional()
|
|
2390
|
+
});
|
|
2391
|
+
var SnapshotSchema = z6.object({
|
|
2392
|
+
name: z6.string(),
|
|
2393
|
+
owner: z6.string(),
|
|
2394
|
+
source: z6.string(),
|
|
2281
2395
|
// the box it was taken from, as owner/name
|
|
2282
|
-
base:
|
|
2396
|
+
base: z6.string(),
|
|
2283
2397
|
// version of the image the overlay stacks on; a restore needs the same one
|
|
2284
2398
|
/** As in MachineSchema: the image when it is not the base one (#87). */
|
|
2285
|
-
image:
|
|
2286
|
-
vcpu:
|
|
2287
|
-
memMib:
|
|
2288
|
-
sizeBytes:
|
|
2399
|
+
image: z6.string().optional(),
|
|
2400
|
+
vcpu: z6.number().int(),
|
|
2401
|
+
memMib: z6.number().int(),
|
|
2402
|
+
sizeBytes: z6.number().int(),
|
|
2289
2403
|
// what vmstate + mem + overlay really occupy on the host
|
|
2290
|
-
createdAt:
|
|
2404
|
+
createdAt: z6.string()
|
|
2291
2405
|
});
|
|
2292
|
-
var CreateSnapshotRequest =
|
|
2293
|
-
box:
|
|
2294
|
-
name:
|
|
2406
|
+
var CreateSnapshotRequest = z6.object({
|
|
2407
|
+
box: z6.string(),
|
|
2408
|
+
name: z6.string(),
|
|
2295
2409
|
/** Retake a snapshot under a name that exists (#83): the old one goes only once the new one is complete. */
|
|
2296
|
-
replace:
|
|
2297
|
-
});
|
|
2298
|
-
var DiskCapacitySchema =
|
|
2299
|
-
totalGib:
|
|
2300
|
-
freeGib:
|
|
2301
|
-
volumesGib:
|
|
2302
|
-
volumesUsedGib:
|
|
2303
|
-
headroomGib:
|
|
2304
|
-
});
|
|
2305
|
-
var CapacitySchema =
|
|
2306
|
-
hostMemMib:
|
|
2307
|
-
hostCores:
|
|
2308
|
-
reservedMemMib:
|
|
2309
|
-
reservedVcpu:
|
|
2310
|
-
running:
|
|
2410
|
+
replace: z6.boolean().optional()
|
|
2411
|
+
});
|
|
2412
|
+
var DiskCapacitySchema = z6.object({
|
|
2413
|
+
totalGib: z6.number().int(),
|
|
2414
|
+
freeGib: z6.number().int(),
|
|
2415
|
+
volumesGib: z6.number().int(),
|
|
2416
|
+
volumesUsedGib: z6.number().int(),
|
|
2417
|
+
headroomGib: z6.number().int()
|
|
2418
|
+
});
|
|
2419
|
+
var CapacitySchema = z6.object({
|
|
2420
|
+
hostMemMib: z6.number().int(),
|
|
2421
|
+
hostCores: z6.number().int(),
|
|
2422
|
+
reservedMemMib: z6.number().int(),
|
|
2423
|
+
reservedVcpu: z6.number().int(),
|
|
2424
|
+
running: z6.number().int(),
|
|
2311
2425
|
/**
|
|
2312
2426
|
* MiB of RAM the host keeps back from its boxes (config.json `memHeadroomMib`). Absent on a kvbox-server
|
|
2313
2427
|
* from before the setting, which keeps 2 GB (`OLD_HOST_MEM_HEADROOM_MIB`).
|
|
2314
2428
|
*/
|
|
2315
|
-
memHeadroomMib:
|
|
2429
|
+
memHeadroomMib: z6.number().int().optional(),
|
|
2316
2430
|
/** Absent on a host from before volumes (#91): it cannot take one. */
|
|
2317
2431
|
disk: DiskCapacitySchema.optional(),
|
|
2318
2432
|
/**
|
|
2319
2433
|
* The images a new box can be made from here (#87), with the version `new` uses; the base is `base`.
|
|
2320
2434
|
* Absent on a host from before images: it has only the base.
|
|
2321
2435
|
*/
|
|
2322
|
-
images:
|
|
2436
|
+
images: z6.array(z6.object({ name: z6.string(), version: z6.string() })).optional(),
|
|
2323
2437
|
/** kvbox-server's version, so the control plane's host list shows it without a call per host. Older servers omit it. */
|
|
2324
|
-
version:
|
|
2438
|
+
version: z6.string().optional(),
|
|
2325
2439
|
/** Present on a host set up as a backup store: the disk its Garage keeps chunks on, and whether Garage runs. */
|
|
2326
|
-
backupStore:
|
|
2440
|
+
backupStore: z6.object({ totalBytes: z6.number().int(), freeBytes: z6.number().int(), running: z6.boolean() }).optional(),
|
|
2327
2441
|
/** 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. */
|
|
2328
|
-
storeClient:
|
|
2442
|
+
storeClient: z6.boolean().optional(),
|
|
2329
2443
|
/** True on a kvbox-server with `POST /machines/from-backup` (#141, `kvbox new --from-backup`); older ones omit it. */
|
|
2330
|
-
fromBackup:
|
|
2444
|
+
fromBackup: z6.boolean().optional(),
|
|
2445
|
+
/** True on a kvbox-server that keeps a box's `integrations` (#205); an older one drops the field without a word. */
|
|
2446
|
+
integrations: z6.boolean().optional()
|
|
2331
2447
|
});
|
|
2332
|
-
var ImageSchema =
|
|
2333
|
-
var ImageIndexSchema =
|
|
2334
|
-
updatedAt:
|
|
2335
|
-
images:
|
|
2448
|
+
var ImageSchema = z6.object({ name: z6.string(), version: z6.string().nullable() });
|
|
2449
|
+
var ImageIndexSchema = z6.object({
|
|
2450
|
+
updatedAt: z6.string(),
|
|
2451
|
+
images: z6.record(z6.string(), z6.object({ version: z6.string().min(1), minServer: z6.string().min(1).optional() }))
|
|
2336
2452
|
});
|
|
2337
|
-
var LatestImagesSchema =
|
|
2338
|
-
updatedAt:
|
|
2453
|
+
var LatestImagesSchema = z6.object({
|
|
2454
|
+
updatedAt: z6.string().nullable(),
|
|
2339
2455
|
images: ImageIndexSchema.shape.images,
|
|
2340
|
-
checkedAt:
|
|
2341
|
-
});
|
|
2342
|
-
var RecoveryReportSchema =
|
|
2343
|
-
at:
|
|
2344
|
-
booted:
|
|
2345
|
-
leftStopped:
|
|
2346
|
-
failed:
|
|
2347
|
-
});
|
|
2348
|
-
var HostUpdateSchema =
|
|
2349
|
-
state:
|
|
2350
|
-
startedAt:
|
|
2351
|
-
finishedAt:
|
|
2456
|
+
checkedAt: z6.string().nullable()
|
|
2457
|
+
});
|
|
2458
|
+
var RecoveryReportSchema = z6.object({
|
|
2459
|
+
at: z6.string(),
|
|
2460
|
+
booted: z6.array(z6.string()),
|
|
2461
|
+
leftStopped: z6.array(z6.string()),
|
|
2462
|
+
failed: z6.array(z6.object({ box: z6.string(), error: z6.string() }))
|
|
2463
|
+
});
|
|
2464
|
+
var HostUpdateSchema = z6.object({
|
|
2465
|
+
state: z6.enum(["running", "done", "failed"]),
|
|
2466
|
+
startedAt: z6.string(),
|
|
2467
|
+
finishedAt: z6.string().nullable(),
|
|
2352
2468
|
/** kvbox-server's version when the update started, and when it ended (null while running or when it failed before). */
|
|
2353
|
-
from:
|
|
2354
|
-
to:
|
|
2355
|
-
error:
|
|
2356
|
-
needsManual:
|
|
2357
|
-
});
|
|
2358
|
-
var HealthSchema =
|
|
2359
|
-
ok:
|
|
2360
|
-
version:
|
|
2361
|
-
pid:
|
|
2469
|
+
from: z6.string(),
|
|
2470
|
+
to: z6.string().nullable(),
|
|
2471
|
+
error: z6.string().nullable(),
|
|
2472
|
+
needsManual: z6.array(z6.string())
|
|
2473
|
+
});
|
|
2474
|
+
var HealthSchema = z6.object({
|
|
2475
|
+
ok: z6.literal(true),
|
|
2476
|
+
version: z6.string(),
|
|
2477
|
+
pid: z6.number().int(),
|
|
2362
2478
|
/** Base image version new boxes get (null when the host has no usable base image yet). */
|
|
2363
|
-
base:
|
|
2479
|
+
base: z6.string().nullable(),
|
|
2364
2480
|
/** Owner that boxes made over the local socket get (the Unix user running the server). */
|
|
2365
|
-
owner:
|
|
2481
|
+
owner: z6.string(),
|
|
2366
2482
|
/** The control plane this host joined (null when none). */
|
|
2367
|
-
controlPlane:
|
|
2483
|
+
controlPlane: z6.object({
|
|
2368
2484
|
/** Realm name, e.g. kvbox.sh. */
|
|
2369
|
-
name:
|
|
2370
|
-
url:
|
|
2485
|
+
name: z6.string(),
|
|
2486
|
+
url: z6.string(),
|
|
2371
2487
|
/** Where this host answers the control plane. */
|
|
2372
|
-
hostUrl:
|
|
2488
|
+
hostUrl: z6.string()
|
|
2373
2489
|
}).nullable(),
|
|
2374
2490
|
/** The relay this host reaches the internet through (#50); null when it has its own public address. Older servers omit it. */
|
|
2375
|
-
relay:
|
|
2376
|
-
name:
|
|
2491
|
+
relay: z6.object({
|
|
2492
|
+
name: z6.string(),
|
|
2377
2493
|
/** The public IP the relay owns for this host. */
|
|
2378
|
-
publicIp:
|
|
2494
|
+
publicIp: z6.string(),
|
|
2379
2495
|
/** The relay's WireGuard endpoint the tunnel dials. */
|
|
2380
|
-
endpoint:
|
|
2496
|
+
endpoint: z6.string(),
|
|
2381
2497
|
/** Times the server redialed the tunnel since it started, because the relay stopped answering. Older servers omit them. */
|
|
2382
|
-
restarts:
|
|
2383
|
-
lastRestartAt:
|
|
2498
|
+
restarts: z6.number().int().optional(),
|
|
2499
|
+
lastRestartAt: z6.string().nullable().optional()
|
|
2384
2500
|
}).nullable().optional(),
|
|
2385
2501
|
/** Boxes brought back at the server's last start; null when there were none or it is still at it. Older servers omit it. */
|
|
2386
2502
|
recovery: RecoveryReportSchema.nullable().optional(),
|
|
2387
2503
|
/** The last self-update; null when none ran. Older servers omit it. */
|
|
2388
2504
|
update: HostUpdateSchema.nullable().optional()
|
|
2389
2505
|
});
|
|
2390
|
-
var MachineUsageSchema =
|
|
2391
|
-
name:
|
|
2392
|
-
owner:
|
|
2506
|
+
var MachineUsageSchema = z6.object({
|
|
2507
|
+
name: z6.string(),
|
|
2508
|
+
owner: z6.string(),
|
|
2393
2509
|
status: BoxStatusSchema,
|
|
2394
|
-
window:
|
|
2395
|
-
seconds:
|
|
2396
|
-
running:
|
|
2397
|
-
standby:
|
|
2398
|
-
hibernated:
|
|
2399
|
-
stopped:
|
|
2510
|
+
window: z6.object({ from: z6.string(), to: z6.string() }),
|
|
2511
|
+
seconds: z6.object({
|
|
2512
|
+
running: z6.number().int(),
|
|
2513
|
+
standby: z6.number().int(),
|
|
2514
|
+
hibernated: z6.number().int(),
|
|
2515
|
+
stopped: z6.number().int()
|
|
2400
2516
|
}),
|
|
2401
|
-
vcpuHours:
|
|
2402
|
-
ramGibHours:
|
|
2403
|
-
diskGibHours:
|
|
2404
|
-
cost:
|
|
2517
|
+
vcpuHours: z6.number(),
|
|
2518
|
+
ramGibHours: z6.number(),
|
|
2519
|
+
diskGibHours: z6.number(),
|
|
2520
|
+
cost: z6.object({ amount: z6.number(), currency: z6.string() }).optional(),
|
|
2405
2521
|
/** Stops the server did not witness (Firecracker died, host rebooted) and dated to when it noticed. */
|
|
2406
|
-
estimatedStops:
|
|
2407
|
-
historyFrom:
|
|
2522
|
+
estimatedStops: z6.number().int(),
|
|
2523
|
+
historyFrom: z6.string().nullable()
|
|
2408
2524
|
});
|
|
2409
|
-
var GuestStatsSchema =
|
|
2525
|
+
var GuestStatsSchema = z6.object({
|
|
2410
2526
|
/** Load average over 1, 5 and 15 minutes. */
|
|
2411
|
-
load:
|
|
2412
|
-
cpus:
|
|
2413
|
-
memTotalMib:
|
|
2527
|
+
load: z6.tuple([z6.number(), z6.number(), z6.number()]),
|
|
2528
|
+
cpus: z6.number().int(),
|
|
2529
|
+
memTotalMib: z6.number().int(),
|
|
2414
2530
|
/** Total minus available: page cache counts as free. */
|
|
2415
|
-
memUsedMib:
|
|
2531
|
+
memUsedMib: z6.number().int(),
|
|
2416
2532
|
/** The box's root, which is its overlay disk: the box's own writes, not the shared base. */
|
|
2417
|
-
diskTotalBytes:
|
|
2418
|
-
diskUsedBytes:
|
|
2419
|
-
uptimeSec:
|
|
2533
|
+
diskTotalBytes: z6.number().int(),
|
|
2534
|
+
diskUsedBytes: z6.number().int(),
|
|
2535
|
+
uptimeSec: z6.number().int()
|
|
2420
2536
|
});
|
|
2421
|
-
var MachineStatsSchema =
|
|
2422
|
-
name:
|
|
2423
|
-
owner:
|
|
2537
|
+
var MachineStatsSchema = z6.object({
|
|
2538
|
+
name: z6.string(),
|
|
2539
|
+
owner: z6.string(),
|
|
2424
2540
|
stats: GuestStatsSchema.nullable()
|
|
2425
2541
|
});
|
|
2426
|
-
var UsageStatusSchema =
|
|
2542
|
+
var UsageStatusSchema = z6.enum([...BoxStatusSchema.options, "removed"]);
|
|
2427
2543
|
var BoxUsageSchema = MachineUsageSchema.omit({ window: true, status: true }).extend({
|
|
2428
2544
|
/** The host's box id; a name removed and recreated appears twice, with two ids. */
|
|
2429
|
-
id:
|
|
2545
|
+
id: z6.string(),
|
|
2430
2546
|
status: UsageStatusSchema,
|
|
2431
2547
|
/** Through a control plane: whether the owner slug is a user's or an org's (what `kvbox ls` shows). */
|
|
2432
|
-
ownerKind:
|
|
2548
|
+
ownerKind: z6.enum(["user", "org"]).optional(),
|
|
2433
2549
|
/**
|
|
2434
2550
|
* Through a control plane: the username that made the box (#60), absent when the box is gone from
|
|
2435
2551
|
* the index (removed), was found by reconcile, or its maker was deleted. The ledger does not record it.
|
|
2436
2552
|
*/
|
|
2437
|
-
createdBy:
|
|
2553
|
+
createdBy: z6.string().optional()
|
|
2438
2554
|
});
|
|
2439
|
-
var VolumeUsageSchema =
|
|
2555
|
+
var VolumeUsageSchema = z6.object({
|
|
2440
2556
|
/** The host's volume id; a name removed and made again appears twice, with two ids. */
|
|
2441
|
-
id:
|
|
2442
|
-
name:
|
|
2443
|
-
owner:
|
|
2444
|
-
ownerKind:
|
|
2557
|
+
id: z6.string(),
|
|
2558
|
+
name: z6.string(),
|
|
2559
|
+
owner: z6.string(),
|
|
2560
|
+
ownerKind: z6.enum(["user", "org"]).optional(),
|
|
2445
2561
|
/** The size at the end of the window (or when removed). */
|
|
2446
|
-
sizeGib:
|
|
2447
|
-
status:
|
|
2448
|
-
volumeHours:
|
|
2449
|
-
volumeGibHours:
|
|
2450
|
-
cost:
|
|
2451
|
-
historyFrom:
|
|
2452
|
-
});
|
|
2453
|
-
var CronUsageSchema =
|
|
2454
|
-
id:
|
|
2455
|
-
name:
|
|
2456
|
-
owner:
|
|
2457
|
-
ownerKind:
|
|
2458
|
-
status:
|
|
2459
|
-
hours:
|
|
2460
|
-
cost:
|
|
2562
|
+
sizeGib: z6.number().int(),
|
|
2563
|
+
status: z6.enum(["present", "removed"]),
|
|
2564
|
+
volumeHours: z6.number(),
|
|
2565
|
+
volumeGibHours: z6.number(),
|
|
2566
|
+
cost: z6.object({ amount: z6.number(), currency: z6.string() }).optional(),
|
|
2567
|
+
historyFrom: z6.string().nullable()
|
|
2568
|
+
});
|
|
2569
|
+
var CronUsageSchema = z6.object({
|
|
2570
|
+
id: z6.string(),
|
|
2571
|
+
name: z6.string(),
|
|
2572
|
+
owner: z6.string(),
|
|
2573
|
+
ownerKind: z6.enum(["user", "org"]).optional(),
|
|
2574
|
+
status: z6.enum(["present", "removed"]),
|
|
2575
|
+
hours: z6.number(),
|
|
2576
|
+
cost: z6.object({ amount: z6.number(), currency: z6.string() }).optional(),
|
|
2461
2577
|
/** When it was made. */
|
|
2462
|
-
historyFrom:
|
|
2463
|
-
});
|
|
2464
|
-
var BackupUsageSchema =
|
|
2465
|
-
id:
|
|
2466
|
-
kind:
|
|
2467
|
-
name:
|
|
2468
|
-
owner:
|
|
2469
|
-
ownerKind:
|
|
2578
|
+
historyFrom: z6.string().nullable()
|
|
2579
|
+
});
|
|
2580
|
+
var BackupUsageSchema = z6.object({
|
|
2581
|
+
id: z6.string(),
|
|
2582
|
+
kind: z6.string(),
|
|
2583
|
+
name: z6.string(),
|
|
2584
|
+
owner: z6.string(),
|
|
2585
|
+
ownerKind: z6.enum(["user", "org"]).optional(),
|
|
2470
2586
|
/** How many paid backups turned ready in the window. */
|
|
2471
|
-
count:
|
|
2472
|
-
cost:
|
|
2587
|
+
count: z6.number().int(),
|
|
2588
|
+
cost: z6.object({ amount: z6.number(), currency: z6.string() })
|
|
2473
2589
|
});
|
|
2474
|
-
var UsageDayItemSchema =
|
|
2475
|
-
id:
|
|
2476
|
-
name:
|
|
2477
|
-
owner:
|
|
2590
|
+
var UsageDayItemSchema = z6.object({
|
|
2591
|
+
id: z6.string(),
|
|
2592
|
+
name: z6.string(),
|
|
2593
|
+
owner: z6.string(),
|
|
2478
2594
|
/** Removed by the end of the report's window. */
|
|
2479
|
-
removed:
|
|
2480
|
-
cost:
|
|
2595
|
+
removed: z6.boolean(),
|
|
2596
|
+
cost: z6.number()
|
|
2481
2597
|
});
|
|
2482
|
-
var UsageDaySchema =
|
|
2598
|
+
var UsageDaySchema = z6.object({
|
|
2483
2599
|
/** `YYYY-MM-DD`, UTC. */
|
|
2484
|
-
date:
|
|
2485
|
-
from:
|
|
2486
|
-
to:
|
|
2487
|
-
cost:
|
|
2488
|
-
currency:
|
|
2489
|
-
boxes:
|
|
2490
|
-
volumes:
|
|
2600
|
+
date: z6.string(),
|
|
2601
|
+
from: z6.string(),
|
|
2602
|
+
to: z6.string(),
|
|
2603
|
+
cost: z6.number(),
|
|
2604
|
+
currency: z6.string(),
|
|
2605
|
+
boxes: z6.array(UsageDayItemSchema),
|
|
2606
|
+
volumes: z6.array(UsageDayItemSchema),
|
|
2491
2607
|
/** Object storage that existed that day (#182); absent on a day without any. */
|
|
2492
|
-
storage:
|
|
2608
|
+
storage: z6.array(UsageDayItemSchema).optional(),
|
|
2493
2609
|
/** Cron services that existed that day (#190); absent on a day without any. */
|
|
2494
|
-
cron:
|
|
2610
|
+
cron: z6.array(UsageDayItemSchema).optional(),
|
|
2495
2611
|
/** Paid backups that turned ready that day, summed per thing backed up (`id` is `<owner>/<kind>:<name>`); absent on a day without any. */
|
|
2496
|
-
backups:
|
|
2612
|
+
backups: z6.array(UsageDayItemSchema).optional()
|
|
2497
2613
|
});
|
|
2498
|
-
var UsageReportSchema =
|
|
2499
|
-
window:
|
|
2500
|
-
boxes:
|
|
2614
|
+
var UsageReportSchema = z6.object({
|
|
2615
|
+
window: z6.object({ from: z6.string(), to: z6.string() }),
|
|
2616
|
+
boxes: z6.array(BoxUsageSchema),
|
|
2501
2617
|
/** Absent from a side older than #91. */
|
|
2502
|
-
volumes:
|
|
2618
|
+
volumes: z6.array(VolumeUsageSchema).optional(),
|
|
2503
2619
|
/**
|
|
2504
2620
|
* Object storage (#182, control plane only): one row per storage a slug has or had, shaped like a
|
|
2505
2621
|
* volume's. `volumeHours` are the hours it existed, `volumeGibHours` those of the GiB beyond the
|
|
2506
2622
|
* included ones, `sizeGib` its whole size. Absent when there is none.
|
|
2507
2623
|
*/
|
|
2508
|
-
storage:
|
|
2624
|
+
storage: z6.array(VolumeUsageSchema).optional(),
|
|
2509
2625
|
/** Cron services (#190, control plane only): one row per service a slug has or had. Absent when there is none. */
|
|
2510
|
-
cron:
|
|
2626
|
+
cron: z6.array(CronUsageSchema).optional(),
|
|
2511
2627
|
/** Paid backups (control plane only): one row per box, volume or service backed up by hand in the window. Absent when there is none. */
|
|
2512
|
-
backups:
|
|
2628
|
+
backups: z6.array(BackupUsageSchema).optional(),
|
|
2513
2629
|
/** With `?by=day` only, oldest day first. */
|
|
2514
|
-
days:
|
|
2515
|
-
totals:
|
|
2630
|
+
days: z6.array(UsageDaySchema).optional(),
|
|
2631
|
+
totals: z6.object({
|
|
2516
2632
|
seconds: MachineUsageSchema.shape.seconds,
|
|
2517
|
-
vcpuHours:
|
|
2518
|
-
ramGibHours:
|
|
2519
|
-
diskGibHours:
|
|
2520
|
-
volumeHours:
|
|
2521
|
-
volumeGibHours:
|
|
2633
|
+
vcpuHours: z6.number(),
|
|
2634
|
+
ramGibHours: z6.number(),
|
|
2635
|
+
diskGibHours: z6.number(),
|
|
2636
|
+
volumeHours: z6.number().optional(),
|
|
2637
|
+
volumeGibHours: z6.number().optional(),
|
|
2522
2638
|
/** Boxes, volumes, object storage, cron services and paid backups together. */
|
|
2523
|
-
cost:
|
|
2639
|
+
cost: z6.object({ amount: z6.number(), currency: z6.string() }).optional()
|
|
2524
2640
|
})
|
|
2525
2641
|
});
|
|
2526
|
-
var UsageEventRowSchema =
|
|
2527
|
-
id:
|
|
2528
|
-
boxId:
|
|
2529
|
-
owner:
|
|
2530
|
-
name:
|
|
2531
|
-
at:
|
|
2532
|
-
state:
|
|
2533
|
-
vcpu:
|
|
2534
|
-
memMib:
|
|
2535
|
-
diskGib:
|
|
2536
|
-
by:
|
|
2537
|
-
});
|
|
2538
|
-
var UsageEventsResponseSchema =
|
|
2539
|
-
ledger:
|
|
2540
|
-
events:
|
|
2541
|
-
next:
|
|
2542
|
-
});
|
|
2543
|
-
var VolumeEventRowSchema =
|
|
2544
|
-
id:
|
|
2545
|
-
volumeId:
|
|
2546
|
-
owner:
|
|
2547
|
-
name:
|
|
2548
|
-
at:
|
|
2549
|
-
sizeGib:
|
|
2550
|
-
by:
|
|
2551
|
-
});
|
|
2552
|
-
var VolumeEventsResponseSchema =
|
|
2553
|
-
ledger:
|
|
2554
|
-
events:
|
|
2555
|
-
next:
|
|
2642
|
+
var UsageEventRowSchema = z6.object({
|
|
2643
|
+
id: z6.number().int(),
|
|
2644
|
+
boxId: z6.string(),
|
|
2645
|
+
owner: z6.string(),
|
|
2646
|
+
name: z6.string(),
|
|
2647
|
+
at: z6.string(),
|
|
2648
|
+
state: z6.enum(["running", "standby", "hibernated", "stopped"]),
|
|
2649
|
+
vcpu: z6.number().int(),
|
|
2650
|
+
memMib: z6.number().int(),
|
|
2651
|
+
diskGib: z6.number().int(),
|
|
2652
|
+
by: z6.string()
|
|
2653
|
+
});
|
|
2654
|
+
var UsageEventsResponseSchema = z6.object({
|
|
2655
|
+
ledger: z6.string().min(1),
|
|
2656
|
+
events: z6.array(UsageEventRowSchema),
|
|
2657
|
+
next: z6.number().int()
|
|
2658
|
+
});
|
|
2659
|
+
var VolumeEventRowSchema = z6.object({
|
|
2660
|
+
id: z6.number().int(),
|
|
2661
|
+
volumeId: z6.string(),
|
|
2662
|
+
owner: z6.string(),
|
|
2663
|
+
name: z6.string(),
|
|
2664
|
+
at: z6.string(),
|
|
2665
|
+
sizeGib: z6.number().int(),
|
|
2666
|
+
by: z6.enum(["create", "resize", "rm"])
|
|
2667
|
+
});
|
|
2668
|
+
var VolumeEventsResponseSchema = z6.object({
|
|
2669
|
+
ledger: z6.string().min(1),
|
|
2670
|
+
events: z6.array(VolumeEventRowSchema),
|
|
2671
|
+
next: z6.number().int()
|
|
2556
2672
|
});
|
|
2557
2673
|
var API_ERROR_CODES = ["account-inactive", "org-inactive", "out-of-credit", "box-outdated", "storage-outdated", "object-exists", "storage-waking"];
|
|
2558
|
-
var ApiErrorCodeSchema =
|
|
2559
|
-
var ApiErrorSchema =
|
|
2560
|
-
error:
|
|
2674
|
+
var ApiErrorCodeSchema = z6.enum(API_ERROR_CODES);
|
|
2675
|
+
var ApiErrorSchema = z6.object({
|
|
2676
|
+
error: z6.string(),
|
|
2561
2677
|
code: ApiErrorCodeSchema.optional()
|
|
2562
2678
|
});
|
|
2563
2679
|
var ACTIVATED_BY = ["card", "admin"];
|
|
2564
|
-
var ActivatedBySchema =
|
|
2565
|
-
var CloudUserSchema =
|
|
2680
|
+
var ActivatedBySchema = z6.enum(ACTIVATED_BY);
|
|
2681
|
+
var CloudUserSchema = z6.object({
|
|
2566
2682
|
/** The handle: what hosts file boxes under (`<username>@<control plane>`). Lowercase, no `@` or `/`. */
|
|
2567
|
-
username:
|
|
2683
|
+
username: z6.string(),
|
|
2568
2684
|
/** Display name, free text ("Alexandru Ghiura"). */
|
|
2569
|
-
name:
|
|
2685
|
+
name: z6.string(),
|
|
2570
2686
|
/** Login identity, unique. */
|
|
2571
|
-
email:
|
|
2572
|
-
role:
|
|
2573
|
-
createdAt:
|
|
2687
|
+
email: z6.string(),
|
|
2688
|
+
role: z6.enum(["admin", "user"]),
|
|
2689
|
+
createdAt: z6.string(),
|
|
2574
2690
|
/**
|
|
2575
2691
|
* False until a card is on file or an admin activates the account (#74): then only `/me` and
|
|
2576
2692
|
* `/logout` answer. Admins are never gated. A control plane older than #74 does not send these and
|
|
2577
2693
|
* gates nobody, hence the defaults: a newer CLI must still parse its answers.
|
|
2578
2694
|
*/
|
|
2579
|
-
active:
|
|
2695
|
+
active: z6.boolean().default(true),
|
|
2580
2696
|
activatedBy: ActivatedBySchema.nullable().default(null),
|
|
2581
2697
|
/** When too many wrong passwords locked the account (#161); null when it is not locked. Older control planes omit it. */
|
|
2582
|
-
lockedAt:
|
|
2698
|
+
lockedAt: z6.string().nullable().default(null)
|
|
2583
2699
|
});
|
|
2584
2700
|
var ORG_ROLES = ["owner", "admin", "member"];
|
|
2585
|
-
var OrgRoleSchema =
|
|
2586
|
-
var CloudOrgSchema =
|
|
2587
|
-
slug:
|
|
2701
|
+
var OrgRoleSchema = z6.enum(ORG_ROLES);
|
|
2702
|
+
var CloudOrgSchema = z6.object({
|
|
2703
|
+
slug: z6.string(),
|
|
2588
2704
|
/** Display name; the slug never changes, this may. */
|
|
2589
|
-
name:
|
|
2590
|
-
createdAt:
|
|
2705
|
+
name: z6.string(),
|
|
2706
|
+
createdAt: z6.string(),
|
|
2591
2707
|
/** An org pays for itself (#74): off until it has a card or an admin activates it; its boxes are 402. Defaults as on CloudUser. */
|
|
2592
|
-
active:
|
|
2708
|
+
active: z6.boolean().default(true),
|
|
2593
2709
|
activatedBy: ActivatedBySchema.nullable().default(null)
|
|
2594
2710
|
});
|
|
2595
2711
|
var OrgMembershipSchema = CloudOrgSchema.extend({ role: OrgRoleSchema });
|
|
2596
|
-
var OrgMemberSchema =
|
|
2597
|
-
username:
|
|
2598
|
-
name:
|
|
2712
|
+
var OrgMemberSchema = z6.object({
|
|
2713
|
+
username: z6.string(),
|
|
2714
|
+
name: z6.string(),
|
|
2599
2715
|
role: OrgRoleSchema,
|
|
2600
|
-
addedAt:
|
|
2716
|
+
addedAt: z6.string()
|
|
2601
2717
|
});
|
|
2602
|
-
var OrgDetailSchema = CloudOrgSchema.extend({ members:
|
|
2603
|
-
var CreateOrgRequestSchema =
|
|
2604
|
-
slug:
|
|
2605
|
-
name:
|
|
2718
|
+
var OrgDetailSchema = CloudOrgSchema.extend({ members: z6.array(OrgMemberSchema) });
|
|
2719
|
+
var CreateOrgRequestSchema = z6.object({
|
|
2720
|
+
slug: z6.string().min(1),
|
|
2721
|
+
name: z6.string().min(1)
|
|
2606
2722
|
});
|
|
2607
|
-
var RenameOrgRequestSchema =
|
|
2608
|
-
var AddMemberRequestSchema =
|
|
2609
|
-
username:
|
|
2723
|
+
var RenameOrgRequestSchema = z6.object({ name: z6.string().min(1) });
|
|
2724
|
+
var AddMemberRequestSchema = z6.object({
|
|
2725
|
+
username: z6.string().min(1),
|
|
2610
2726
|
role: OrgRoleSchema.default("member")
|
|
2611
2727
|
});
|
|
2612
|
-
var SetRoleRequestSchema =
|
|
2613
|
-
var MeResponseSchema = CloudUserSchema.extend({ orgs:
|
|
2614
|
-
var BalanceSchema =
|
|
2615
|
-
slug:
|
|
2616
|
-
balance:
|
|
2617
|
-
currency:
|
|
2618
|
-
topUps:
|
|
2619
|
-
spent:
|
|
2728
|
+
var SetRoleRequestSchema = z6.object({ role: OrgRoleSchema });
|
|
2729
|
+
var MeResponseSchema = CloudUserSchema.extend({ orgs: z6.array(OrgMembershipSchema) });
|
|
2730
|
+
var BalanceSchema = z6.object({
|
|
2731
|
+
slug: z6.string(),
|
|
2732
|
+
balance: z6.number(),
|
|
2733
|
+
currency: z6.string(),
|
|
2734
|
+
topUps: z6.number(),
|
|
2735
|
+
spent: z6.number(),
|
|
2620
2736
|
/** The first moment usage counts from: the slug's first top-up or redeemed code; null when it has none. */
|
|
2621
|
-
since:
|
|
2737
|
+
since: z6.string().nullable(),
|
|
2622
2738
|
/** When the slug ran out and its boxes were hibernated (the `sweep-credit` job); null in good standing. Absent from a control plane older than this field. */
|
|
2623
|
-
suspendedAt:
|
|
2739
|
+
suspendedAt: z6.string().nullable().default(null),
|
|
2624
2740
|
/** Promo credit left (#163), already counted in `balance`; 0 with none. Absent from a control plane older than this field. */
|
|
2625
|
-
promo:
|
|
2741
|
+
promo: z6.number().default(0),
|
|
2626
2742
|
/** When the next promo credit expires; null with none left. */
|
|
2627
|
-
promoExpiresAt:
|
|
2743
|
+
promoExpiresAt: z6.string().nullable().default(null)
|
|
2628
2744
|
});
|
|
2629
|
-
var TopUpRequestSchema =
|
|
2630
|
-
slug:
|
|
2745
|
+
var TopUpRequestSchema = z6.object({
|
|
2746
|
+
slug: z6.string().min(1),
|
|
2631
2747
|
/** In the control plane's currency; negative corrects a mistake. */
|
|
2632
|
-
amount:
|
|
2633
|
-
note:
|
|
2634
|
-
});
|
|
2635
|
-
var TopUpSchema =
|
|
2636
|
-
id:
|
|
2637
|
-
slug:
|
|
2638
|
-
amount:
|
|
2639
|
-
currency:
|
|
2748
|
+
amount: z6.number().finite(),
|
|
2749
|
+
note: z6.string().max(200).optional()
|
|
2750
|
+
});
|
|
2751
|
+
var TopUpSchema = z6.object({
|
|
2752
|
+
id: z6.string(),
|
|
2753
|
+
slug: z6.string(),
|
|
2754
|
+
amount: z6.number(),
|
|
2755
|
+
currency: z6.string(),
|
|
2640
2756
|
/** `transfer` (#93): an owner moving credit to an org they own, a negative row on their slug and a positive one on the org's. */
|
|
2641
|
-
source:
|
|
2642
|
-
note:
|
|
2643
|
-
at:
|
|
2757
|
+
source: z6.enum(["admin", "card", "trial", "transfer"]),
|
|
2758
|
+
note: z6.string().nullable(),
|
|
2759
|
+
at: z6.string()
|
|
2644
2760
|
});
|
|
2645
|
-
var CreateCodeRequestSchema =
|
|
2761
|
+
var CreateCodeRequestSchema = z6.object({
|
|
2646
2762
|
/** In the control plane's currency, cents at most. */
|
|
2647
|
-
amount:
|
|
2763
|
+
amount: z6.number().positive().multipleOf(0.01, "amount is in cents at most"),
|
|
2648
2764
|
/** A day (`2026-12-11`, through the end of it, UTC) or an ISO time. The credit is gone then, and so is the code. */
|
|
2649
|
-
expiresAt:
|
|
2650
|
-
note:
|
|
2651
|
-
});
|
|
2652
|
-
var CreditCodeSchema =
|
|
2653
|
-
code:
|
|
2654
|
-
amount:
|
|
2655
|
-
currency:
|
|
2656
|
-
expiresAt:
|
|
2657
|
-
note:
|
|
2658
|
-
status:
|
|
2659
|
-
createdBy:
|
|
2660
|
-
createdAt:
|
|
2765
|
+
expiresAt: z6.string().min(1),
|
|
2766
|
+
note: z6.string().max(200).optional()
|
|
2767
|
+
});
|
|
2768
|
+
var CreditCodeSchema = z6.object({
|
|
2769
|
+
code: z6.string(),
|
|
2770
|
+
amount: z6.number(),
|
|
2771
|
+
currency: z6.string(),
|
|
2772
|
+
expiresAt: z6.string(),
|
|
2773
|
+
note: z6.string().nullable(),
|
|
2774
|
+
status: z6.enum(["unused", "redeemed", "expired", "revoked"]),
|
|
2775
|
+
createdBy: z6.string(),
|
|
2776
|
+
createdAt: z6.string(),
|
|
2661
2777
|
/** Who redeemed it and the slug the credit went to (their own, or an org they own). */
|
|
2662
|
-
redeemedBy:
|
|
2663
|
-
redeemedSlug:
|
|
2664
|
-
redeemedAt:
|
|
2665
|
-
revokedAt:
|
|
2666
|
-
});
|
|
2667
|
-
var RedeemRequestSchema =
|
|
2668
|
-
code:
|
|
2669
|
-
org:
|
|
2670
|
-
});
|
|
2671
|
-
var RedeemResponseSchema =
|
|
2672
|
-
slug:
|
|
2673
|
-
amount:
|
|
2674
|
-
currency:
|
|
2675
|
-
expiresAt:
|
|
2778
|
+
redeemedBy: z6.string().nullable(),
|
|
2779
|
+
redeemedSlug: z6.string().nullable(),
|
|
2780
|
+
redeemedAt: z6.string().nullable(),
|
|
2781
|
+
revokedAt: z6.string().nullable()
|
|
2782
|
+
});
|
|
2783
|
+
var RedeemRequestSchema = z6.object({
|
|
2784
|
+
code: z6.string().min(1).max(64),
|
|
2785
|
+
org: z6.string().min(1).optional()
|
|
2786
|
+
});
|
|
2787
|
+
var RedeemResponseSchema = z6.object({
|
|
2788
|
+
slug: z6.string(),
|
|
2789
|
+
amount: z6.number(),
|
|
2790
|
+
currency: z6.string(),
|
|
2791
|
+
expiresAt: z6.string(),
|
|
2676
2792
|
balance: BalanceSchema,
|
|
2677
2793
|
/** The slug was out of credit and this put it back above zero: it may start boxes again. */
|
|
2678
|
-
reinstated:
|
|
2794
|
+
reinstated: z6.boolean()
|
|
2679
2795
|
});
|
|
2680
2796
|
var TOP_UP_AMOUNTS = [10, 25, 50, 100];
|
|
2681
|
-
var BillingInfoSchema =
|
|
2682
|
-
card:
|
|
2683
|
-
cardInUse:
|
|
2797
|
+
var BillingInfoSchema = z6.object({
|
|
2798
|
+
card: z6.object({ brand: z6.string(), last4: z6.string() }).nullable(),
|
|
2799
|
+
cardInUse: z6.boolean(),
|
|
2684
2800
|
balance: BalanceSchema
|
|
2685
2801
|
});
|
|
2686
|
-
var BillingRedirectSchema =
|
|
2687
|
-
var TopUpCheckoutRequestSchema =
|
|
2688
|
-
amount:
|
|
2802
|
+
var BillingRedirectSchema = z6.object({ url: z6.string() });
|
|
2803
|
+
var TopUpCheckoutRequestSchema = z6.object({
|
|
2804
|
+
amount: z6.literal(TOP_UP_AMOUNTS)
|
|
2689
2805
|
});
|
|
2690
|
-
var TransferRequestSchema =
|
|
2691
|
-
org:
|
|
2692
|
-
amount:
|
|
2806
|
+
var TransferRequestSchema = z6.object({
|
|
2807
|
+
org: z6.string().min(1),
|
|
2808
|
+
amount: z6.number().positive().multipleOf(0.01, "amount is in cents at most")
|
|
2693
2809
|
});
|
|
2694
|
-
var TransferResponseSchema =
|
|
2695
|
-
var LoginRequestSchema =
|
|
2696
|
-
email:
|
|
2697
|
-
password:
|
|
2698
|
-
publicKey:
|
|
2810
|
+
var TransferResponseSchema = z6.object({ from: BalanceSchema, to: BalanceSchema, activated: z6.boolean() });
|
|
2811
|
+
var LoginRequestSchema = z6.object({
|
|
2812
|
+
email: z6.string().min(1),
|
|
2813
|
+
password: z6.string().min(1),
|
|
2814
|
+
publicKey: z6.string().optional()
|
|
2699
2815
|
});
|
|
2700
|
-
var SignupRequestSchema =
|
|
2701
|
-
username:
|
|
2702
|
-
name:
|
|
2703
|
-
email:
|
|
2704
|
-
password:
|
|
2816
|
+
var SignupRequestSchema = z6.object({
|
|
2817
|
+
username: z6.string().min(1),
|
|
2818
|
+
name: z6.string().min(1),
|
|
2819
|
+
email: z6.string().min(1),
|
|
2820
|
+
password: z6.string().min(1)
|
|
2705
2821
|
});
|
|
2706
|
-
var LoginResponseSchema =
|
|
2707
|
-
token:
|
|
2822
|
+
var LoginResponseSchema = z6.object({
|
|
2823
|
+
token: z6.string(),
|
|
2708
2824
|
user: CloudUserSchema,
|
|
2709
|
-
sshCert:
|
|
2710
|
-
sshCertExpires:
|
|
2825
|
+
sshCert: z6.string().optional(),
|
|
2826
|
+
sshCertExpires: z6.string().optional(),
|
|
2711
2827
|
/** Whose boxes the certificate opens: `<slug>@<realm>` for the user and each org they are in (orgs phase 4). */
|
|
2712
|
-
sshCertPrincipals:
|
|
2828
|
+
sshCertPrincipals: z6.array(z6.string()).optional()
|
|
2713
2829
|
});
|
|
2714
|
-
var DeviceLoginRequestSchema =
|
|
2830
|
+
var DeviceLoginRequestSchema = z6.object({
|
|
2715
2831
|
// Capped: anyone may open a login, and the key is stored until it expires (an RSA-16384 key is ~2.8 KB).
|
|
2716
|
-
publicKey:
|
|
2717
|
-
hostname:
|
|
2718
|
-
});
|
|
2719
|
-
var DeviceLoginStartSchema =
|
|
2720
|
-
deviceCode:
|
|
2721
|
-
userCode:
|
|
2722
|
-
verifyUrl:
|
|
2723
|
-
expiresIn:
|
|
2724
|
-
interval:
|
|
2725
|
-
});
|
|
2726
|
-
var DeviceLoginPollRequestSchema =
|
|
2727
|
-
var DeviceLoginPollSchema =
|
|
2728
|
-
|
|
2729
|
-
LoginResponseSchema.extend({ status:
|
|
2832
|
+
publicKey: z6.string().max(16384).optional(),
|
|
2833
|
+
hostname: z6.string().max(255).optional()
|
|
2834
|
+
});
|
|
2835
|
+
var DeviceLoginStartSchema = z6.object({
|
|
2836
|
+
deviceCode: z6.string(),
|
|
2837
|
+
userCode: z6.string(),
|
|
2838
|
+
verifyUrl: z6.string(),
|
|
2839
|
+
expiresIn: z6.number(),
|
|
2840
|
+
interval: z6.number()
|
|
2841
|
+
});
|
|
2842
|
+
var DeviceLoginPollRequestSchema = z6.object({ deviceCode: z6.string().min(1) });
|
|
2843
|
+
var DeviceLoginPollSchema = z6.union([
|
|
2844
|
+
z6.object({ status: z6.enum(["pending", "slow_down", "refused", "expired"]) }),
|
|
2845
|
+
LoginResponseSchema.extend({ status: z6.literal("approved") })
|
|
2730
2846
|
]);
|
|
2731
|
-
var DeviceLoginInfoSchema =
|
|
2732
|
-
userCode:
|
|
2733
|
-
hostname:
|
|
2847
|
+
var DeviceLoginInfoSchema = z6.object({
|
|
2848
|
+
userCode: z6.string(),
|
|
2849
|
+
hostname: z6.string(),
|
|
2734
2850
|
/** The address the request came from; null when the control plane could not tell. */
|
|
2735
|
-
ip:
|
|
2736
|
-
createdAt:
|
|
2737
|
-
expiresAt:
|
|
2851
|
+
ip: z6.string().nullable(),
|
|
2852
|
+
createdAt: z6.string(),
|
|
2853
|
+
expiresAt: z6.string()
|
|
2738
2854
|
});
|
|
2739
2855
|
var API_KEY_NAME_RE = /^[a-z0-9][a-z0-9._-]{0,31}$/;
|
|
2740
|
-
var ApiKeySchema =
|
|
2741
|
-
name:
|
|
2742
|
-
createdAt:
|
|
2856
|
+
var ApiKeySchema = z6.object({
|
|
2857
|
+
name: z6.string(),
|
|
2858
|
+
createdAt: z6.string(),
|
|
2743
2859
|
/** Last request made with it (ISO); null: never used. */
|
|
2744
|
-
lastUsedAt:
|
|
2860
|
+
lastUsedAt: z6.string().nullable(),
|
|
2745
2861
|
/** When it stops working (ISO); null: never. */
|
|
2746
|
-
expiresAt:
|
|
2862
|
+
expiresAt: z6.string().nullable()
|
|
2747
2863
|
});
|
|
2748
|
-
var CreateApiKeyRequestSchema =
|
|
2749
|
-
name:
|
|
2750
|
-
expiresAt:
|
|
2864
|
+
var CreateApiKeyRequestSchema = z6.object({
|
|
2865
|
+
name: z6.string().regex(API_KEY_NAME_RE, "a key's name is lowercase letters, digits, '.', '_' or '-' (up to 32 characters)"),
|
|
2866
|
+
expiresAt: z6.iso.datetime({ offset: true }).nullable().optional()
|
|
2751
2867
|
});
|
|
2752
|
-
var CreatedApiKeySchema = ApiKeySchema.extend({ key:
|
|
2753
|
-
var SshCertRequestSchema =
|
|
2754
|
-
publicKey:
|
|
2868
|
+
var CreatedApiKeySchema = ApiKeySchema.extend({ key: z6.string() });
|
|
2869
|
+
var SshCertRequestSchema = z6.object({
|
|
2870
|
+
publicKey: z6.string().min(1)
|
|
2755
2871
|
});
|
|
2756
|
-
var SshCertResponseSchema =
|
|
2757
|
-
cert:
|
|
2758
|
-
expires:
|
|
2759
|
-
principals:
|
|
2872
|
+
var SshCertResponseSchema = z6.object({
|
|
2873
|
+
cert: z6.string(),
|
|
2874
|
+
expires: z6.string(),
|
|
2875
|
+
principals: z6.array(z6.string())
|
|
2760
2876
|
});
|
|
2761
|
-
var SshCaResponseSchema =
|
|
2762
|
-
publicKey:
|
|
2877
|
+
var SshCaResponseSchema = z6.object({
|
|
2878
|
+
publicKey: z6.string(),
|
|
2763
2879
|
/** CAs replaced by `ca rotate` (#55), newest first; a box still holding one of these has not had `kvbox-server trust-ca` run on its host. */
|
|
2764
|
-
retired:
|
|
2880
|
+
retired: z6.array(z6.object({ publicKey: z6.string(), retiredAt: z6.string() })).optional()
|
|
2765
2881
|
});
|
|
2766
|
-
var HostSshCaResponseSchema =
|
|
2767
|
-
publicKey:
|
|
2882
|
+
var HostSshCaResponseSchema = z6.object({
|
|
2883
|
+
publicKey: z6.string()
|
|
2768
2884
|
});
|
|
2769
|
-
var CloudCaSchema =
|
|
2770
|
-
controlPlane:
|
|
2771
|
-
publicKey:
|
|
2772
|
-
fingerprint:
|
|
2885
|
+
var CloudCaSchema = z6.object({
|
|
2886
|
+
controlPlane: z6.string(),
|
|
2887
|
+
publicKey: z6.string(),
|
|
2888
|
+
fingerprint: z6.string()
|
|
2773
2889
|
});
|
|
2774
|
-
var TrustCaRequestSchema =
|
|
2775
|
-
publicKey:
|
|
2890
|
+
var TrustCaRequestSchema = z6.object({
|
|
2891
|
+
publicKey: z6.string().min(1)
|
|
2776
2892
|
});
|
|
2777
|
-
var SshKeysAppliedSchema =
|
|
2778
|
-
var TrustCaReportSchema =
|
|
2779
|
-
publicKey:
|
|
2780
|
-
fingerprint:
|
|
2893
|
+
var SshKeysAppliedSchema = z6.enum(["now", "start", "wake", "resume", "later"]);
|
|
2894
|
+
var TrustCaReportSchema = z6.object({
|
|
2895
|
+
publicKey: z6.string(),
|
|
2896
|
+
fingerprint: z6.string(),
|
|
2781
2897
|
/** The guest trusts the CA now. */
|
|
2782
|
-
updated:
|
|
2898
|
+
updated: z6.array(z6.string()),
|
|
2783
2899
|
/** meta.json has the line; the guest gets it at `when`. */
|
|
2784
|
-
pending:
|
|
2785
|
-
failed:
|
|
2900
|
+
pending: z6.array(z6.object({ box: z6.string(), when: SshKeysAppliedSchema, why: z6.string().optional() })),
|
|
2901
|
+
failed: z6.array(z6.object({ box: z6.string(), error: z6.string() })),
|
|
2786
2902
|
/** Local boxes, untouched: they trust the host's key only. */
|
|
2787
|
-
local:
|
|
2903
|
+
local: z6.number().int(),
|
|
2788
2904
|
/** Cloud boxes made without a CA line (a managed service's, #173), untouched: no certificate opens them. Absent from older servers. */
|
|
2789
|
-
skipped:
|
|
2790
|
-
});
|
|
2791
|
-
var HostJoinRequestSchema =
|
|
2792
|
-
token:
|
|
2793
|
-
name:
|
|
2794
|
-
url:
|
|
2795
|
-
fingerprint:
|
|
2796
|
-
publicAddress:
|
|
2905
|
+
skipped: z6.array(z6.string()).optional()
|
|
2906
|
+
});
|
|
2907
|
+
var HostJoinRequestSchema = z6.object({
|
|
2908
|
+
token: z6.string().min(1),
|
|
2909
|
+
name: z6.string().min(1),
|
|
2910
|
+
url: z6.string().url(),
|
|
2911
|
+
fingerprint: z6.string().regex(/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/),
|
|
2912
|
+
publicAddress: z6.string().min(1),
|
|
2797
2913
|
/** Where the host is (`kvbox-server join --country`): a code or an English name. */
|
|
2798
|
-
country:
|
|
2799
|
-
});
|
|
2800
|
-
var HostJoinResponseSchema =
|
|
2801
|
-
hostSecret:
|
|
2802
|
-
controlPlane:
|
|
2803
|
-
});
|
|
2804
|
-
var CloudHostSchema =
|
|
2805
|
-
name:
|
|
2806
|
-
url:
|
|
2807
|
-
publicAddress:
|
|
2808
|
-
joinedAt:
|
|
2809
|
-
lastSeenAt:
|
|
2914
|
+
country: z6.string().optional()
|
|
2915
|
+
});
|
|
2916
|
+
var HostJoinResponseSchema = z6.object({
|
|
2917
|
+
hostSecret: z6.string(),
|
|
2918
|
+
controlPlane: z6.object({ name: z6.string() })
|
|
2919
|
+
});
|
|
2920
|
+
var CloudHostSchema = z6.object({
|
|
2921
|
+
name: z6.string(),
|
|
2922
|
+
url: z6.string(),
|
|
2923
|
+
publicAddress: z6.string(),
|
|
2924
|
+
joinedAt: z6.string(),
|
|
2925
|
+
lastSeenAt: z6.string().nullable(),
|
|
2810
2926
|
capacity: CapacitySchema.nullable(),
|
|
2811
2927
|
/** ISO 3166-1 alpha-2 code (`RO`), null when nobody said where the host is. */
|
|
2812
|
-
country:
|
|
2928
|
+
country: z6.string().nullable(),
|
|
2813
2929
|
/** The S3 region a storage made on this host answers to (`ro-west-1`); null: it takes no storage. */
|
|
2814
|
-
region:
|
|
2930
|
+
region: z6.string().nullable(),
|
|
2815
2931
|
/** kvbox-server's version as of the poller's last look (`capacity.version`); null before one, or for a server older than 0.5.45. */
|
|
2816
|
-
version:
|
|
2932
|
+
version: z6.string().nullable()
|
|
2817
2933
|
});
|
|
2818
|
-
var HostInfoSchema =
|
|
2934
|
+
var HostInfoSchema = z6.object({
|
|
2819
2935
|
host: CloudHostSchema,
|
|
2820
2936
|
health: HealthSchema.nullable(),
|
|
2821
|
-
error:
|
|
2937
|
+
error: z6.string().nullable()
|
|
2822
2938
|
});
|
|
2823
|
-
var HostPatchRequest =
|
|
2824
|
-
var CountrySchema =
|
|
2939
|
+
var HostPatchRequest = z6.object({ country: z6.string().nullable().optional(), region: z6.string().nullable().optional() }).refine((b) => b.country !== void 0 || b.region !== void 0, { message: "give country, region or both" });
|
|
2940
|
+
var CountrySchema = z6.object({ code: z6.string(), name: z6.string() });
|
|
2825
2941
|
|
|
2826
2942
|
// src/core/locks.ts
|
|
2827
2943
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
@@ -2851,6 +2967,9 @@ async function withLock(key, fn) {
|
|
|
2851
2967
|
if (tails.get(key) === tail) tails.delete(key);
|
|
2852
2968
|
}
|
|
2853
2969
|
}
|
|
2970
|
+
function outsideLocks(fn) {
|
|
2971
|
+
return held.exit(fn);
|
|
2972
|
+
}
|
|
2854
2973
|
function boxBusy(ref) {
|
|
2855
2974
|
return tails.has(refKey(ref));
|
|
2856
2975
|
}
|
|
@@ -3454,7 +3573,9 @@ async function capacity(p = paths()) {
|
|
|
3454
3573
|
// Backups and restores here reach a store by its certificate's pin (core/storeFetch.ts).
|
|
3455
3574
|
storeClient: true,
|
|
3456
3575
|
// A new box on a backup's disk (#141): the control plane places `new --from-backup` only here.
|
|
3457
|
-
fromBackup: true
|
|
3576
|
+
fromBackup: true,
|
|
3577
|
+
// A box's integrations are kept here (#205): the control plane sends a list only to such a host.
|
|
3578
|
+
integrations: true
|
|
3458
3579
|
};
|
|
3459
3580
|
}
|
|
3460
3581
|
function gb(mib) {
|
|
@@ -3504,7 +3625,7 @@ async function assertRoomFor(vcpu, memMib, force, box, by, p = paths()) {
|
|
|
3504
3625
|
// src/core/env.ts
|
|
3505
3626
|
import { existsSync as existsSync7 } from "node:fs";
|
|
3506
3627
|
import { copyFile, mkdir as mkdir4, readFile as readFile7, readdir as readdir4, rename as rename4, writeFile as writeFile5 } from "node:fs/promises";
|
|
3507
|
-
import { z as
|
|
3628
|
+
import { z as z7 } from "zod";
|
|
3508
3629
|
|
|
3509
3630
|
// ../shared/src/env.ts
|
|
3510
3631
|
var ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
@@ -3524,10 +3645,10 @@ function envValueProblem(value) {
|
|
|
3524
3645
|
}
|
|
3525
3646
|
|
|
3526
3647
|
// src/core/env.ts
|
|
3527
|
-
var OwnerEnvSchema =
|
|
3648
|
+
var OwnerEnvSchema = z7.object({
|
|
3528
3649
|
/** The control plane's counter for the list; only ever grows. */
|
|
3529
|
-
version:
|
|
3530
|
-
vars:
|
|
3650
|
+
version: z7.number().int().min(0),
|
|
3651
|
+
vars: z7.array(z7.object({ name: z7.string(), value: z7.string() }))
|
|
3531
3652
|
});
|
|
3532
3653
|
async function readOwnerEnv(owner, p = paths()) {
|
|
3533
3654
|
try {
|
|
@@ -3548,8 +3669,8 @@ async function envForBoot(box, p = paths()) {
|
|
|
3548
3669
|
const mine = new Set(own.map((v) => v.name));
|
|
3549
3670
|
return [...(slug ?? []).filter((v) => !mine.has(v.name)), ...own.map((v) => ({ name: v.name, value: v.value }))];
|
|
3550
3671
|
}
|
|
3551
|
-
var BoxEnvFileSchema =
|
|
3552
|
-
vars:
|
|
3672
|
+
var BoxEnvFileSchema = z7.object({
|
|
3673
|
+
vars: z7.array(z7.object({ name: z7.string(), value: z7.string(), secret: z7.boolean(), updatedAt: z7.string() }))
|
|
3553
3674
|
});
|
|
3554
3675
|
async function readBoxEnv(box, p = paths()) {
|
|
3555
3676
|
return readBoxEnvFile(p.machine(box.owner, box.name).env);
|
|
@@ -3766,81 +3887,7 @@ function recordState(meta, state, by, p, at = (/* @__PURE__ */ new Date()).toISO
|
|
|
3766
3887
|
}
|
|
3767
3888
|
}
|
|
3768
3889
|
|
|
3769
|
-
// src/core/machines/
|
|
3770
|
-
import { existsSync as existsSync9 } from "node:fs";
|
|
3771
|
-
function isHibernated(meta, p) {
|
|
3772
|
-
return !vmAlive(meta) && existsSync9(p.machine(meta.owner, meta.name).hibernateVmstate);
|
|
3773
|
-
}
|
|
3774
|
-
function statusOf(meta, p = paths()) {
|
|
3775
|
-
if (vmAlive(meta)) return meta.paused ? "standby" : "running";
|
|
3776
|
-
return isHibernated(meta, p) ? "hibernated" : "stopped";
|
|
3777
|
-
}
|
|
3778
|
-
function stateMessage(ref, status) {
|
|
3779
|
-
return `box ${shown(ref)} is ${status === "standby" ? "in standby" : status}`;
|
|
3780
|
-
}
|
|
3781
|
-
function assertNotHibernated(meta, p) {
|
|
3782
|
-
if (isHibernated(meta, p)) {
|
|
3783
|
-
throw new KvboxError(`${stateMessage(meta, "hibernated")}; its memory image was made with its current shape and base: kvbox wake ${shown(meta)} first`);
|
|
3784
|
-
}
|
|
3785
|
-
}
|
|
3786
|
-
|
|
3787
|
-
// src/core/machines/list.ts
|
|
3788
|
-
function toMachine(meta, p = paths()) {
|
|
3789
|
-
const alive2 = vmAlive(meta);
|
|
3790
|
-
if (!alive2 && meta.pid !== null) {
|
|
3791
|
-
try {
|
|
3792
|
-
closeOpenRun(meta.id, (/* @__PURE__ */ new Date()).toISOString(), p);
|
|
3793
|
-
} catch (err) {
|
|
3794
|
-
log.warn(`usage ledger: ${err.message}`);
|
|
3795
|
-
}
|
|
3796
|
-
}
|
|
3797
|
-
return {
|
|
3798
|
-
id: meta.id,
|
|
3799
|
-
name: meta.name,
|
|
3800
|
-
owner: meta.owner,
|
|
3801
|
-
ip: meta.ip,
|
|
3802
|
-
mac: meta.mac,
|
|
3803
|
-
pid: alive2 ? meta.pid : null,
|
|
3804
|
-
vcpu: meta.vcpu,
|
|
3805
|
-
memMib: meta.memMib,
|
|
3806
|
-
...diskStats(p.machine(meta.owner, meta.name).overlay),
|
|
3807
|
-
base: meta.base,
|
|
3808
|
-
...meta.image !== void 0 ? { image: meta.image } : {},
|
|
3809
|
-
...meta.url !== void 0 ? { url: urlFor(meta.url, meta.name) } : {},
|
|
3810
|
-
createdAt: meta.createdAt,
|
|
3811
|
-
source: meta.source,
|
|
3812
|
-
status: statusOf(meta, p),
|
|
3813
|
-
...meta.sshPort === void 0 ? {} : { sshPort: meta.sshPort },
|
|
3814
|
-
...meta.ports?.length ? { ports: meta.ports.map((f) => ({ ...f })) } : {},
|
|
3815
|
-
...meta.autoHibernateSec ? { autoHibernateSec: meta.autoHibernateSec } : {},
|
|
3816
|
-
...meta.idleCheck !== void 0 ? { idleCheck: meta.idleCheck } : {},
|
|
3817
|
-
...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {},
|
|
3818
|
-
...meta.links?.some((l) => !l.stale) ? { links: meta.links.filter((l) => !l.stale).map((l) => ({ from: linkFrom(l, meta.owner), port: l.port })) } : {}
|
|
3819
|
-
};
|
|
3820
|
-
}
|
|
3821
|
-
var linkFrom = (l, owner) => l.owner === owner ? l.name : `${l.owner.split("@")[0]}/${l.name}`;
|
|
3822
|
-
async function listMachines(scope, p = paths()) {
|
|
3823
|
-
return (await readAllMeta(p)).filter((m) => inScope(m.owner, scope)).map((m) => toMachine(m, p));
|
|
3824
|
-
}
|
|
3825
|
-
async function getMachine(ref, p = paths()) {
|
|
3826
|
-
return toMachine(await readMeta(ref, p), p);
|
|
3827
|
-
}
|
|
3828
|
-
|
|
3829
|
-
// src/core/machines/boot.ts
|
|
3830
|
-
async function launch(spec, nic, cfg, pubkeyB64, p) {
|
|
3831
|
-
const root = imageFileFor(spec, p);
|
|
3832
|
-
const kernel = kernelFor(await imageManifest(root), cfg, p);
|
|
3833
|
-
const volumes = (await placeVolumeDrives(spec, p)).map((v) => ({ id: volumeDriveId(v.name), path: volumeDriveRel(v.name) }));
|
|
3834
|
-
return driver().vm.boot(spec, { kernel, root, volumes, pubkeyB64 }, nic, cfg, p);
|
|
3835
|
-
}
|
|
3836
|
-
async function loadSnapshot(spec, image, nic, cfg, p) {
|
|
3837
|
-
return driver().vm.restore(spec, { vmstate: image.vmstate, mem: image.mem }, nic, cfg, p);
|
|
3838
|
-
}
|
|
3839
|
-
async function resumeVm(box, p) {
|
|
3840
|
-
await driver().vm.resume(box, p);
|
|
3841
|
-
}
|
|
3842
|
-
|
|
3843
|
-
// src/core/machines/guest.ts
|
|
3890
|
+
// src/core/machines/integrations.ts
|
|
3844
3891
|
import { setTimeout as sleep3 } from "node:timers/promises";
|
|
3845
3892
|
|
|
3846
3893
|
// src/core/agent.ts
|
|
@@ -3913,47 +3960,409 @@ async function idle(udsPath, script, timeoutMs = 15e3) {
|
|
|
3913
3960
|
async function runScript(udsPath, path, input, timeoutMs = 35e3) {
|
|
3914
3961
|
return (await agentCall(udsPath, { op: "script", path, input: input ?? null }, timeoutMs))["output"];
|
|
3915
3962
|
}
|
|
3916
|
-
|
|
3917
|
-
return
|
|
3963
|
+
function setIntegrations(udsPath, list, identity, timeoutMs) {
|
|
3964
|
+
return agentCall(udsPath, { op: "integrations", list: [...list], ...identity ? { identity } : {} }, timeoutMs);
|
|
3965
|
+
}
|
|
3966
|
+
async function startRun(udsPath, id, command, timeoutSec, timeoutMs = 15e3) {
|
|
3967
|
+
return (await agentCall(udsPath, { op: "run", id, command, timeoutSec }, timeoutMs))["started"] === true;
|
|
3968
|
+
}
|
|
3969
|
+
async function runStatus(udsPath, id, timeoutMs) {
|
|
3970
|
+
const reply = await agentCall(udsPath, { op: "runStatus", id }, timeoutMs);
|
|
3971
|
+
const state = reply["state"];
|
|
3972
|
+
if (state !== "running" && state !== "exited" && state !== "timeout" && state !== "unknown") throw new KvboxError("kvbox-agent sent a run state this server does not know");
|
|
3973
|
+
const durationMs = reply["durationMs"];
|
|
3974
|
+
return {
|
|
3975
|
+
state,
|
|
3976
|
+
...typeof reply["exitCode"] === "number" ? { exitCode: reply["exitCode"] } : {},
|
|
3977
|
+
...typeof durationMs === "number" && Number.isInteger(durationMs) && durationMs >= 0 ? { durationMs } : {}
|
|
3978
|
+
};
|
|
3979
|
+
}
|
|
3980
|
+
async function runOutput(udsPath, id, stream, offset, limit, timeoutMs = 15e3) {
|
|
3981
|
+
const reply = await agentCall(udsPath, { op: "runOutput", id, stream, offset, limit }, timeoutMs);
|
|
3982
|
+
const { size: size2, data } = reply;
|
|
3983
|
+
if (typeof size2 !== "number" || !Number.isInteger(size2) || size2 < 0 || typeof data !== "string") throw new KvboxError("kvbox-agent sent run output this server does not understand");
|
|
3984
|
+
return { size: size2, offset, data };
|
|
3985
|
+
}
|
|
3986
|
+
var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
|
|
3987
|
+
var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
|
|
3988
|
+
var isNoAgent = (err) => /vsock connect refused|vsock connection closed before the guest accepted|did not accept the vsock connection|kvbox-agent unreachable: connect (ENOENT|ECONNREFUSED)/.test(err.message ?? "");
|
|
3989
|
+
|
|
3990
|
+
// src/core/credentials.ts
|
|
3991
|
+
import { request as request3 } from "undici";
|
|
3992
|
+
var TIMEOUT_MS = 1e4;
|
|
3993
|
+
var PROBE_KEPT_MS = 6e4;
|
|
3994
|
+
var unavailable = (message) => ({ ok: false, code: "unavailable", message });
|
|
3995
|
+
async function ask(cp, body) {
|
|
3996
|
+
const res = await request3(`${cp.url}/hosts/self/integrations/credential`, {
|
|
3997
|
+
method: "POST",
|
|
3998
|
+
headers: { authorization: `Bearer ${cp.secret}`, "content-type": "application/json" },
|
|
3999
|
+
body: JSON.stringify(body),
|
|
4000
|
+
headersTimeout: TIMEOUT_MS,
|
|
4001
|
+
bodyTimeout: TIMEOUT_MS
|
|
4002
|
+
});
|
|
4003
|
+
const text = await res.body.text();
|
|
4004
|
+
try {
|
|
4005
|
+
return { status: res.statusCode, json: JSON.parse(text) };
|
|
4006
|
+
} catch {
|
|
4007
|
+
return { status: res.statusCode, json: null };
|
|
4008
|
+
}
|
|
4009
|
+
}
|
|
4010
|
+
async function askCredential(cp, box, integration) {
|
|
4011
|
+
let answer;
|
|
4012
|
+
try {
|
|
4013
|
+
answer = await ask(cp, { owner: box.owner, box: box.name, integration });
|
|
4014
|
+
} catch (err) {
|
|
4015
|
+
return unavailable(`${cp.name} could not be reached (${err.message}); try again shortly`);
|
|
4016
|
+
}
|
|
4017
|
+
if (answer.status === 404) return unavailable(`${cp.name} has no integrations yet`);
|
|
4018
|
+
const parsed = CredentialAnswerSchema.safeParse(answer.json);
|
|
4019
|
+
if (!parsed.success) return unavailable(`${cp.name} answered ${answer.status}; try again shortly`);
|
|
4020
|
+
return parsed.data;
|
|
4021
|
+
}
|
|
4022
|
+
var probes = /* @__PURE__ */ new Map();
|
|
4023
|
+
async function probeConnection(cp, box, integration, now = Date.now()) {
|
|
4024
|
+
const key = `${box.owner}/${box.name}/${integration}`;
|
|
4025
|
+
const kept = probes.get(key);
|
|
4026
|
+
if (kept && now - kept.at < PROBE_KEPT_MS) return kept.answer;
|
|
4027
|
+
try {
|
|
4028
|
+
const parsed = ConnectedAnswerSchema.safeParse((await ask(cp, { owner: box.owner, box: box.name, integration, probe: true })).json);
|
|
4029
|
+
if (!parsed.success) return null;
|
|
4030
|
+
probes.set(key, { at: now, answer: parsed.data });
|
|
4031
|
+
if (probes.size > 5e3) {
|
|
4032
|
+
for (const [k, v] of probes) if (now - v.at >= PROBE_KEPT_MS) probes.delete(k);
|
|
4033
|
+
}
|
|
4034
|
+
return parsed.data;
|
|
4035
|
+
} catch {
|
|
4036
|
+
return null;
|
|
4037
|
+
}
|
|
4038
|
+
}
|
|
4039
|
+
|
|
4040
|
+
// src/core/guestRequests.ts
|
|
4041
|
+
import { rm as rm5 } from "node:fs/promises";
|
|
4042
|
+
import { createServer } from "node:net";
|
|
4043
|
+
var MAX_REQUEST_BYTES = 4096;
|
|
4044
|
+
var REQUEST_TIMEOUT_MS = 5e3;
|
|
4045
|
+
var MAX_OPEN = 32;
|
|
4046
|
+
var listeners = /* @__PURE__ */ new Map();
|
|
4047
|
+
var unreadable = (message) => ({ ok: false, code: "unavailable", message });
|
|
4048
|
+
function serve(sock, answer, timeoutMs) {
|
|
4049
|
+
let buf = "";
|
|
4050
|
+
let taken = false;
|
|
4051
|
+
const reply = (body) => {
|
|
4052
|
+
if (!sock.destroyed) sock.end(JSON.stringify(body) + "\n");
|
|
4053
|
+
};
|
|
4054
|
+
const late = setTimeout(() => sock.destroy(), timeoutMs);
|
|
4055
|
+
late.unref();
|
|
4056
|
+
sock.once("close", () => clearTimeout(late));
|
|
4057
|
+
sock.on("error", () => void 0);
|
|
4058
|
+
sock.on("data", (chunk) => {
|
|
4059
|
+
if (taken) return;
|
|
4060
|
+
buf += chunk.toString("utf8");
|
|
4061
|
+
const nl = buf.indexOf("\n");
|
|
4062
|
+
if (nl === -1) {
|
|
4063
|
+
if (buf.length > MAX_REQUEST_BYTES) sock.destroy();
|
|
4064
|
+
return;
|
|
4065
|
+
}
|
|
4066
|
+
taken = true;
|
|
4067
|
+
clearTimeout(late);
|
|
4068
|
+
let request7;
|
|
4069
|
+
try {
|
|
4070
|
+
request7 = JSON.parse(buf.slice(0, nl));
|
|
4071
|
+
} catch {
|
|
4072
|
+
return reply(unreadable("the request is not JSON"));
|
|
4073
|
+
}
|
|
4074
|
+
answer(request7).then(reply, (err) => reply(unreadable(err.message)));
|
|
4075
|
+
});
|
|
4076
|
+
}
|
|
4077
|
+
async function listenGuest(path, answer, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
4078
|
+
await closeGuest(path);
|
|
4079
|
+
await rm5(path, { force: true });
|
|
4080
|
+
const open3 = /* @__PURE__ */ new Set();
|
|
4081
|
+
const server = createServer((sock) => {
|
|
4082
|
+
open3.add(sock);
|
|
4083
|
+
sock.once("close", () => open3.delete(sock));
|
|
4084
|
+
serve(sock, answer, timeoutMs);
|
|
4085
|
+
});
|
|
4086
|
+
server.maxConnections = MAX_OPEN;
|
|
4087
|
+
await new Promise((resolve3, reject) => {
|
|
4088
|
+
server.once("error", reject);
|
|
4089
|
+
server.listen(path, () => {
|
|
4090
|
+
server.off("error", reject);
|
|
4091
|
+
resolve3();
|
|
4092
|
+
});
|
|
4093
|
+
});
|
|
4094
|
+
server.unref();
|
|
4095
|
+
server.on("error", () => void 0);
|
|
4096
|
+
listeners.set(path, { server, open: open3 });
|
|
4097
|
+
}
|
|
4098
|
+
async function closeGuest(path) {
|
|
4099
|
+
const l = listeners.get(path);
|
|
4100
|
+
if (!l) return;
|
|
4101
|
+
listeners.delete(path);
|
|
4102
|
+
for (const sock of l.open) sock.destroy();
|
|
4103
|
+
await new Promise((resolve3) => l.server.close(() => resolve3()));
|
|
4104
|
+
await rm5(path, { force: true });
|
|
4105
|
+
}
|
|
4106
|
+
var guestListening = (path) => listeners.has(path);
|
|
4107
|
+
|
|
4108
|
+
// src/core/machines/integrations.ts
|
|
4109
|
+
var AGENT_REPLY_MS = 2e4;
|
|
4110
|
+
function socketOf(box, p) {
|
|
4111
|
+
try {
|
|
4112
|
+
return driver().vm.guestSocket(box, GUEST_REQUEST_PORT, p);
|
|
4113
|
+
} catch (err) {
|
|
4114
|
+
if (err instanceof NotImplementedError) return void 0;
|
|
4115
|
+
throw err;
|
|
4116
|
+
}
|
|
4117
|
+
}
|
|
4118
|
+
async function listenForGuest(box, p) {
|
|
4119
|
+
const ref = { owner: box.owner, name: box.name };
|
|
4120
|
+
try {
|
|
4121
|
+
const path = socketOf(box, p);
|
|
4122
|
+
if (path !== void 0) await listenGuest(path, (request7) => answerGuest(ref, request7, p));
|
|
4123
|
+
} catch (err) {
|
|
4124
|
+
log.warn(`box ${shown(ref)}: integrations will not answer in it: ${err.message}`);
|
|
4125
|
+
}
|
|
4126
|
+
}
|
|
4127
|
+
async function stopListeningForGuest(box, p) {
|
|
4128
|
+
try {
|
|
4129
|
+
const path = socketOf(box, p);
|
|
4130
|
+
if (path !== void 0) await closeGuest(path);
|
|
4131
|
+
} catch {
|
|
4132
|
+
}
|
|
4133
|
+
}
|
|
4134
|
+
async function listenForRunning(p) {
|
|
4135
|
+
for (const listed of await readAllMeta(p)) {
|
|
4136
|
+
if (!vmAlive(listed)) continue;
|
|
4137
|
+
await withBoxLock(listed, async () => {
|
|
4138
|
+
const meta = await readMachineMeta(listed, p).catch(() => null);
|
|
4139
|
+
if (meta !== null && vmAlive(meta)) await listenForGuest(meta, p);
|
|
4140
|
+
});
|
|
4141
|
+
}
|
|
4142
|
+
}
|
|
4143
|
+
async function closeDeadListeners(p) {
|
|
4144
|
+
for (const meta of await readAllMeta(p)) {
|
|
4145
|
+
if (vmAlive(meta)) continue;
|
|
4146
|
+
const path = socketOf(meta, p);
|
|
4147
|
+
if (path === void 0 || !guestListening(path)) continue;
|
|
4148
|
+
await withBoxLock(meta, async () => {
|
|
4149
|
+
const now = await readMachineMeta(meta, p).catch(() => null);
|
|
4150
|
+
if (now === null || !vmAlive(now)) await stopListeningForGuest(meta, p);
|
|
4151
|
+
});
|
|
4152
|
+
}
|
|
4153
|
+
}
|
|
4154
|
+
function forgetGuest(box) {
|
|
4155
|
+
asked.delete(refKey(box));
|
|
4156
|
+
told.delete(box.id);
|
|
4157
|
+
}
|
|
4158
|
+
var refusal = (code, message, connected) => ({ ok: false, code, message, ...connected === void 0 ? {} : { connected } });
|
|
4159
|
+
var asked = /* @__PURE__ */ new Map();
|
|
4160
|
+
function withinLimit(box, now) {
|
|
4161
|
+
const w = asked.get(box);
|
|
4162
|
+
if (!w || now - w.since >= 6e4) {
|
|
4163
|
+
asked.set(box, { since: now, count: 1 });
|
|
4164
|
+
return true;
|
|
4165
|
+
}
|
|
4166
|
+
w.count += 1;
|
|
4167
|
+
return w.count <= GUEST_REQUESTS_PER_MINUTE;
|
|
4168
|
+
}
|
|
4169
|
+
async function answerGuest(ref, request7, p, now = Date.now()) {
|
|
4170
|
+
if (!withinLimit(refKey(ref), now)) return refusal("unavailable", `this box asked more than ${GUEST_REQUESTS_PER_MINUTE} times in a minute; try again shortly`);
|
|
4171
|
+
const parsed = GuestRequestSchema.safeParse(request7);
|
|
4172
|
+
if (!parsed.success) return refusal("unavailable", "this host does not know that request; it may need updating");
|
|
4173
|
+
const integration = parsed.data.integration;
|
|
4174
|
+
let meta;
|
|
4175
|
+
try {
|
|
4176
|
+
meta = await readMachineMeta(ref, p);
|
|
4177
|
+
} catch {
|
|
4178
|
+
return refusal("unavailable", "this box is being removed");
|
|
4179
|
+
}
|
|
4180
|
+
const cp = (await loadConfig(p)).controlPlane;
|
|
4181
|
+
if (!cp || !isCloudBox(meta.owner)) return refusal("unavailable", "integrations are not available in a box made on the host itself");
|
|
4182
|
+
if (!(meta.integrations ?? []).includes(integration)) {
|
|
4183
|
+
const probe = await probeConnection(cp, meta, integration, now);
|
|
4184
|
+
return refusal("off", `${integration} is not turned on for this box`, probe?.connected);
|
|
4185
|
+
}
|
|
4186
|
+
const answer = await askCredential(cp, meta, integration);
|
|
4187
|
+
if (answer.ok && answer.identity && !(told.has(meta.id) && sameIdentity(told.get(meta.id), answer.identity))) {
|
|
4188
|
+
void tellCurrent(ref, p.machine(meta.owner, meta.name).vsock, p, answer.identity).catch(() => void 0);
|
|
4189
|
+
}
|
|
4190
|
+
return answer;
|
|
4191
|
+
}
|
|
4192
|
+
var told = /* @__PURE__ */ new Map();
|
|
4193
|
+
var sameIdentity = (a, b) => a?.name === b?.name && a?.email === b?.email;
|
|
4194
|
+
async function tellGuest(box, vsock, identity) {
|
|
4195
|
+
await setIntegrations(vsock, box.integrations ?? [], identity, AGENT_REPLY_MS);
|
|
4196
|
+
told.set(box.id, identity);
|
|
4197
|
+
}
|
|
4198
|
+
async function identityOf(box, p) {
|
|
4199
|
+
if (!(box.integrations ?? []).includes("github")) return void 0;
|
|
4200
|
+
const cp = (await loadConfig(p)).controlPlane;
|
|
4201
|
+
if (!cp) return void 0;
|
|
4202
|
+
const probe = await probeConnection(cp, box, "github");
|
|
4203
|
+
if (probe !== null) return probe.identity;
|
|
4204
|
+
return told.has(box.id) ? told.get(box.id) : null;
|
|
4205
|
+
}
|
|
4206
|
+
var sameList = (a, b) => JSON.stringify(a ?? []) === JSON.stringify(b ?? []);
|
|
4207
|
+
async function tellCurrent(ref, vsock, p, identity) {
|
|
4208
|
+
for (; ; ) {
|
|
4209
|
+
const asked2 = await readMachineMeta(ref, p);
|
|
4210
|
+
const who = identity !== void 0 && (asked2.integrations ?? []).includes("github") ? identity : await identityOf(asked2, p);
|
|
4211
|
+
if (who === null) return false;
|
|
4212
|
+
const done = await withBoxLock(ref, async () => {
|
|
4213
|
+
const box = await readMachineMeta(ref, p);
|
|
4214
|
+
if (!sameList(box.integrations, asked2.integrations)) return false;
|
|
4215
|
+
await tellGuest(box, vsock, who);
|
|
4216
|
+
return true;
|
|
4217
|
+
});
|
|
4218
|
+
if (done) return true;
|
|
4219
|
+
}
|
|
4220
|
+
}
|
|
4221
|
+
var outdated = (box) => `its image is from before base v${INTEGRATIONS_BASE}, which has no integrations (kvbox vm update ${shown(box)} moves it onto the current one)`;
|
|
4222
|
+
async function applyIntegrations(box, vsock, p) {
|
|
4223
|
+
if (!isCloudBox(box.owner)) return;
|
|
4224
|
+
try {
|
|
4225
|
+
const who = await identityOf(box, p);
|
|
4226
|
+
await tellGuest(box, vsock, who ?? void 0);
|
|
4227
|
+
if (who === null) {
|
|
4228
|
+
told.delete(box.id);
|
|
4229
|
+
if (box.pid !== null) void tellIntegrationsWhenUp(box, box.pid, vsock, p);
|
|
4230
|
+
}
|
|
4231
|
+
} catch (err) {
|
|
4232
|
+
if (!isUnknownOp(err)) return void log.warn(`box ${shown(box)} was not told its integrations: ${err.message}`);
|
|
4233
|
+
if ((box.integrations ?? []).length > 0) throw new KvboxError(`box ${shown(box)} cannot use integrations yet: ${outdated(box)}`);
|
|
4234
|
+
}
|
|
4235
|
+
}
|
|
4236
|
+
var BOOT_WAIT_MS = 12e4;
|
|
4237
|
+
var WHO_RETRY_MS = 3e3;
|
|
4238
|
+
function tellIntegrationsWhenUp(ref, pid, vsock, p, timing = { waitMs: BOOT_WAIT_MS }) {
|
|
4239
|
+
return outsideLocks(async () => {
|
|
4240
|
+
if (!isCloudBox(ref.owner)) return;
|
|
4241
|
+
const deadline = Date.now() + timing.waitMs;
|
|
4242
|
+
for (; ; ) {
|
|
4243
|
+
if (!pidAlive(pid)) return;
|
|
4244
|
+
try {
|
|
4245
|
+
if (await tellCurrent(ref, vsock, p)) return;
|
|
4246
|
+
if (Date.now() >= deadline) return void log.warn(`box ${shown(ref)} was not told who commits in it: the control plane could not be asked`);
|
|
4247
|
+
await sleep3(timing.retryMs ?? WHO_RETRY_MS);
|
|
4248
|
+
} catch (err) {
|
|
4249
|
+
if (!pidAlive(pid)) return;
|
|
4250
|
+
if (isNoAgent(err) && Date.now() < deadline) {
|
|
4251
|
+
await sleep3(500);
|
|
4252
|
+
continue;
|
|
4253
|
+
}
|
|
4254
|
+
const box = await readMachineMeta(ref, p).catch(() => null);
|
|
4255
|
+
if (box === null) return;
|
|
4256
|
+
if (!isUnknownOp(err)) log.warn(`box ${shown(ref)} was not told its integrations: ${err.message}`);
|
|
4257
|
+
else if ((box.integrations ?? []).length > 0) log.warn(`box ${shown(ref)} has integrations it cannot use: ${outdated(ref)}`);
|
|
4258
|
+
return;
|
|
4259
|
+
}
|
|
4260
|
+
}
|
|
4261
|
+
}).catch(() => void 0);
|
|
4262
|
+
}
|
|
4263
|
+
|
|
4264
|
+
// src/core/machines/status.ts
|
|
4265
|
+
import { existsSync as existsSync9 } from "node:fs";
|
|
4266
|
+
function isHibernated(meta, p) {
|
|
4267
|
+
return !vmAlive(meta) && existsSync9(p.machine(meta.owner, meta.name).hibernateVmstate);
|
|
4268
|
+
}
|
|
4269
|
+
function statusOf(meta, p = paths()) {
|
|
4270
|
+
if (vmAlive(meta)) return meta.paused ? "standby" : "running";
|
|
4271
|
+
return isHibernated(meta, p) ? "hibernated" : "stopped";
|
|
4272
|
+
}
|
|
4273
|
+
function stateMessage(ref, status) {
|
|
4274
|
+
return `box ${shown(ref)} is ${status === "standby" ? "in standby" : status}`;
|
|
4275
|
+
}
|
|
4276
|
+
function assertNotHibernated(meta, p) {
|
|
4277
|
+
if (isHibernated(meta, p)) {
|
|
4278
|
+
throw new KvboxError(`${stateMessage(meta, "hibernated")}; its memory image was made with its current shape and base: kvbox wake ${shown(meta)} first`);
|
|
4279
|
+
}
|
|
4280
|
+
}
|
|
4281
|
+
|
|
4282
|
+
// src/core/machines/list.ts
|
|
4283
|
+
function toMachine(meta, p = paths()) {
|
|
4284
|
+
const alive2 = vmAlive(meta);
|
|
4285
|
+
if (!alive2 && meta.pid !== null) {
|
|
4286
|
+
try {
|
|
4287
|
+
closeOpenRun(meta.id, (/* @__PURE__ */ new Date()).toISOString(), p);
|
|
4288
|
+
} catch (err) {
|
|
4289
|
+
log.warn(`usage ledger: ${err.message}`);
|
|
4290
|
+
}
|
|
4291
|
+
}
|
|
4292
|
+
return {
|
|
4293
|
+
id: meta.id,
|
|
4294
|
+
name: meta.name,
|
|
4295
|
+
owner: meta.owner,
|
|
4296
|
+
ip: meta.ip,
|
|
4297
|
+
mac: meta.mac,
|
|
4298
|
+
pid: alive2 ? meta.pid : null,
|
|
4299
|
+
vcpu: meta.vcpu,
|
|
4300
|
+
memMib: meta.memMib,
|
|
4301
|
+
...diskStats(p.machine(meta.owner, meta.name).overlay),
|
|
4302
|
+
base: meta.base,
|
|
4303
|
+
...meta.image !== void 0 ? { image: meta.image } : {},
|
|
4304
|
+
...meta.url !== void 0 ? { url: urlFor(meta.url, meta.name) } : {},
|
|
4305
|
+
createdAt: meta.createdAt,
|
|
4306
|
+
source: meta.source,
|
|
4307
|
+
status: statusOf(meta, p),
|
|
4308
|
+
...meta.sshPort === void 0 ? {} : { sshPort: meta.sshPort },
|
|
4309
|
+
...meta.ports?.length ? { ports: meta.ports.map((f) => ({ ...f })) } : {},
|
|
4310
|
+
...meta.autoHibernateSec ? { autoHibernateSec: meta.autoHibernateSec } : {},
|
|
4311
|
+
...meta.idleCheck !== void 0 ? { idleCheck: meta.idleCheck } : {},
|
|
4312
|
+
...meta.integrations?.length ? { integrations: [...meta.integrations] } : {},
|
|
4313
|
+
...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {},
|
|
4314
|
+
...meta.links?.some((l) => !l.stale) ? { links: meta.links.filter((l) => !l.stale).map((l) => ({ from: linkFrom(l, meta.owner), port: l.port })) } : {}
|
|
4315
|
+
};
|
|
4316
|
+
}
|
|
4317
|
+
var linkFrom = (l, owner) => l.owner === owner ? l.name : `${l.owner.split("@")[0]}/${l.name}`;
|
|
4318
|
+
async function listMachines(scope, p = paths()) {
|
|
4319
|
+
return (await readAllMeta(p)).filter((m) => inScope(m.owner, scope)).map((m) => toMachine(m, p));
|
|
4320
|
+
}
|
|
4321
|
+
async function getMachine(ref, p = paths()) {
|
|
4322
|
+
return toMachine(await readMeta(ref, p), p);
|
|
4323
|
+
}
|
|
4324
|
+
|
|
4325
|
+
// src/core/machines/boot.ts
|
|
4326
|
+
async function launch(spec, nic, cfg, pubkeyB64, p) {
|
|
4327
|
+
const root = imageFileFor(spec, p);
|
|
4328
|
+
const kernel = kernelFor(await imageManifest(root), cfg, p);
|
|
4329
|
+
const volumes = (await placeVolumeDrives(spec, p)).map((v) => ({ id: volumeDriveId(v.name), path: volumeDriveRel(v.name) }));
|
|
4330
|
+
return withGuestListener(spec, p, () => driver().vm.boot(spec, { kernel, root, volumes, pubkeyB64 }, nic, cfg, p));
|
|
4331
|
+
}
|
|
4332
|
+
async function loadSnapshot(spec, image, nic, cfg, p) {
|
|
4333
|
+
return withGuestListener(spec, p, () => driver().vm.restore(spec, { vmstate: image.vmstate, mem: image.mem }, nic, cfg, p));
|
|
3918
4334
|
}
|
|
3919
|
-
async function
|
|
3920
|
-
|
|
3921
|
-
|
|
3922
|
-
|
|
3923
|
-
|
|
3924
|
-
|
|
3925
|
-
|
|
3926
|
-
|
|
3927
|
-
...typeof durationMs === "number" && Number.isInteger(durationMs) && durationMs >= 0 ? { durationMs } : {}
|
|
3928
|
-
};
|
|
4335
|
+
async function withGuestListener(box, p, bringUp) {
|
|
4336
|
+
await listenForGuest(box, p);
|
|
4337
|
+
try {
|
|
4338
|
+
return await bringUp();
|
|
4339
|
+
} catch (err) {
|
|
4340
|
+
await stopListeningForGuest(box, p);
|
|
4341
|
+
throw err;
|
|
4342
|
+
}
|
|
3929
4343
|
}
|
|
3930
|
-
async function
|
|
3931
|
-
|
|
3932
|
-
const { size: size2, data } = reply;
|
|
3933
|
-
if (typeof size2 !== "number" || !Number.isInteger(size2) || size2 < 0 || typeof data !== "string") throw new KvboxError("kvbox-agent sent run output this server does not understand");
|
|
3934
|
-
return { size: size2, offset, data };
|
|
4344
|
+
async function resumeVm(box, p) {
|
|
4345
|
+
await driver().vm.resume(box, p);
|
|
3935
4346
|
}
|
|
3936
|
-
var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
|
|
3937
|
-
var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
|
|
3938
|
-
var isNoAgent = (err) => /vsock connect refused|vsock connection closed before the guest accepted|did not accept the vsock connection|kvbox-agent unreachable: connect (ENOENT|ECONNREFUSED)/.test(err.message ?? "");
|
|
3939
4347
|
|
|
3940
4348
|
// src/core/machines/guest.ts
|
|
4349
|
+
import { setTimeout as sleep4 } from "node:timers/promises";
|
|
3941
4350
|
function prefixLenOf(subnet) {
|
|
3942
4351
|
return Number(subnet.split("/")[1]);
|
|
3943
4352
|
}
|
|
3944
|
-
var
|
|
4353
|
+
var AGENT_REPLY_MS2 = 2e4;
|
|
3945
4354
|
async function introduce(spec, vsock, cfg, failure2) {
|
|
3946
4355
|
const id = { name: spec.name, ip: spec.ip, prefixLen: prefixLenOf(cfg.subnet), gateway: cfg.gateway, mac: spec.mac, time: Math.floor(Date.now() / 1e3) };
|
|
3947
4356
|
const deadline = Date.now() + 3e3;
|
|
3948
4357
|
for (; ; ) {
|
|
3949
4358
|
try {
|
|
3950
|
-
await setIdentity(vsock, id,
|
|
4359
|
+
await setIdentity(vsock, id, AGENT_REPLY_MS2);
|
|
3951
4360
|
return;
|
|
3952
4361
|
} catch (err) {
|
|
3953
4362
|
const msg = err.message;
|
|
3954
4363
|
const transient = /unreachable|refused|before the guest accepted/.test(msg);
|
|
3955
4364
|
if (transient && Date.now() < deadline) {
|
|
3956
|
-
await
|
|
4365
|
+
await sleep4(100);
|
|
3957
4366
|
continue;
|
|
3958
4367
|
}
|
|
3959
4368
|
if (transient) throw new KvboxError(`${msg}
|
|
@@ -3965,7 +4374,7 @@ async function introduce(spec, vsock, cfg, failure2) {
|
|
|
3965
4374
|
}
|
|
3966
4375
|
async function dropGuestVolumes(box, vsock) {
|
|
3967
4376
|
try {
|
|
3968
|
-
await dropVolumes(vsock,
|
|
4377
|
+
await dropVolumes(vsock, AGENT_REPLY_MS2);
|
|
3969
4378
|
} catch (err) {
|
|
3970
4379
|
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;
|
|
3971
4380
|
log.warn(`box ${shown(box)} keeps the volume mounts it was frozen with, over empty disks now: ${why}`);
|
|
@@ -3975,7 +4384,7 @@ async function pushEnv(box, vsock, p) {
|
|
|
3975
4384
|
const vars = await envForBoot(box, p);
|
|
3976
4385
|
if (vars === null) return;
|
|
3977
4386
|
try {
|
|
3978
|
-
await setEnv(vsock, vars,
|
|
4387
|
+
await setEnv(vsock, vars, AGENT_REPLY_MS2);
|
|
3979
4388
|
} catch (err) {
|
|
3980
4389
|
warnEnv(box, vars, err);
|
|
3981
4390
|
}
|
|
@@ -3989,7 +4398,7 @@ function warnEnv(box, vars, err) {
|
|
|
3989
4398
|
log.warn(`box ${shown(box)} did not get its environment variables: ${err.message}`);
|
|
3990
4399
|
}
|
|
3991
4400
|
var ENV_BOOT_WAIT_MS = 12e4;
|
|
3992
|
-
function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs:
|
|
4401
|
+
function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs: AGENT_REPLY_MS2, waitMs: ENV_BOOT_WAIT_MS }) {
|
|
3993
4402
|
return (async () => {
|
|
3994
4403
|
const deadline = Date.now() + timing.waitMs;
|
|
3995
4404
|
for (; ; ) {
|
|
@@ -4002,7 +4411,7 @@ function pushEnvAfterBoot(box, pid, vsock, p, timing = { replyMs: AGENT_REPLY_MS
|
|
|
4002
4411
|
} catch (err) {
|
|
4003
4412
|
if (!pidAlive(pid)) return;
|
|
4004
4413
|
if (isNoAgent(err) && Date.now() < deadline) {
|
|
4005
|
-
await
|
|
4414
|
+
await sleep4(500);
|
|
4006
4415
|
continue;
|
|
4007
4416
|
}
|
|
4008
4417
|
warnEnv(box, vars, err);
|
|
@@ -4053,7 +4462,7 @@ function authorizedKeysB64(hostKey, extra) {
|
|
|
4053
4462
|
}
|
|
4054
4463
|
async function pushAuthorizedKeys(box, vsock, p) {
|
|
4055
4464
|
try {
|
|
4056
|
-
await setAuthorizedKeys(vsock, authorizedKeysLines(await readHostPubkey(p), box.sshKeys ?? []),
|
|
4465
|
+
await setAuthorizedKeys(vsock, authorizedKeysLines(await readHostPubkey(p), box.sshKeys ?? []), AGENT_REPLY_MS2);
|
|
4057
4466
|
return void 0;
|
|
4058
4467
|
} catch (err) {
|
|
4059
4468
|
const why = isUnknownOp(err) ? `its image predates base v0.6.0, whose kvbox-agent can replace authorized_keys (kvbox vm update ${shown(box)} moves it onto the current base)` : err.message;
|
|
@@ -4256,17 +4665,131 @@ var startMachine = locked(async function startMachine2(ref, p = paths(), force =
|
|
|
4256
4665
|
const started = { ...meta, pid, bootId: currentBootId(), sshKeysStale: void 0, paused: void 0 };
|
|
4257
4666
|
await writeMachineMeta(started, p);
|
|
4258
4667
|
recordState(started, "running", "start", p);
|
|
4668
|
+
void tellIntegrationsWhenUp(started, pid, p.machine(meta.owner, meta.name).vsock, p);
|
|
4259
4669
|
return toMachine(started, p);
|
|
4260
4670
|
} catch (err) {
|
|
4261
4671
|
if (pid !== void 0) killQuietly(pid);
|
|
4672
|
+
await stopListeningForGuest(meta, p);
|
|
4262
4673
|
await closePorts(meta, cfg);
|
|
4263
4674
|
await driver().net.remove(meta.id, cfg).catch(() => void 0);
|
|
4264
4675
|
throw err;
|
|
4265
4676
|
}
|
|
4266
4677
|
});
|
|
4267
4678
|
|
|
4679
|
+
// src/core/machines/newbox.ts
|
|
4680
|
+
import { mkdir as mkdir5, rm as rm6 } from "node:fs/promises";
|
|
4681
|
+
var NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
|
|
4682
|
+
var AUTO_PREFIX = "box";
|
|
4683
|
+
function pickName(requested, taken) {
|
|
4684
|
+
if (requested !== void 0) {
|
|
4685
|
+
if (!NAME_RE.test(requested)) {
|
|
4686
|
+
throw new KvboxError(`invalid box name "${requested}": 1-12 chars, lowercase letters, digits and '-', starting with a letter or digit`);
|
|
4687
|
+
}
|
|
4688
|
+
if (taken.has(requested)) throw new KvboxError(`box ${requested} already exists`);
|
|
4689
|
+
return requested;
|
|
4690
|
+
}
|
|
4691
|
+
for (let i = 1; ; i++) {
|
|
4692
|
+
const candidate = `${AUTO_PREFIX}${i}`;
|
|
4693
|
+
if (!taken.has(candidate)) return candidate;
|
|
4694
|
+
}
|
|
4695
|
+
}
|
|
4696
|
+
function autoHibernateFor(req, cfg, manifest = {}) {
|
|
4697
|
+
if (req.autoHibernateSec !== void 0) return req.autoHibernateSec || void 0;
|
|
4698
|
+
if (manifest.autoHibernate === false) return void 0;
|
|
4699
|
+
if (typeof manifest.autoHibernate === "string") return parseDuration(manifest.autoHibernate) || void 0;
|
|
4700
|
+
return cfg.autoHibernateSec || void 0;
|
|
4701
|
+
}
|
|
4702
|
+
var integrationsOf = (list) => list && list.length > 0 ? [...list] : void 0;
|
|
4703
|
+
function requestedIntegrations(list) {
|
|
4704
|
+
assertKnownIntegrations(list, "this host's kvbox-server", "it needs updating first");
|
|
4705
|
+
return integrationsOf(list);
|
|
4706
|
+
}
|
|
4707
|
+
var inheritedIntegrations = (list, sourceOwner, owner) => sourceOwner === owner ? integrationsOf(list) : void 0;
|
|
4708
|
+
async function bootInto(box, prepare, origin, cfg, p) {
|
|
4709
|
+
const { id, ip, owner, name } = box;
|
|
4710
|
+
const keysB64 = authorizedKeysB64(await readHostPubkey(p), box.sshKeys ?? []);
|
|
4711
|
+
const m = p.machine(owner, name);
|
|
4712
|
+
await driver().net.prepare(cfg);
|
|
4713
|
+
await mkdir5(m.dir, { recursive: true, mode: 448 });
|
|
4714
|
+
let tapCreated = false;
|
|
4715
|
+
let pid;
|
|
4716
|
+
let sshPort;
|
|
4717
|
+
let drawn;
|
|
4718
|
+
try {
|
|
4719
|
+
drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
|
|
4720
|
+
sshPort = drawn?.ports[0];
|
|
4721
|
+
await prepare(m);
|
|
4722
|
+
const tap = await driver().net.create(box, cfg);
|
|
4723
|
+
tapCreated = true;
|
|
4724
|
+
const spec = { ...box, sshPort };
|
|
4725
|
+
pid = await launch(spec, tap, cfg, keysB64, p);
|
|
4726
|
+
await openPorts(spec, cfg, p);
|
|
4727
|
+
void pushEnvAfterBoot(spec, pid, m.vsock, p);
|
|
4728
|
+
const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin };
|
|
4729
|
+
await writeMachineMeta(meta, p);
|
|
4730
|
+
recordState(meta, "running", "new", p, meta.createdAt);
|
|
4731
|
+
void tellIntegrationsWhenUp(meta, pid, m.vsock, p);
|
|
4732
|
+
return toMachine(meta, p);
|
|
4733
|
+
} catch (err) {
|
|
4734
|
+
if (pid !== void 0) killQuietly(pid);
|
|
4735
|
+
await stopListeningForGuest(box, p);
|
|
4736
|
+
await closePorts({ id, ip, sshPort }, cfg);
|
|
4737
|
+
if (tapCreated) await driver().net.remove(id, cfg).catch(() => void 0);
|
|
4738
|
+
await rm6(m.dir, { recursive: true, force: true });
|
|
4739
|
+
boxListChanged();
|
|
4740
|
+
throw err;
|
|
4741
|
+
} finally {
|
|
4742
|
+
drawn?.release();
|
|
4743
|
+
}
|
|
4744
|
+
}
|
|
4745
|
+
async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
|
|
4746
|
+
const { id, ip, owner, name } = box;
|
|
4747
|
+
const m = p.machine(owner, name);
|
|
4748
|
+
await driver().net.prepare(cfg);
|
|
4749
|
+
await mkdir5(m.dir, { recursive: true, mode: 448 });
|
|
4750
|
+
let tapCreated = false;
|
|
4751
|
+
let pid;
|
|
4752
|
+
let sshPort;
|
|
4753
|
+
let drawn;
|
|
4754
|
+
try {
|
|
4755
|
+
drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
|
|
4756
|
+
sshPort = drawn?.ports[0];
|
|
4757
|
+
const image = await prepare(m);
|
|
4758
|
+
const tap = await driver().net.create(box, cfg, { detached: true });
|
|
4759
|
+
tapCreated = true;
|
|
4760
|
+
const spec = { ...box, sshPort };
|
|
4761
|
+
pid = await loadSnapshot(spec, image, tap, cfg, p);
|
|
4762
|
+
await resumeVm(box, p);
|
|
4763
|
+
await introduce(spec, m.vsock, cfg, {
|
|
4764
|
+
silent: `nothing answered on the restored box's control channel for 3 s; the restored box was discarded, try again`,
|
|
4765
|
+
noAnswer: "the restored box was discarded. kvbox-agent inside it took the request but gave no answer; try again, and if it keeps happening look at the box's journal (kvbox exec <box> -- sudo journalctl -u kvbox-agent) on a box started from the same snapshot."
|
|
4766
|
+
});
|
|
4767
|
+
const stale = await pushAuthorizedKeys(box, m.vsock, p);
|
|
4768
|
+
if (stale && keysOrFail) throw new KvboxError(`${keysOrFail}: ${stale}`);
|
|
4769
|
+
if (image.volumes?.length) await dropGuestVolumes(box, m.vsock);
|
|
4770
|
+
await pushEnv(box, m.vsock, p);
|
|
4771
|
+
await driver().net.attach(box, cfg);
|
|
4772
|
+
await openPorts(spec, cfg, p);
|
|
4773
|
+
const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin, memSnapshots: 1, sshKeysStale: stale ? true : void 0 };
|
|
4774
|
+
await writeMachineMeta(meta, p);
|
|
4775
|
+
recordState(meta, "running", "new", p, meta.createdAt);
|
|
4776
|
+
void tellIntegrationsWhenUp(meta, pid, m.vsock, p);
|
|
4777
|
+
return toMachine(meta, p);
|
|
4778
|
+
} catch (err) {
|
|
4779
|
+
if (pid !== void 0) killQuietly(pid);
|
|
4780
|
+
await stopListeningForGuest(box, p);
|
|
4781
|
+
await closePorts({ id, ip, sshPort }, cfg);
|
|
4782
|
+
if (tapCreated) await driver().net.remove(id, cfg).catch(() => void 0);
|
|
4783
|
+
await rm6(m.dir, { recursive: true, force: true });
|
|
4784
|
+
boxListChanged();
|
|
4785
|
+
throw err;
|
|
4786
|
+
} finally {
|
|
4787
|
+
drawn?.release();
|
|
4788
|
+
}
|
|
4789
|
+
}
|
|
4790
|
+
|
|
4268
4791
|
// src/core/machines/stop.ts
|
|
4269
|
-
import { rm as
|
|
4792
|
+
import { rm as rm7 } from "node:fs/promises";
|
|
4270
4793
|
|
|
4271
4794
|
// src/core/machines/links.ts
|
|
4272
4795
|
function linkSource(req, caller, target) {
|
|
@@ -4364,9 +4887,13 @@ async function waitDead(pid, graceMs) {
|
|
|
4364
4887
|
}
|
|
4365
4888
|
}
|
|
4366
4889
|
async function cleanupProcess(meta, cfg, p) {
|
|
4367
|
-
|
|
4368
|
-
|
|
4369
|
-
|
|
4890
|
+
try {
|
|
4891
|
+
await closePorts(meta, cfg);
|
|
4892
|
+
await driver().net.remove(meta.id, cfg);
|
|
4893
|
+
await driver().vm.cleanup(meta, p);
|
|
4894
|
+
} finally {
|
|
4895
|
+
await stopListeningForGuest(meta, p);
|
|
4896
|
+
}
|
|
4370
4897
|
}
|
|
4371
4898
|
var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
|
|
4372
4899
|
const meta = await readMeta(ref, p);
|
|
@@ -4375,8 +4902,8 @@ var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
|
|
|
4375
4902
|
if (!vmAlive(meta) && !isHibernated(meta, p)) throw new KvboxError(`box ${shown(ref)} is already stopped`);
|
|
4376
4903
|
await shutdown2(meta, cfg, p, 1e4);
|
|
4377
4904
|
await compactDisk(m.overlay).catch((err) => log.warn(`box ${shown(ref)}: disk not compacted: ${err.message}`));
|
|
4378
|
-
await
|
|
4379
|
-
await
|
|
4905
|
+
await rm7(m.hibernateDir, { recursive: true, force: true });
|
|
4906
|
+
await rm7(m.memBase, { force: true });
|
|
4380
4907
|
const stopped = { ...meta, pid: null, memSnapshots: void 0, paused: void 0 };
|
|
4381
4908
|
await writeMachineMeta(stopped, p);
|
|
4382
4909
|
recordState(stopped, "stopped", "stop", p);
|
|
@@ -4395,7 +4922,8 @@ var destroyBox = locked(async function destroyBox2(ref, p = paths()) {
|
|
|
4395
4922
|
throw err;
|
|
4396
4923
|
});
|
|
4397
4924
|
recordState(meta, "stopped", "rm", p);
|
|
4398
|
-
await
|
|
4925
|
+
await rm7(p.machine(ref.owner, ref.name).dir, { recursive: true, force: true });
|
|
4926
|
+
forgetGuest(meta);
|
|
4399
4927
|
boxListChanged();
|
|
4400
4928
|
return meta;
|
|
4401
4929
|
});
|
|
@@ -4405,7 +4933,7 @@ async function applyAtNextBoot(meta, changes, by, cfg, p, whileStopped) {
|
|
|
4405
4933
|
const wasRunning = vmAlive(meta);
|
|
4406
4934
|
if (wasRunning) {
|
|
4407
4935
|
await shutdown2(meta, cfg, p, 1e4);
|
|
4408
|
-
await
|
|
4936
|
+
await rm8(p.machine(meta.owner, meta.name).memBase, { force: true });
|
|
4409
4937
|
}
|
|
4410
4938
|
const updated = { ...meta, ...changes, pid: null, memSnapshots: void 0, paused: void 0 };
|
|
4411
4939
|
await writeMachineMeta(updated, p);
|
|
@@ -4470,7 +4998,7 @@ var replaceDisk = locked(async function replaceDisk2(ref, file, disk, p = paths(
|
|
|
4470
4998
|
const currentGib = Math.round(statSync3(m.overlay).size / 1024 ** 3);
|
|
4471
4999
|
const restoredGib = Math.round(statSync3(file).size / 1024 ** 3);
|
|
4472
5000
|
return applyAtNextBoot(meta, { base: disk.base, image: disk.image }, "restore", cfg, p, async () => {
|
|
4473
|
-
if (disk.vars === null) await
|
|
5001
|
+
if (disk.vars === null) await rm8(m.env, { force: true });
|
|
4474
5002
|
else await writeBoxEnv(ref, disk.vars, p);
|
|
4475
5003
|
await rename5(file, m.overlay);
|
|
4476
5004
|
if (currentGib > restoredGib) await growDisk(m.overlay, currentGib);
|
|
@@ -4481,6 +5009,10 @@ var setMachine = locked(async function setMachine2(ref, req, p = paths()) {
|
|
|
4481
5009
|
const next = { ...meta };
|
|
4482
5010
|
if (req.autoHibernateSec !== void 0) next.autoHibernateSec = req.autoHibernateSec || void 0;
|
|
4483
5011
|
if (req.idleCheck !== void 0) next.idleCheck = req.idleCheck || void 0;
|
|
5012
|
+
if (req.integrations !== void 0) {
|
|
5013
|
+
next.integrations = requestedIntegrations(req.integrations);
|
|
5014
|
+
if (statusOf(meta, p) === "running") await applyIntegrations(next, p.machine(meta.owner, meta.name).vsock, p);
|
|
5015
|
+
}
|
|
4484
5016
|
await writeMachineMeta(next, p);
|
|
4485
5017
|
return toMachine(next, p);
|
|
4486
5018
|
});
|
|
@@ -4488,108 +5020,6 @@ var setMachine = locked(async function setMachine2(ref, req, p = paths()) {
|
|
|
4488
5020
|
// src/core/machines/create.ts
|
|
4489
5021
|
import { rename as rename6, stat as stat3 } from "node:fs/promises";
|
|
4490
5022
|
|
|
4491
|
-
// src/core/machines/newbox.ts
|
|
4492
|
-
import { mkdir as mkdir5, rm as rm7 } from "node:fs/promises";
|
|
4493
|
-
var NAME_RE = /^[a-z0-9][a-z0-9-]{0,11}$/;
|
|
4494
|
-
var AUTO_PREFIX = "box";
|
|
4495
|
-
function pickName(requested, taken) {
|
|
4496
|
-
if (requested !== void 0) {
|
|
4497
|
-
if (!NAME_RE.test(requested)) {
|
|
4498
|
-
throw new KvboxError(`invalid box name "${requested}": 1-12 chars, lowercase letters, digits and '-', starting with a letter or digit`);
|
|
4499
|
-
}
|
|
4500
|
-
if (taken.has(requested)) throw new KvboxError(`box ${requested} already exists`);
|
|
4501
|
-
return requested;
|
|
4502
|
-
}
|
|
4503
|
-
for (let i = 1; ; i++) {
|
|
4504
|
-
const candidate = `${AUTO_PREFIX}${i}`;
|
|
4505
|
-
if (!taken.has(candidate)) return candidate;
|
|
4506
|
-
}
|
|
4507
|
-
}
|
|
4508
|
-
function autoHibernateFor(req, cfg, manifest = {}) {
|
|
4509
|
-
if (req.autoHibernateSec !== void 0) return req.autoHibernateSec || void 0;
|
|
4510
|
-
if (manifest.autoHibernate === false) return void 0;
|
|
4511
|
-
if (typeof manifest.autoHibernate === "string") return parseDuration(manifest.autoHibernate) || void 0;
|
|
4512
|
-
return cfg.autoHibernateSec || void 0;
|
|
4513
|
-
}
|
|
4514
|
-
async function bootInto(box, prepare, origin, cfg, p) {
|
|
4515
|
-
const { id, ip, owner, name } = box;
|
|
4516
|
-
const keysB64 = authorizedKeysB64(await readHostPubkey(p), box.sshKeys ?? []);
|
|
4517
|
-
const m = p.machine(owner, name);
|
|
4518
|
-
await driver().net.prepare(cfg);
|
|
4519
|
-
await mkdir5(m.dir, { recursive: true, mode: 448 });
|
|
4520
|
-
let tapCreated = false;
|
|
4521
|
-
let pid;
|
|
4522
|
-
let sshPort;
|
|
4523
|
-
let drawn;
|
|
4524
|
-
try {
|
|
4525
|
-
drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
|
|
4526
|
-
sshPort = drawn?.ports[0];
|
|
4527
|
-
await prepare(m);
|
|
4528
|
-
const tap = await driver().net.create(box, cfg);
|
|
4529
|
-
tapCreated = true;
|
|
4530
|
-
const spec = { ...box, sshPort };
|
|
4531
|
-
pid = await launch(spec, tap, cfg, keysB64, p);
|
|
4532
|
-
await openPorts(spec, cfg, p);
|
|
4533
|
-
void pushEnvAfterBoot(spec, pid, m.vsock, p);
|
|
4534
|
-
const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin };
|
|
4535
|
-
await writeMachineMeta(meta, p);
|
|
4536
|
-
recordState(meta, "running", "new", p, meta.createdAt);
|
|
4537
|
-
return toMachine(meta, p);
|
|
4538
|
-
} catch (err) {
|
|
4539
|
-
if (pid !== void 0) killQuietly(pid);
|
|
4540
|
-
await closePorts({ id, ip, sshPort }, cfg);
|
|
4541
|
-
if (tapCreated) await driver().net.remove(id, cfg).catch(() => void 0);
|
|
4542
|
-
await rm7(m.dir, { recursive: true, force: true });
|
|
4543
|
-
boxListChanged();
|
|
4544
|
-
throw err;
|
|
4545
|
-
} finally {
|
|
4546
|
-
drawn?.release();
|
|
4547
|
-
}
|
|
4548
|
-
}
|
|
4549
|
-
async function restoreInto(box, prepare, origin, cfg, p, keysOrFail) {
|
|
4550
|
-
const { id, ip, owner, name } = box;
|
|
4551
|
-
const m = p.machine(owner, name);
|
|
4552
|
-
await driver().net.prepare(cfg);
|
|
4553
|
-
await mkdir5(m.dir, { recursive: true, mode: 448 });
|
|
4554
|
-
let tapCreated = false;
|
|
4555
|
-
let pid;
|
|
4556
|
-
let sshPort;
|
|
4557
|
-
let drawn;
|
|
4558
|
-
try {
|
|
4559
|
-
drawn = isCloudBox(owner) ? await drawPorts(1, p) : void 0;
|
|
4560
|
-
sshPort = drawn?.ports[0];
|
|
4561
|
-
const image = await prepare(m);
|
|
4562
|
-
const tap = await driver().net.create(box, cfg, { detached: true });
|
|
4563
|
-
tapCreated = true;
|
|
4564
|
-
const spec = { ...box, sshPort };
|
|
4565
|
-
pid = await loadSnapshot(spec, image, tap, cfg, p);
|
|
4566
|
-
await resumeVm(box, p);
|
|
4567
|
-
await introduce(spec, m.vsock, cfg, {
|
|
4568
|
-
silent: `nothing answered on the restored box's control channel for 3 s; the restored box was discarded, try again`,
|
|
4569
|
-
noAnswer: "the restored box was discarded. kvbox-agent inside it took the request but gave no answer; try again, and if it keeps happening look at the box's journal (kvbox exec <box> -- sudo journalctl -u kvbox-agent) on a box started from the same snapshot."
|
|
4570
|
-
});
|
|
4571
|
-
const stale = await pushAuthorizedKeys(box, m.vsock, p);
|
|
4572
|
-
if (stale && keysOrFail) throw new KvboxError(`${keysOrFail}: ${stale}`);
|
|
4573
|
-
if (image.volumes?.length) await dropGuestVolumes(box, m.vsock);
|
|
4574
|
-
await pushEnv(box, m.vsock, p);
|
|
4575
|
-
await driver().net.attach(box, cfg);
|
|
4576
|
-
await openPorts(spec, cfg, p);
|
|
4577
|
-
const meta = { ...spec, pid, bootId: currentBootId(), createdAt: (/* @__PURE__ */ new Date()).toISOString(), ...origin, memSnapshots: 1, sshKeysStale: stale ? true : void 0 };
|
|
4578
|
-
await writeMachineMeta(meta, p);
|
|
4579
|
-
recordState(meta, "running", "new", p, meta.createdAt);
|
|
4580
|
-
return toMachine(meta, p);
|
|
4581
|
-
} catch (err) {
|
|
4582
|
-
if (pid !== void 0) killQuietly(pid);
|
|
4583
|
-
await closePorts({ id, ip, sshPort }, cfg);
|
|
4584
|
-
if (tapCreated) await driver().net.remove(id, cfg).catch(() => void 0);
|
|
4585
|
-
await rm7(m.dir, { recursive: true, force: true });
|
|
4586
|
-
boxListChanged();
|
|
4587
|
-
throw err;
|
|
4588
|
-
} finally {
|
|
4589
|
-
drawn?.release();
|
|
4590
|
-
}
|
|
4591
|
-
}
|
|
4592
|
-
|
|
4593
5023
|
// src/core/machines/restore.ts
|
|
4594
5024
|
import { existsSync as existsSync10 } from "node:fs";
|
|
4595
5025
|
import { link } from "node:fs/promises";
|
|
@@ -4639,7 +5069,7 @@ async function restoreFrom(from, owner, req, cfg, p) {
|
|
|
4639
5069
|
await placeholderDrives(m.dir, snap.volumes ?? []);
|
|
4640
5070
|
return { vmstate: s.vmstate, mem: s.mem, label: shown(from), volumes: snap.volumes };
|
|
4641
5071
|
},
|
|
4642
|
-
{ source: `snapshot:${refKey(from)}`, autoHibernateSec: autoHibernateFor(req, cfg, manifest), idleCheck: manifest.idle, url: maskedUrl(manifest, vars) },
|
|
5072
|
+
{ source: `snapshot:${refKey(from)}`, autoHibernateSec: autoHibernateFor(req, cfg, manifest), idleCheck: manifest.idle, url: maskedUrl(manifest, vars), integrations: req.integrations !== void 0 ? requestedIntegrations(req.integrations) : inheritedIntegrations(snap.integrations, from.owner, owner) },
|
|
4643
5073
|
cfg,
|
|
4644
5074
|
p
|
|
4645
5075
|
);
|
|
@@ -4696,7 +5126,7 @@ async function createMachine(req, owner, p = paths(), from) {
|
|
|
4696
5126
|
} else await createOverlay(m.overlay, size2.diskGib);
|
|
4697
5127
|
if (vars.length > 0) await writeBoxEnv({ owner, name }, vars, p);
|
|
4698
5128
|
},
|
|
4699
|
-
{ source: from ? `backup:${from.id}` : "base", autoHibernateSec, idleCheck: manifest.idle, url: maskedUrl(manifest, vars) },
|
|
5129
|
+
{ source: from ? `backup:${from.id}` : "base", autoHibernateSec, idleCheck: manifest.idle, url: maskedUrl(manifest, vars), integrations: requestedIntegrations(req.integrations) },
|
|
4700
5130
|
cfg,
|
|
4701
5131
|
p
|
|
4702
5132
|
);
|
|
@@ -4705,11 +5135,11 @@ async function createMachine(req, owner, p = paths(), from) {
|
|
|
4705
5135
|
|
|
4706
5136
|
// src/core/machines/fork.ts
|
|
4707
5137
|
import { statSync as statSync4 } from "node:fs";
|
|
4708
|
-
import { rm as
|
|
5138
|
+
import { rm as rm10 } from "node:fs/promises";
|
|
4709
5139
|
|
|
4710
5140
|
// src/core/snapshots.ts
|
|
4711
5141
|
import { existsSync as existsSync11 } from "node:fs";
|
|
4712
|
-
import { link as link2, mkdir as mkdir6, readdir as readdir5, rename as rename7, rm as
|
|
5142
|
+
import { link as link2, mkdir as mkdir6, readdir as readdir5, rename as rename7, rm as rm9, stat as stat4 } from "node:fs/promises";
|
|
4713
5143
|
var NAME_RE2 = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
4714
5144
|
function toSnapshot(meta) {
|
|
4715
5145
|
return {
|
|
@@ -4770,7 +5200,7 @@ async function snapshotBox(ref, req, owner, p) {
|
|
|
4770
5200
|
if (existsSync11(final.dir) && !req.replace) throw new KvboxError(`snapshot ${req.name} already exists (--replace retakes it)`);
|
|
4771
5201
|
const s = req.replace ? p.snapshot(owner, `.${req.name}.new-${box.id}`) : final;
|
|
4772
5202
|
const cfg = await loadConfig(p);
|
|
4773
|
-
if (s !== final) await
|
|
5203
|
+
if (s !== final) await rm9(s.dir, { recursive: true, force: true });
|
|
4774
5204
|
await mkdir6(s.dir, { recursive: true, mode: 448 });
|
|
4775
5205
|
try {
|
|
4776
5206
|
const volumes = await captureDrivesOf(box, p);
|
|
@@ -4778,6 +5208,7 @@ async function snapshotBox(ref, req, owner, p) {
|
|
|
4778
5208
|
await copyBoxEnv(p.machine(box.owner, box.name).env, s.env);
|
|
4779
5209
|
const meta = {
|
|
4780
5210
|
...volumes.length > 0 ? { volumes } : {},
|
|
5211
|
+
...box.integrations?.length ? { integrations: [...box.integrations] } : {},
|
|
4781
5212
|
name: req.name,
|
|
4782
5213
|
owner,
|
|
4783
5214
|
source: refKey(box),
|
|
@@ -4792,7 +5223,7 @@ async function snapshotBox(ref, req, owner, p) {
|
|
|
4792
5223
|
if (s !== final) await swapIn({ owner, name: req.name }, s.dir, box.id, p);
|
|
4793
5224
|
return toSnapshot(meta);
|
|
4794
5225
|
} catch (err) {
|
|
4795
|
-
await
|
|
5226
|
+
await rm9(s.dir, { recursive: true, force: true });
|
|
4796
5227
|
throw err;
|
|
4797
5228
|
}
|
|
4798
5229
|
}
|
|
@@ -4800,7 +5231,7 @@ async function swapIn(ref, from, boxId, p) {
|
|
|
4800
5231
|
const to = p.snapshot(ref.owner, ref.name).dir;
|
|
4801
5232
|
const old = p.snapshot(ref.owner, `.${ref.name}.old-${boxId}`).dir;
|
|
4802
5233
|
await withSnapshotLock(ref, async () => {
|
|
4803
|
-
await
|
|
5234
|
+
await rm9(old, { recursive: true, force: true });
|
|
4804
5235
|
const hadOld = existsSync11(to);
|
|
4805
5236
|
if (hadOld) await rename7(to, old);
|
|
4806
5237
|
try {
|
|
@@ -4810,7 +5241,7 @@ async function swapIn(ref, from, boxId, p) {
|
|
|
4810
5241
|
throw err;
|
|
4811
5242
|
}
|
|
4812
5243
|
});
|
|
4813
|
-
await
|
|
5244
|
+
await rm9(old, { recursive: true, force: true });
|
|
4814
5245
|
}
|
|
4815
5246
|
async function captureBox(box, to, cfg, p) {
|
|
4816
5247
|
const m = p.machine(box.owner, box.name);
|
|
@@ -4839,10 +5270,10 @@ async function captureBox(box, to, cfg, p) {
|
|
|
4839
5270
|
} else if (since > 0) {
|
|
4840
5271
|
await mergeOntoPrevious(m.memBase, to.mem, cfg.snapshotEditor ?? p.snapshotEditor);
|
|
4841
5272
|
}
|
|
4842
|
-
await
|
|
5273
|
+
await rm9(m.memBase, { force: true });
|
|
4843
5274
|
await link2(to.mem, m.memBase);
|
|
4844
5275
|
} catch (err) {
|
|
4845
|
-
if (lineageTouched) await
|
|
5276
|
+
if (lineageTouched) await rm9(m.memBase, { force: true }).catch(() => void 0);
|
|
4846
5277
|
throw err;
|
|
4847
5278
|
}
|
|
4848
5279
|
}
|
|
@@ -4856,7 +5287,7 @@ async function mergeOntoPrevious(previous, diffFile, editor) {
|
|
|
4856
5287
|
async function deleteSnapshot(ref, p = paths()) {
|
|
4857
5288
|
const dir = p.snapshot(ref.owner, ref.name).dir;
|
|
4858
5289
|
if (ref.name.startsWith(".") || !existsSync11(dir)) throw new NotFoundError(`snapshot ${shown(ref)}`);
|
|
4859
|
-
await withSnapshotLock(ref, () =>
|
|
5290
|
+
await withSnapshotLock(ref, () => rm9(dir, { recursive: true, force: true }));
|
|
4860
5291
|
}
|
|
4861
5292
|
|
|
4862
5293
|
// src/core/machines/fork.ts
|
|
@@ -4891,7 +5322,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
|
|
|
4891
5322
|
const { ip, mac } = driver().net.allocate(cfg, existing.map((m) => m.ip));
|
|
4892
5323
|
const box = { id, name, owner, ip, mac, ...shape, base: src.base, image: src.image, sshKeys };
|
|
4893
5324
|
const srcEnv = p.machine(src.owner, src.name).env;
|
|
4894
|
-
const origin = { source: `fork:${refKey(src)}`, autoHibernateSec: (req.autoHibernateSec ?? src.autoHibernateSec) || void 0, idleCheck: src.idleCheck, url: src.url };
|
|
5325
|
+
const origin = { source: `fork:${refKey(src)}`, autoHibernateSec: (req.autoHibernateSec ?? src.autoHibernateSec) || void 0, idleCheck: src.idleCheck, url: src.url, integrations: inheritedIntegrations(src.integrations, src.owner, owner) };
|
|
4895
5326
|
if (!warm) {
|
|
4896
5327
|
return bootInto(
|
|
4897
5328
|
box,
|
|
@@ -4921,12 +5352,12 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
|
|
|
4921
5352
|
// another slug. Such a fork is discarded rather than kept stale; a cold fork boots with the new line.
|
|
4922
5353
|
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)`
|
|
4923
5354
|
);
|
|
4924
|
-
await
|
|
5355
|
+
await rm10(p.machine(owner, name).forkVmstate, { force: true });
|
|
4925
5356
|
return machine;
|
|
4926
5357
|
});
|
|
4927
5358
|
|
|
4928
5359
|
// src/core/machines/recovery.ts
|
|
4929
|
-
import { rm as
|
|
5360
|
+
import { rm as rm11 } from "node:fs/promises";
|
|
4930
5361
|
var RECOVERY_CONCURRENCY = 2;
|
|
4931
5362
|
async function settleDeadBoxes(p = paths()) {
|
|
4932
5363
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
@@ -4940,7 +5371,7 @@ async function settleDeadBoxes(p = paths()) {
|
|
|
4940
5371
|
} catch (err) {
|
|
4941
5372
|
log.warn(`usage ledger: ${err.message}`);
|
|
4942
5373
|
}
|
|
4943
|
-
await
|
|
5374
|
+
await rm11(p.machine(meta.owner, meta.name).memBase, { force: true });
|
|
4944
5375
|
if (meta.paused) {
|
|
4945
5376
|
await writeMachineMeta({ ...meta, pid: null, bootId: void 0, memSnapshots: void 0, paused: void 0 }, p);
|
|
4946
5377
|
leftStopped.push(refKey(meta));
|
|
@@ -4997,7 +5428,7 @@ async function bootRecovered(settled, p = paths()) {
|
|
|
4997
5428
|
|
|
4998
5429
|
// src/core/machines/standby.ts
|
|
4999
5430
|
import { existsSync as existsSync12 } from "node:fs";
|
|
5000
|
-
import { link as link3, mkdir as mkdir7, rm as
|
|
5431
|
+
import { link as link3, mkdir as mkdir7, rm as rm12 } from "node:fs/promises";
|
|
5001
5432
|
var pauseMachine = locked(async function pauseMachine2(ref, p = paths()) {
|
|
5002
5433
|
const meta = await readMeta(ref, p);
|
|
5003
5434
|
const status = statusOf(meta, p);
|
|
@@ -5022,6 +5453,7 @@ var resumeMachine = locked(async function resumeMachine2(ref, p = paths()) {
|
|
|
5022
5453
|
const running = { ...meta, paused: void 0, sshKeysStale: stale ? true : void 0 };
|
|
5023
5454
|
await writeMachineMeta(running, p);
|
|
5024
5455
|
recordState(running, "running", "resume", p);
|
|
5456
|
+
if (meta.pid !== null) void tellIntegrationsWhenUp(running, meta.pid, m.vsock, p);
|
|
5025
5457
|
return toMachine(running, p);
|
|
5026
5458
|
});
|
|
5027
5459
|
var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(), by = "hibernate") {
|
|
@@ -5031,14 +5463,14 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
|
|
|
5031
5463
|
if (status === "hibernated") throw new KvboxError(`${stateMessage(ref, status)} already`);
|
|
5032
5464
|
if (status === "stopped") throw new KvboxError(`${stateMessage(ref, status)}; only a running box can be hibernated (there is no memory to keep)`);
|
|
5033
5465
|
const m = p.machine(ref.owner, ref.name);
|
|
5034
|
-
await
|
|
5466
|
+
await rm12(m.hibernateDir, { recursive: true, force: true });
|
|
5035
5467
|
await mkdir7(m.hibernateDir, { recursive: true, mode: 448 });
|
|
5036
5468
|
const vm = driver().vm;
|
|
5037
5469
|
try {
|
|
5038
5470
|
await vm.pause(ref, p);
|
|
5039
5471
|
await vm.saveState(ref, { vmstate: m.hibernateVmstate, mem: m.hibernateMem }, "full", p);
|
|
5040
5472
|
} catch (err) {
|
|
5041
|
-
await
|
|
5473
|
+
await rm12(m.hibernateDir, { recursive: true, force: true });
|
|
5042
5474
|
if (!meta.paused) await vm.resume(ref, p).catch(() => void 0);
|
|
5043
5475
|
throw err;
|
|
5044
5476
|
}
|
|
@@ -5046,7 +5478,7 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
|
|
|
5046
5478
|
await waitFor(() => !pidAlive(meta.pid), 5e3, 50);
|
|
5047
5479
|
await cleanupProcess(meta, cfg, p);
|
|
5048
5480
|
await run(["fallocate", "--dig-holes", m.hibernateMem]);
|
|
5049
|
-
await
|
|
5481
|
+
await rm12(m.memBase, { force: true });
|
|
5050
5482
|
const hibernated = { ...meta, pid: null, memSnapshots: void 0, paused: void 0 };
|
|
5051
5483
|
await writeMachineMeta(hibernated, p);
|
|
5052
5484
|
recordState(hibernated, "hibernated", by, p);
|
|
@@ -5081,22 +5513,24 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths(), force = f
|
|
|
5081
5513
|
await openPorts(meta, cfg, p);
|
|
5082
5514
|
} catch (err) {
|
|
5083
5515
|
if (pid !== void 0) killQuietly(pid);
|
|
5516
|
+
await stopListeningForGuest(meta, p);
|
|
5084
5517
|
await closePorts(meta, cfg);
|
|
5085
5518
|
await driver().net.remove(meta.id, cfg).catch(() => void 0);
|
|
5086
5519
|
throw err;
|
|
5087
5520
|
}
|
|
5088
|
-
await
|
|
5521
|
+
await rm12(m.memBase, { force: true });
|
|
5089
5522
|
await link3(m.hibernateMem, m.memBase);
|
|
5090
|
-
await
|
|
5523
|
+
await rm12(m.hibernateDir, { recursive: true, force: true });
|
|
5091
5524
|
const running = { ...meta, pid, bootId: currentBootId(), memSnapshots: 1, paused: void 0, sshKeysStale: stale ? true : void 0 };
|
|
5092
5525
|
await writeMachineMeta(running, p);
|
|
5093
5526
|
recordState(running, "running", "wake", p);
|
|
5527
|
+
void tellIntegrationsWhenUp(running, pid, m.vsock, p);
|
|
5094
5528
|
return toMachine(running, p);
|
|
5095
5529
|
});
|
|
5096
5530
|
|
|
5097
5531
|
// src/core/machines/volumes.ts
|
|
5098
5532
|
import { statSync as statSync5 } from "node:fs";
|
|
5099
|
-
import { rename as rename8, rm as
|
|
5533
|
+
import { rename as rename8, rm as rm13 } from "node:fs/promises";
|
|
5100
5534
|
var attachVolume = locked(async function attachVolume2(ref, volume, p = paths()) {
|
|
5101
5535
|
const cfg = await loadConfig(p);
|
|
5102
5536
|
const claimed = await withHostLock("volumes", async () => {
|
|
@@ -5119,7 +5553,7 @@ var detachVolume = locked(async function detachVolume2(ref, volume, p = paths())
|
|
|
5119
5553
|
if (!meta.volumes?.includes(volume.name) || volume.owner !== meta.owner) throw new KvboxError(`volume ${shown(volume)} is not attached to box ${shown(ref)}`);
|
|
5120
5554
|
assertNotHibernated(meta, p);
|
|
5121
5555
|
const kept = meta.volumes.filter((v) => v !== volume.name);
|
|
5122
|
-
return applyAtNextBoot(meta, { volumes: kept.length > 0 ? kept : void 0 }, "detach", cfg, p, () =>
|
|
5556
|
+
return applyAtNextBoot(meta, { volumes: kept.length > 0 ? kept : void 0 }, "detach", cfg, p, () => rm13(p.machine(ref.owner, ref.name).volumeDrive(volume.name), { force: true }));
|
|
5123
5557
|
});
|
|
5124
5558
|
async function resizeVolume(volume, sizeGib, p = paths()) {
|
|
5125
5559
|
await assertCanGrow(volume, sizeGib, p);
|
|
@@ -5175,9 +5609,9 @@ async function replaceVolumeDisk(volume, file, p = paths()) {
|
|
|
5175
5609
|
// src/core/backups.ts
|
|
5176
5610
|
import { randomBytes as randomBytes5 } from "node:crypto";
|
|
5177
5611
|
import { existsSync as existsSync13 } from "node:fs";
|
|
5178
|
-
import { mkdir as mkdir8, open, readdir as readdir6, readFile as readFile9, rm as
|
|
5612
|
+
import { mkdir as mkdir8, open, readdir as readdir6, readFile as readFile9, rm as rm14, stat as stat5, statfs as statfs3, writeFile as writeFile7 } from "node:fs/promises";
|
|
5179
5613
|
import { basename as basename2, join as join3 } from "node:path";
|
|
5180
|
-
import { setTimeout as
|
|
5614
|
+
import { setTimeout as sleep5 } from "node:timers/promises";
|
|
5181
5615
|
|
|
5182
5616
|
// ../shared/src/backup.ts
|
|
5183
5617
|
import { createCipheriv, createDecipheriv, createHmac, randomBytes as randomBytes4 } from "node:crypto";
|
|
@@ -5347,7 +5781,7 @@ async function stageBackup(ref, req, p = paths()) {
|
|
|
5347
5781
|
checkId(req.id);
|
|
5348
5782
|
const keys = backupKeys(req.key);
|
|
5349
5783
|
const s = p.backup(req.id);
|
|
5350
|
-
await
|
|
5784
|
+
await rm14(s.dir, { recursive: true, force: true });
|
|
5351
5785
|
await mkdir8(s.dir, { recursive: true, mode: 448 });
|
|
5352
5786
|
try {
|
|
5353
5787
|
const { meta, envText } = await withBoxLock(ref, async () => {
|
|
@@ -5368,10 +5802,11 @@ async function stageBackup(ref, req, p = paths()) {
|
|
|
5368
5802
|
base: meta.base,
|
|
5369
5803
|
...meta.image !== void 0 ? { image: meta.image } : {},
|
|
5370
5804
|
vcpu: meta.vcpu,
|
|
5371
|
-
memMib: meta.memMib
|
|
5805
|
+
memMib: meta.memMib,
|
|
5806
|
+
...meta.integrations?.length ? { integrations: [...meta.integrations] } : {}
|
|
5372
5807
|
};
|
|
5373
5808
|
} catch (err) {
|
|
5374
|
-
await
|
|
5809
|
+
await rm14(s.dir, { recursive: true, force: true });
|
|
5375
5810
|
throw err;
|
|
5376
5811
|
}
|
|
5377
5812
|
}
|
|
@@ -5390,7 +5825,7 @@ async function stageVolumeBackup(ref, req, p = paths()) {
|
|
|
5390
5825
|
await readVolume(ref, p);
|
|
5391
5826
|
const from = p.volume(ref.owner, ref.name).disk;
|
|
5392
5827
|
const s = p.backup(req.id);
|
|
5393
|
-
await
|
|
5828
|
+
await rm14(s.dir, { recursive: true, force: true });
|
|
5394
5829
|
await mkdir8(s.dir, { recursive: true, mode: 448 });
|
|
5395
5830
|
try {
|
|
5396
5831
|
await assertRoom(s.dir, 0, `a backup of volume ${shown(ref)}`, p);
|
|
@@ -5413,7 +5848,7 @@ async function stageVolumeBackup(ref, req, p = paths()) {
|
|
|
5413
5848
|
await writeFile7(s.chunks, JSON.stringify({ chunks }), { mode: 384 });
|
|
5414
5849
|
return { id: req.id, sizeBytes, chunks };
|
|
5415
5850
|
} catch (err) {
|
|
5416
|
-
await
|
|
5851
|
+
await rm14(s.dir, { recursive: true, force: true });
|
|
5417
5852
|
throw err;
|
|
5418
5853
|
}
|
|
5419
5854
|
}
|
|
@@ -5478,25 +5913,25 @@ async function uploadOnce(id, req, signal, p) {
|
|
|
5478
5913
|
} finally {
|
|
5479
5914
|
await fh.close();
|
|
5480
5915
|
}
|
|
5481
|
-
await
|
|
5916
|
+
await rm14(s.dir, { recursive: true, force: true });
|
|
5482
5917
|
return { chunks: work.length, bytes, sizes };
|
|
5483
5918
|
}
|
|
5484
5919
|
async function dropBackup(id, p = paths()) {
|
|
5485
5920
|
checkId(id);
|
|
5486
5921
|
uploads.get(id)?.abort();
|
|
5487
|
-
await
|
|
5922
|
+
await rm14(p.backup(id).dir, { recursive: true, force: true });
|
|
5488
5923
|
}
|
|
5489
5924
|
async function clearStagedBackups(p = paths()) {
|
|
5490
|
-
await
|
|
5925
|
+
await rm14(p.backups, { recursive: true, force: true });
|
|
5491
5926
|
const prefix = basename2(p.machine("x", "x").restoring);
|
|
5492
5927
|
for (const ref of await listMachineRefs(p)) {
|
|
5493
5928
|
const dir = p.machine(ref.owner, ref.name).dir;
|
|
5494
|
-
for (const f of await readdir6(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await
|
|
5929
|
+
for (const f of await readdir6(dir).catch(() => [])) if (f === prefix || f.startsWith(`${prefix}.`)) await rm14(join3(dir, f), { force: true });
|
|
5495
5930
|
}
|
|
5496
5931
|
const volumePrefix = basename2(p.volume("x", "x").restoring);
|
|
5497
5932
|
for (const ref of await listVolumeRefs(p)) {
|
|
5498
5933
|
const dir = p.volume(ref.owner, ref.name).dir;
|
|
5499
|
-
for (const f of await readdir6(dir).catch(() => [])) if (f.startsWith(`${volumePrefix}.`)) await
|
|
5934
|
+
for (const f of await readdir6(dir).catch(() => [])) if (f.startsWith(`${volumePrefix}.`)) await rm14(join3(dir, f), { force: true });
|
|
5500
5935
|
}
|
|
5501
5936
|
}
|
|
5502
5937
|
async function downloadDisk(file, req, p = paths()) {
|
|
@@ -5570,8 +6005,8 @@ async function restoreOnce(ref, req, p) {
|
|
|
5570
6005
|
await downloadDisk(file, req, p);
|
|
5571
6006
|
return await replaceDisk(ref, file, { base: req.base, image: req.image, vars }, p);
|
|
5572
6007
|
} finally {
|
|
5573
|
-
await
|
|
5574
|
-
await
|
|
6008
|
+
await rm14(file, { force: true });
|
|
6009
|
+
await rm14(envFile, { force: true });
|
|
5575
6010
|
}
|
|
5576
6011
|
}
|
|
5577
6012
|
async function createFromBackup(req, owner, p = paths()) {
|
|
@@ -5596,7 +6031,7 @@ async function createFromBackup(req, owner, p = paths()) {
|
|
|
5596
6031
|
const sent = create;
|
|
5597
6032
|
return await createMachine(sent, owner, p, { disk, base, image: backup.image, vars, id: backup.id });
|
|
5598
6033
|
} finally {
|
|
5599
|
-
await
|
|
6034
|
+
await rm14(dir, { recursive: true, force: true });
|
|
5600
6035
|
}
|
|
5601
6036
|
}
|
|
5602
6037
|
async function baseFor(backup, p) {
|
|
@@ -5649,7 +6084,7 @@ async function restoreVolumeBackup(ref, req, p = paths()) {
|
|
|
5649
6084
|
if (n > 0) holding.set(held2, n);
|
|
5650
6085
|
else holding.delete(held2);
|
|
5651
6086
|
}
|
|
5652
|
-
await
|
|
6087
|
+
await rm14(file, { force: true });
|
|
5653
6088
|
}
|
|
5654
6089
|
}
|
|
5655
6090
|
async function pool(items, fn) {
|
|
@@ -5677,34 +6112,34 @@ async function withTries(what, fn, signal) {
|
|
|
5677
6112
|
} catch (err) {
|
|
5678
6113
|
if (signal?.aborted) throw new KvboxError(`${what}: the backup was dropped`);
|
|
5679
6114
|
last = err;
|
|
5680
|
-
await
|
|
6115
|
+
await sleep5(250 * 2 ** i);
|
|
5681
6116
|
}
|
|
5682
6117
|
}
|
|
5683
6118
|
throw new KvboxError(`${what} failed ${TRIES} times: ${last.message}`);
|
|
5684
6119
|
}
|
|
5685
6120
|
|
|
5686
6121
|
// src/core/relay.ts
|
|
5687
|
-
import { access as access2, chmod as chmod4, mkdir as mkdir10, rm as
|
|
6122
|
+
import { access as access2, chmod as chmod4, mkdir as mkdir10, rm as rm15, writeFile as writeFile8 } from "node:fs/promises";
|
|
5688
6123
|
|
|
5689
6124
|
// ../shared/src/relay.ts
|
|
5690
|
-
import { z as
|
|
6125
|
+
import { z as z8 } from "zod";
|
|
5691
6126
|
var RELAY_TUNNEL_GATEWAY = "10.77.0.1";
|
|
5692
6127
|
var IPV4_RE = /^(\d{1,3})(\.\d{1,3}){3}$/;
|
|
5693
6128
|
var WG_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
|
|
5694
|
-
var RelayJoinSchema =
|
|
5695
|
-
v:
|
|
6129
|
+
var RelayJoinSchema = z8.object({
|
|
6130
|
+
v: z8.literal(1),
|
|
5696
6131
|
/** How the relay lists this host. */
|
|
5697
|
-
name:
|
|
6132
|
+
name: z8.string().regex(/^[a-z0-9][a-z0-9-]{0,30}$/),
|
|
5698
6133
|
/** `<relay-primary-ip>:<port>`, the WireGuard endpoint the host dials. */
|
|
5699
|
-
relay:
|
|
6134
|
+
relay: z8.string().regex(/^(\d{1,3})(\.\d{1,3}){3}:\d{1,5}$/),
|
|
5700
6135
|
/** The relay's WireGuard public key. */
|
|
5701
|
-
relayKey:
|
|
6136
|
+
relayKey: z8.string().regex(WG_KEY_RE),
|
|
5702
6137
|
/** This host's address inside the tunnel. */
|
|
5703
|
-
tunnelIp:
|
|
6138
|
+
tunnelIp: z8.string().regex(IPV4_RE),
|
|
5704
6139
|
/** This host's WireGuard private key, generated on the relay, kept nowhere else. */
|
|
5705
|
-
privateKey:
|
|
6140
|
+
privateKey: z8.string().regex(WG_KEY_RE),
|
|
5706
6141
|
/** The extra public IPv4 the relay owns for this host; what the host advertises to the control plane. */
|
|
5707
|
-
publicIp:
|
|
6142
|
+
publicIp: z8.string().regex(IPV4_RE)
|
|
5708
6143
|
});
|
|
5709
6144
|
function decodeRelayJoin(text) {
|
|
5710
6145
|
let parsed;
|
|
@@ -5721,7 +6156,7 @@ function decodeRelayJoin(text) {
|
|
|
5721
6156
|
import { X509Certificate } from "node:crypto";
|
|
5722
6157
|
import { chmod as chmod3, mkdir as mkdir9, readFile as readFile10 } from "node:fs/promises";
|
|
5723
6158
|
import { hostname as osHostname } from "node:os";
|
|
5724
|
-
import { request as
|
|
6159
|
+
import { request as request4 } from "undici";
|
|
5725
6160
|
|
|
5726
6161
|
// ../shared/src/country.ts
|
|
5727
6162
|
var names = new Intl.DisplayNames(["en"], { type: "region", fallback: "none" });
|
|
@@ -5826,7 +6261,7 @@ async function joinControlPlane(opts, p = paths(), guessAddress = defaultAdverti
|
|
|
5826
6261
|
const { fingerprint } = await ensureTlsCert(p);
|
|
5827
6262
|
const hostUrl = `https://${advertise}:${port}`;
|
|
5828
6263
|
const body = { token: opts.token, name, url: hostUrl, fingerprint, publicAddress: advertise, ...country !== void 0 ? { country } : {} };
|
|
5829
|
-
const res = await
|
|
6264
|
+
const res = await request4(`${url}/hosts/join`, {
|
|
5830
6265
|
method: "POST",
|
|
5831
6266
|
headers: { "content-type": "application/json" },
|
|
5832
6267
|
body: JSON.stringify(body),
|
|
@@ -5851,7 +6286,7 @@ async function fetchCloudCa(p = paths()) {
|
|
|
5851
6286
|
const cfg = await loadConfig(p);
|
|
5852
6287
|
const cp = cfg.controlPlane;
|
|
5853
6288
|
if (!cp) throw new KvboxError("this host has not joined a control plane, so there is no CA to fetch; paste the key instead: kvbox-server trust-ca <public-key>");
|
|
5854
|
-
const res = await
|
|
6289
|
+
const res = await request4(`${cp.url}/hosts/self/ssh-ca`, {
|
|
5855
6290
|
headers: { authorization: `Bearer ${cp.secret}` },
|
|
5856
6291
|
headersTimeout: 1e4,
|
|
5857
6292
|
bodyTimeout: 1e4
|
|
@@ -5870,7 +6305,7 @@ async function fetchCloudName(p = paths()) {
|
|
|
5870
6305
|
const cfg = await loadConfig(p);
|
|
5871
6306
|
const cp = cfg.controlPlane;
|
|
5872
6307
|
if (!cp) throw new KvboxError("this host has not joined a control plane, so there is no name to ask for; give it: kvbox-server rename-realm <name>");
|
|
5873
|
-
const res = await
|
|
6308
|
+
const res = await request4(`${cp.url}/health`, { headersTimeout: 1e4, bodyTimeout: 1e4 }).catch((err) => {
|
|
5874
6309
|
throw new KvboxError(`cannot reach ${cp.url} (${err.message})`);
|
|
5875
6310
|
});
|
|
5876
6311
|
const text = await res.body.text();
|
|
@@ -5883,7 +6318,7 @@ async function leaveControlPlane(p = paths()) {
|
|
|
5883
6318
|
const cfg = await loadConfig(p);
|
|
5884
6319
|
const cp = cfg.controlPlane;
|
|
5885
6320
|
if (!cp) throw new KvboxError("this host has not joined a control plane");
|
|
5886
|
-
const
|
|
6321
|
+
const told2 = await request4(`${cp.url}/hosts/self`, {
|
|
5887
6322
|
method: "DELETE",
|
|
5888
6323
|
headers: { authorization: `Bearer ${cp.secret}` },
|
|
5889
6324
|
headersTimeout: 3e3,
|
|
@@ -5894,7 +6329,7 @@ async function leaveControlPlane(p = paths()) {
|
|
|
5894
6329
|
}).catch(() => false);
|
|
5895
6330
|
const { controlPlane: _gone, ...rest } = cfg;
|
|
5896
6331
|
await saveConfig({ ...rest, ...rest.backupStore ? { backupStore: { ...rest.backupStore, registered: false } } : {} }, p);
|
|
5897
|
-
return { controlPlane: cp.name, told };
|
|
6332
|
+
return { controlPlane: cp.name, told: told2 };
|
|
5898
6333
|
}
|
|
5899
6334
|
function jsonOrNull(text) {
|
|
5900
6335
|
try {
|
|
@@ -5963,7 +6398,7 @@ async function dropRelay(p = paths()) {
|
|
|
5963
6398
|
throw new KvboxError(`${cfg.controlPlane.name} reaches this host through the relay (${relay.publicIp}); run kvbox-server leave first`);
|
|
5964
6399
|
}
|
|
5965
6400
|
await driver().net.relay(cfg, ["relay", "down"]);
|
|
5966
|
-
await
|
|
6401
|
+
await rm15(p.relayConf, { force: true });
|
|
5967
6402
|
const { relay: _gone, ...rest } = cfg;
|
|
5968
6403
|
await saveConfig(rest, p);
|
|
5969
6404
|
return relay;
|
|
@@ -5993,7 +6428,7 @@ function boxHasRun(ref, now = Date.now()) {
|
|
|
5993
6428
|
if (runs.size === 0) going.delete(keyOf(ref));
|
|
5994
6429
|
return runs.size > 0;
|
|
5995
6430
|
}
|
|
5996
|
-
async function
|
|
6431
|
+
async function socketOf2(ref, p) {
|
|
5997
6432
|
const meta = await readMachineMeta(ref, p).catch((err) => {
|
|
5998
6433
|
if (err.code === "ENOENT") throw new NotFoundError(`box ${shown(ref)}`);
|
|
5999
6434
|
throw err;
|
|
@@ -6003,7 +6438,7 @@ async function socketOf(ref, p) {
|
|
|
6003
6438
|
return p.machine(meta.owner, meta.name).vsock;
|
|
6004
6439
|
}
|
|
6005
6440
|
var OUTPUT_BASE = "v0.16.0";
|
|
6006
|
-
var
|
|
6441
|
+
var outdated2 = (ref, err, needs = "v0.15.0") => {
|
|
6007
6442
|
if (isUnknownOp(err)) throw new BoxOutdatedError(`box ${shown(ref)} runs on an image from before ${needs === OUTPUT_BASE ? "reading a command's output" : "commands"} (it needs base ${needs} or later)`);
|
|
6008
6443
|
if (isNoAgent(err)) throw new AgentNotAnsweringError(`box ${shown(ref)} did not take the request: its kvbox-agent is not answering (${err.message}); ask again`);
|
|
6009
6444
|
throw err;
|
|
@@ -6014,25 +6449,25 @@ var unanswered = (ref, err, needs) => {
|
|
|
6014
6449
|
if (isNoAgent(err) || /kvbox-agent did not answer within/.test(err.message ?? "")) {
|
|
6015
6450
|
throw new AgentNotAnsweringError(`box ${shown(ref)}: its kvbox-agent is not answering (${err.message}); ask again`);
|
|
6016
6451
|
}
|
|
6017
|
-
return
|
|
6452
|
+
return outdated2(ref, err, needs);
|
|
6018
6453
|
};
|
|
6019
6454
|
async function startBoxRun(ref, req, p = paths()) {
|
|
6020
|
-
const vsock = await
|
|
6021
|
-
if (req.output) await runOutput(vsock, req.id, "stdout", 0, 0).catch((err) =>
|
|
6455
|
+
const vsock = await socketOf2(ref, p);
|
|
6456
|
+
if (req.output) await runOutput(vsock, req.id, "stdout", 0, 0).catch((err) => outdated2(ref, err, OUTPUT_BASE));
|
|
6022
6457
|
const had = going.get(keyOf(ref))?.has(req.id) ?? false;
|
|
6023
6458
|
note(ref, req.id, Date.now() + req.timeoutSec * 1e3 + 6e4);
|
|
6024
6459
|
return startRun(vsock, req.id, req.command, req.timeoutSec).catch((err) => {
|
|
6025
6460
|
if (!had) note(ref, req.id, null);
|
|
6026
|
-
return
|
|
6461
|
+
return outdated2(ref, err);
|
|
6027
6462
|
});
|
|
6028
6463
|
}
|
|
6029
6464
|
async function boxRunOutput(ref, id, stream, offset, limit, p = paths()) {
|
|
6030
|
-
const vsock = await
|
|
6465
|
+
const vsock = await socketOf2(ref, p);
|
|
6031
6466
|
const out = await runOutput(vsock, id, stream, offset, limit).catch((err) => unanswered(ref, err, OUTPUT_BASE));
|
|
6032
6467
|
return { id, stream, ...out };
|
|
6033
6468
|
}
|
|
6034
6469
|
async function boxRunStatus(ref, id, p = paths()) {
|
|
6035
|
-
const vsock = await
|
|
6470
|
+
const vsock = await socketOf2(ref, p);
|
|
6036
6471
|
const run2 = await runStatus(vsock, id).catch((err) => unanswered(ref, err));
|
|
6037
6472
|
note(ref, id, run2.state === "running" ? Date.now() + SEEN_RUNNING_MS : null);
|
|
6038
6473
|
return { id, ...run2 };
|
|
@@ -6203,7 +6638,7 @@ import { spawn as spawn3 } from "node:child_process";
|
|
|
6203
6638
|
import { accessSync, constants as constants2, openSync as openSync5, readFileSync as readFileSync3, statSync as statSync6 } from "node:fs";
|
|
6204
6639
|
import { mkdir as mkdir11, readFile as readFile11, stat as stat6 } from "node:fs/promises";
|
|
6205
6640
|
import { userInfo as userInfo3 } from "node:os";
|
|
6206
|
-
import { setTimeout as
|
|
6641
|
+
import { setTimeout as sleep6 } from "node:timers/promises";
|
|
6207
6642
|
|
|
6208
6643
|
// ../shared/src/systemd.ts
|
|
6209
6644
|
import { spawnSync } from "node:child_process";
|
|
@@ -6239,7 +6674,7 @@ function startsAtBoot(p) {
|
|
|
6239
6674
|
}
|
|
6240
6675
|
|
|
6241
6676
|
// src/socketClient.ts
|
|
6242
|
-
import { Agent as Agent3, request as
|
|
6677
|
+
import { Agent as Agent3, request as request5 } from "undici";
|
|
6243
6678
|
var SocketClient = class {
|
|
6244
6679
|
agent;
|
|
6245
6680
|
constructor(socketPath) {
|
|
@@ -6267,7 +6702,7 @@ var SocketClient = class {
|
|
|
6267
6702
|
async call(method, path, schema, body, timeoutMs) {
|
|
6268
6703
|
let res;
|
|
6269
6704
|
try {
|
|
6270
|
-
res = await
|
|
6705
|
+
res = await request5(`http://kvbox-server${path}`, {
|
|
6271
6706
|
method,
|
|
6272
6707
|
dispatcher: this.agent,
|
|
6273
6708
|
...timeoutMs === void 0 ? {} : { headersTimeout: timeoutMs, bodyTimeout: timeoutMs },
|
|
@@ -6338,7 +6773,7 @@ async function stopDaemon(pid, timeoutMs = 1e4) {
|
|
|
6338
6773
|
const deadline = Date.now() + timeoutMs;
|
|
6339
6774
|
while (alive(pid)) {
|
|
6340
6775
|
if (Date.now() > deadline) throw new KvboxError(`kvbox-server (pid ${pid}) did not stop within ${timeoutMs / 1e3}s`);
|
|
6341
|
-
await
|
|
6776
|
+
await sleep6(100);
|
|
6342
6777
|
}
|
|
6343
6778
|
}
|
|
6344
6779
|
async function answering(p = paths()) {
|
|
@@ -6411,7 +6846,7 @@ async function serving(p, timeoutMs, check) {
|
|
|
6411
6846
|
await probe.close();
|
|
6412
6847
|
}
|
|
6413
6848
|
}
|
|
6414
|
-
await
|
|
6849
|
+
await sleep6(100);
|
|
6415
6850
|
}
|
|
6416
6851
|
throw new KvboxError(`kvbox-server did not start within ${timeoutMs / 1e3}s; see ${p.serverLog}`);
|
|
6417
6852
|
}
|
|
@@ -6464,7 +6899,7 @@ function groupWithMember(gid, user, groupFile) {
|
|
|
6464
6899
|
}
|
|
6465
6900
|
|
|
6466
6901
|
// src/listen.ts
|
|
6467
|
-
import { readFile as readFile13, rm as
|
|
6902
|
+
import { readFile as readFile13, rm as rm16, writeFile as writeFile10 } from "node:fs/promises";
|
|
6468
6903
|
import { createServer as createHttpsServer } from "node:https";
|
|
6469
6904
|
import { createAdaptorServer } from "@hono/node-server";
|
|
6470
6905
|
|
|
@@ -6475,7 +6910,7 @@ var PROXIED_HEADER = "x-kvbox-proxied";
|
|
|
6475
6910
|
var VISITOR_PATH_HEADER = "x-kvbox-path";
|
|
6476
6911
|
var WAKE_HEADER = "x-kvbox-wake";
|
|
6477
6912
|
var WAKE_WAIT_MS = 3e4;
|
|
6478
|
-
var
|
|
6913
|
+
var REQUEST_TIMEOUT_MS2 = 36e5;
|
|
6479
6914
|
var WOKE_HEADER = "x-kvbox-woke";
|
|
6480
6915
|
var VISITOR_AUTH_HEADER = "x-kvbox-authorization";
|
|
6481
6916
|
var NOT_FORWARDED = /* @__PURE__ */ new Set(["expect"]);
|
|
@@ -6505,7 +6940,7 @@ function versionOf(srcFileUrl, injected) {
|
|
|
6505
6940
|
}
|
|
6506
6941
|
|
|
6507
6942
|
// src/version.ts
|
|
6508
|
-
var VERSION = versionOf(import.meta.url, true ? "0.6.
|
|
6943
|
+
var VERSION = versionOf(import.meta.url, true ? "0.6.13" : void 0);
|
|
6509
6944
|
|
|
6510
6945
|
// src/caller.ts
|
|
6511
6946
|
import { createHash as createHash3, timingSafeEqual } from "node:crypto";
|
|
@@ -6682,7 +7117,7 @@ function backupStoreRoutes(opts = {}) {
|
|
|
6682
7117
|
import { connect as connect2 } from "node:net";
|
|
6683
7118
|
import { Readable } from "node:stream";
|
|
6684
7119
|
import { Hono as Hono3 } from "hono";
|
|
6685
|
-
import { request as
|
|
7120
|
+
import { request as request6 } from "undici";
|
|
6686
7121
|
|
|
6687
7122
|
// ../shared/src/httpHead.ts
|
|
6688
7123
|
var END = "\r\n\r\n";
|
|
@@ -6827,7 +7262,7 @@ async function forward(c, wake) {
|
|
|
6827
7262
|
raw.headers.forEach((value, name) => pairs.push([name, value]));
|
|
6828
7263
|
let res;
|
|
6829
7264
|
try {
|
|
6830
|
-
res = await
|
|
7265
|
+
res = await request6(`http://${target.ip}:${target.port}${target.path}`, {
|
|
6831
7266
|
method: raw.method,
|
|
6832
7267
|
headers: boxHeaders(pairs, target).flat(),
|
|
6833
7268
|
body: raw.body === null ? null : Readable.fromWeb(raw.body),
|
|
@@ -7108,18 +7543,18 @@ function machineRoutes() {
|
|
|
7108
7543
|
|
|
7109
7544
|
// src/routes/runs.ts
|
|
7110
7545
|
import { Hono as Hono7 } from "hono";
|
|
7111
|
-
import { z as
|
|
7112
|
-
var
|
|
7546
|
+
import { z as z9 } from "zod";
|
|
7547
|
+
var refusal2 = (c, err) => {
|
|
7113
7548
|
if (err instanceof ProxyFailure) return c.json({ error: err.message, code: err.code }, err.status);
|
|
7114
7549
|
if (err instanceof BoxOutdatedError) return c.json({ error: err.message, code: "box-outdated" }, 409);
|
|
7115
7550
|
if (err instanceof AgentNotAnsweringError) return c.json({ error: err.message, code: "unreachable" }, 503);
|
|
7116
7551
|
if (err instanceof NotFoundError) return c.json({ error: err.message, code: "not-found" }, 404);
|
|
7117
7552
|
throw err;
|
|
7118
7553
|
};
|
|
7119
|
-
var OutputQuery =
|
|
7120
|
-
stream:
|
|
7121
|
-
offset:
|
|
7122
|
-
limit:
|
|
7554
|
+
var OutputQuery = z9.object({
|
|
7555
|
+
stream: z9.enum(RUN_STREAMS).default("stdout"),
|
|
7556
|
+
offset: z9.coerce.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).default(0),
|
|
7557
|
+
limit: z9.coerce.number().int().min(0).max(RUN_OUTPUT_MAX_BYTES).default(RUN_OUTPUT_MAX_BYTES)
|
|
7123
7558
|
});
|
|
7124
7559
|
function runRoutes(wake = wakeBox) {
|
|
7125
7560
|
const r = new Hono7();
|
|
@@ -7130,7 +7565,7 @@ function runRoutes(wake = wakeBox) {
|
|
|
7130
7565
|
const started = await startBoxRun(ref, body);
|
|
7131
7566
|
return c.json(StartRunAnswerSchema.parse({ id: body.id, started, woke }), 202);
|
|
7132
7567
|
} catch (err) {
|
|
7133
|
-
return
|
|
7568
|
+
return refusal2(c, err);
|
|
7134
7569
|
}
|
|
7135
7570
|
});
|
|
7136
7571
|
r.get("/:name/runs/:id", async (c) => {
|
|
@@ -7138,7 +7573,7 @@ function runRoutes(wake = wakeBox) {
|
|
|
7138
7573
|
const { ref } = await runningBox(c.req.param("name"), c.get("owner"), wants(c.req.header(WAKE_HEADER)) ? wake : void 0);
|
|
7139
7574
|
return c.json(BoxRunSchema.parse(await boxRunStatus(ref, c.req.param("id"))));
|
|
7140
7575
|
} catch (err) {
|
|
7141
|
-
return
|
|
7576
|
+
return refusal2(c, err);
|
|
7142
7577
|
}
|
|
7143
7578
|
});
|
|
7144
7579
|
r.get("/:name/runs/:id/output", async (c) => {
|
|
@@ -7151,7 +7586,7 @@ function runRoutes(wake = wakeBox) {
|
|
|
7151
7586
|
const { ref } = await runningBox(c.req.param("name"), c.get("owner"));
|
|
7152
7587
|
return c.json(RunOutputSchema.parse(await boxRunOutput(ref, id, stream, offset, limit)));
|
|
7153
7588
|
} catch (err) {
|
|
7154
|
-
return
|
|
7589
|
+
return refusal2(c, err);
|
|
7155
7590
|
}
|
|
7156
7591
|
});
|
|
7157
7592
|
return r;
|
|
@@ -7313,7 +7748,7 @@ async function listen(opts = {}) {
|
|
|
7313
7748
|
throw new KvboxError(`socket path too long for a Unix socket (${socketPath}); set KVBOX_HOME to a shorter path`);
|
|
7314
7749
|
}
|
|
7315
7750
|
if (socketPath === p.serverSock) await refuseSecondDaemon(p);
|
|
7316
|
-
await
|
|
7751
|
+
await rm16(socketPath, { force: true });
|
|
7317
7752
|
const server = createAdaptorServer({ fetch: createApp().fetch });
|
|
7318
7753
|
await new Promise((resolve3, reject) => {
|
|
7319
7754
|
server.once("error", reject);
|
|
@@ -7332,7 +7767,7 @@ async function listen(opts = {}) {
|
|
|
7332
7767
|
fetch: createApp({ controlPlane: { name: cp.name, secret: cp.secret } }).fetch,
|
|
7333
7768
|
createServer: createHttpsServer,
|
|
7334
7769
|
// A body forwarded to a box may take long to arrive (a large upload through the edge, #182).
|
|
7335
|
-
serverOptions: { key, cert, requestTimeout:
|
|
7770
|
+
serverOptions: { key, cert, requestTimeout: REQUEST_TIMEOUT_MS2 }
|
|
7336
7771
|
});
|
|
7337
7772
|
const appListeners = httpsServer.listeners("request");
|
|
7338
7773
|
httpsServer.removeAllListeners("request");
|
|
@@ -7351,8 +7786,8 @@ async function listen(opts = {}) {
|
|
|
7351
7786
|
httpsServer.listen(port, "0.0.0.0", () => resolve3());
|
|
7352
7787
|
}).catch(async (err) => {
|
|
7353
7788
|
server.close();
|
|
7354
|
-
await
|
|
7355
|
-
await
|
|
7789
|
+
await rm16(socketPath, { force: true });
|
|
7790
|
+
await rm16(p.serverPid, { force: true });
|
|
7356
7791
|
throw new KvboxError(`cannot listen on port ${port} for ${cp.name} (${err.message})`);
|
|
7357
7792
|
});
|
|
7358
7793
|
const bound = httpsServer.address().port;
|
|
@@ -7363,15 +7798,15 @@ async function listen(opts = {}) {
|
|
|
7363
7798
|
new Promise((resolve3) => server.close(() => resolve3())),
|
|
7364
7799
|
httpsServer ? new Promise((resolve3) => httpsServer.close(() => resolve3())) : void 0
|
|
7365
7800
|
]);
|
|
7366
|
-
await
|
|
7367
|
-
await
|
|
7801
|
+
await rm16(socketPath, { force: true });
|
|
7802
|
+
await rm16(p.serverPid, { force: true });
|
|
7368
7803
|
};
|
|
7369
7804
|
const shutdown3 = async () => {
|
|
7370
7805
|
server.close();
|
|
7371
7806
|
httpsServer?.close();
|
|
7372
7807
|
await stopRecovery();
|
|
7373
|
-
await
|
|
7374
|
-
await
|
|
7808
|
+
await rm16(socketPath, { force: true });
|
|
7809
|
+
await rm16(p.serverPid, { force: true });
|
|
7375
7810
|
process.exit(0);
|
|
7376
7811
|
};
|
|
7377
7812
|
process.once("SIGINT", () => void shutdown3());
|
|
@@ -7415,6 +7850,8 @@ var startCommand = new Command("start").description("run the daemon in the foreg
|
|
|
7415
7850
|
const cfg = await loadConfig(paths());
|
|
7416
7851
|
log.info(`control plane ${cfg.controlPlane?.name}: answering on ${https.url}`);
|
|
7417
7852
|
}
|
|
7853
|
+
await listenForRunning(paths()).catch((err) => log.warn(`running boxes cannot reach their integrations: ${err.message}`));
|
|
7854
|
+
setInterval(() => void closeDeadListeners(paths()).catch(() => void 0), 6e4).unref();
|
|
7418
7855
|
try {
|
|
7419
7856
|
const cfg = await loadConfig(paths());
|
|
7420
7857
|
const state = await driver().net.prepare(cfg);
|
|
@@ -7542,7 +7979,7 @@ var leaveCommand = new Command6("leave").description("take this host out from be
|
|
|
7542
7979
|
|
|
7543
7980
|
// src/commands/logs.ts
|
|
7544
7981
|
import { open as open2, readFile as readFile14, stat as stat7 } from "node:fs/promises";
|
|
7545
|
-
import { setTimeout as
|
|
7982
|
+
import { setTimeout as sleep7 } from "node:timers/promises";
|
|
7546
7983
|
import { Command as Command7 } from "commander";
|
|
7547
7984
|
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) => {
|
|
7548
7985
|
const n = Number.parseInt(opts.lines, 10);
|
|
@@ -7583,7 +8020,7 @@ async function follow(path, write, opts = {}) {
|
|
|
7583
8020
|
await fh.close();
|
|
7584
8021
|
}
|
|
7585
8022
|
}
|
|
7586
|
-
await
|
|
8023
|
+
await sleep7(intervalMs, void 0, { signal: opts.signal }).catch(() => void 0);
|
|
7587
8024
|
}
|
|
7588
8025
|
}
|
|
7589
8026
|
|
|
@@ -7617,8 +8054,8 @@ var relayCommand = new Command9("relay").description("reach the internet through
|
|
|
7617
8054
|
import { Command as Command11 } from "commander";
|
|
7618
8055
|
|
|
7619
8056
|
// src/core/realm.ts
|
|
7620
|
-
import { lstat as lstat2, readFile as readFile15, readdir as readdir7, readlink, rename as rename9, rm as
|
|
7621
|
-
import { z as
|
|
8057
|
+
import { lstat as lstat2, readFile as readFile15, readdir as readdir7, readlink, rename as rename9, rm as rm17, symlink as symlink2, writeFile as writeFile11 } from "node:fs/promises";
|
|
8058
|
+
import { z as z10 } from "zod";
|
|
7622
8059
|
var esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
7623
8060
|
async function ownersIn(root, from, suffix = "") {
|
|
7624
8061
|
const entries = await readdir7(root).catch((err) => {
|
|
@@ -7682,7 +8119,7 @@ async function plan(from, to, p) {
|
|
|
7682
8119
|
for (const oldOwner of await ownersIn(p.volumes, from)) {
|
|
7683
8120
|
await clash(p.ownerVolumes(owner(oldOwner)), `volumes of ${owner(oldOwner)}`);
|
|
7684
8121
|
for (const name of await namesIn2(p.ownerVolumes(oldOwner))) {
|
|
7685
|
-
const meta = await read(p.volume(oldOwner, name).meta, VolumeMetaSchema.extend({ id:
|
|
8122
|
+
const meta = await read(p.volume(oldOwner, name).meta, VolumeMetaSchema.extend({ id: z10.string().optional() }), `volume ${oldOwner}/${name}`);
|
|
7686
8123
|
out.volumes.push({ oldOwner, name, meta: { ...meta, owner: owner(meta.owner) } });
|
|
7687
8124
|
}
|
|
7688
8125
|
}
|
|
@@ -7693,6 +8130,14 @@ async function countRealm(from, to, p = paths()) {
|
|
|
7693
8130
|
const planned = await plan(from, to, p);
|
|
7694
8131
|
return { boxes: planned.boxes.length, snapshots: planned.snapshots.length, volumes: planned.volumes.length };
|
|
7695
8132
|
}
|
|
8133
|
+
async function boundSockets() {
|
|
8134
|
+
try {
|
|
8135
|
+
const lines = (await readFile15("/proc/net/unix", "utf8")).split("\n");
|
|
8136
|
+
return new Set(lines.map((l) => l.split(" ").slice(7).join(" ")).filter((path) => path.startsWith("/")));
|
|
8137
|
+
} catch {
|
|
8138
|
+
return null;
|
|
8139
|
+
}
|
|
8140
|
+
}
|
|
7696
8141
|
async function writeJson(file, value) {
|
|
7697
8142
|
const tmp = `${file}.tmp`;
|
|
7698
8143
|
await writeFile11(tmp, JSON.stringify(value, null, 2) + "\n");
|
|
@@ -7706,6 +8151,8 @@ async function renameRealm(from, to, p = paths()) {
|
|
|
7706
8151
|
const planned = await plan(from, to, p);
|
|
7707
8152
|
const tail = new RegExp(`@${esc(from)}$`);
|
|
7708
8153
|
const owner = (o) => o.replace(tail, `@${to}`);
|
|
8154
|
+
const bound = await boundSockets();
|
|
8155
|
+
const integrationsPending = planned.boxes.filter((b) => (b.status === "running" || b.status === "standby") && (b.meta.integrations ?? []).length > 0).filter((b) => bound === null || bound.has(p.machine(b.oldOwner, b.name).vsock)).map((b) => `${b.meta.owner}/${b.name}`);
|
|
7709
8156
|
await move(planned.volumes, (o, n) => p.volume(o, n).meta, p.ownerVolumes, await ownersIn(p.volumes, from), owner);
|
|
7710
8157
|
await move(planned.snapshots, (o, n) => p.snapshot(o, n).meta, p.ownerSnapshots, await ownersIn(p.snapshots, from), owner);
|
|
7711
8158
|
await move(planned.boxes, (o, n) => p.machine(o, n).meta, p.ownerMachines, await ownersIn(p.machines, from), owner);
|
|
@@ -7715,7 +8162,7 @@ async function renameRealm(from, to, p = paths()) {
|
|
|
7715
8162
|
const link4 = m.volumeDrive(volume);
|
|
7716
8163
|
const target = await readlink(link4).catch(() => null);
|
|
7717
8164
|
if (target !== p.volume(box.oldOwner, volume).disk) continue;
|
|
7718
|
-
await
|
|
8165
|
+
await rm17(link4, { force: true });
|
|
7719
8166
|
await symlink2(p.volume(box.meta.owner, volume).disk, link4);
|
|
7720
8167
|
}
|
|
7721
8168
|
}
|
|
@@ -7724,7 +8171,7 @@ async function renameRealm(from, to, p = paths()) {
|
|
|
7724
8171
|
closeDb(p);
|
|
7725
8172
|
const cfg = await loadConfig(p);
|
|
7726
8173
|
if (cfg.controlPlane?.name === from) await saveConfig({ ...cfg, controlPlane: { ...cfg.controlPlane, name: to } }, p);
|
|
7727
|
-
const report2 = { from, to, boxes: planned.boxes.length, snapshots: planned.snapshots.length, volumes: planned.volumes.length, keysUpdated: [], keysPending: [] };
|
|
8174
|
+
const report2 = { from, to, boxes: planned.boxes.length, snapshots: planned.snapshots.length, volumes: planned.volumes.length, keysUpdated: [], keysPending: [], integrationsPending };
|
|
7728
8175
|
for (const box of planned.boxes) {
|
|
7729
8176
|
const { meta, status } = box;
|
|
7730
8177
|
if (!(meta.sshKeys ?? []).some(isCaLine)) continue;
|
|
@@ -7809,7 +8256,7 @@ var renameRealmCommand = new Command11("rename-realm").description("move this ho
|
|
|
7809
8256
|
const to = name ?? await fetchCloudName(p);
|
|
7810
8257
|
if (from === to) {
|
|
7811
8258
|
if (!opts.json) console.log(`nothing to do: the control plane is called ${to} and this host's boxes are already under that name`);
|
|
7812
|
-
else console.log(JSON.stringify({ from, to, boxes: 0, snapshots: 0, volumes: 0, keysUpdated: [], keysPending: [] }, null, 2));
|
|
8259
|
+
else console.log(JSON.stringify({ from, to, boxes: 0, snapshots: 0, volumes: 0, keysUpdated: [], keysPending: [], integrationsPending: [] }, null, 2));
|
|
7813
8260
|
return;
|
|
7814
8261
|
}
|
|
7815
8262
|
const count = await countRealm(from, to, p);
|
|
@@ -7840,6 +8287,9 @@ function describe(report2, restarted) {
|
|
|
7840
8287
|
console.log(`moved ${report2.boxes} box(es), ${report2.snapshots} snapshot(s) and ${report2.volumes} volume(s) from ${report2.from} to ${report2.to}`);
|
|
7841
8288
|
for (const box of report2.keysUpdated) console.log(`box ${box} accepts SSH certificates for ${report2.to} now`);
|
|
7842
8289
|
for (const k of report2.keysPending) console.log(`box ${k.box} ${WHEN2[k.when]}${k.why ? ` (${k.why})` : ""}`);
|
|
8290
|
+
for (const box of report2.integrationsPending) {
|
|
8291
|
+
console.log(`box ${box} has integrations on and cannot fetch their credentials (git, gh) until it is stopped and started, or hibernated and woken`);
|
|
8292
|
+
}
|
|
7843
8293
|
console.log(restarted ? "kvbox-server restarted" : "kvbox-server was not running; start it with kvbox-server start -d");
|
|
7844
8294
|
}
|
|
7845
8295
|
|