@kvbox/cli 0.5.45 → 0.5.47
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.js +1113 -197
- package/dist/kvbox.js.map +1 -1
- package/package.json +1 -1
package/dist/kvbox.js
CHANGED
|
@@ -29,10 +29,10 @@ var width = (s) => s.replace(ANSI, "").length;
|
|
|
29
29
|
function table(rows2, columns) {
|
|
30
30
|
if (rows2.length === 0) return;
|
|
31
31
|
const cols = columns ?? Object.keys(rows2[0]);
|
|
32
|
-
const cells = rows2.map((r) => cols.map((
|
|
33
|
-
const widths = cols.map((
|
|
32
|
+
const cells = rows2.map((r) => cols.map((c2) => String(r[c2] ?? "")));
|
|
33
|
+
const widths = cols.map((c2, i) => Math.max(c2.length, ...cells.map((r) => width(r[i]))));
|
|
34
34
|
const line = (parts) => parts.map((p, i) => p + " ".repeat(Math.max(0, widths[i] - width(p)))).join(" ").trimEnd();
|
|
35
|
-
process.stdout.write(color.dim(line(cols.map((
|
|
35
|
+
process.stdout.write(color.dim(line(cols.map((c2) => c2.toUpperCase()))) + "\n");
|
|
36
36
|
for (const row of cells) process.stdout.write(line(row) + "\n");
|
|
37
37
|
}
|
|
38
38
|
function info(msg) {
|
|
@@ -149,7 +149,7 @@ async function spin(message, work, opts = {}) {
|
|
|
149
149
|
}
|
|
150
150
|
|
|
151
151
|
// src/program.ts
|
|
152
|
-
import { Command as
|
|
152
|
+
import { Command as Command70 } from "commander";
|
|
153
153
|
|
|
154
154
|
// ../shared/src/version.ts
|
|
155
155
|
import { createRequire } from "module";
|
|
@@ -164,7 +164,7 @@ function versionOf(srcFileUrl, injected) {
|
|
|
164
164
|
}
|
|
165
165
|
|
|
166
166
|
// src/version.ts
|
|
167
|
-
var VERSION = versionOf(import.meta.url, true ? "0.5.
|
|
167
|
+
var VERSION = versionOf(import.meta.url, true ? "0.5.47" : void 0);
|
|
168
168
|
|
|
169
169
|
// src/commands/vm/index.ts
|
|
170
170
|
import { Command as Command37 } from "commander";
|
|
@@ -701,6 +701,11 @@ var CreateMachineRequest = z2.object({
|
|
|
701
701
|
* `@kvbox/shared/country`. Only the control plane reads it.
|
|
702
702
|
*/
|
|
703
703
|
country: z2.string().optional(),
|
|
704
|
+
/**
|
|
705
|
+
* Place the box on the host of this name and nowhere else (`kvbox new --host kvbox2`, a hidden flag):
|
|
706
|
+
* an admin's, to try a host out. Only the control plane reads it, and refuses it from anyone else.
|
|
707
|
+
*/
|
|
708
|
+
host: z2.string().optional(),
|
|
704
709
|
/** The image to boot (#87, `kvbox new --base postgres`). Absent: the base image. */
|
|
705
710
|
image: z2.string().optional(),
|
|
706
711
|
/** The box's own environment variables (#87, `kvbox new -e NAME=value`), over its owner's. */
|
|
@@ -967,7 +972,9 @@ var CloudUserSchema = z2.object({
|
|
|
967
972
|
* gates nobody, hence the defaults: a newer CLI must still parse its answers.
|
|
968
973
|
*/
|
|
969
974
|
active: z2.boolean().default(true),
|
|
970
|
-
activatedBy: ActivatedBySchema.nullable().default(null)
|
|
975
|
+
activatedBy: ActivatedBySchema.nullable().default(null),
|
|
976
|
+
/** When too many wrong passwords locked the account (#161); null when it is not locked. Older control planes omit it. */
|
|
977
|
+
lockedAt: z2.string().nullable().default(null)
|
|
971
978
|
});
|
|
972
979
|
var ORG_ROLES = ["owner", "admin", "member"];
|
|
973
980
|
var OrgRoleSchema = z2.enum(ORG_ROLES);
|
|
@@ -1005,10 +1012,14 @@ var BalanceSchema = z2.object({
|
|
|
1005
1012
|
currency: z2.string(),
|
|
1006
1013
|
topUps: z2.number(),
|
|
1007
1014
|
spent: z2.number(),
|
|
1008
|
-
/** The first moment usage counts from: the slug's first top-up; null when it has none. */
|
|
1015
|
+
/** The first moment usage counts from: the slug's first top-up or redeemed code; null when it has none. */
|
|
1009
1016
|
since: z2.string().nullable(),
|
|
1010
1017
|
/** 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. */
|
|
1011
|
-
suspendedAt: z2.string().nullable().default(null)
|
|
1018
|
+
suspendedAt: z2.string().nullable().default(null),
|
|
1019
|
+
/** Promo credit left (#163), already counted in `balance`; 0 with none. Absent from a control plane older than this field. */
|
|
1020
|
+
promo: z2.number().default(0),
|
|
1021
|
+
/** When the next promo credit expires; null with none left. */
|
|
1022
|
+
promoExpiresAt: z2.string().nullable().default(null)
|
|
1012
1023
|
});
|
|
1013
1024
|
var TopUpRequestSchema = z2.object({
|
|
1014
1025
|
slug: z2.string().min(1),
|
|
@@ -1026,6 +1037,41 @@ var TopUpSchema = z2.object({
|
|
|
1026
1037
|
note: z2.string().nullable(),
|
|
1027
1038
|
at: z2.string()
|
|
1028
1039
|
});
|
|
1040
|
+
var CreateCodeRequestSchema = z2.object({
|
|
1041
|
+
/** In the control plane's currency, cents at most. */
|
|
1042
|
+
amount: z2.number().positive().multipleOf(0.01, "amount is in cents at most"),
|
|
1043
|
+
/** 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. */
|
|
1044
|
+
expiresAt: z2.string().min(1),
|
|
1045
|
+
note: z2.string().max(200).optional()
|
|
1046
|
+
});
|
|
1047
|
+
var CreditCodeSchema = z2.object({
|
|
1048
|
+
code: z2.string(),
|
|
1049
|
+
amount: z2.number(),
|
|
1050
|
+
currency: z2.string(),
|
|
1051
|
+
expiresAt: z2.string(),
|
|
1052
|
+
note: z2.string().nullable(),
|
|
1053
|
+
status: z2.enum(["unused", "redeemed", "expired", "revoked"]),
|
|
1054
|
+
createdBy: z2.string(),
|
|
1055
|
+
createdAt: z2.string(),
|
|
1056
|
+
/** Who redeemed it and the slug the credit went to (their own, or an org they own). */
|
|
1057
|
+
redeemedBy: z2.string().nullable(),
|
|
1058
|
+
redeemedSlug: z2.string().nullable(),
|
|
1059
|
+
redeemedAt: z2.string().nullable(),
|
|
1060
|
+
revokedAt: z2.string().nullable()
|
|
1061
|
+
});
|
|
1062
|
+
var RedeemRequestSchema = z2.object({
|
|
1063
|
+
code: z2.string().min(1).max(64),
|
|
1064
|
+
org: z2.string().min(1).optional()
|
|
1065
|
+
});
|
|
1066
|
+
var RedeemResponseSchema = z2.object({
|
|
1067
|
+
slug: z2.string(),
|
|
1068
|
+
amount: z2.number(),
|
|
1069
|
+
currency: z2.string(),
|
|
1070
|
+
expiresAt: z2.string(),
|
|
1071
|
+
balance: BalanceSchema,
|
|
1072
|
+
/** The slug was out of credit and this put it back above zero: it may start boxes again. */
|
|
1073
|
+
reinstated: z2.boolean()
|
|
1074
|
+
});
|
|
1029
1075
|
var TOP_UP_AMOUNTS = [10, 25, 50, 100];
|
|
1030
1076
|
var BillingInfoSchema = z2.object({
|
|
1031
1077
|
card: z2.object({ brand: z2.string(), last4: z2.string() }).nullable(),
|
|
@@ -1418,6 +1464,10 @@ var ServerClient = class {
|
|
|
1418
1464
|
balance(org) {
|
|
1419
1465
|
return this.call("GET", "/billing/balance", BalanceSchema, void 0, org);
|
|
1420
1466
|
}
|
|
1467
|
+
/** Redeem a promo code (#163) for the caller's slug, or for `--org`'s org, which they own; a control plane only. */
|
|
1468
|
+
redeem(code) {
|
|
1469
|
+
return this.call("POST", "/billing/redeem", RedeemResponseSchema, { code });
|
|
1470
|
+
}
|
|
1421
1471
|
deleteMachine(name) {
|
|
1422
1472
|
return this.call("DELETE", `/machines/${encodeURIComponent(name)}`, z3.undefined());
|
|
1423
1473
|
}
|
|
@@ -1582,17 +1632,17 @@ function sshArgs(ep, p = paths()) {
|
|
|
1582
1632
|
async function waitForSsh(ep, timeoutMs = 3e4) {
|
|
1583
1633
|
const { connect } = await import("net");
|
|
1584
1634
|
const deadline = Date.now() + timeoutMs;
|
|
1585
|
-
const attempt = () => new Promise((
|
|
1635
|
+
const attempt = () => new Promise((resolve4) => {
|
|
1586
1636
|
const sock = connect({ host: ep.host, port: ep.port, timeout: 1e3 });
|
|
1587
1637
|
sock.once("connect", () => {
|
|
1588
1638
|
sock.destroy();
|
|
1589
|
-
|
|
1639
|
+
resolve4(true);
|
|
1590
1640
|
});
|
|
1591
1641
|
sock.once("timeout", () => {
|
|
1592
1642
|
sock.destroy();
|
|
1593
|
-
|
|
1643
|
+
resolve4(false);
|
|
1594
1644
|
});
|
|
1595
|
-
sock.once("error", () =>
|
|
1645
|
+
sock.once("error", () => resolve4(false));
|
|
1596
1646
|
});
|
|
1597
1647
|
while (Date.now() < deadline) {
|
|
1598
1648
|
if (await attempt()) return;
|
|
@@ -1607,8 +1657,8 @@ async function checkDirect(ep) {
|
|
|
1607
1657
|
}
|
|
1608
1658
|
var NOT_A_HOST_HINT = "kvbox-server is not installed, so this machine is not a kvbox host. Set it up with install-server.sh, or log in to the cloud with: kvbox login";
|
|
1609
1659
|
async function lastErrorLine(logPath, from = 0) {
|
|
1610
|
-
const { readFile:
|
|
1611
|
-
const text2 = (await
|
|
1660
|
+
const { readFile: readFile9 } = await import("fs/promises");
|
|
1661
|
+
const text2 = (await readFile9(logPath).catch(() => Buffer.alloc(0))).subarray(from).toString("utf8");
|
|
1612
1662
|
for (const line of text2.trimEnd().split("\n").slice(-20).reverse()) {
|
|
1613
1663
|
const m = /^(?:\[[^\]]*\])?\[?error\]?: (.*)$/.exec(line);
|
|
1614
1664
|
if (m?.[1] !== void 0) return m[1];
|
|
@@ -1722,9 +1772,9 @@ async function select(message, choices, initial = 0) {
|
|
|
1722
1772
|
if (drawn > 0) out.write(`${ESC}[${drawn}A`);
|
|
1723
1773
|
const lines = [
|
|
1724
1774
|
`${color.green("?")} ${color.bold(message)} ${color.dim("\u2191\u2193 to move, enter to pick")}`,
|
|
1725
|
-
...choices.map((
|
|
1726
|
-
const hint =
|
|
1727
|
-
return i === index ? `${color.cyan(`\u276F ${
|
|
1775
|
+
...choices.map((c2, i) => {
|
|
1776
|
+
const hint = c2.hint ? color.dim(` ${c2.hint}`) : "";
|
|
1777
|
+
return i === index ? `${color.cyan(`\u276F ${c2.label}`)}${hint}` : ` ${c2.label}${hint}`;
|
|
1728
1778
|
})
|
|
1729
1779
|
];
|
|
1730
1780
|
out.write(`\r${ESC}[J${lines.join("\n")}
|
|
@@ -1737,7 +1787,7 @@ async function select(message, choices, initial = 0) {
|
|
|
1737
1787
|
render();
|
|
1738
1788
|
let done = false;
|
|
1739
1789
|
try {
|
|
1740
|
-
return await new Promise((
|
|
1790
|
+
return await new Promise((resolve4, reject) => {
|
|
1741
1791
|
const onData = (chunk) => {
|
|
1742
1792
|
for (const key of keysIn(chunk)) {
|
|
1743
1793
|
if (isUp(key)) index = (index - 1 + choices.length) % choices.length;
|
|
@@ -1745,7 +1795,7 @@ async function select(message, choices, initial = 0) {
|
|
|
1745
1795
|
else if (key === ENTER || key === "\n") {
|
|
1746
1796
|
inp.off("data", onData);
|
|
1747
1797
|
done = true;
|
|
1748
|
-
|
|
1798
|
+
resolve4(choices[index].value);
|
|
1749
1799
|
return;
|
|
1750
1800
|
} else if (key === CTRL_C || key === CTRL_D) {
|
|
1751
1801
|
inp.off("data", onData);
|
|
@@ -1795,13 +1845,13 @@ async function hiddenText(message) {
|
|
|
1795
1845
|
let chars = [];
|
|
1796
1846
|
let done = false;
|
|
1797
1847
|
try {
|
|
1798
|
-
return await new Promise((
|
|
1848
|
+
return await new Promise((resolve4, reject) => {
|
|
1799
1849
|
const onData = (chunk) => {
|
|
1800
1850
|
for (const key of keysIn(chunk)) {
|
|
1801
1851
|
if (key === ENTER || key === "\n") {
|
|
1802
1852
|
inp.off("data", onData);
|
|
1803
1853
|
done = true;
|
|
1804
|
-
|
|
1854
|
+
resolve4(chars.join(""));
|
|
1805
1855
|
return;
|
|
1806
1856
|
}
|
|
1807
1857
|
if (key === CTRL_C || key === CTRL_D) {
|
|
@@ -1930,7 +1980,7 @@ function parseDuration(text2) {
|
|
|
1930
1980
|
}
|
|
1931
1981
|
|
|
1932
1982
|
// src/commands/vm/new.ts
|
|
1933
|
-
var newCommand = new Command("new").description("boot a new box from an image (the base one, or e.g. postgres) or a snapshot").argument("[name]", "box name (box1, box2, \u2026 when omitted)").addOption(new Option("-s, --size <size>", "box size (default: server config, s)").choices(SIZE_NAMES)).option("-b, --base <image>", "the image to boot: base (default) or one the host has, e.g. postgres").option("-e, --env <NAME=value>", "a variable of the box's own, over yours (repeatable; change later with kvbox env set --box)", collect, []).option("-f, --from <snapshot>", "start from a snapshot instead of an image").option("--near <box>", "put it on the same host as this box, so the two can be linked (kvbox vm link)").option("--country <country>", "put it on a host in this country, a name or a code, e.g. romania or US").option("--auto-hibernate <duration>", "hibernate the box after this long without network traffic (30m, 4h, 1d; off: never; default: server config, off)").option("--force", "skip the capacity guard").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
|
|
1983
|
+
var newCommand = new Command("new").description("boot a new box from an image (the base one, or e.g. postgres) or a snapshot").argument("[name]", "box name (box1, box2, \u2026 when omitted)").addOption(new Option("-s, --size <size>", "box size (default: server config, s)").choices(SIZE_NAMES)).option("-b, --base <image>", "the image to boot: base (default) or one the host has, e.g. postgres").option("-e, --env <NAME=value>", "a variable of the box's own, over yours (repeatable; change later with kvbox env set --box)", collect, []).option("-f, --from <snapshot>", "start from a snapshot instead of an image").option("--near <box>", "put it on the same host as this box, so the two can be linked (kvbox vm link)").option("--country <country>", "put it on a host in this country, a name or a code, e.g. romania or US").addOption(new Option("--host <name>", "put it on this host and no other (admins only)").hideHelp()).option("--auto-hibernate <duration>", "hibernate the box after this long without network traffic (30m, 4h, 1d; off: never; default: server config, off)").option("--force", "skip the capacity guard").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
|
|
1934
1984
|
const autoHibernateSec = opts.autoHibernate === void 0 ? void 0 : parseIdleTimeout(opts.autoHibernate);
|
|
1935
1985
|
const env = parseEnvFlags(opts.env);
|
|
1936
1986
|
const country = opts.country === void 0 ? void 0 : parseCountry(opts.country);
|
|
@@ -1940,6 +1990,10 @@ var newCommand = new Command("new").description("boot a new box from an image (t
|
|
|
1940
1990
|
await client.close();
|
|
1941
1991
|
throw new KvboxError("--country picks a host through the control plane; this machine is the only host here (kvbox login first)");
|
|
1942
1992
|
}
|
|
1993
|
+
if (opts.host !== void 0 && client.target.kind !== "cloud") {
|
|
1994
|
+
await client.close();
|
|
1995
|
+
throw new KvboxError("--host picks a host through the control plane; this machine is the only host here (kvbox login first)");
|
|
1996
|
+
}
|
|
1943
1997
|
try {
|
|
1944
1998
|
const what = opts.from !== void 0 ? `restoring ${name ?? "a new box"} from snapshot ${opts.from}\u2026` : `booting ${name ?? "a new box"}${opts.base !== void 0 && opts.base !== "base" ? ` from image ${opts.base}` : ""}\u2026`;
|
|
1945
1999
|
const box = await spin(what, client.createMachine({
|
|
@@ -1950,6 +2004,7 @@ var newCommand = new Command("new").description("boot a new box from an image (t
|
|
|
1950
2004
|
...env.length > 0 ? { env } : {},
|
|
1951
2005
|
...opts.near !== void 0 ? { near: opts.near } : {},
|
|
1952
2006
|
...country !== void 0 ? { country } : {},
|
|
2007
|
+
...opts.host !== void 0 ? { host: opts.host } : {},
|
|
1953
2008
|
...autoHibernateSec !== void 0 ? { autoHibernateSec } : {},
|
|
1954
2009
|
...opts.force ? { force: true } : {}
|
|
1955
2010
|
}));
|
|
@@ -2101,19 +2156,19 @@ function positiveSeconds(value) {
|
|
|
2101
2156
|
async function runSsh(ssh, opts) {
|
|
2102
2157
|
const child = spawn2("ssh", ssh, { stdio: ["inherit", opts.json ? "pipe" : "inherit", opts.json ? "pipe" : "inherit"] });
|
|
2103
2158
|
const chunks = [];
|
|
2104
|
-
child.stdout?.on("data", (
|
|
2105
|
-
child.stderr?.on("data", (
|
|
2159
|
+
child.stdout?.on("data", (c2) => chunks.push(c2));
|
|
2160
|
+
child.stderr?.on("data", (c2) => chunks.push(c2));
|
|
2106
2161
|
let timedOut = false;
|
|
2107
2162
|
const timer = opts.timeout === void 0 ? void 0 : setTimeout(() => {
|
|
2108
2163
|
timedOut = true;
|
|
2109
2164
|
child.kill("SIGTERM");
|
|
2110
2165
|
}, opts.timeout * 1e3);
|
|
2111
|
-
const status2 = await new Promise((
|
|
2166
|
+
const status2 = await new Promise((resolve4, reject) => {
|
|
2112
2167
|
child.once("error", (err) => reject(new KvboxError(`could not run ssh: ${err.message}`)));
|
|
2113
2168
|
child.once("close", (code, signal) => {
|
|
2114
|
-
if (timedOut)
|
|
2115
|
-
else if (code !== null)
|
|
2116
|
-
else
|
|
2169
|
+
if (timedOut) resolve4(TIMEOUT_EXIT);
|
|
2170
|
+
else if (code !== null) resolve4(code);
|
|
2171
|
+
else resolve4(signal === "SIGINT" ? 130 : 1);
|
|
2117
2172
|
});
|
|
2118
2173
|
}).finally(() => clearTimeout(timer));
|
|
2119
2174
|
return { status: status2, chunks, timedOut };
|
|
@@ -3045,11 +3100,11 @@ function parseSwapReport(output) {
|
|
|
3045
3100
|
function runSwap(ep, mib) {
|
|
3046
3101
|
const child = spawn3("ssh", ["-n", ...sshArgs(ep), swapCommand(mib)], { stdio: ["ignore", "pipe", "pipe"] });
|
|
3047
3102
|
const chunks = [];
|
|
3048
|
-
child.stdout.on("data", (
|
|
3049
|
-
child.stderr.on("data", (
|
|
3050
|
-
return new Promise((
|
|
3103
|
+
child.stdout.on("data", (c2) => chunks.push(c2));
|
|
3104
|
+
child.stderr.on("data", (c2) => chunks.push(c2));
|
|
3105
|
+
return new Promise((resolve4, reject) => {
|
|
3051
3106
|
child.once("error", (err) => reject(new KvboxError(`could not run ssh: ${err.message}`)));
|
|
3052
|
-
child.once("close", (code) =>
|
|
3107
|
+
child.once("close", (code) => resolve4({ status: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
|
|
3053
3108
|
});
|
|
3054
3109
|
}
|
|
3055
3110
|
|
|
@@ -3756,7 +3811,8 @@ async function creditLine(client, me2) {
|
|
|
3756
3811
|
}
|
|
3757
3812
|
const whose = b.slug === me2 ? "private" : b.slug;
|
|
3758
3813
|
const left = money(b.balance, b.currency);
|
|
3759
|
-
const
|
|
3814
|
+
const promo = b.promo > 0 && b.promoExpiresAt ? `, ${money(b.promo, b.currency)} of it promo credit that expires on ${day2(b.promoExpiresAt)}` : "";
|
|
3815
|
+
const line = `credit: ${b.balance > 0 ? left : color.red(left)} left${promo} ${color.dim(`(${whose})`)}`;
|
|
3760
3816
|
return b.suspendedAt ? `${line} ${color.red("out of credit: boxes hibernated until you top up")}` : line;
|
|
3761
3817
|
}
|
|
3762
3818
|
function ownerCell2(b, me2) {
|
|
@@ -3877,26 +3933,46 @@ function creditRow(b, me2) {
|
|
|
3877
3933
|
return {
|
|
3878
3934
|
owner: b.slug === me2 ? "private" : boxName(b.slug),
|
|
3879
3935
|
credit: b.balance > 0 ? left : color.red(left),
|
|
3936
|
+
promo: b.promo > 0 && b.promoExpiresAt ? `${money(b.promo, b.currency)} until ${b.promoExpiresAt.slice(0, 10)}` : "-",
|
|
3880
3937
|
"topped up": money(b.topUps, b.currency),
|
|
3881
3938
|
spent: money(b.spent, b.currency),
|
|
3882
3939
|
// Suspended (#76): the sweep hibernated the boxes at zero; a top-up brings them back.
|
|
3883
|
-
state: b.suspendedAt ? color.red("suspended") : b.since === null ? color.dim("
|
|
3940
|
+
state: b.suspendedAt ? color.red("suspended") : b.since === null ? color.dim("no credit yet") : "ok"
|
|
3884
3941
|
};
|
|
3885
3942
|
}
|
|
3886
3943
|
|
|
3944
|
+
// src/commands/redeem.ts
|
|
3945
|
+
import { Command as Command53 } from "commander";
|
|
3946
|
+
var redeemCommand = new Command53("redeem").description("redeem a promo code for credit, on your account or (--org) an org you own").argument("<code>", "the code, like KV-7F3K-9QXM-2HBD").option("--org <slug>", "give the credit to this org, which you own; it cannot be moved later").option("--json", "print as JSON").action(async (code, opts, cmd) => {
|
|
3947
|
+
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
3948
|
+
try {
|
|
3949
|
+
if (client.target.kind === "local") throw new KvboxError("codes are redeemed on the control plane: kvbox login first");
|
|
3950
|
+
const done = await client.redeem(code);
|
|
3951
|
+
if (opts.json) {
|
|
3952
|
+
json(done);
|
|
3953
|
+
return;
|
|
3954
|
+
}
|
|
3955
|
+
const whose = done.slug === client.target.user ? "your account" : `org ${done.slug}`;
|
|
3956
|
+
info(`${money(done.amount, done.currency)} of credit added to ${whose}. It is used first and expires on ${done.expiresAt.slice(0, 10)}.`);
|
|
3957
|
+
info(`credit: ${money(done.balance.balance, done.balance.currency)} left${done.reinstated ? "; you can start your boxes again" : ""}`);
|
|
3958
|
+
} finally {
|
|
3959
|
+
await client.close();
|
|
3960
|
+
}
|
|
3961
|
+
});
|
|
3962
|
+
|
|
3887
3963
|
// src/commands/deploy/index.ts
|
|
3888
|
-
import { access as
|
|
3889
|
-
import { basename, resolve as
|
|
3890
|
-
import { Command as
|
|
3964
|
+
import { access as access5, readFile as readFile8 } from "fs/promises";
|
|
3965
|
+
import { basename as basename2, resolve as resolve3 } from "path";
|
|
3966
|
+
import { Command as Command54, InvalidArgumentError as InvalidArgumentError2, Option as Option5 } from "commander";
|
|
3891
3967
|
|
|
3892
3968
|
// src/commands/deploy/config.ts
|
|
3893
3969
|
import { readFile as readFile6, writeFile as writeFile4 } from "fs/promises";
|
|
3894
|
-
import { join as join6 } from "path";
|
|
3970
|
+
import { isAbsolute, join as join6, normalize, relative as relative2 } from "path";
|
|
3895
3971
|
import { z as z5 } from "zod";
|
|
3896
3972
|
|
|
3897
3973
|
// src/commands/deploy/templates/docker.ts
|
|
3898
3974
|
import { readFile as readFile5 } from "fs/promises";
|
|
3899
|
-
import { join as join2 } from "path";
|
|
3975
|
+
import { join as join2, relative, sep } from "path";
|
|
3900
3976
|
|
|
3901
3977
|
// src/commands/deploy/templates/server.ts
|
|
3902
3978
|
var APP_DIR = "/srv/app/current";
|
|
@@ -3917,19 +3993,24 @@ function commands(pm) {
|
|
|
3917
3993
|
return { setup: [], install: "if [ -f package-lock.json ]; then npm ci; else npm install; fi", build: "npm run build", start: "npm run start" };
|
|
3918
3994
|
}
|
|
3919
3995
|
}
|
|
3996
|
+
var DROP_SINGLE = `sudo -n systemctl disable --now --quiet ${SERVICE} 2>/dev/null || true
|
|
3997
|
+
${DROP_CONTAINER}`;
|
|
3920
3998
|
function serverRemote(opts) {
|
|
3921
|
-
const
|
|
3999
|
+
const c2 = commands(opts.pm);
|
|
4000
|
+
const root = opts.target?.root ?? "/srv/app";
|
|
4001
|
+
const appDir = opts.target ? `${root}/current` : APP_DIR;
|
|
4002
|
+
const service = opts.target?.unit ?? SERVICE;
|
|
3922
4003
|
const unit = [
|
|
3923
4004
|
"[Unit]",
|
|
3924
|
-
"Description=kvbox deploy: the app in " +
|
|
4005
|
+
"Description=kvbox deploy: the app in " + appDir,
|
|
3925
4006
|
"After=network.target",
|
|
3926
4007
|
"",
|
|
3927
4008
|
"[Service]",
|
|
3928
4009
|
"User=kvbox",
|
|
3929
|
-
`WorkingDirectory=${
|
|
4010
|
+
`WorkingDirectory=${appDir}`,
|
|
3930
4011
|
// PORT on the command line: the proxied address points at it, and nothing in the environment
|
|
3931
4012
|
// file below may move the app off it (env's PORT, say, copied from a .env).
|
|
3932
|
-
`ExecStart=/usr/bin/env PORT=${opts.port} ${
|
|
4013
|
+
`ExecStart=/usr/bin/env PORT=${opts.port} ${c2.start}`,
|
|
3933
4014
|
"Environment=NODE_ENV=production",
|
|
3934
4015
|
// The box owner's variables (#88, base v0.10.0+; the `-` makes an older box start without them).
|
|
3935
4016
|
"EnvironmentFile=-/etc/kvbox/env",
|
|
@@ -3942,32 +4023,34 @@ function serverRemote(opts) {
|
|
|
3942
4023
|
return [
|
|
3943
4024
|
"set -e",
|
|
3944
4025
|
"test -d /srv/app -a -w /srv/app || exit 3",
|
|
3945
|
-
|
|
3946
|
-
|
|
3947
|
-
|
|
3948
|
-
|
|
4026
|
+
`rm -rf ${root}/.incoming ${root}/.old`,
|
|
4027
|
+
`mkdir -p ${root}/.incoming`,
|
|
4028
|
+
`tar -xf - -C ${root}/.incoming`,
|
|
4029
|
+
`cd ${root}/.incoming`,
|
|
3949
4030
|
// Not NODE_ENV=production here: the install would skip devDependencies, which the build needs (TypeScript, Tailwind).
|
|
3950
4031
|
`export ${["CI=1", ...opts.env ?? []].join(" ")}`,
|
|
3951
|
-
...
|
|
3952
|
-
|
|
3953
|
-
...opts.build ? [
|
|
4032
|
+
...c2.setup,
|
|
4033
|
+
c2.install,
|
|
4034
|
+
...opts.build ? [c2.build] : [],
|
|
3954
4035
|
"cd /",
|
|
3955
|
-
|
|
4036
|
+
// Before the unit is written: in a stack the single deploy's unit is the one being dropped.
|
|
4037
|
+
...opts.target ? [DROP_SINGLE] : [],
|
|
4038
|
+
`sudo -n tee /etc/systemd/system/${service}.service >/dev/null <<'UNIT'`,
|
|
3956
4039
|
...unit,
|
|
3957
4040
|
"UNIT",
|
|
3958
|
-
`if [ -e ${
|
|
3959
|
-
`mv
|
|
4041
|
+
`if [ -e ${appDir} ]; then mv ${appDir} ${root}/.old; fi`,
|
|
4042
|
+
`mv ${root}/.incoming ${appDir}`,
|
|
3960
4043
|
"sudo -n systemctl daemon-reload",
|
|
3961
|
-
`sudo -n systemctl enable --quiet ${
|
|
4044
|
+
`sudo -n systemctl enable --quiet ${service}`,
|
|
3962
4045
|
// A box that switched from the Docker template: its container holds the same box port.
|
|
3963
|
-
DROP_CONTAINER,
|
|
3964
|
-
`sudo -n systemctl restart ${
|
|
3965
|
-
|
|
4046
|
+
...opts.target ? [] : [DROP_CONTAINER],
|
|
4047
|
+
`sudo -n systemctl restart ${service}`,
|
|
4048
|
+
`rm -rf ${root}/.old`,
|
|
3966
4049
|
// bash's /dev/tcp: no curl or nc in the image needed.
|
|
3967
4050
|
"i=0",
|
|
3968
4051
|
`until timeout 1 bash -c '</dev/tcp/127.0.0.1/${opts.port}' 2>/dev/null; do`,
|
|
3969
4052
|
" i=$((i+1))",
|
|
3970
|
-
` if [ "$i" -ge ${START_WAIT_SEC} ]; then echo '${LOG_MARKER}'; sudo -n journalctl -u ${
|
|
4053
|
+
` if [ "$i" -ge ${START_WAIT_SEC} ]; then echo '${LOG_MARKER}'; sudo -n journalctl -u ${service} -n 20 --no-pager -o cat || true; exit ${APP_NOT_LISTENING}; fi`,
|
|
3971
4054
|
" sleep 1",
|
|
3972
4055
|
"done"
|
|
3973
4056
|
].join("\n");
|
|
@@ -3997,9 +4080,14 @@ var dockerTemplate = {
|
|
|
3997
4080
|
const dockerfile = await readFile5(join2(ctx.dir, "Dockerfile"), "utf8").catch(() => void 0);
|
|
3998
4081
|
if (dockerfile === void 0) throw new KvboxError(`${ctx.dir}: no Dockerfile; the Docker template builds the image from it`);
|
|
3999
4082
|
const containerPort = exposedPort(dockerfile);
|
|
4083
|
+
if (ctx.context !== void 0 && ctx.context !== ctx.dir) {
|
|
4084
|
+
const dockerfilePath = relative(ctx.context, join2(ctx.dir, "Dockerfile")).split(sep).join("/");
|
|
4085
|
+
return { outDir: ctx.context, exclude: ["node_modules", ".git", ".venv"], pm: "npm", what: "the build context", dockerfile: dockerfilePath, ...containerPort !== void 0 ? { containerPort } : {} };
|
|
4086
|
+
}
|
|
4000
4087
|
return { outDir: ctx.dir, exclude: ["node_modules", ".git"], pm: "npm", what: "the source", ...containerPort !== void 0 ? { containerPort } : {} };
|
|
4001
4088
|
},
|
|
4002
|
-
remote(built, port) {
|
|
4089
|
+
remote(built, port, target) {
|
|
4090
|
+
if (target) return dockerServiceRemote(port, target, built.dockerfile);
|
|
4003
4091
|
return dockerRemote(port, built.containerPort ?? port);
|
|
4004
4092
|
}
|
|
4005
4093
|
};
|
|
@@ -4033,6 +4121,61 @@ function dockerRemote(port, containerPort) {
|
|
|
4033
4121
|
"done"
|
|
4034
4122
|
].join("\n");
|
|
4035
4123
|
}
|
|
4124
|
+
var BOX_ENV_PLAIN = "/home/kvbox/.ssh/environment";
|
|
4125
|
+
function dockerServiceRemote(port, target, dockerfile) {
|
|
4126
|
+
const image = target.unit;
|
|
4127
|
+
const unit = [
|
|
4128
|
+
"[Unit]",
|
|
4129
|
+
`Description=kvbox deploy: the container ${image}`,
|
|
4130
|
+
"After=docker.service network-online.target",
|
|
4131
|
+
"Requires=docker.service",
|
|
4132
|
+
"",
|
|
4133
|
+
"[Service]",
|
|
4134
|
+
// A box that never had a variable has no file yet, and docker refuses a missing --env-file.
|
|
4135
|
+
`ExecStartPre=/bin/sh -c '[ -e ${BOX_ENV_PLAIN} ] || install -m 600 -o kvbox -g kvbox /dev/null ${BOX_ENV_PLAIN}'`,
|
|
4136
|
+
`ExecStartPre=-/usr/bin/docker rm -f ${image}`,
|
|
4137
|
+
`ExecStart=/usr/bin/docker run --rm --name ${image} --network host --env-file ${BOX_ENV_PLAIN} -e PORT=${port} ${image}`,
|
|
4138
|
+
`ExecStop=/usr/bin/docker stop ${image}`,
|
|
4139
|
+
"Restart=always",
|
|
4140
|
+
"RestartSec=2",
|
|
4141
|
+
"",
|
|
4142
|
+
"[Install]",
|
|
4143
|
+
"WantedBy=multi-user.target"
|
|
4144
|
+
];
|
|
4145
|
+
const root = target.root;
|
|
4146
|
+
return [
|
|
4147
|
+
"set -eo pipefail",
|
|
4148
|
+
"test -d /srv/app -a -w /srv/app || exit 3",
|
|
4149
|
+
"command -v docker >/dev/null || exit 3",
|
|
4150
|
+
`rm -rf ${root}/.incoming ${root}/.old`,
|
|
4151
|
+
`mkdir -p ${root}/.incoming`,
|
|
4152
|
+
`tar -xf - -C ${root}/.incoming`,
|
|
4153
|
+
`cd ${root}/.incoming`,
|
|
4154
|
+
// Quoted: the path is the user's `dir`, which may hold a space.
|
|
4155
|
+
`docker build --progress=plain${dockerfile !== void 0 ? ` -f '${dockerfile.replaceAll("'", `'\\''`)}'` : ""} -t ${image} . 2>&1 | tail -n ${BUILD_LOG_LINES}`,
|
|
4156
|
+
"cd /",
|
|
4157
|
+
// The single deploy's app or container would hold its port and RAM beside the services.
|
|
4158
|
+
DROP_SINGLE,
|
|
4159
|
+
`sudo -n tee /etc/systemd/system/${target.unit}.service >/dev/null <<'UNIT'`,
|
|
4160
|
+
...unit,
|
|
4161
|
+
"UNIT",
|
|
4162
|
+
`if [ -e ${root}/current ]; then mv ${root}/current ${root}/.old; fi`,
|
|
4163
|
+
`mv ${root}/.incoming ${root}/current`,
|
|
4164
|
+
`rm -rf ${root}/.old`,
|
|
4165
|
+
"sudo -n systemctl daemon-reload",
|
|
4166
|
+
"sudo -n systemctl enable --quiet docker",
|
|
4167
|
+
`sudo -n systemctl enable --quiet ${target.unit}`,
|
|
4168
|
+
`sudo -n systemctl restart ${target.unit}`,
|
|
4169
|
+
"docker image prune -f >/dev/null",
|
|
4170
|
+
// The box's network: the port is the box's own, and nothing but the app answers on it.
|
|
4171
|
+
"i=0",
|
|
4172
|
+
`until timeout 1 bash -c '</dev/tcp/127.0.0.1/${port}' 2>/dev/null; do`,
|
|
4173
|
+
" i=$((i+1))",
|
|
4174
|
+
` if [ "$i" -ge ${START_WAIT_SEC} ] || ! systemctl is-active --quiet ${target.unit}; then echo '${LOG_MARKER}'; sudo -n journalctl -u ${target.unit} -n 20 --no-pager -o cat || true; exit ${APP_NOT_LISTENING}; fi`,
|
|
4175
|
+
" sleep 1",
|
|
4176
|
+
"done"
|
|
4177
|
+
].join("\n");
|
|
4178
|
+
}
|
|
4036
4179
|
|
|
4037
4180
|
// src/commands/deploy/templates/pm.ts
|
|
4038
4181
|
import { access } from "fs/promises";
|
|
@@ -4068,8 +4211,8 @@ var nextjsTemplate = {
|
|
|
4068
4211
|
const pm = await packageManager(ctx.dir);
|
|
4069
4212
|
return { outDir: ctx.dir, exclude: ["node_modules", ".next", ".git"], pm, what: "the source", boxBuild: true };
|
|
4070
4213
|
},
|
|
4071
|
-
remote(built, port) {
|
|
4072
|
-
return serverRemote({ pm: built.pm, port, build: true, env: ["NEXT_TELEMETRY_DISABLED=1"] });
|
|
4214
|
+
remote(built, port, target) {
|
|
4215
|
+
return serverRemote({ pm: built.pm, port, build: true, env: ["NEXT_TELEMETRY_DISABLED=1"], ...target ? { target } : {} });
|
|
4073
4216
|
}
|
|
4074
4217
|
};
|
|
4075
4218
|
|
|
@@ -4095,8 +4238,8 @@ var nodeTemplate = {
|
|
|
4095
4238
|
const boxBuild = typeof ctx.pkg.scripts["build"] === "string";
|
|
4096
4239
|
return { outDir: ctx.dir, exclude: ["node_modules", ".git"], pm, what: "the source", boxBuild };
|
|
4097
4240
|
},
|
|
4098
|
-
remote(built, port) {
|
|
4099
|
-
return serverRemote({ pm: built.pm, port, build: built.boxBuild === true });
|
|
4241
|
+
remote(built, port, target) {
|
|
4242
|
+
return serverRemote({ pm: built.pm, port, build: built.boxBuild === true, ...target ? { target } : {} });
|
|
4100
4243
|
}
|
|
4101
4244
|
};
|
|
4102
4245
|
|
|
@@ -4108,10 +4251,10 @@ var OUT_DIRS = ["dist", "build"];
|
|
|
4108
4251
|
async function runBuild(dir, pm) {
|
|
4109
4252
|
const args = runScript(pm, "build");
|
|
4110
4253
|
info(`${color.dim("$")} ${pm} ${args.join(" ")}`);
|
|
4111
|
-
const status2 = await new Promise((
|
|
4254
|
+
const status2 = await new Promise((resolve4, reject) => {
|
|
4112
4255
|
const child = spawn4(pm, args, { cwd: dir, stdio: ["ignore", process.stderr, process.stderr], shell: process.platform === "win32" });
|
|
4113
4256
|
child.once("error", (err) => reject(new KvboxError(`could not run ${pm}: ${err.message}`)));
|
|
4114
|
-
child.once("close", (code) =>
|
|
4257
|
+
child.once("close", (code) => resolve4(code ?? 1));
|
|
4115
4258
|
});
|
|
4116
4259
|
if (status2 !== 0) throw new KvboxError(`the build failed (${pm} exited ${status2}); nothing was deployed`);
|
|
4117
4260
|
}
|
|
@@ -4141,9 +4284,23 @@ var reactTemplate = {
|
|
|
4141
4284
|
`the build left no ${candidates.join(" or ")}/index.html. The React template ships a directory of static files; set "dist" in kvbox.json to the build output directory, or pick the right template with --template`
|
|
4142
4285
|
);
|
|
4143
4286
|
},
|
|
4144
|
-
remote: nginxRemote
|
|
4287
|
+
remote: (_built, _port, target) => nginxRemote(target)
|
|
4145
4288
|
};
|
|
4146
|
-
function nginxRemote() {
|
|
4289
|
+
function nginxRemote(target) {
|
|
4290
|
+
if (target) {
|
|
4291
|
+
return [
|
|
4292
|
+
"set -e",
|
|
4293
|
+
"test -d /srv/app -a -w /srv/app || exit 3",
|
|
4294
|
+
DROP_SINGLE,
|
|
4295
|
+
`rm -rf ${target.root}/.incoming ${target.root}/.old`,
|
|
4296
|
+
`mkdir -p ${target.root}/.incoming`,
|
|
4297
|
+
`tar -xf - -C ${target.root}/.incoming`,
|
|
4298
|
+
`chmod -R a+rX ${target.root}/.incoming`,
|
|
4299
|
+
`if [ -e ${target.root}/dist ]; then mv ${target.root}/dist ${target.root}/.old; fi`,
|
|
4300
|
+
`mv ${target.root}/.incoming ${target.root}/dist`,
|
|
4301
|
+
`rm -rf ${target.root}/.old`
|
|
4302
|
+
].join("\n");
|
|
4303
|
+
}
|
|
4147
4304
|
return [
|
|
4148
4305
|
"set -e",
|
|
4149
4306
|
"test -e /etc/nginx/sites-enabled/kvbox-app || exit 3",
|
|
@@ -4186,7 +4343,7 @@ var staticTemplate = {
|
|
|
4186
4343
|
const pm = ctx.pkg !== void 0 ? await packageManager(ctx.dir) : "npm";
|
|
4187
4344
|
return { outDir, ...dist !== void 0 ? { dist } : {}, exclude: EXCLUDE, pm, what: dist !== void 0 ? `${dist}/` : "the directory" };
|
|
4188
4345
|
},
|
|
4189
|
-
remote: nginxRemote
|
|
4346
|
+
remote: (_built, _port, target) => nginxRemote(target)
|
|
4190
4347
|
};
|
|
4191
4348
|
|
|
4192
4349
|
// src/commands/deploy/templates/index.ts
|
|
@@ -4222,7 +4379,134 @@ var DeployConfigSchema = z5.object({
|
|
|
4222
4379
|
/** The port a Next.js app or Node server serves; the template's (3000) when absent. */
|
|
4223
4380
|
port: z5.number().int().min(1).max(65535).optional()
|
|
4224
4381
|
});
|
|
4225
|
-
|
|
4382
|
+
var SERVICE_KEY_RE = /^[a-z][a-z0-9-]{0,19}$/;
|
|
4383
|
+
var RESERVED_SERVICE_KEYS = ["app", "agent", "init", "volumes"];
|
|
4384
|
+
var STATIC_TEMPLATES = ["react", "static"];
|
|
4385
|
+
var FRONT_PORT = 80;
|
|
4386
|
+
var ROUTE_RE = /^\/(?:[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)*)?$/;
|
|
4387
|
+
var POSTGRES = "postgres";
|
|
4388
|
+
var POSTGRES_PORT = 5432;
|
|
4389
|
+
var POSTGRES_IMAGE = "postgres:17";
|
|
4390
|
+
var POSTGRES_ENV = "DATABASE_URL";
|
|
4391
|
+
var IMAGE_RE = /^[a-z0-9][a-z0-9._/:@-]*$/;
|
|
4392
|
+
var ServiceSchema = z5.strictObject({
|
|
4393
|
+
template: z5.enum([...TEMPLATE_IDS, POSTGRES]),
|
|
4394
|
+
/** The service's directory, relative to the one holding kvbox.json; every template but postgres has one. */
|
|
4395
|
+
dir: z5.string().min(1).optional(),
|
|
4396
|
+
/** A postgres service's image, `postgres:17` when absent (`pgvector/pgvector:pg17` for vectors). */
|
|
4397
|
+
image: z5.string().regex(IMAGE_RE, "an image name like postgres:17").optional(),
|
|
4398
|
+
/** The volume (a key of `volumes`) a postgres service keeps its data on. */
|
|
4399
|
+
volume: z5.string().optional(),
|
|
4400
|
+
/** The box variable a postgres service's URL is written to, `DATABASE_URL` when absent. */
|
|
4401
|
+
env: z5.string().optional(),
|
|
4402
|
+
/** A docker service's build context, relative to kvbox.json, when it is not `dir` (a monorepo built from its root); the Dockerfile stays in `dir`. */
|
|
4403
|
+
context: z5.string().min(1).optional(),
|
|
4404
|
+
dist: z5.string().optional(),
|
|
4405
|
+
/** The box port of a service with its own server; the template's (3000) when absent. */
|
|
4406
|
+
port: z5.number().int().min(1).max(65535).optional(),
|
|
4407
|
+
/** The URL paths that go to this service, each with everything under it; the prefix is kept. */
|
|
4408
|
+
paths: z5.array(z5.string().regex(ROUTE_RE, "a path like / or /api, no trailing slash")).min(1).optional()
|
|
4409
|
+
});
|
|
4410
|
+
var StackConfigSchema = z5.strictObject({
|
|
4411
|
+
name: DeployConfigSchema.shape.name.optional(),
|
|
4412
|
+
org: DeployConfigSchema.shape.org,
|
|
4413
|
+
subdomain: DeployConfigSchema.shape.subdomain,
|
|
4414
|
+
size: DeployConfigSchema.shape.size,
|
|
4415
|
+
/** The stack's volumes, name to size ("10GB"): made for its box and attached to it on the first deploy that needs one. */
|
|
4416
|
+
volumes: z5.record(z5.string(), z5.string()).optional(),
|
|
4417
|
+
services: z5.record(z5.string(), ServiceSchema)
|
|
4418
|
+
});
|
|
4419
|
+
function volumeGib(text2) {
|
|
4420
|
+
const mib = parseMib(text2);
|
|
4421
|
+
if (mib === void 0 || mib === 0 || mib % 1024 !== 0 || mib / 1024 > MAX_VOLUME_GIB) return void 0;
|
|
4422
|
+
return mib / 1024;
|
|
4423
|
+
}
|
|
4424
|
+
function stackServices(stack, defaultPort, exposed = /* @__PURE__ */ new Map()) {
|
|
4425
|
+
const services = [];
|
|
4426
|
+
const ports = /* @__PURE__ */ new Map();
|
|
4427
|
+
const routes = /* @__PURE__ */ new Map();
|
|
4428
|
+
const entries = Object.entries(stack.services);
|
|
4429
|
+
if (entries.length === 0) throw new KvboxError(`${CONFIG_FILE}: services: at least one service`);
|
|
4430
|
+
for (const [name, size] of Object.entries(stack.volumes ?? {})) {
|
|
4431
|
+
if (!VOLUME_NAME_RE.test(name)) throw new KvboxError(`${CONFIG_FILE}: volumes.${name}: a volume name is ${VOLUME_NAME_RULE}`);
|
|
4432
|
+
if (volumeGib(size) === void 0) throw new KvboxError(`${CONFIG_FILE}: volumes.${name}: ${size} is not a size; write whole GB, like "10GB" (at most ${MAX_VOLUME_GIB})`);
|
|
4433
|
+
}
|
|
4434
|
+
const volumeUsers = /* @__PURE__ */ new Map();
|
|
4435
|
+
const envUsers = /* @__PURE__ */ new Map();
|
|
4436
|
+
for (const [key, config] of entries) {
|
|
4437
|
+
const at = `${CONFIG_FILE}: services.${key}`;
|
|
4438
|
+
if (!SERVICE_KEY_RE.test(key)) throw new KvboxError(`${at}: a service name is 1-20 chars, lowercase letters, digits and '-', starting with a letter`);
|
|
4439
|
+
if (RESERVED_SERVICE_KEYS.includes(key)) throw new KvboxError(`${at}: the name ${key} is taken by kvbox itself; call the service something else (web, api, site)`);
|
|
4440
|
+
const outside = (p) => isAbsolute(p) || p.split(/[\\/]/).includes("..");
|
|
4441
|
+
if (config.template === POSTGRES) {
|
|
4442
|
+
services.push(postgresService(key, config, stack, { volumeUsers, envUsers }, ports));
|
|
4443
|
+
continue;
|
|
4444
|
+
}
|
|
4445
|
+
for (const field of ["image", "volume", "env"]) {
|
|
4446
|
+
if (config[field] !== void 0) throw new KvboxError(`${at}.${field}: only a postgres service has one`);
|
|
4447
|
+
}
|
|
4448
|
+
if (config.dir === void 0) throw new KvboxError(`${at}.dir: the service's directory, relative to ${CONFIG_FILE}`);
|
|
4449
|
+
if (outside(config.dir)) throw new KvboxError(`${at}.dir: a directory inside the project, relative to ${CONFIG_FILE}`);
|
|
4450
|
+
if (config.context !== void 0) {
|
|
4451
|
+
if (config.template !== "docker") throw new KvboxError(`${at}.context: only a docker service has a build context`);
|
|
4452
|
+
if (outside(config.context)) throw new KvboxError(`${at}.context: a directory inside the project, relative to ${CONFIG_FILE}`);
|
|
4453
|
+
const rel = relative2(normalize(config.context), normalize(config.dir));
|
|
4454
|
+
if (rel.startsWith("..") || isAbsolute(rel)) throw new KvboxError(`${at}.context: must hold the service's dir (${config.dir}), where its Dockerfile is`);
|
|
4455
|
+
}
|
|
4456
|
+
const isStatic = STATIC_TEMPLATES.includes(config.template);
|
|
4457
|
+
const paths2 = config.paths ?? [];
|
|
4458
|
+
if (isStatic && config.port !== void 0) throw new KvboxError(`${at}.port: a ${config.template} service has no port of its own; nginx serves its files`);
|
|
4459
|
+
if (isStatic && paths2.length === 0) throw new KvboxError(`${at}.paths: say where the site is served, for example "paths": ["/"]`);
|
|
4460
|
+
let port;
|
|
4461
|
+
if (!isStatic) {
|
|
4462
|
+
const fromExpose = config.port === void 0 ? exposed.get(key) : void 0;
|
|
4463
|
+
port = config.port ?? fromExpose ?? defaultPort(config.template);
|
|
4464
|
+
const instead = `set its own "port" in ${CONFIG_FILE}; the container must listen on it, given as PORT`;
|
|
4465
|
+
if (port === FRONT_PORT) {
|
|
4466
|
+
if (fromExpose !== void 0) throw new KvboxError(`${at}: its Dockerfile EXPOSEs ${FRONT_PORT}, nginx's, the front door of the box; ${instead}`);
|
|
4467
|
+
throw new KvboxError(`${at}.port: ${FRONT_PORT} is nginx's, the front door of the box; pick another`);
|
|
4468
|
+
}
|
|
4469
|
+
const other = ports.get(port);
|
|
4470
|
+
if (other !== void 0) {
|
|
4471
|
+
if (fromExpose !== void 0) throw new KvboxError(`${at}: its Dockerfile EXPOSEs ${port}, which is also ${other}'s; ${instead}`);
|
|
4472
|
+
throw new KvboxError(`${at}.port: ${port} is also ${other}'s; give each service its own "port"`);
|
|
4473
|
+
}
|
|
4474
|
+
ports.set(port, key);
|
|
4475
|
+
}
|
|
4476
|
+
for (const path of paths2) {
|
|
4477
|
+
const other = routes.get(path);
|
|
4478
|
+
if (other !== void 0) throw new KvboxError(`${at}.paths: ${path} is also ${other}'s; a path goes to one service`);
|
|
4479
|
+
routes.set(path, key);
|
|
4480
|
+
}
|
|
4481
|
+
services.push({ key, config, static: isStatic, ...port !== void 0 ? { port } : {}, paths: paths2 });
|
|
4482
|
+
}
|
|
4483
|
+
return services;
|
|
4484
|
+
}
|
|
4485
|
+
function postgresService(key, config, stack, { volumeUsers, envUsers }, ports) {
|
|
4486
|
+
const at = `${CONFIG_FILE}: services.${key}`;
|
|
4487
|
+
for (const field of ["dir", "context", "dist", "paths"]) {
|
|
4488
|
+
if (config[field] !== void 0) throw new KvboxError(`${at}.${field}: a postgres service has none${field === "paths" ? "; it is reached by the other services on 127.0.0.1, never from the internet" : ""}`);
|
|
4489
|
+
}
|
|
4490
|
+
const env = config.env ?? POSTGRES_ENV;
|
|
4491
|
+
const envProblem = envNameProblem(env);
|
|
4492
|
+
if (envProblem !== null) throw new KvboxError(`${at}.env: ${envProblem}`);
|
|
4493
|
+
const envOwner = envUsers.get(env);
|
|
4494
|
+
if (envOwner !== void 0) throw new KvboxError(`${at}.env: ${env} already holds ${envOwner}'s URL; give each database its own "env" (like ${key.toUpperCase().replace(/-/g, "_")}_URL)`);
|
|
4495
|
+
envUsers.set(env, key);
|
|
4496
|
+
if (config.volume !== void 0) {
|
|
4497
|
+
if (stack.volumes?.[config.volume] === void 0) throw new KvboxError(`${at}.volume: no volume ${config.volume} in "volumes"; add it there with its size, like "volumes": { "${config.volume}": "10GB" }`);
|
|
4498
|
+
const other2 = volumeUsers.get(config.volume);
|
|
4499
|
+
if (other2 !== void 0) throw new KvboxError(`${at}.volume: ${config.volume} already holds ${other2}'s data; give each database its own volume`);
|
|
4500
|
+
volumeUsers.set(config.volume, key);
|
|
4501
|
+
}
|
|
4502
|
+
const port = config.port ?? POSTGRES_PORT;
|
|
4503
|
+
if (port === FRONT_PORT) throw new KvboxError(`${at}.port: ${FRONT_PORT} is nginx's, the front door of the box; pick another`);
|
|
4504
|
+
const other = ports.get(port);
|
|
4505
|
+
if (other !== void 0) throw new KvboxError(`${at}.port: ${port} is also ${other}'s; give each service its own "port"`);
|
|
4506
|
+
ports.set(port, key);
|
|
4507
|
+
return { key, config, static: false, port, paths: [], postgres: { image: config.image ?? POSTGRES_IMAGE, env, ...config.volume !== void 0 ? { volume: config.volume } : {} } };
|
|
4508
|
+
}
|
|
4509
|
+
async function readDeployFile(dir) {
|
|
4226
4510
|
const path = join6(dir, CONFIG_FILE);
|
|
4227
4511
|
let raw;
|
|
4228
4512
|
try {
|
|
@@ -4237,12 +4521,13 @@ async function readConfig(dir) {
|
|
|
4237
4521
|
} catch {
|
|
4238
4522
|
throw new KvboxError(`${path}: not valid JSON`);
|
|
4239
4523
|
}
|
|
4240
|
-
const
|
|
4524
|
+
const stack = typeof json2 === "object" && json2 !== null && "services" in json2;
|
|
4525
|
+
const parsed = stack ? StackConfigSchema.safeParse(json2) : DeployConfigSchema.safeParse(json2);
|
|
4241
4526
|
if (!parsed.success) {
|
|
4242
4527
|
const issue = parsed.error.issues[0];
|
|
4243
4528
|
throw new KvboxError(`${path}: ${issue.path.join(".") || "file"}: ${issue.message}`);
|
|
4244
4529
|
}
|
|
4245
|
-
return parsed.data;
|
|
4530
|
+
return stack ? { kind: "stack", config: parsed.data } : { kind: "single", config: parsed.data };
|
|
4246
4531
|
}
|
|
4247
4532
|
async function writeConfig(dir, config) {
|
|
4248
4533
|
await writeFile4(join6(dir, CONFIG_FILE), JSON.stringify(config, null, 2) + "\n");
|
|
@@ -4282,9 +4567,9 @@ async function ship(ep, dir, remote, exclude = []) {
|
|
|
4282
4567
|
const ssh = spawn5("ssh", [...sshArgs(ep), remote], { stdio: ["pipe", "pipe", "pipe"] });
|
|
4283
4568
|
tar.stdout.pipe(ssh.stdin);
|
|
4284
4569
|
const chunks = [];
|
|
4285
|
-
ssh.stdout.on("data", (
|
|
4286
|
-
ssh.stderr.on("data", (
|
|
4287
|
-
tar.stderr.on("data", (
|
|
4570
|
+
ssh.stdout.on("data", (c2) => chunks.push(c2));
|
|
4571
|
+
ssh.stderr.on("data", (c2) => chunks.push(c2));
|
|
4572
|
+
tar.stderr.on("data", (c2) => chunks.push(c2));
|
|
4288
4573
|
ssh.stdin.on("error", () => {
|
|
4289
4574
|
});
|
|
4290
4575
|
tar.stdout.on("error", () => {
|
|
@@ -4293,35 +4578,625 @@ async function ship(ep, dir, remote, exclude = []) {
|
|
|
4293
4578
|
tar.once("close", (code) => {
|
|
4294
4579
|
if (code !== 0) ssh.stdin.end();
|
|
4295
4580
|
});
|
|
4296
|
-
const tarDone = new Promise((
|
|
4297
|
-
const status2 = await new Promise((
|
|
4581
|
+
const tarDone = new Promise((resolve4) => tar.once("close", () => resolve4()));
|
|
4582
|
+
const status2 = await new Promise((resolve4, reject) => {
|
|
4298
4583
|
ssh.once("error", (err) => reject(new KvboxError(`could not run ssh: ${err.message}`)));
|
|
4299
4584
|
ssh.once("close", (code, signal) => {
|
|
4300
4585
|
tar.stdout.unpipe(ssh.stdin);
|
|
4301
4586
|
tar.stdout.resume();
|
|
4302
4587
|
tar.kill();
|
|
4303
|
-
|
|
4588
|
+
resolve4(code ?? (signal === "SIGINT" ? 130 : 1));
|
|
4304
4589
|
});
|
|
4305
4590
|
});
|
|
4306
4591
|
await tarDone;
|
|
4307
4592
|
return { status: status2, output: Buffer.concat(chunks).toString("utf8") };
|
|
4308
4593
|
}
|
|
4309
|
-
|
|
4594
|
+
async function run(ep, remote) {
|
|
4595
|
+
const ssh = spawn5("ssh", [...sshArgs(ep), remote], { stdio: ["ignore", "pipe", "pipe"] });
|
|
4596
|
+
const chunks = [];
|
|
4597
|
+
ssh.stdout.on("data", (c2) => chunks.push(c2));
|
|
4598
|
+
ssh.stderr.on("data", (c2) => chunks.push(c2));
|
|
4599
|
+
const status2 = await new Promise((resolve4, reject) => {
|
|
4600
|
+
ssh.once("error", (err) => reject(new KvboxError(`could not run ssh: ${err.message}`)));
|
|
4601
|
+
ssh.once("close", (code, signal) => resolve4(code ?? (signal === "SIGINT" ? 130 : 1)));
|
|
4602
|
+
});
|
|
4603
|
+
return { status: status2, output: Buffer.concat(chunks).toString("utf8") };
|
|
4604
|
+
}
|
|
4605
|
+
var shipping = { ship, run, measure, waitForSsh };
|
|
4606
|
+
|
|
4607
|
+
// src/commands/deploy/box.ts
|
|
4608
|
+
var NAME_RULE = "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit";
|
|
4609
|
+
function refuseFailedShip(result, ctx) {
|
|
4610
|
+
const { ref, template, port, built, service } = ctx;
|
|
4611
|
+
const app = service ? `service ${service.key}` : "the app";
|
|
4612
|
+
if (result.status === SSH_FAILED3) throw new KvboxError(`box ${ref}: could not reach it over SSH (still booting?)${result.output ? `
|
|
4613
|
+
${result.output.trim()}` : ""}`, SSH_FAILED3);
|
|
4614
|
+
if (result.status === IMAGE_TOO_OLD) {
|
|
4615
|
+
throw new KvboxError(
|
|
4616
|
+
`box ${ref} runs an image too old for the ${template.label} template (base v0.8.0 or newer). Update the box (kvbox vm update ${ref}) once its host has the new image, or deploy under another name (--name) to get a fresh box`
|
|
4617
|
+
);
|
|
4618
|
+
}
|
|
4619
|
+
if (result.status === APP_NOT_LISTENING) {
|
|
4620
|
+
const log = result.output.split(LOG_MARKER)[1]?.trim();
|
|
4621
|
+
const where = built.containerPort !== void 0 && built.containerPort !== port ? `the container's port ${built.containerPort} (box port ${port})` : `port ${port}`;
|
|
4622
|
+
const fix = service ? `, or say its port with "port" in ${CONFIG_FILE}` : template.customPort ? ", or say its port with --port" : "";
|
|
4623
|
+
const listens = service && template.id === "docker" ? `The container must listen on PORT (${port}), on the box's own network` : template.listens ?? `It must listen on process.env.PORT (${port})`;
|
|
4624
|
+
throw new KvboxError(
|
|
4625
|
+
`${app} did not answer on ${service ? `port ${port}` : where} within ${START_WAIT_SEC} s: it crashed, or listens on another port. ${listens}${fix}. Its log: kvbox exec ${ref} -- ${service ? `journalctl -u ${service.unit}` : template.logs ?? "journalctl -u kvbox-app"}${log ? `
|
|
4626
|
+
last lines:
|
|
4627
|
+
${log}` : ""}`
|
|
4628
|
+
);
|
|
4629
|
+
}
|
|
4630
|
+
if (result.status !== 0) throw new KvboxError(`deploying ${service ? `service ${service.key} ` : ""}to ${ref} failed (exit ${result.status}):
|
|
4631
|
+
${result.output.trim()}`);
|
|
4632
|
+
}
|
|
4633
|
+
async function findOrCreate(client, config) {
|
|
4634
|
+
const user = me(client);
|
|
4635
|
+
const slug = config.org ?? user;
|
|
4636
|
+
const named = (await client.listMachines()).filter((b) => b.name === config.name);
|
|
4637
|
+
let box = slug === void 0 ? named[0] : named.find((b) => slugOf(b.owner) === slug);
|
|
4638
|
+
let created = false;
|
|
4639
|
+
if (!box) {
|
|
4640
|
+
box = await spin(`booting a new box ${config.name}\u2026`, client.createMachine({ name: config.name, ...config.size !== void 0 ? { size: config.size } : {}, autoHibernateSec: DEPLOY_AUTO_HIBERNATE_SEC }));
|
|
4641
|
+
created = true;
|
|
4642
|
+
info(`${color.green("\u2713")} box ${color.bold(config.name)} is up: ${box.vcpu} vCPU, ${gb(box.memMib * 1024 ** 2)} RAM, ${gb(box.diskBytes)} disk`);
|
|
4643
|
+
}
|
|
4644
|
+
return { box, ref: displayName(box, user), created };
|
|
4645
|
+
}
|
|
4646
|
+
async function existingAddresses(client, config) {
|
|
4647
|
+
const slug = config.org ?? me(client);
|
|
4648
|
+
return (await client.listSubdomains()).filter((s) => s.box === config.name && s.owner === slug);
|
|
4649
|
+
}
|
|
4650
|
+
async function refuseOtherAddress(client, config) {
|
|
4651
|
+
const have = await existingAddresses(client, config);
|
|
4652
|
+
if (have.length < MAX_BOX_SUBDOMAINS || have.some((s) => s.subdomain === config.subdomain)) return;
|
|
4653
|
+
const ref = config.org !== void 0 ? `${config.org}/${config.name}` : config.name;
|
|
4654
|
+
throw new KvboxError(
|
|
4655
|
+
`box ${ref} already has ${MAX_BOX_SUBDOMAINS} addresses (${have.map((s) => s.subdomain).join(", ")}), none of them ${config.subdomain}. Deploy to one: kvbox deploy --sub <name>. Or free one: kvbox vm proxy release ${ref} --sub <name>`
|
|
4656
|
+
);
|
|
4657
|
+
}
|
|
4658
|
+
async function address(client, box, ref, config, port) {
|
|
4659
|
+
const subs = (await client.listSubdomains()).filter((s) => s.box === box.name && s.owner === slugOf(box.owner));
|
|
4660
|
+
const have = config.subdomain !== void 0 ? subs.find((s) => s.subdomain === config.subdomain) : subs[0];
|
|
4661
|
+
if (have) {
|
|
4662
|
+
if (have.port !== port) await client.setSubdomainPort(ref, { port }, have.subdomain);
|
|
4663
|
+
return { url: have.url, subdomain: have.subdomain };
|
|
4664
|
+
}
|
|
4665
|
+
const wanted = config.subdomain ?? subdomainFor(config.name);
|
|
4666
|
+
try {
|
|
4667
|
+
const sub = await spin(`claiming https://${wanted}.kvbox.app\u2026`, client.claimSubdomain(ref, { name: wanted, port }));
|
|
4668
|
+
return { url: sub.url, subdomain: sub.subdomain };
|
|
4669
|
+
} catch (err) {
|
|
4670
|
+
if (!(err instanceof KvboxError)) throw err;
|
|
4671
|
+
throw new KvboxError(`${err.message}
|
|
4672
|
+
the app is on box ${ref} but has no address yet: pick another with kvbox deploy --sub <name> (saved to ${CONFIG_FILE})`);
|
|
4673
|
+
}
|
|
4674
|
+
}
|
|
4675
|
+
|
|
4676
|
+
// src/commands/deploy/stack.ts
|
|
4677
|
+
import { access as access4, readFile as readFile7 } from "fs/promises";
|
|
4678
|
+
import { basename, join as join8, resolve as resolve2 } from "path";
|
|
4679
|
+
|
|
4680
|
+
// src/commands/deploy/postgres.ts
|
|
4681
|
+
import { randomBytes } from "crypto";
|
|
4682
|
+
var POSTGRES_USER = "kvbox";
|
|
4683
|
+
var POSTGRES_DB = "app";
|
|
4684
|
+
var ENV_MISSING = 6;
|
|
4685
|
+
var VOLUME_NOT_MOUNTED = 7;
|
|
4686
|
+
var DB_NOT_READY = 8;
|
|
4687
|
+
var URL_OTHER_PORT = 9;
|
|
4688
|
+
var URL_FOREIGN = 10;
|
|
4689
|
+
var OTHER_DATA = 11;
|
|
4690
|
+
var DB_WAIT_SEC = 90;
|
|
4691
|
+
var AGENT = "/usr/local/sbin/kvbox-agent";
|
|
4692
|
+
var ENV_WAIT_SEC = 60;
|
|
4693
|
+
function newPassword() {
|
|
4694
|
+
return randomBytes(24).toString("hex");
|
|
4695
|
+
}
|
|
4696
|
+
function postgresUrl(password, port) {
|
|
4697
|
+
return `postgres://${POSTGRES_USER}:${password}@127.0.0.1:${port}/${POSTGRES_DB}`;
|
|
4698
|
+
}
|
|
4699
|
+
function postgresRemote(o) {
|
|
4700
|
+
const { root, unit } = o.target;
|
|
4701
|
+
const mount = `/mnt/${o.volume}`;
|
|
4702
|
+
const key = o.target.root.split("/").pop();
|
|
4703
|
+
const data = `${mount}/${key}`;
|
|
4704
|
+
const envFile = `${root}/current/postgres.env`;
|
|
4705
|
+
const unitText = [
|
|
4706
|
+
"[Unit]",
|
|
4707
|
+
`Description=kvbox deploy: the database ${unit}`,
|
|
4708
|
+
"After=docker.service kvbox-volumes.service network-online.target",
|
|
4709
|
+
"Requires=docker.service",
|
|
4710
|
+
"",
|
|
4711
|
+
"[Service]",
|
|
4712
|
+
`ExecStartPre=/usr/bin/mountpoint -q ${mount}`,
|
|
4713
|
+
`ExecStartPre=-/usr/bin/docker rm -f ${unit}`,
|
|
4714
|
+
`ExecStart=/usr/bin/docker run --rm --name ${unit} --network host --env-file ${envFile} -e POSTGRES_USER=${POSTGRES_USER} -e POSTGRES_DB=${POSTGRES_DB} -e PGDATA=/kvbox-data/pgdata -v ${data}:/kvbox-data ${o.image} -c listen_addresses=127.0.0.1 -c port=${o.port}`,
|
|
4715
|
+
`ExecStop=/usr/bin/docker stop ${unit}`,
|
|
4716
|
+
"Restart=always",
|
|
4717
|
+
"RestartSec=2",
|
|
4718
|
+
"",
|
|
4719
|
+
"[Install]",
|
|
4720
|
+
"WantedBy=multi-user.target"
|
|
4721
|
+
];
|
|
4722
|
+
return [
|
|
4723
|
+
"set -eo pipefail",
|
|
4724
|
+
"test -d /srv/app -a -w /srv/app || exit 3",
|
|
4725
|
+
"command -v docker >/dev/null || exit 3",
|
|
4726
|
+
// The host hands a booting box its variables a few seconds after it starts. Only an agent that marks
|
|
4727
|
+
// it (base v0.12.0+) is waited for: on an older image the file never comes, and every deploy would stall.
|
|
4728
|
+
`if grep -qs env-ready ${AGENT}; then i=0; until [ -e /run/kvbox/env-ready ] || [ "$i" -ge ${ENV_WAIT_SEC} ]; do i=$((i+1)); sleep 1; done; fi`,
|
|
4729
|
+
`url=$(sed -n 's/^${o.env}=//p' ${BOX_ENV_PLAIN} 2>/dev/null | head -n 1 || true)`,
|
|
4730
|
+
`[ -n "$url" ] || exit ${ENV_MISSING}`,
|
|
4731
|
+
// Only a URL this CLI made, for this port, is the database's: never a value set for something else.
|
|
4732
|
+
`pw=\${url#postgres://${POSTGRES_USER}:}`,
|
|
4733
|
+
"pw=${pw%%@*}",
|
|
4734
|
+
`case "$pw" in ''|*[!0-9a-f]*) exit ${URL_FOREIGN} ;; esac`,
|
|
4735
|
+
`case "$url" in "${postgresUrl("$pw", o.port)}") ;; "postgres://${POSTGRES_USER}:$pw@127.0.0.1:"*"/${POSTGRES_DB}") exit ${URL_OTHER_PORT} ;; *) exit ${URL_FOREIGN} ;; esac`,
|
|
4736
|
+
`mountpoint -q ${mount} || exit ${VOLUME_NOT_MOUNTED}`,
|
|
4737
|
+
`mkdir -p ${root}/current`,
|
|
4738
|
+
// One database per volume: another service's data there is a renamed service, never started empty beside it.
|
|
4739
|
+
// Its pgdata (mode 700, postgres's) is seen from the folder above, which is this user's.
|
|
4740
|
+
`for f in ${mount}/*/pgdata; do [ -d "$f" ] || continue; o=\${f#${mount}/}; o=\${o%%/*}; [ "$o" = ${key} ] || { echo "$o"; exit ${OTHER_DATA}; }; done`,
|
|
4741
|
+
`mkdir -p ${data}`,
|
|
4742
|
+
`(umask 077; printf 'POSTGRES_PASSWORD=%s\\n' "$pw" > ${envFile})`,
|
|
4743
|
+
`docker image inspect ${o.image} >/dev/null 2>&1 || docker pull -q ${o.image} >/dev/null`,
|
|
4744
|
+
DROP_SINGLE,
|
|
4745
|
+
`cat > ${root}/.unit <<'UNIT'`,
|
|
4746
|
+
...unitText,
|
|
4747
|
+
"UNIT",
|
|
4748
|
+
"changed=0",
|
|
4749
|
+
`if ! cmp -s ${root}/.unit /etc/systemd/system/${unit}.service; then sudo -n cp ${root}/.unit /etc/systemd/system/${unit}.service; sudo -n systemctl daemon-reload; changed=1; fi`,
|
|
4750
|
+
`rm -f ${root}/.unit`,
|
|
4751
|
+
"sudo -n systemctl enable --quiet docker",
|
|
4752
|
+
`sudo -n systemctl enable --quiet ${unit}`,
|
|
4753
|
+
`if [ "$changed" = 1 ] || ! systemctl is-active --quiet ${unit}; then sudo -n systemctl restart ${unit}; fi`,
|
|
4754
|
+
// Ready on TCP, not only on its socket: during the first start's initdb it listens on no port.
|
|
4755
|
+
"i=0",
|
|
4756
|
+
`until docker exec ${unit} pg_isready -q -h 127.0.0.1 -p ${o.port} 2>/dev/null; do`,
|
|
4757
|
+
" i=$((i+1))",
|
|
4758
|
+
` if [ "$i" -ge ${DB_WAIT_SEC} ]; then echo '${LOG_MARKER}'; sudo -n journalctl -u ${unit} -n 20 --no-pager -o cat || true; exit ${DB_NOT_READY}; fi`,
|
|
4759
|
+
" sleep 1",
|
|
4760
|
+
"done",
|
|
4761
|
+
// The box's password is the one that counts, whatever the data was made with (a new box on an old volume).
|
|
4762
|
+
// Over the local socket (trust in the image), whose name carries the port: without -p it is 5432's.
|
|
4763
|
+
`docker exec ${unit} psql -q -p ${o.port} -U ${POSTGRES_USER} -d ${POSTGRES_DB} -c "ALTER ROLE ${POSTGRES_USER} PASSWORD '$pw'" >/dev/null`
|
|
4764
|
+
].join("\n");
|
|
4765
|
+
}
|
|
4766
|
+
|
|
4767
|
+
// src/commands/deploy/nginx.ts
|
|
4768
|
+
var STACK_SITE = "kvbox-stack";
|
|
4769
|
+
var SITE_REFUSED = 5;
|
|
4770
|
+
var NO_PREVIOUS_SITE = "--- kvbox: no previous stack site ---";
|
|
4771
|
+
var PROXY = (port) => [
|
|
4772
|
+
`proxy_pass http://127.0.0.1:${port};`,
|
|
4773
|
+
"proxy_http_version 1.1;",
|
|
4774
|
+
"proxy_set_header Host $http_host;",
|
|
4775
|
+
"proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;",
|
|
4776
|
+
"proxy_set_header X-Forwarded-Proto $kvbox_proto;",
|
|
4777
|
+
// WebSocket, and streamed answers (server-sent events) as they are written.
|
|
4778
|
+
"proxy_set_header Upgrade $http_upgrade;",
|
|
4779
|
+
"proxy_set_header Connection $kvbox_connection;",
|
|
4780
|
+
"proxy_buffering off;",
|
|
4781
|
+
"proxy_read_timeout 3600s;"
|
|
4782
|
+
];
|
|
4783
|
+
var block2 = (head, body) => [` ${head} {`, ...body.map((l) => ` ${l}`), " }", ""];
|
|
4784
|
+
function locations(service, path) {
|
|
4785
|
+
const dist = `/srv/app/${service.key}/dist`;
|
|
4786
|
+
if (service.static) {
|
|
4787
|
+
if (path === "/") return block2("location /", [`root ${dist};`, "try_files $uri $uri/ /index.html;"]);
|
|
4788
|
+
return [...block2(`location = ${path}`, [`return 301 ${path}/;`]), ...block2(`location ${path}/`, [`alias ${dist}/;`, `try_files $uri $uri/ ${path}/index.html;`])];
|
|
4789
|
+
}
|
|
4790
|
+
const proxy = PROXY(service.port);
|
|
4791
|
+
if (path === "/") return block2("location /", proxy);
|
|
4792
|
+
return [...block2(`location = ${path}`, proxy), ...block2(`location ${path}/`, proxy)];
|
|
4793
|
+
}
|
|
4794
|
+
function stackSite(services) {
|
|
4795
|
+
const routed = services.flatMap((s) => s.paths.map((path) => ({ service: s, path })));
|
|
4796
|
+
const root = routed.find((r) => r.path === "/");
|
|
4797
|
+
return [
|
|
4798
|
+
"# Written by kvbox deploy from kvbox.json; the next deploy writes it again.",
|
|
4799
|
+
"map $http_upgrade $kvbox_connection {",
|
|
4800
|
+
" default upgrade;",
|
|
4801
|
+
" '' close;",
|
|
4802
|
+
"}",
|
|
4803
|
+
"map $http_x_forwarded_proto $kvbox_proto {",
|
|
4804
|
+
" default $http_x_forwarded_proto;",
|
|
4805
|
+
" '' $scheme;",
|
|
4806
|
+
"}",
|
|
4807
|
+
"server {",
|
|
4808
|
+
" listen 80 default_server;",
|
|
4809
|
+
" listen [::]:80 default_server;",
|
|
4810
|
+
" server_name _;",
|
|
4811
|
+
" index index.html;",
|
|
4812
|
+
// The app behind a path decides how much it takes.
|
|
4813
|
+
" client_max_body_size 0;",
|
|
4814
|
+
"",
|
|
4815
|
+
" gzip on;",
|
|
4816
|
+
" gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;",
|
|
4817
|
+
"",
|
|
4818
|
+
...routed.flatMap((r) => locations(r.service, r.path)),
|
|
4819
|
+
// No service at the top: say so instead of nginx's own welcome page.
|
|
4820
|
+
...root ? [] : block2("location /", ["return 404;"]),
|
|
4821
|
+
"}",
|
|
4822
|
+
""
|
|
4823
|
+
].join("\n");
|
|
4824
|
+
}
|
|
4825
|
+
function frontRemote(site) {
|
|
4826
|
+
const available = `/etc/nginx/sites-available/${STACK_SITE}`;
|
|
4827
|
+
const enabled2 = `/etc/nginx/sites-enabled/${STACK_SITE}`;
|
|
4828
|
+
return [
|
|
4829
|
+
"set -e",
|
|
4830
|
+
"command -v nginx >/dev/null || exit 3",
|
|
4831
|
+
`if [ -e ${available} ]; then sudo -n cp -f ${available} ${available}.old; fi`,
|
|
4832
|
+
`sudo -n tee ${available} >/dev/null <<'KVBOX_SITE'`,
|
|
4833
|
+
site,
|
|
4834
|
+
"KVBOX_SITE",
|
|
4835
|
+
`sudo -n ln -sf ${available} ${enabled2}`,
|
|
4836
|
+
"sudo -n rm -f /etc/nginx/sites-enabled/kvbox-app",
|
|
4837
|
+
"if ! sudo -n nginx -t 2>&1; then",
|
|
4838
|
+
` if [ -e ${available}.old ]; then sudo -n mv -f ${available}.old ${available}; else echo '${NO_PREVIOUS_SITE}'; sudo -n rm -f ${available} ${enabled2}; sudo -n ln -sf /etc/nginx/sites-available/kvbox-app /etc/nginx/sites-enabled/kvbox-app; fi`,
|
|
4839
|
+
` exit ${SITE_REFUSED}`,
|
|
4840
|
+
"fi",
|
|
4841
|
+
`sudo -n rm -f ${available}.old`,
|
|
4842
|
+
"sudo -n systemctl enable --now --quiet nginx",
|
|
4843
|
+
"sudo -n systemctl reload nginx"
|
|
4844
|
+
].join("\n");
|
|
4845
|
+
}
|
|
4846
|
+
|
|
4847
|
+
// src/commands/deploy/stack.ts
|
|
4848
|
+
var STACK_SIZE = "s";
|
|
4849
|
+
var exists = (path) => access4(path).then(() => true, () => false);
|
|
4850
|
+
async function deployStack(d) {
|
|
4851
|
+
const { dir, opts, client, cloud } = d;
|
|
4852
|
+
if (opts.template !== void 0 || opts.port !== void 0) throw new KvboxError(`--template and --port are one app's; with several services each says its own in ${CONFIG_FILE}`);
|
|
4853
|
+
const exposed = await exposedPorts(dir, d.stack);
|
|
4854
|
+
const portOf = (template) => templateById(template).port;
|
|
4855
|
+
pick(stackServices(d.stack, portOf, exposed), opts.only);
|
|
4856
|
+
const config = await settle(d);
|
|
4857
|
+
const services = stackServices(config, portOf, exposed);
|
|
4858
|
+
const picked = pick(services, opts.only);
|
|
4859
|
+
if (cloud && config.subdomain !== void 0) await refuseOtherAddress(client, { ...config, name: config.name });
|
|
4860
|
+
let saved = config;
|
|
4861
|
+
if (JSON.stringify(saved) !== JSON.stringify(d.stack)) await writeConfig(dir, saved);
|
|
4862
|
+
const box = { name: config.name, org: config.org, subdomain: config.subdomain, size: config.size };
|
|
4863
|
+
const all = [];
|
|
4864
|
+
for (const service of picked) {
|
|
4865
|
+
if (service.postgres) continue;
|
|
4866
|
+
const template = templateById(service.config.template);
|
|
4867
|
+
const serviceDir = resolve2(dir, service.config.dir);
|
|
4868
|
+
if (!await exists(serviceDir)) throw new KvboxError(`${CONFIG_FILE}: services.${service.key}.dir: no directory ${serviceDir}`);
|
|
4869
|
+
info(`${color.bold("Building")} ${color.cyan(service.key)} ${color.dim(`(${template.label})`)}`);
|
|
4870
|
+
const context = service.config.context !== void 0 ? resolve2(dir, service.config.context) : void 0;
|
|
4871
|
+
const built = await template.build({ dir: serviceDir, pkg: await readPackageJson(serviceDir), dist: service.config.dist, ...context !== void 0 ? { context } : {} });
|
|
4872
|
+
if (built.dist !== void 0 && built.dist !== service.config.dist) {
|
|
4873
|
+
saved = { ...saved, services: { ...saved.services, [service.key]: { ...saved.services[service.key], dist: built.dist } } };
|
|
4874
|
+
await writeConfig(dir, saved);
|
|
4875
|
+
}
|
|
4876
|
+
all.push({ service, template, built, size: await shipping.measure(built.outDir, built.exclude) });
|
|
4877
|
+
}
|
|
4878
|
+
info("");
|
|
4879
|
+
const { box: found, ref, created } = await findOrCreate(client, box);
|
|
4880
|
+
const cert = await ensureCert(client, void 0, void 0, { owner: found.owner });
|
|
4881
|
+
const wasRunning = !created && found.status === "running";
|
|
4882
|
+
const machine = created || wasRunning ? found : await wakeUp(client, found, ref);
|
|
4883
|
+
const ep = sshEndpoint(machine, client.target);
|
|
4884
|
+
if (!wasRunning) await spin(`waiting for ${ref} to accept SSH\u2026`, shipping.waitForSsh(ep));
|
|
4885
|
+
let renewed = false;
|
|
4886
|
+
const renewOnce = async () => {
|
|
4887
|
+
if (renewed || !await renewAfterRefusal(client, cert, machine.owner)) return false;
|
|
4888
|
+
renewed = true;
|
|
4889
|
+
info("renewed your SSH certificate, trying again\u2026");
|
|
4890
|
+
return true;
|
|
4891
|
+
};
|
|
4892
|
+
const databases = picked.filter((s) => s.postgres);
|
|
4893
|
+
if (databases.length > 0) await deployDatabases({ client, ref, owner: machine.owner, name: machine.name, ep, volumes: config.volumes ?? {}, databases, renewOnce });
|
|
4894
|
+
for (const { service, template, built, size } of all) {
|
|
4895
|
+
const target = { root: `/srv/app/${service.key}`, unit: `kvbox-${service.key}` };
|
|
4896
|
+
const port = service.port ?? FRONT_PORT;
|
|
4897
|
+
const shipIt = () => shipping.ship(ep, built.outDir, template.remote(built, port, target), built.exclude);
|
|
4898
|
+
const there = service.static ? "" : template.id === "docker" ? " and building the image there, a minute or two" : built.boxBuild ? " and installing and building there, a minute or two" : " and installing there, a minute or two";
|
|
4899
|
+
const doing = `${service.key}: shipping ${built.what} (${size.files} files, ${gb(size.bytes)}) to ${ref}${there}\u2026`;
|
|
4900
|
+
let result = await spin(doing, shipIt);
|
|
4901
|
+
if (result.status === SSH_FAILED3 && await renewOnce()) result = await spin(doing, shipIt);
|
|
4902
|
+
refuseFailedShip(result, { ref, template, port, built, ...service.static ? {} : { service: { key: service.key, unit: target.unit } } });
|
|
4903
|
+
}
|
|
4904
|
+
const front = await spin(`pointing the box's front door at ${services.length === 1 ? "the service" : `the ${services.length} services`}\u2026`, shipping.run(ep, frontRemote(stackSite(services))));
|
|
4905
|
+
if (front.status === IMAGE_TOO_OLD) throw new KvboxError(`box ${ref} has no nginx: its image is too old (base v0.8.0 or newer). Update the box (kvbox vm update ${ref}), or deploy under another name (--name) to get a fresh box`);
|
|
4906
|
+
if (front.status === SITE_REFUSED) {
|
|
4907
|
+
const first = front.output.includes(NO_PREVIOUS_SITE);
|
|
4908
|
+
const after = first ? "this was the box's first stack, so there are no previous routes to keep, and any single app it ran was stopped for the services: its address answers nothing until a deploy whose routes nginx takes" : "the previous ones keep serving";
|
|
4909
|
+
throw new KvboxError(`nginx in box ${ref} refused the routes made from ${CONFIG_FILE}; ${after}. The services themselves were deployed.
|
|
4910
|
+
${front.output.replace(NO_PREVIOUS_SITE, "").trim()}`);
|
|
4911
|
+
}
|
|
4912
|
+
if (front.status !== 0) throw new KvboxError(`setting up nginx in box ${ref} failed (exit ${front.status}):
|
|
4913
|
+
${front.output.trim()}`);
|
|
4914
|
+
const missing = picked.length < services.length ? await neverShipped(ep, services.filter((s) => !picked.includes(s))) : [];
|
|
4915
|
+
let url = `http://${machine.ip}`;
|
|
4916
|
+
if (cloud) {
|
|
4917
|
+
const got = await address(client, machine, ref, box, FRONT_PORT);
|
|
4918
|
+
url = got.url;
|
|
4919
|
+
if (got.subdomain !== saved.subdomain) await writeConfig(dir, { ...saved, subdomain: got.subdomain });
|
|
4920
|
+
}
|
|
4921
|
+
if (opts.json) {
|
|
4922
|
+
json({
|
|
4923
|
+
box: ref,
|
|
4924
|
+
created,
|
|
4925
|
+
url,
|
|
4926
|
+
services: [
|
|
4927
|
+
...databases.map((s) => ({ key: s.key, template: POSTGRES, image: s.postgres.image, volume: s.postgres.volume, env: s.postgres.env, port: s.port, paths: [] })),
|
|
4928
|
+
...all.map(({ service, template, built, size }) => ({
|
|
4929
|
+
key: service.key,
|
|
4930
|
+
template: template.id,
|
|
4931
|
+
files: size.files,
|
|
4932
|
+
bytes: size.bytes,
|
|
4933
|
+
...built.dist !== void 0 ? { dist: built.dist } : {},
|
|
4934
|
+
...service.port !== void 0 ? { port: service.port } : {},
|
|
4935
|
+
paths: service.paths
|
|
4936
|
+
}))
|
|
4937
|
+
],
|
|
4938
|
+
...missing.length > 0 ? { missing: missing.map((s) => s.key) } : {}
|
|
4939
|
+
});
|
|
4940
|
+
return;
|
|
4941
|
+
}
|
|
4942
|
+
process.stdout.write(`${url}
|
|
4943
|
+
`);
|
|
4944
|
+
info(`${color.green("\u2713")} ${color.bold(config.name)} is live at ${color.bold(url)}`);
|
|
4945
|
+
info(` box ${ref}${created ? " (new)" : ""}`);
|
|
4946
|
+
for (const s of databases) {
|
|
4947
|
+
const vol = s.postgres.volume;
|
|
4948
|
+
info(` ${color.cyan(s.key)} \xB7 Postgres ${s.postgres.image} \xB7 port ${s.port} \xB7 data on volume ${vol} (${config.volumes?.[vol] ?? "?"}) \xB7 URL in ${s.postgres.env}`);
|
|
4949
|
+
}
|
|
4950
|
+
for (const { service, template, size } of all) {
|
|
4951
|
+
const where = service.paths.length > 0 ? service.paths.join(", ") : "no path, reached by the other services only";
|
|
4952
|
+
info(` ${color.cyan(service.key)} \xB7 ${template.label} \xB7 ${where}${service.port !== void 0 ? ` \xB7 port ${service.port}` : ""} \xB7 ${size.files} files, ${gb(size.bytes)}`);
|
|
4953
|
+
}
|
|
4954
|
+
for (const s of missing) {
|
|
4955
|
+
const where = s.postgres ? `no database, and no service gets ${s.postgres.env},` : s.paths.length > 0 ? `${s.paths.join(", ")} answer${s.paths.length === 1 ? "s" : ""} nothing` : "nothing runs";
|
|
4956
|
+
warn(` ! ${s.key} was never deployed to this box: ${where} until kvbox deploy --only ${s.key} (or a full kvbox deploy)`);
|
|
4957
|
+
}
|
|
4958
|
+
const at = d.dirArg !== void 0 ? ` ${d.dirArg}` : "";
|
|
4959
|
+
info(` redeploy: kvbox deploy${at} one service: kvbox deploy${at} --only <service>`);
|
|
4960
|
+
}
|
|
4961
|
+
async function exposedPorts(dir, stack) {
|
|
4962
|
+
const ports = /* @__PURE__ */ new Map();
|
|
4963
|
+
for (const [key, s] of Object.entries(stack.services)) {
|
|
4964
|
+
if (s.template !== "docker" || s.port !== void 0 || s.dir === void 0) continue;
|
|
4965
|
+
const text2 = await readFile7(resolve2(dir, s.dir, "Dockerfile"), "utf8").catch(() => void 0);
|
|
4966
|
+
const port = text2 !== void 0 ? exposedPort(text2) : void 0;
|
|
4967
|
+
if (port !== void 0) ports.set(key, port);
|
|
4968
|
+
}
|
|
4969
|
+
return ports;
|
|
4970
|
+
}
|
|
4971
|
+
async function deployDatabases(d) {
|
|
4972
|
+
const { client, ref } = d;
|
|
4973
|
+
let stale = false;
|
|
4974
|
+
const own = new Set((await client.boxEnv(ref)).vars.map((v) => v.name));
|
|
4975
|
+
for (const s of d.databases) {
|
|
4976
|
+
const pg = s.postgres;
|
|
4977
|
+
if (own.has(pg.env)) continue;
|
|
4978
|
+
await spin(`${s.key}: making a password, its URL in the box variable ${pg.env} (secret)\u2026`, client.setBoxEnv(ref, pg.env, { value: postgresUrl(newPassword(), s.port), secret: true }));
|
|
4979
|
+
stale = true;
|
|
4980
|
+
}
|
|
4981
|
+
let restarted = false;
|
|
4982
|
+
const slug = slugOf(d.owner);
|
|
4983
|
+
const existing = (await client.listVolumes()).filter((v) => slugOf(v.owner) === slug);
|
|
4984
|
+
for (const s of d.databases) {
|
|
4985
|
+
const name = s.postgres.volume;
|
|
4986
|
+
const have = existing.find((v) => v.name === name);
|
|
4987
|
+
if (have?.attachedTo === d.name) continue;
|
|
4988
|
+
if (have && have.attachedTo !== null) throw new KvboxError(`volume ${name} (in ${CONFIG_FILE} for ${s.key}) is attached to box ${have.attachedTo}. Detach it there (kvbox volume detach ${name} ${have.attachedTo}), or name another volume for ${s.key}`);
|
|
4989
|
+
if (have?.host !== void 0) {
|
|
4990
|
+
const boxHost = (await client.listMachines()).find((m) => m.name === d.name && slugOf(m.owner) === slug)?.host;
|
|
4991
|
+
if (boxHost !== void 0 && boxHost !== have.host) {
|
|
4992
|
+
throw new KvboxError(
|
|
4993
|
+
`volume ${name} (${s.key}'s data) is on host ${have.host} and box ${ref} on host ${boxHost}: a volume attaches only to a box on its own host, and its data cannot move yet. Deploy to a box on ${have.host} (one that is still there, --name), or name another volume for ${s.key} in ${CONFIG_FILE} for a new, empty database`
|
|
4994
|
+
);
|
|
4995
|
+
}
|
|
4996
|
+
}
|
|
4997
|
+
if (!have) {
|
|
4998
|
+
const sizeGib = volumeGib(d.volumes[name]);
|
|
4999
|
+
await spin(`${s.key}: making volume ${name} (${sizeGib} GB) for box ${ref}\u2026`, client.createVolume({ name, sizeGib, box: ref }));
|
|
5000
|
+
}
|
|
5001
|
+
await spin(`${s.key}: attaching volume ${name} to box ${ref} (the box restarts once)\u2026`, client.attachVolume(name, { box: ref }));
|
|
5002
|
+
restarted = true;
|
|
5003
|
+
}
|
|
5004
|
+
const restart = async (why) => {
|
|
5005
|
+
info(`restarting box ${ref} so ${why}`);
|
|
5006
|
+
await spin(`restarting box ${ref}\u2026`, async () => {
|
|
5007
|
+
await client.stopMachine(ref);
|
|
5008
|
+
await client.startMachine(ref);
|
|
5009
|
+
});
|
|
5010
|
+
restarted = true;
|
|
5011
|
+
};
|
|
5012
|
+
if (stale && !restarted) await restart("it gets the new database URL");
|
|
5013
|
+
if (restarted) await spin(`waiting for ${ref} to accept SSH\u2026`, shipping.waitForSsh(d.ep));
|
|
5014
|
+
for (const s of d.databases) {
|
|
5015
|
+
const pg = s.postgres;
|
|
5016
|
+
const script = postgresRemote({ target: { root: `/srv/app/${s.key}`, unit: `kvbox-${s.key}` }, image: pg.image, volume: pg.volume, env: pg.env, port: s.port });
|
|
5017
|
+
const doing = `${s.key}: starting ${pg.image} with its data on volume ${pg.volume} (the first start takes a while)\u2026`;
|
|
5018
|
+
const runScript2 = async () => {
|
|
5019
|
+
const result2 = await spin(doing, shipping.run(d.ep, script));
|
|
5020
|
+
return result2.status === SSH_FAILED3 && await d.renewOnce() ? spin(doing, shipping.run(d.ep, script)) : result2;
|
|
5021
|
+
};
|
|
5022
|
+
let result = await runScript2();
|
|
5023
|
+
if (result.status === ENV_MISSING && !restarted) {
|
|
5024
|
+
await restart(`it gets ${pg.env}`);
|
|
5025
|
+
await spin(`waiting for ${ref} to accept SSH\u2026`, shipping.waitForSsh(d.ep));
|
|
5026
|
+
result = await runScript2();
|
|
5027
|
+
}
|
|
5028
|
+
if (result.status === URL_OTHER_PORT) {
|
|
5029
|
+
await spin(`${s.key}: the database moved to port ${s.port}; a new URL in ${pg.env} (secret)\u2026`, client.setBoxEnv(ref, pg.env, { value: postgresUrl(newPassword(), s.port), secret: true }));
|
|
5030
|
+
await restart(`it gets ${pg.env} for port ${s.port}`);
|
|
5031
|
+
await spin(`waiting for ${ref} to accept SSH\u2026`, shipping.waitForSsh(d.ep));
|
|
5032
|
+
result = await runScript2();
|
|
5033
|
+
}
|
|
5034
|
+
refuseFailedDatabase(result, s, ref);
|
|
5035
|
+
}
|
|
5036
|
+
}
|
|
5037
|
+
function refuseFailedDatabase(result, s, ref) {
|
|
5038
|
+
const pg = s.postgres;
|
|
5039
|
+
const unit = `kvbox-${s.key}`;
|
|
5040
|
+
switch (result.status) {
|
|
5041
|
+
case 0:
|
|
5042
|
+
return;
|
|
5043
|
+
case SSH_FAILED3:
|
|
5044
|
+
throw new KvboxError(`box ${ref}: could not reach it over SSH (still booting?)${result.output ? `
|
|
5045
|
+
${result.output.trim()}` : ""}`, SSH_FAILED3);
|
|
5046
|
+
case IMAGE_TOO_OLD:
|
|
5047
|
+
throw new KvboxError(`box ${ref} runs an image too old for a database service (base v0.9.1 or newer). Update the box (kvbox vm update ${ref}), or deploy under another name (--name) to get a fresh box`);
|
|
5048
|
+
case ENV_MISSING:
|
|
5049
|
+
throw new KvboxError(`box ${ref} has not got the variable ${pg.env} although it is set (kvbox env ls --box ${ref}). Restart the box (kvbox stop ${ref} && kvbox start ${ref}) and deploy again`);
|
|
5050
|
+
case VOLUME_NOT_MOUNTED:
|
|
5051
|
+
throw new KvboxError(`volume ${pg.volume} is attached to box ${ref} but not mounted at /mnt/${pg.volume}: the box's image is too old for volumes (base v0.9.1 or newer, kvbox vm update ${ref}), or the box needs a restart. The database was not started, so nothing was written to the box's own disk`);
|
|
5052
|
+
case URL_FOREIGN:
|
|
5053
|
+
throw new KvboxError(`box ${ref}'s variable ${pg.env} holds something other than ${s.key}'s URL (another database?), so ${s.key} was not started. Name another variable for ${s.key} ("env" in ${CONFIG_FILE}), or remove it (kvbox env rm ${pg.env} --box ${ref}) and deploy again`);
|
|
5054
|
+
case URL_OTHER_PORT:
|
|
5055
|
+
throw new KvboxError(`box ${ref} still has ${s.key}'s URL for another port after a restart. Restart the box (kvbox stop ${ref} && kvbox start ${ref}) and deploy again`);
|
|
5056
|
+
case OTHER_DATA: {
|
|
5057
|
+
const other = result.output.trim().split("\n").at(-1);
|
|
5058
|
+
throw new KvboxError(
|
|
5059
|
+
`volume ${pg.volume} holds the database of service ${other}, not ${s.key}'s (a renamed service?), so ${s.key} was not started. To keep that data as ${s.key}'s: kvbox exec ${ref} -- 'sudo systemctl disable --now kvbox-${other}; sudo mv /mnt/${pg.volume}/${other} /mnt/${pg.volume}/${s.key}', then deploy again. Otherwise give ${s.key} another volume`
|
|
5060
|
+
);
|
|
5061
|
+
}
|
|
5062
|
+
case DB_NOT_READY: {
|
|
5063
|
+
const log = result.output.split(LOG_MARKER)[1]?.trim();
|
|
5064
|
+
throw new KvboxError(`${s.key}: ${pg.image} did not answer on port ${s.port} within ${DB_WAIT_SEC} s. Its log: kvbox exec ${ref} -- journalctl -u ${unit}${log ? `
|
|
5065
|
+
last lines:
|
|
5066
|
+
${log}` : ""}`);
|
|
5067
|
+
}
|
|
5068
|
+
default:
|
|
5069
|
+
throw new KvboxError(`starting ${s.key} in ${ref} failed (exit ${result.status}):
|
|
5070
|
+
${result.output.trim()}`);
|
|
5071
|
+
}
|
|
5072
|
+
}
|
|
5073
|
+
async function neverShipped(ep, services) {
|
|
5074
|
+
if (services.length === 0) return [];
|
|
5075
|
+
const checks = services.map((s) => `[ -e /srv/app/${s.key}/${s.static ? "dist" : "current"} ] || echo ${s.key}`);
|
|
5076
|
+
const result = await shipping.run(ep, checks.join("\n"));
|
|
5077
|
+
if (result.status !== 0) return [];
|
|
5078
|
+
const keys = new Set(result.output.split("\n").map((l) => l.trim()));
|
|
5079
|
+
return services.filter((s) => keys.has(s.key));
|
|
5080
|
+
}
|
|
5081
|
+
function pick(services, only) {
|
|
5082
|
+
if (only === void 0) return services;
|
|
5083
|
+
for (const key of only) {
|
|
5084
|
+
if (!services.some((s) => s.key === key)) throw new KvboxError(`--only ${key}: no such service in ${CONFIG_FILE} (it has ${services.map((s) => s.key).join(", ")})`);
|
|
5085
|
+
}
|
|
5086
|
+
return services.filter((s) => only.includes(s.key));
|
|
5087
|
+
}
|
|
5088
|
+
async function settle(d) {
|
|
5089
|
+
const { stack, opts, orgFlag, cloud } = d;
|
|
5090
|
+
if (opts.name !== void 0 && !BOX_NAME_RE.test(opts.name)) throw new KvboxError(`--name ${opts.name}: ${NAME_RULE}`);
|
|
5091
|
+
if (opts.sub !== void 0) assertSubdomain(opts.sub);
|
|
5092
|
+
const renamed = stack.name !== void 0 && (opts.name !== void 0 && opts.name !== stack.name || orgFlag !== void 0 && orgFlag !== stack.org);
|
|
5093
|
+
const savedSub = renamed ? void 0 : stack.subdomain;
|
|
5094
|
+
const defaults = { name: opts.name ?? stack.name ?? nameFromDir(basename(d.dir)), size: opts.size ?? stack.size ?? STACK_SIZE };
|
|
5095
|
+
const open = {
|
|
5096
|
+
name: opts.name === void 0 && stack.name === void 0,
|
|
5097
|
+
subdomain: cloud && opts.sub === void 0 && savedSub === void 0,
|
|
5098
|
+
size: opts.size === void 0 && stack.size === void 0,
|
|
5099
|
+
// Only for the databases this run deploys: one left out by --only is asked when it is deployed.
|
|
5100
|
+
volumes: Object.entries(stack.services).filter(([key, s]) => s.template === POSTGRES && s.volume === void 0 && (opts.only === void 0 || opts.only.includes(key))).map(([key]) => key)
|
|
5101
|
+
};
|
|
5102
|
+
const anyOpen = open.name || open.subdomain || open.size || open.volumes.length > 0;
|
|
5103
|
+
const accountVolumes = open.volumes.length > 0 ? new Set((await d.client.listVolumes()).map((v) => v.name)) : /* @__PURE__ */ new Set();
|
|
5104
|
+
if (anyOpen && !opts.yes && !interactive()) {
|
|
5105
|
+
throw new KvboxError(
|
|
5106
|
+
`kvbox deploy asks a few questions the first time, and this is not a terminal. Pass -y to take the defaults (box ${defaults.name}${cloud ? `, https://${opts.sub ?? savedSub ?? subdomainFor(defaults.name)}.kvbox.app` : ""}, size ${defaults.size}${defaultVolumes(defaults.name, stack.volumes ?? {}, accountVolumes, open.volumes).map(([key, v]) => `, a ${VOLUME_GIB} GB volume ${v} for ${key}`).join("")}), or answer with --name${cloud ? ", --sub" : ""} and --size, or in ${CONFIG_FILE}`
|
|
5107
|
+
);
|
|
5108
|
+
}
|
|
5109
|
+
const ask = anyOpen && !opts.yes;
|
|
5110
|
+
if (ask) info(`${color.bold("kvbox deploy")} ${color.dim(d.dir)} ${color.dim(`\xB7 ${Object.keys(stack.services).length} services`)}
|
|
5111
|
+
`);
|
|
5112
|
+
let name = defaults.name;
|
|
5113
|
+
if (open.name && ask) name = await text("Box name", { default: defaults.name, validate: (a) => BOX_NAME_RE.test(a) ? void 0 : NAME_RULE });
|
|
5114
|
+
let subdomain = opts.sub ?? savedSub ?? (cloud ? subdomainFor(name) : void 0);
|
|
5115
|
+
if (open.subdomain && ask) {
|
|
5116
|
+
subdomain = await text("Address", {
|
|
5117
|
+
default: subdomainFor(name),
|
|
5118
|
+
validate: (a) => {
|
|
5119
|
+
const problem = subdomainProblem(a);
|
|
5120
|
+
return problem ? `that name ${problem}` : void 0;
|
|
5121
|
+
}
|
|
5122
|
+
});
|
|
5123
|
+
info(` ${color.dim(`https://${subdomain}.kvbox.app`)}`);
|
|
5124
|
+
}
|
|
5125
|
+
let size = defaults.size;
|
|
5126
|
+
if (open.size && ask) {
|
|
5127
|
+
size = await select("Box size", SIZE_NAMES.map((s) => ({ value: s, label: s, hint: `${SIZES[s].vcpu} vCPU, ${SIZES[s].memMib / 1024} GB RAM, ${SIZES[s].diskGib} GB disk` })), SIZE_NAMES.indexOf(STACK_SIZE));
|
|
5128
|
+
}
|
|
5129
|
+
const volumes = { ...stack.volumes };
|
|
5130
|
+
const services = { ...stack.services };
|
|
5131
|
+
for (const key of open.volumes) {
|
|
5132
|
+
let volume = volumeNameFor(name, volumes, accountVolumes);
|
|
5133
|
+
let gib = `${VOLUME_GIB}GB`;
|
|
5134
|
+
if (ask) {
|
|
5135
|
+
volume = await text(`Volume for ${key}'s data`, { default: volume, validate: (a) => !VOLUME_NAME_RE.test(a) ? VOLUME_NAME_RULE : volumes[a] !== void 0 ? "already a volume of this stack" : accountVolumes.has(a) ? `already a volume of yours, another box's data; to reuse it on purpose, name it in ${CONFIG_FILE}` : void 0 });
|
|
5136
|
+
gib = await text("Volume size", { default: gib, validate: (a) => volumeGib(a) === void 0 ? "whole GB, like 10GB" : void 0 });
|
|
5137
|
+
}
|
|
5138
|
+
volumes[volume] = gib;
|
|
5139
|
+
services[key] = { ...services[key], volume };
|
|
5140
|
+
}
|
|
5141
|
+
if (ask) info(` ${color.dim(`saved to ${CONFIG_FILE}; next time kvbox deploy asks nothing`)}
|
|
5142
|
+
`);
|
|
5143
|
+
const org = orgFlag ?? stack.org;
|
|
5144
|
+
return {
|
|
5145
|
+
name,
|
|
5146
|
+
...org !== void 0 ? { org } : {},
|
|
5147
|
+
...subdomain !== void 0 ? { subdomain } : {},
|
|
5148
|
+
size,
|
|
5149
|
+
...Object.keys(volumes).length > 0 ? { volumes } : {},
|
|
5150
|
+
services
|
|
5151
|
+
};
|
|
5152
|
+
}
|
|
5153
|
+
var VOLUME_GIB = 10;
|
|
5154
|
+
function defaultVolumes(box, stackVolumes, account, keys) {
|
|
5155
|
+
const taken = { ...stackVolumes };
|
|
5156
|
+
return keys.map((key) => {
|
|
5157
|
+
const v = volumeNameFor(box, taken, account);
|
|
5158
|
+
taken[v] = `${VOLUME_GIB}GB`;
|
|
5159
|
+
return [key, v];
|
|
5160
|
+
});
|
|
5161
|
+
}
|
|
5162
|
+
function volumeNameFor(box, taken, account = /* @__PURE__ */ new Set()) {
|
|
5163
|
+
const free = (n) => taken[n] === void 0 && !account.has(n);
|
|
5164
|
+
const base = `${box.slice(0, 9).replace(/-+$/, "")}-db`;
|
|
5165
|
+
if (free(base)) return base;
|
|
5166
|
+
for (let i = 2; ; i++) {
|
|
5167
|
+
const n = `${box.slice(0, 8).replace(/-+$/, "")}-db${i}`;
|
|
5168
|
+
if (free(n)) return n;
|
|
5169
|
+
}
|
|
5170
|
+
}
|
|
5171
|
+
async function readPackageJson(dir) {
|
|
5172
|
+
try {
|
|
5173
|
+
return JSON.parse(await readFile7(join8(dir, "package.json"), "utf8"));
|
|
5174
|
+
} catch (err) {
|
|
5175
|
+
if (err.code === "ENOENT") return void 0;
|
|
5176
|
+
throw new KvboxError(`${join8(dir, "package.json")}: ${err.message}`);
|
|
5177
|
+
}
|
|
5178
|
+
}
|
|
4310
5179
|
|
|
4311
5180
|
// src/commands/deploy/index.ts
|
|
4312
|
-
var deployCommand = new
|
|
4313
|
-
const dir =
|
|
4314
|
-
const pkg = await
|
|
4315
|
-
const facts = { indexHtml: await
|
|
4316
|
-
const
|
|
5181
|
+
var deployCommand = new Command54("deploy").description("put the app in this directory (React, Next.js, a Node server, a Dockerfile or a static site) on a box with its own HTTPS address; redeploy by running it again").argument("[dir]", "the app's directory (default: the current one)").addOption(new Option5("-t, --template <template>", "what kind of app it is (detected from package.json and the directory when not given)").choices(TEMPLATE_IDS)).option("-n, --name <name>", "the box's name (default: the directory's name)").option("--sub <subdomain>", "its HTTPS name, https://<subdomain>.kvbox.app (default: the box's name)").addOption(new Option5("-s, --size <size>", "size of the box when it has to be made").choices(SIZE_NAMES)).option("--port <port>", "the box port of a Next.js app, Node server or container (default 3000; saved to kvbox.json)", parsePort).option("--only <service>", "with several services in kvbox.json: deploy this one only (repeatable)", (v, all) => [...all ?? [], v]).option("-y, --yes", "ask nothing: take the defaults for whatever the flags and kvbox.json leave open").option("--json", "print the result as JSON").option("--org <slug>", "deploy into this org's boxes (saved to kvbox.json)").action(async (dirArg, opts, cmd) => {
|
|
5182
|
+
const dir = resolve3(dirArg ?? ".");
|
|
5183
|
+
const pkg = await readPackageJson2(dir);
|
|
5184
|
+
const facts = { indexHtml: await exists2(resolve3(dir, "index.html")), dockerfile: await exists2(resolve3(dir, "Dockerfile")) };
|
|
5185
|
+
const file = await readDeployFile(dir);
|
|
5186
|
+
const saved = file?.kind === "single" ? file.config : void 0;
|
|
4317
5187
|
const globals = cmd.optsWithGlobals();
|
|
4318
5188
|
const orgFlag = orgOption(globals);
|
|
4319
|
-
const org = orgFlag ??
|
|
5189
|
+
const org = orgFlag ?? file?.config.org;
|
|
4320
5190
|
const client = await clientFor({ ...globals.local ? { local: true } : {}, ...org !== void 0 ? { org } : {} });
|
|
4321
5191
|
try {
|
|
4322
5192
|
const cloud = client.target.kind === "cloud";
|
|
4323
5193
|
if (!cloud && org !== void 0) throw new KvboxError("--org needs a control plane: kvbox login, or drop --org");
|
|
4324
|
-
|
|
5194
|
+
if (file?.kind === "stack") {
|
|
5195
|
+
await deployStack({ dir, dirArg, stack: file.config, opts, orgFlag, client, cloud });
|
|
5196
|
+
return;
|
|
5197
|
+
}
|
|
5198
|
+
if (opts.only !== void 0) throw new KvboxError(`--only picks a service of a ${CONFIG_FILE} with "services"; this one describes a single app`);
|
|
5199
|
+
const { config, template, fresh } = await settle2(dir, pkg, facts, saved, opts, orgFlag, cloud);
|
|
4325
5200
|
if (cloud && config.subdomain !== void 0) await refuseOtherAddress(client, config);
|
|
4326
5201
|
await writeConfig(dir, config);
|
|
4327
5202
|
if (fresh) info(` ${color.dim(`saved to ${CONFIG_FILE}; next time kvbox deploy asks nothing`)}
|
|
@@ -4346,24 +5221,7 @@ var deployCommand = new Command53("deploy").description("put the app in this dir
|
|
|
4346
5221
|
info("renewed your SSH certificate, trying again\u2026");
|
|
4347
5222
|
result = await spin(doing, shipIt);
|
|
4348
5223
|
}
|
|
4349
|
-
|
|
4350
|
-
${result.output.trim()}` : ""}`, SSH_FAILED3);
|
|
4351
|
-
if (result.status === IMAGE_TOO_OLD) {
|
|
4352
|
-
throw new KvboxError(
|
|
4353
|
-
`box ${ref} runs an image too old for the ${template.label} template (base v0.8.0 or newer). Update the box (kvbox vm update ${ref}) once its host has the new image, or deploy under another name (--name) to get a fresh box`
|
|
4354
|
-
);
|
|
4355
|
-
}
|
|
4356
|
-
if (result.status === APP_NOT_LISTENING) {
|
|
4357
|
-
const log = result.output.split(LOG_MARKER)[1]?.trim();
|
|
4358
|
-
const where = built.containerPort !== void 0 && built.containerPort !== port ? `the container's port ${built.containerPort} (box port ${port})` : `port ${port}`;
|
|
4359
|
-
throw new KvboxError(
|
|
4360
|
-
`the app did not answer on ${where} within ${START_WAIT_SEC} s: it crashed, or listens on another port. ${template.listens ?? `It must listen on process.env.PORT (${port})`}${template.customPort ? ", or say its port with --port" : ""}. Its log: kvbox exec ${ref} -- ${template.logs ?? "journalctl -u kvbox-app"}${log ? `
|
|
4361
|
-
last lines:
|
|
4362
|
-
${log}` : ""}`
|
|
4363
|
-
);
|
|
4364
|
-
}
|
|
4365
|
-
if (result.status !== 0) throw new KvboxError(`deploying to ${ref} failed (exit ${result.status}):
|
|
4366
|
-
${result.output.trim()}`);
|
|
5224
|
+
refuseFailedShip(result, { ref, template, port, built });
|
|
4367
5225
|
let url = `http://${box.ip}${port === 80 ? "" : `:${port}`}`;
|
|
4368
5226
|
if (cloud) {
|
|
4369
5227
|
const got = await address(client, box, ref, config, port);
|
|
@@ -4391,16 +5249,16 @@ function parsePort(v) {
|
|
|
4391
5249
|
if (portProblem(v)) throw new InvalidArgumentError2("expected a port, 1-65535");
|
|
4392
5250
|
return Number(v);
|
|
4393
5251
|
}
|
|
4394
|
-
var
|
|
4395
|
-
async function
|
|
5252
|
+
var exists2 = (path) => access5(path).then(() => true, () => false);
|
|
5253
|
+
async function readPackageJson2(dir) {
|
|
4396
5254
|
try {
|
|
4397
|
-
return JSON.parse(await
|
|
5255
|
+
return JSON.parse(await readFile8(resolve3(dir, "package.json"), "utf8"));
|
|
4398
5256
|
} catch (err) {
|
|
4399
5257
|
if (err.code === "ENOENT") return void 0;
|
|
4400
|
-
throw new KvboxError(`${
|
|
5258
|
+
throw new KvboxError(`${resolve3(dir, "package.json")}: ${err.message}`);
|
|
4401
5259
|
}
|
|
4402
5260
|
}
|
|
4403
|
-
async function
|
|
5261
|
+
async function settle2(dir, pkg, facts, saved, opts, orgFlag, cloud) {
|
|
4404
5262
|
const [detected, ...also] = detectTemplates(pkg, facts);
|
|
4405
5263
|
if (opts.name !== void 0 && !BOX_NAME_RE.test(opts.name)) throw new KvboxError(`--name ${opts.name}: ${NAME_RULE}`);
|
|
4406
5264
|
if (opts.sub !== void 0) assertSubdomain(opts.sub);
|
|
@@ -4408,7 +5266,7 @@ async function settle(dir, pkg, facts, saved, opts, orgFlag, cloud) {
|
|
|
4408
5266
|
const savedSub = renamed ? void 0 : saved?.subdomain;
|
|
4409
5267
|
const defaults = {
|
|
4410
5268
|
template: opts.template ?? saved?.template ?? detected?.id,
|
|
4411
|
-
name: opts.name ?? saved?.name ?? nameFromDir(
|
|
5269
|
+
name: opts.name ?? saved?.name ?? nameFromDir(basename2(dir)),
|
|
4412
5270
|
subdomain: opts.sub ?? savedSub,
|
|
4413
5271
|
size: opts.size ?? saved?.size
|
|
4414
5272
|
};
|
|
@@ -4475,60 +5333,17 @@ async function settle(dir, pkg, facts, saved, opts, orgFlag, cloud) {
|
|
|
4475
5333
|
};
|
|
4476
5334
|
return { config, template, fresh };
|
|
4477
5335
|
}
|
|
4478
|
-
var NAME_RULE = "1-12 chars, lowercase letters, digits and '-', starting with a letter or digit";
|
|
4479
|
-
async function findOrCreate(client, config) {
|
|
4480
|
-
const user = me(client);
|
|
4481
|
-
const slug = config.org ?? user;
|
|
4482
|
-
const named = (await client.listMachines()).filter((b) => b.name === config.name);
|
|
4483
|
-
let box = slug === void 0 ? named[0] : named.find((b) => slugOf(b.owner) === slug);
|
|
4484
|
-
let created = false;
|
|
4485
|
-
if (!box) {
|
|
4486
|
-
box = await spin(`booting a new box ${config.name}\u2026`, client.createMachine({ name: config.name, ...config.size !== void 0 ? { size: config.size } : {}, autoHibernateSec: DEPLOY_AUTO_HIBERNATE_SEC }));
|
|
4487
|
-
created = true;
|
|
4488
|
-
info(`${color.green("\u2713")} box ${color.bold(config.name)} is up: ${box.vcpu} vCPU, ${gb(box.memMib * 1024 ** 2)} RAM, ${gb(box.diskBytes)} disk`);
|
|
4489
|
-
}
|
|
4490
|
-
return { box, ref: displayName(box, user), created };
|
|
4491
|
-
}
|
|
4492
|
-
async function existingAddresses(client, config) {
|
|
4493
|
-
const slug = config.org ?? me(client);
|
|
4494
|
-
return (await client.listSubdomains()).filter((s) => s.box === config.name && s.owner === slug);
|
|
4495
|
-
}
|
|
4496
|
-
async function refuseOtherAddress(client, config) {
|
|
4497
|
-
const have = await existingAddresses(client, config);
|
|
4498
|
-
if (have.length < MAX_BOX_SUBDOMAINS || have.some((s) => s.subdomain === config.subdomain)) return;
|
|
4499
|
-
const ref = config.org !== void 0 ? `${config.org}/${config.name}` : config.name;
|
|
4500
|
-
throw new KvboxError(
|
|
4501
|
-
`box ${ref} already has ${MAX_BOX_SUBDOMAINS} addresses (${have.map((s) => s.subdomain).join(", ")}), none of them ${config.subdomain}. Deploy to one: kvbox deploy --sub <name>. Or free one: kvbox vm proxy release ${ref} --sub <name>`
|
|
4502
|
-
);
|
|
4503
|
-
}
|
|
4504
|
-
async function address(client, box, ref, config, port) {
|
|
4505
|
-
const subs = (await client.listSubdomains()).filter((s) => s.box === box.name && s.owner === slugOf(box.owner));
|
|
4506
|
-
const have = config.subdomain !== void 0 ? subs.find((s) => s.subdomain === config.subdomain) : subs[0];
|
|
4507
|
-
if (have) {
|
|
4508
|
-
if (have.port !== port) await client.setSubdomainPort(ref, { port }, have.subdomain);
|
|
4509
|
-
return { url: have.url, subdomain: have.subdomain };
|
|
4510
|
-
}
|
|
4511
|
-
const wanted = config.subdomain ?? subdomainFor(config.name);
|
|
4512
|
-
try {
|
|
4513
|
-
const sub = await spin(`claiming https://${wanted}.kvbox.app\u2026`, client.claimSubdomain(ref, { name: wanted, port }));
|
|
4514
|
-
return { url: sub.url, subdomain: sub.subdomain };
|
|
4515
|
-
} catch (err) {
|
|
4516
|
-
if (!(err instanceof KvboxError)) throw err;
|
|
4517
|
-
throw new KvboxError(`${err.message}
|
|
4518
|
-
the app is on box ${ref} but has no address yet: pick another with kvbox deploy --sub <name> (saved to ${CONFIG_FILE})`);
|
|
4519
|
-
}
|
|
4520
|
-
}
|
|
4521
5336
|
|
|
4522
5337
|
// src/commands/volume/index.ts
|
|
4523
|
-
import { Command as
|
|
5338
|
+
import { Command as Command60 } from "commander";
|
|
4524
5339
|
|
|
4525
5340
|
// src/commands/volume/attach.ts
|
|
4526
|
-
import { Command as
|
|
5341
|
+
import { Command as Command55 } from "commander";
|
|
4527
5342
|
function describeMount(machine, volume, box) {
|
|
4528
5343
|
const path = machine.volumes?.find((v) => volume === v.name || volume.endsWith(`/${v.name}`))?.mountPath ?? volumeMountPath(volume.slice(volume.lastIndexOf("/") + 1));
|
|
4529
5344
|
return machine.status === "running" ? ` the box was restarted; the volume is at ${path} inside it` : ` box ${box} is ${machine.status}; the volume is at ${path} once it runs`;
|
|
4530
5345
|
}
|
|
4531
|
-
var attachCommand = new
|
|
5346
|
+
var attachCommand = new Command55("attach").description("attach a volume to a box at /mnt/<volume> (a running box is restarted to take it)").argument("[volume]", "volume name (picked from a list when left out)").argument("[box]", "box name (picked from a list when left out)").option("--json", "print the box as JSON").action(async (volumeArg, boxArg, opts, cmd) => {
|
|
4532
5347
|
if (volumeArg === void 0 || boxArg === void 0) askOrUsage("give the volume and the box: kvbox volume attach <volume> <box>");
|
|
4533
5348
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
4534
5349
|
try {
|
|
@@ -4547,7 +5362,7 @@ var attachCommand = new Command54("attach").description("attach a volume to a bo
|
|
|
4547
5362
|
});
|
|
4548
5363
|
|
|
4549
5364
|
// src/commands/volume/create.ts
|
|
4550
|
-
import { Command as
|
|
5365
|
+
import { Command as Command56 } from "commander";
|
|
4551
5366
|
function parseGib2(text2) {
|
|
4552
5367
|
const mib = parseMib(text2);
|
|
4553
5368
|
if (mib === void 0 || mib % 1024 !== 0) throw new KvboxError(`--size ${text2}: write whole GB, like 50 or 50GB`);
|
|
@@ -4563,7 +5378,7 @@ function sizeProblem(answer) {
|
|
|
4563
5378
|
return err instanceof KvboxError ? err.message.replace(/^--size \S+: /, "") : String(err);
|
|
4564
5379
|
}
|
|
4565
5380
|
}
|
|
4566
|
-
var createCommand3 = new
|
|
5381
|
+
var createCommand3 = new Command56("create").alias("new").description("create a volume for a box: an empty disk of its own at /mnt/<name> inside it (a running box is restarted)").argument("[name]", "volume name (1-12 chars; the box mounts it at /mnt/<name>; asked for when left out)").option("--size <gb>", "size in GB, like 50 or 50GB (whole GB; it only occupies what is written)").option("--box <box>", "the box it is for: made on that box's host and attached to it (required on kvbox.sh; optional with --local)").option("--json", "print the volume as JSON").action(async (nameArg, opts, cmd) => {
|
|
4567
5382
|
const ask = interactive();
|
|
4568
5383
|
if (nameArg === void 0 || opts.size === void 0) askOrUsage("give the name and the size: kvbox volume create <name> --size <gb> --box <box>");
|
|
4569
5384
|
const name = nameArg ?? await text("Volume name", { validate: (a) => VOLUME_NAME_RE.test(a) ? void 0 : VOLUME_NAME_RULE });
|
|
@@ -4596,8 +5411,8 @@ var createCommand3 = new Command55("create").alias("new").description("create a
|
|
|
4596
5411
|
});
|
|
4597
5412
|
|
|
4598
5413
|
// src/commands/volume/detach.ts
|
|
4599
|
-
import { Command as
|
|
4600
|
-
var detachCommand = new
|
|
5414
|
+
import { Command as Command57 } from "commander";
|
|
5415
|
+
var detachCommand = new Command57("detach").description("detach a volume from a box; its data is kept (a running box is restarted)").argument("[volume]", "volume name (picked from a list when left out)").argument("[box]", "box name (the one the volume is on when left out)").option("--json", "print the box as JSON").action(async (volumeArg, boxArg, opts, cmd) => {
|
|
4601
5416
|
if (volumeArg === void 0) askOrUsage("give the volume: kvbox volume detach <volume> [box]");
|
|
4602
5417
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
4603
5418
|
try {
|
|
@@ -4622,8 +5437,8 @@ var detachCommand = new Command56("detach").description("detach a volume from a
|
|
|
4622
5437
|
});
|
|
4623
5438
|
|
|
4624
5439
|
// src/commands/volume/ls.ts
|
|
4625
|
-
import { Command as
|
|
4626
|
-
var lsCommand8 = new
|
|
5440
|
+
import { Command as Command58 } from "commander";
|
|
5441
|
+
var lsCommand8 = new Command58("ls").alias("list").description("list volumes: size, what they occupy, which box has them").option("-a, --all", "every volume on the platform (platform admins only)").option("--json", "print as JSON").action(async (opts, cmd) => {
|
|
4627
5442
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
4628
5443
|
try {
|
|
4629
5444
|
const cloud = client.target.kind === "cloud";
|
|
@@ -4654,8 +5469,8 @@ var lsCommand8 = new Command57("ls").alias("list").description("list volumes: si
|
|
|
4654
5469
|
});
|
|
4655
5470
|
|
|
4656
5471
|
// src/commands/volume/rm.ts
|
|
4657
|
-
import { Command as
|
|
4658
|
-
var rmCommand7 = new
|
|
5472
|
+
import { Command as Command59 } from "commander";
|
|
5473
|
+
var rmCommand7 = new Command59("rm").alias("remove").description("delete a volume and everything on it (detach it first)").argument("<name>", "volume name").option("-y, --yes", "do not ask for confirmation").action(async (name, opts, cmd) => {
|
|
4659
5474
|
if (!await confirm(`Delete volume ${name} and everything on it?`, opts.yes ?? false)) {
|
|
4660
5475
|
info("cancelled");
|
|
4661
5476
|
process.exitCode = 1;
|
|
@@ -4671,14 +5486,14 @@ var rmCommand7 = new Command58("rm").alias("remove").description("delete a volum
|
|
|
4671
5486
|
});
|
|
4672
5487
|
|
|
4673
5488
|
// src/commands/volume/index.ts
|
|
4674
|
-
var volumeCommand = new
|
|
5489
|
+
var volumeCommand = new Command60("volume").aliases(["volumes", "vol"]).description("disks of their own: create one, attach it to a box at /mnt/<name>, move it to another box later").addCommand(createCommand3).addCommand(lsCommand8).addCommand(attachCommand).addCommand(detachCommand).addCommand(rmCommand7);
|
|
4675
5490
|
for (const cmd of volumeCommand.commands) cmd.option("--org <slug>", "act in this org (- for your personal volumes)");
|
|
4676
5491
|
|
|
4677
5492
|
// src/commands/env/index.ts
|
|
4678
|
-
import { Command as
|
|
5493
|
+
import { Command as Command64 } from "commander";
|
|
4679
5494
|
|
|
4680
5495
|
// src/commands/env/ls.ts
|
|
4681
|
-
import { Command as
|
|
5496
|
+
import { Command as Command61 } from "commander";
|
|
4682
5497
|
|
|
4683
5498
|
// src/commands/env/shared.ts
|
|
4684
5499
|
function requireCloud4(client) {
|
|
@@ -4705,7 +5520,7 @@ function firstBootHint(box, name) {
|
|
|
4705
5520
|
}
|
|
4706
5521
|
|
|
4707
5522
|
// src/commands/env/ls.ts
|
|
4708
|
-
var lsCommand9 = new
|
|
5523
|
+
var lsCommand9 = new Command61("ls").alias("list").description("list the variables (a secret shows as (sealed))").option("--box <box>", "what this box gets: its own variables and the ones it inherits").option("--json", "print as JSON").action(async (opts, cmd) => {
|
|
4709
5524
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
4710
5525
|
try {
|
|
4711
5526
|
if (opts.box !== void 0) {
|
|
@@ -4744,8 +5559,8 @@ var lsCommand9 = new Command60("ls").alias("list").description("list the variabl
|
|
|
4744
5559
|
});
|
|
4745
5560
|
|
|
4746
5561
|
// src/commands/env/rm.ts
|
|
4747
|
-
import { Command as
|
|
4748
|
-
var rmCommand8 = new
|
|
5562
|
+
import { Command as Command62 } from "commander";
|
|
5563
|
+
var rmCommand8 = new Command62("rm").alias("remove").description("remove variables; boxes lose them when they next start").argument("<names...>", "variable names").option("-y, --yes", "do not ask for confirmation").option("--box <box>", "remove this box's own variables (yours, or the org's, of the same name come back)").option("--json", "print as JSON").action(async (names2, opts, cmd) => {
|
|
4749
5564
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
4750
5565
|
try {
|
|
4751
5566
|
const target = opts.box === void 0 ? void 0 : await findBox2(client, opts.box);
|
|
@@ -4760,14 +5575,14 @@ var rmCommand8 = new Command61("rm").alias("remove").description("remove variabl
|
|
|
4760
5575
|
for (const name of names2) {
|
|
4761
5576
|
try {
|
|
4762
5577
|
if (target !== void 0) {
|
|
4763
|
-
const
|
|
4764
|
-
changes.push(
|
|
4765
|
-
if (!opts.json) info(`${color.green("\u2713")} removed ${
|
|
5578
|
+
const c3 = await spin(`removing ${name}\u2026`, client.removeBoxEnv(target.ref, name));
|
|
5579
|
+
changes.push(c3);
|
|
5580
|
+
if (!opts.json) info(`${color.green("\u2713")} removed ${c3.name} from ${owner}: ${boxReach(c3.running, "loses")}`);
|
|
4766
5581
|
continue;
|
|
4767
5582
|
}
|
|
4768
|
-
const
|
|
4769
|
-
changes.push(
|
|
4770
|
-
if (!opts.json) info(`${color.green("\u2713")} removed ${
|
|
5583
|
+
const c2 = await spin(`removing ${name}\u2026`, client.removeEnv(name));
|
|
5584
|
+
changes.push(c2);
|
|
5585
|
+
if (!opts.json) info(`${color.green("\u2713")} removed ${c2.name} from ${owner}: ${reach(c2.boxes, "lose")}`);
|
|
4771
5586
|
} catch (err) {
|
|
4772
5587
|
failed.push({ name, err });
|
|
4773
5588
|
}
|
|
@@ -4782,8 +5597,8 @@ var rmCommand8 = new Command61("rm").alias("remove").description("remove variabl
|
|
|
4782
5597
|
});
|
|
4783
5598
|
|
|
4784
5599
|
// src/commands/env/set.ts
|
|
4785
|
-
import { Command as
|
|
4786
|
-
var setCommand2 = new
|
|
5600
|
+
import { Command as Command63 } from "commander";
|
|
5601
|
+
var setCommand2 = new Command63("set").description("add or change a variable; boxes get it when they next start").argument("[name]", "variable name, e.g. DATABASE_URL (asked for when left out)").argument("[value]", "its value (asked for when left out; hidden with --secret)").option("--secret", "write-only: the value is never shown again, by any command").option("--box <box>", "this box's own variable, over yours (or the org's) of the same name").option("--json", "print as JSON").action(async (nameArg, valueArg, opts, cmd) => {
|
|
4787
5602
|
const client = await clientFor(cmd.optsWithGlobals(), { autoStart: false });
|
|
4788
5603
|
try {
|
|
4789
5604
|
const owner = opts.box === void 0 ? requireCloud4(client) : void 0;
|
|
@@ -4820,14 +5635,14 @@ var setCommand2 = new Command62("set").description("add or change a variable; bo
|
|
|
4820
5635
|
});
|
|
4821
5636
|
|
|
4822
5637
|
// src/commands/env/index.ts
|
|
4823
|
-
var envCommand = new
|
|
5638
|
+
var envCommand = new Command64("env").description("environment variables every box of yours gets when it starts (secrets too)").addCommand(lsCommand9, { isDefault: true }).addCommand(setCommand2).addCommand(rmCommand8);
|
|
4824
5639
|
for (const cmd of envCommand.commands) cmd.option("--org <slug>", "the org's variables instead of yours");
|
|
4825
5640
|
|
|
4826
5641
|
// src/commands/domain/index.ts
|
|
4827
|
-
import { Command as
|
|
5642
|
+
import { Command as Command68 } from "commander";
|
|
4828
5643
|
|
|
4829
5644
|
// src/commands/domain/add.ts
|
|
4830
|
-
import { Command as
|
|
5645
|
+
import { Command as Command65 } from "commander";
|
|
4831
5646
|
|
|
4832
5647
|
// src/commands/domain/shared.ts
|
|
4833
5648
|
function requireCloud5(client) {
|
|
@@ -4847,7 +5662,7 @@ function hostIn(name, zone) {
|
|
|
4847
5662
|
}
|
|
4848
5663
|
|
|
4849
5664
|
// src/commands/domain/add.ts
|
|
4850
|
-
var addCommand3 = new
|
|
5665
|
+
var addCommand3 = new Command65("add").description("serve a box at a domain of your own, https://<domain>, with its certificate made for you").argument("<domain>", "a domain you control, like example.com or app.example.com").argument("<box>", "box name").option("--port <port>", "the box port the domain serves (default: the port of its kvbox.app address)").option("--json", "print the domain as JSON").action(async (domainArg, name, opts, cmd) => {
|
|
4851
5666
|
const domain = assertDomain(domainArg.trim().toLowerCase());
|
|
4852
5667
|
const port = opts.port === void 0 ? void 0 : parsePorts([opts.port])[0];
|
|
4853
5668
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
@@ -4883,8 +5698,8 @@ kvbox checks every minute; ${domain} is served at ${d.url} once its records are
|
|
|
4883
5698
|
});
|
|
4884
5699
|
|
|
4885
5700
|
// src/commands/domain/ls.ts
|
|
4886
|
-
import { Command as
|
|
4887
|
-
var lsCommand10 = new
|
|
5701
|
+
import { Command as Command66 } from "commander";
|
|
5702
|
+
var lsCommand10 = new Command66("ls").alias("list").description("list your custom domains and whether they are live").option("--json", "print as JSON").action(async (opts, cmd) => {
|
|
4888
5703
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
4889
5704
|
try {
|
|
4890
5705
|
requireCloud5(client);
|
|
@@ -4913,8 +5728,8 @@ var lsCommand10 = new Command65("ls").alias("list").description("list your custo
|
|
|
4913
5728
|
});
|
|
4914
5729
|
|
|
4915
5730
|
// src/commands/domain/rm.ts
|
|
4916
|
-
import { Command as
|
|
4917
|
-
var rmCommand9 = new
|
|
5731
|
+
import { Command as Command67 } from "commander";
|
|
5732
|
+
var rmCommand9 = new Command67("rm").alias("remove").description("stop serving a box at a custom domain").argument("<domain>", "the domain").option("-y, --yes", "do not ask for confirmation").action(async (domainArg, opts, cmd) => {
|
|
4918
5733
|
const domain = domainArg.trim().toLowerCase();
|
|
4919
5734
|
const client = await clientFor(cmd.optsWithGlobals());
|
|
4920
5735
|
try {
|
|
@@ -4935,15 +5750,15 @@ var rmCommand9 = new Command66("rm").alias("remove").description("stop serving a
|
|
|
4935
5750
|
});
|
|
4936
5751
|
|
|
4937
5752
|
// src/commands/domain/index.ts
|
|
4938
|
-
var domainCommand = new
|
|
5753
|
+
var domainCommand = new Command68("domain").alias("domains").description("serve a box at a domain of your own").addCommand(addCommand3).addCommand(lsCommand10).addCommand(rmCommand9);
|
|
4939
5754
|
for (const cmd of domainCommand.commands) cmd.option("--org <slug>", "act in this org (- for your personal boxes)");
|
|
4940
5755
|
|
|
4941
5756
|
// src/commands/update.ts
|
|
4942
5757
|
import { spawn as spawn6 } from "child_process";
|
|
4943
5758
|
import { mkdtempSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
|
|
4944
5759
|
import { tmpdir } from "os";
|
|
4945
|
-
import { join as
|
|
4946
|
-
import { Command as
|
|
5760
|
+
import { join as join9 } from "path";
|
|
5761
|
+
import { Command as Command69 } from "commander";
|
|
4947
5762
|
|
|
4948
5763
|
// src/update.ts
|
|
4949
5764
|
import { mkdirSync, readFileSync as readFileSync3, writeFileSync } from "fs";
|
|
@@ -5055,26 +5870,26 @@ async function download(url) {
|
|
|
5055
5870
|
if (!body.startsWith("#!")) throw new KvboxError(`${url} did not return a shell script`);
|
|
5056
5871
|
return body;
|
|
5057
5872
|
}
|
|
5058
|
-
function
|
|
5059
|
-
return new Promise((
|
|
5873
|
+
function run2(cmd, args) {
|
|
5874
|
+
return new Promise((resolve4, reject) => {
|
|
5060
5875
|
const child = spawn6(cmd, args, { stdio: "inherit" });
|
|
5061
5876
|
child.on("error", (err) => reject(new KvboxError(`could not run ${cmd}: ${err.message}`)));
|
|
5062
|
-
child.on("exit", (code, signal) =>
|
|
5877
|
+
child.on("exit", (code, signal) => resolve4(code ?? (signal ? 1 : 0)));
|
|
5063
5878
|
});
|
|
5064
5879
|
}
|
|
5065
|
-
var selfUpdateCommand = new
|
|
5880
|
+
var selfUpdateCommand = new Command69("update").description("update kvbox to the latest version (reruns the installer from kvbox.sh, agent skill included)").action(async () => {
|
|
5066
5881
|
suppressUpdateNotice();
|
|
5067
5882
|
const inst = installerFor(process.platform, process.env["KVBOX_INSTALL_URL"] || INSTALL_BASE);
|
|
5068
5883
|
let code;
|
|
5069
5884
|
if (process.platform === "win32") {
|
|
5070
|
-
code = await
|
|
5885
|
+
code = await run2(inst.cmd, inst.args);
|
|
5071
5886
|
} else {
|
|
5072
5887
|
const script = await download(inst.url);
|
|
5073
|
-
const dir = mkdtempSync(
|
|
5074
|
-
const file =
|
|
5888
|
+
const dir = mkdtempSync(join9(tmpdir(), "kvbox-update-"));
|
|
5889
|
+
const file = join9(dir, "install.sh");
|
|
5075
5890
|
try {
|
|
5076
5891
|
writeFileSync2(file, script, { mode: 448 });
|
|
5077
|
-
code = await
|
|
5892
|
+
code = await run2(inst.cmd, inst.args.map((a) => a === "{script}" ? file : a));
|
|
5078
5893
|
} finally {
|
|
5079
5894
|
rmSync(dir, { recursive: true, force: true });
|
|
5080
5895
|
}
|
|
@@ -5082,9 +5897,108 @@ var selfUpdateCommand = new Command68("update").description("update kvbox to the
|
|
|
5082
5897
|
if (code !== 0) throw new KvboxError(`the installer failed (exit ${code})`, code);
|
|
5083
5898
|
});
|
|
5084
5899
|
|
|
5900
|
+
// src/help.ts
|
|
5901
|
+
import pc2 from "picocolors";
|
|
5902
|
+
var c = pc2.createColors(true);
|
|
5903
|
+
var TAGLINE = "microVMs with Docker-like ergonomics";
|
|
5904
|
+
var LOGO = [
|
|
5905
|
+
"\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557",
|
|
5906
|
+
"\u2588\u2588\u2551 \u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D",
|
|
5907
|
+
"\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2554\u255D",
|
|
5908
|
+
"\u2588\u2588\u2554\u2550\u2588\u2588\u2557 \u255A\u2588\u2588\u2557 \u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2588\u2588\u2557",
|
|
5909
|
+
"\u2588\u2588\u2551 \u2588\u2588\u2557 \u255A\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2554\u255D \u2588\u2588\u2557",
|
|
5910
|
+
"\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D"
|
|
5911
|
+
];
|
|
5912
|
+
var LOGO_WIDTH = 42;
|
|
5913
|
+
var HELP_GROUPS = [
|
|
5914
|
+
{
|
|
5915
|
+
title: "Everyday",
|
|
5916
|
+
commands: [
|
|
5917
|
+
["new", "boot a new box from an image or a snapshot"],
|
|
5918
|
+
["ls", "list your boxes with status and address"],
|
|
5919
|
+
["get", "show one box in full"],
|
|
5920
|
+
["connect", "open a shell in a box, or run a command there (short: cn)"],
|
|
5921
|
+
["exec", "run a command in a box and exit with its status"],
|
|
5922
|
+
["claim", "give a box an HTTPS address, https://<name>.kvbox.app"],
|
|
5923
|
+
["deploy", "put the app in this directory on a box with its own HTTPS address"],
|
|
5924
|
+
["rm", "destroy a box and its disk"]
|
|
5925
|
+
]
|
|
5926
|
+
},
|
|
5927
|
+
{
|
|
5928
|
+
title: "Stop and continue",
|
|
5929
|
+
commands: [
|
|
5930
|
+
["stop", "shut a box down, keeping its disk"],
|
|
5931
|
+
["start", "boot a stopped box again"],
|
|
5932
|
+
["pause", "freeze a box in place, memory kept"],
|
|
5933
|
+
["resume", "continue a paused box"],
|
|
5934
|
+
["hibernate", "save a box's memory to disk and free its RAM"],
|
|
5935
|
+
["wake", "continue a hibernated box where it left off"]
|
|
5936
|
+
]
|
|
5937
|
+
},
|
|
5938
|
+
{
|
|
5939
|
+
title: "Manage",
|
|
5940
|
+
commands: [
|
|
5941
|
+
["vm", "everything about boxes: fork, rescale, ports, hooks, backups"],
|
|
5942
|
+
["snapshots", "freeze a running box into a snapshot, start new boxes from it"],
|
|
5943
|
+
["volume", "disks of their own that move between boxes"],
|
|
5944
|
+
["env", "environment variables and secrets every box of yours gets"],
|
|
5945
|
+
["domain", "serve a box at a domain of your own"]
|
|
5946
|
+
]
|
|
5947
|
+
},
|
|
5948
|
+
{
|
|
5949
|
+
title: "Account",
|
|
5950
|
+
commands: [
|
|
5951
|
+
["login", "log in to the kvbox cloud or your own control plane"],
|
|
5952
|
+
["logout", "log out; commands target this machine again"],
|
|
5953
|
+
["whoami", "show the account and control plane in use"],
|
|
5954
|
+
["org", "shared slugs that own boxes, with owners, admins and members"],
|
|
5955
|
+
["usage", "what your boxes and volumes used, and what it cost"],
|
|
5956
|
+
["credit", "the prepaid credit left on your account and orgs"],
|
|
5957
|
+
["redeem", "redeem a promo code for credit"],
|
|
5958
|
+
["update", "update kvbox to the latest version"]
|
|
5959
|
+
]
|
|
5960
|
+
}
|
|
5961
|
+
];
|
|
5962
|
+
function banner(stream) {
|
|
5963
|
+
if (stream.isTTY !== true || (stream.columns || 80) < LOGO_WIDTH + 2) return `kvbox ${VERSION} \xB7 ${TAGLINE}
|
|
5964
|
+
`;
|
|
5965
|
+
return ["", ...LOGO.map((line) => c.blue(line)), c.dim(` v${VERSION} \xB7 ${TAGLINE}`), ""].join("\n");
|
|
5966
|
+
}
|
|
5967
|
+
function formatRootHelp(cmd, helper) {
|
|
5968
|
+
const visible = new Map(helper.visibleCommands(cmd).map((sub) => [sub.name(), sub]));
|
|
5969
|
+
const groups = HELP_GROUPS.map((g) => ({
|
|
5970
|
+
title: g.title,
|
|
5971
|
+
items: g.commands.filter(([name]) => visible.delete(name))
|
|
5972
|
+
}));
|
|
5973
|
+
const help = visible.get("help");
|
|
5974
|
+
visible.delete("help");
|
|
5975
|
+
const other = [...visible.values()].map((sub) => [sub.name(), helper.subcommandDescription(sub)]);
|
|
5976
|
+
if (other.length > 0) groups.push({ title: "Other", items: other });
|
|
5977
|
+
if (help) groups.at(-1).items.push(["help", "show the help of a command"]);
|
|
5978
|
+
const options = helper.visibleOptions(cmd).map((o) => [helper.optionTerm(o), helper.optionDescription(o)]);
|
|
5979
|
+
const termWidth = Math.max(...groups.flatMap((g) => g.items).map(([term]) => term.length), ...options.map(([term]) => term.length));
|
|
5980
|
+
const section = (title, items) => [
|
|
5981
|
+
c.bold(title),
|
|
5982
|
+
...items.map(([term, text2]) => helper.formatItem(c.cyan(term), termWidth, text2, helper)),
|
|
5983
|
+
""
|
|
5984
|
+
];
|
|
5985
|
+
return [
|
|
5986
|
+
`${c.bold("Usage:")} ${helper.commandUsage(cmd)}`,
|
|
5987
|
+
"",
|
|
5988
|
+
...groups.filter((g) => g.items.length > 0).flatMap((g) => section(g.title, g.items)),
|
|
5989
|
+
...section("Options", options),
|
|
5990
|
+
c.dim("kvbox <command> --help shows one command in full. Docs: https://kvbox.sh/docs"),
|
|
5991
|
+
""
|
|
5992
|
+
].join("\n");
|
|
5993
|
+
}
|
|
5994
|
+
function installRootHelp(program) {
|
|
5995
|
+
program.configureHelp({ formatHelp: formatRootHelp });
|
|
5996
|
+
program.addHelpText("before", (ctx) => banner(ctx.error ? process.stderr : process.stdout));
|
|
5997
|
+
}
|
|
5998
|
+
|
|
5085
5999
|
// src/program.ts
|
|
5086
6000
|
function buildProgram() {
|
|
5087
|
-
const program = new
|
|
6001
|
+
const program = new Command70("kvbox").description("self-hosted Firecracker microVMs with Docker-like ergonomics").version(VERSION, "-v, --version").option("--local", "use this machine's kvbox-server over its socket, ignoring kvbox login").option("--org <slug>", "the org: where kvbox new creates, and which box a name means when it is not one of yours; before the command here, or after it").showHelpAfterError().enablePositionalOptions();
|
|
5088
6002
|
program.addCommand(vmCommand);
|
|
5089
6003
|
program.addCommand(snapshotsCommand);
|
|
5090
6004
|
program.addCommand(volumeCommand);
|
|
@@ -5096,9 +6010,11 @@ function buildProgram() {
|
|
|
5096
6010
|
program.addCommand(orgCommand);
|
|
5097
6011
|
program.addCommand(usageCommand2);
|
|
5098
6012
|
program.addCommand(creditCommand);
|
|
6013
|
+
program.addCommand(redeemCommand);
|
|
5099
6014
|
program.addCommand(deployCommand);
|
|
5100
6015
|
program.addCommand(selfUpdateCommand);
|
|
5101
6016
|
for (const cmd of vmAliases) program.addCommand(cmd);
|
|
6017
|
+
installRootHelp(program);
|
|
5102
6018
|
return program;
|
|
5103
6019
|
}
|
|
5104
6020
|
|