@kvbox/cli 0.5.35 → 0.5.36

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 CHANGED
@@ -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.35" : void 0);
167
+ var VERSION = versionOf(import.meta.url, true ? "0.5.36" : void 0);
168
168
 
169
169
  // src/commands/vm/index.ts
170
170
  import { Command as Command33 } from "commander";
@@ -1802,6 +1802,10 @@ var newCommand = new Command("new").description("boot a new box from an image (t
1802
1802
  info(` from another box once linked: kvbox vm link <box> ${displayName(box, user)} --port <port>`);
1803
1803
  info(` its variables: kvbox env ls --box ${displayName(box, user)}`);
1804
1804
  }
1805
+ if (box.image === "gh-runner") {
1806
+ info(` wake it on queued jobs: kvbox vm hook create ${displayName(box, user)}`);
1807
+ info(` then add it on GitHub: Settings \u2192 Webhooks \u2192 Add webhook (the hook's URL and secret, content type application/json, event Workflow jobs)`);
1808
+ }
1805
1809
  } finally {
1806
1810
  await client.close();
1807
1811
  }
@@ -2654,28 +2658,139 @@ var rmCommand3 = new Command24("rm").description("destroy a box (its disk is del
2654
2658
 
2655
2659
  // src/commands/vm/set.ts
2656
2660
  import { Command as Command25 } from "commander";
2657
- var setCommand = new Command25("set").description("change a box's settings, e.g. --auto-hibernate 30m (off: never), --idle-check /home/kvbox/idle.sh").argument("<name>", "box name").option("--auto-hibernate <duration>", "hibernate the box after this long without network traffic (30m, 4h, 1d; off: never)").option("--idle-check <script>", "a script in the box that exits 0 when it is idle, asked instead of network traffic (off: none)").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
2658
- if (opts.autoHibernate === void 0 && opts.idleCheck === void 0) throw new KvboxError("nothing to change: give --auto-hibernate or --idle-check");
2661
+
2662
+ // src/swap.ts
2663
+ import { spawn as spawn3 } from "child_process";
2664
+ var SWAP_FILE = "/rom/overlay/swapfile";
2665
+ var SWAP_KEEP_FREE_MIB = 1024;
2666
+ var SWAP_MIN_MIB = 256;
2667
+ function parseSwap(text2) {
2668
+ const t = text2.trim().toLowerCase();
2669
+ if (t === "off" || t === "none" || t === "0") return 0;
2670
+ const mib = parseMib(t);
2671
+ if (mib === void 0 || mib < SWAP_MIN_MIB) throw new KvboxError(`--swap ${text2}: give a size of at least ${SWAP_MIN_MIB}M (2G, 512M), or off`);
2672
+ return mib;
2673
+ }
2674
+ function swapScript() {
2675
+ return [
2676
+ "set -eu",
2677
+ 'mib="$1"',
2678
+ "disk=/rom/overlay",
2679
+ `f=${SWAP_FILE}`,
2680
+ "zs=/sys/module/zswap/parameters/enabled",
2681
+ 'mountpoint -q "$disk" || { echo "this box has no separate box disk at $disk (an image older than the overlay one)" >&2; exit 3; }',
2682
+ 'active() { grep -q "^$f " /proc/swaps; }',
2683
+ 'have=0; [ -f "$f" ] && have=$(( $(stat -c %s "$f") / 1048576 ))',
2684
+ 'if [ "$mib" -gt 0 ] && ! { [ "$have" -eq "$mib" ] && active; }; then',
2685
+ ' free=$(( $(stat -f -c %a "$disk") * $(stat -f -c %S "$disk") / 1048576 + have ))',
2686
+ ` if [ $(( free - mib )) -lt ${SWAP_KEEP_FREE_MIB} ]; then echo "the box disk has $free MiB free; $mib MiB of swap would leave less than ${SWAP_KEEP_FREE_MIB} MiB" >&2; exit 5; fi`,
2687
+ "fi",
2688
+ 'if [ "$mib" -eq 0 ] || ! { [ "$have" -eq "$mib" ] && active; }; then',
2689
+ ' if active; then swapoff "$f" || { echo "swapoff failed: what is in swap does not fit back in RAM; stop something first" >&2; exit 4; }; fi',
2690
+ ' rm -f "$f"',
2691
+ ' if [ "$mib" -gt 0 ]; then',
2692
+ ' fallocate -l "${mib}M" "$f"',
2693
+ ' chmod 600 "$f"',
2694
+ ' mkswap "$f" >/dev/null',
2695
+ ' swapon "$f"',
2696
+ " fi",
2697
+ "fi",
2698
+ "touch /etc/fstab",
2699
+ 'sed -i "\\#^$f #d" /etc/fstab',
2700
+ 'if [ "$mib" -gt 0 ]; then',
2701
+ ' echo "$f none swap sw 0 0" >> /etc/fstab',
2702
+ " printf 'vm.swappiness = 10\\n' > /etc/sysctl.d/90-kvbox-swap.conf",
2703
+ " sysctl -q vm.swappiness=10",
2704
+ " printf 'w /sys/module/zswap/parameters/enabled - - - - 1\\n' > /etc/tmpfiles.d/kvbox-swap.conf",
2705
+ ' echo 1 > "$zs" 2>/dev/null || true',
2706
+ "else",
2707
+ " rm -f /etc/sysctl.d/90-kvbox-swap.conf /etc/tmpfiles.d/kvbox-swap.conf",
2708
+ " sysctl -q vm.swappiness=60",
2709
+ ' echo 0 > "$zs" 2>/dev/null || true',
2710
+ "fi",
2711
+ 'line=$(grep "^$f " /proc/swaps || true)',
2712
+ "set -- $line",
2713
+ 'echo "kvbox-swap ${3:-0} ${4:-0} $(cat "$zs" 2>/dev/null || echo N)"'
2714
+ ].join("\n");
2715
+ }
2716
+ function swapCommand(mib) {
2717
+ return `sudo -n sh -c ${shellQuote(swapScript())} kvbox-swap ${mib}`;
2718
+ }
2719
+ function parseSwapReport(output) {
2720
+ const m = /^kvbox-swap (\d+) (\d+) (\S+)\s*$/m.exec(output);
2721
+ if (!m) return void 0;
2722
+ return { sizeMib: Math.round(Number(m[1]) / 1024), usedMib: Math.round(Number(m[2]) / 1024), zswap: m[3] === "Y" || m[3] === "1" };
2723
+ }
2724
+ function runSwap(ep, mib) {
2725
+ const child = spawn3("ssh", ["-n", ...sshArgs(ep), swapCommand(mib)], { stdio: ["ignore", "pipe", "pipe"] });
2726
+ const chunks = [];
2727
+ child.stdout.on("data", (c) => chunks.push(c));
2728
+ child.stderr.on("data", (c) => chunks.push(c));
2729
+ return new Promise((resolve3, reject) => {
2730
+ child.once("error", (err) => reject(new KvboxError(`could not run ssh: ${err.message}`)));
2731
+ child.once("close", (code) => resolve3({ status: code ?? 1, output: Buffer.concat(chunks).toString("utf8") }));
2732
+ });
2733
+ }
2734
+
2735
+ // src/commands/vm/set.ts
2736
+ var setCommand = new Command25("set").description("change a box's settings, e.g. --auto-hibernate 30m (off: never), --idle-check /home/kvbox/idle.sh, --swap 2G").argument("<name>", "box name").option("--auto-hibernate <duration>", "hibernate the box after this long without network traffic (30m, 4h, 1d; off: never)").option("--idle-check <script>", "a script in the box that exits 0 when it is idle, asked instead of network traffic (off: none)").option("--swap <size>", "a swap file on the box's disk for memory spikes such as a build (2G, 512M; off: none)").option("--json", "print the box as JSON").action(async (name, opts, cmd) => {
2737
+ if (opts.autoHibernate === void 0 && opts.idleCheck === void 0 && opts.swap === void 0) {
2738
+ throw new KvboxError("nothing to change: give --auto-hibernate, --idle-check or --swap");
2739
+ }
2659
2740
  const autoHibernateSec = opts.autoHibernate === void 0 ? void 0 : parseIdleTimeout(opts.autoHibernate);
2660
2741
  const idleCheck = opts.idleCheck === void 0 ? void 0 : parseIdleCheck(opts.idleCheck);
2742
+ const swapMib = opts.swap === void 0 ? void 0 : parseSwap(opts.swap);
2743
+ const hostSettings = autoHibernateSec !== void 0 || idleCheck !== void 0;
2661
2744
  const client = await clientFor(cmd.optsWithGlobals());
2662
2745
  try {
2663
2746
  const found = pickRef(await boxesFor(client, name), name, me(client));
2664
2747
  if (!found) throw new KvboxError(`box ${name}: not found (kvbox ls)`);
2665
- const box = await spin(`updating ${name}\u2026`, client.setMachine(displayName(found, me(client)), { ...autoHibernateSec !== void 0 ? { autoHibernateSec } : {}, ...idleCheck !== void 0 ? { idleCheck } : {} }));
2666
- if (!idleCheckKept(idleCheck, box)) {
2667
- throw new KvboxError(`box ${name}: its host runs a kvbox-server too old for --idle-check; it needs updating first${autoHibernateSec !== void 0 ? " (--auto-hibernate was applied)" : ""}`);
2748
+ if (swapMib !== void 0 && found.status === "stopped") throw new KvboxError(`box ${name} is stopped; --swap is set up inside the box (kvbox start ${name})`);
2749
+ let box = found;
2750
+ if (hostSettings) {
2751
+ box = await spin(`updating ${name}\u2026`, client.setMachine(displayName(found, me(client)), { ...autoHibernateSec !== void 0 ? { autoHibernateSec } : {}, ...idleCheck !== void 0 ? { idleCheck } : {} }));
2752
+ if (!idleCheckKept(idleCheck, box)) {
2753
+ throw new KvboxError(`box ${name}: its host runs a kvbox-server too old for --idle-check; it needs updating first${autoHibernateSec !== void 0 ? " (--auto-hibernate was applied)" : ""}`);
2754
+ }
2668
2755
  }
2756
+ const swap = swapMib === void 0 ? void 0 : await setSwap(client, box, name, swapMib, cmd);
2669
2757
  if (opts.json) {
2670
- json(box);
2758
+ json(swap === void 0 ? box : { ...box, swap });
2671
2759
  return;
2672
2760
  }
2673
- info(`${color.green("\u2713")} box ${color.bold(name)}: ${autoHibernateText(box.autoHibernateSec, box.idleCheck)}`);
2761
+ if (hostSettings) info(`${color.green("\u2713")} box ${color.bold(name)}: ${autoHibernateText(box.autoHibernateSec, box.idleCheck)}`);
2674
2762
  if (idleCheck && !box.autoHibernateSec) info(color.dim(` the idle check is used once auto-hibernate is on: kvbox vm set ${name} --auto-hibernate 10m`));
2763
+ if (swap) info(`${color.green("\u2713")} box ${color.bold(name)}: ${swapText(swap)}`);
2675
2764
  } finally {
2676
2765
  await client.close();
2677
2766
  }
2678
2767
  });
2768
+ async function setSwap(client, found, name, mib, cmd) {
2769
+ const cert = await ensureCert(client, void 0, void 0, { owner: found.owner });
2770
+ const wasRunning = found.status === "running";
2771
+ const box = wasRunning ? found : await wakeUp(client, found, displayName(found, me(client)));
2772
+ const ep = sshEndpoint(box, client.target);
2773
+ if (!wasRunning) await spin(`waiting for ${name} to accept SSH\u2026`, waitForSsh(ep));
2774
+ const what = mib === 0 ? `removing ${name}'s swap\u2026` : `setting up ${mib >= 1024 ? `${mib / 1024}G` : `${mib}M`} of swap in ${name}\u2026`;
2775
+ let result = await spin(what, runSwap(ep, mib));
2776
+ if (result.status === 255) {
2777
+ const again = await clientFor(cmd.optsWithGlobals());
2778
+ if (await renewAfterRefusal(again, cert, found.owner).finally(() => again.close())) result = await spin(what, runSwap(ep, mib));
2779
+ }
2780
+ const report = parseSwapReport(result.output);
2781
+ if (result.status !== 0 || !report) {
2782
+ const said = result.output.split("\n").filter((l) => l.trim() !== "" && !l.startsWith("kvbox-swap ")).join("\n ");
2783
+ if (result.status === 255) throw new KvboxError(`box ${name}: could not reach it over SSH${said ? `
2784
+ ${said}` : ""}`, 255);
2785
+ throw new KvboxError(`box ${name}: --swap failed${said ? `: ${said}` : ""}`);
2786
+ }
2787
+ return report;
2788
+ }
2789
+ function swapText(s) {
2790
+ if (s.sizeMib === 0) return "no swap";
2791
+ const size = s.sizeMib % 1024 === 0 ? `${s.sizeMib / 1024} GB` : `${s.sizeMib} MB`;
2792
+ return `${size} swap (${s.usedMib} MB used, zswap ${s.zswap ? "on" : "off"})`;
2793
+ }
2679
2794
  function idleCheckKept(asked, box) {
2680
2795
  return asked === void 0 || (box.idleCheck ?? "") === asked;
2681
2796
  }
@@ -2891,7 +3006,7 @@ import { Command as Command41 } from "commander";
2891
3006
  import { Command as Command34 } from "commander";
2892
3007
 
2893
3008
  // src/commands/server/daemon.ts
2894
- import { spawn as spawn3 } from "child_process";
3009
+ import { spawn as spawn4 } from "child_process";
2895
3010
  import { readFile as readFile4 } from "fs/promises";
2896
3011
  import { setTimeout as sleep2 } from "timers/promises";
2897
3012
  async function runningPid(p = paths()) {
@@ -2926,7 +3041,7 @@ async function restartLocalServer(p = paths()) {
2926
3041
  }
2927
3042
  function runKvboxServer(args) {
2928
3043
  return new Promise((resolve3, reject) => {
2929
- const child = spawn3("kvbox-server", args, { stdio: ["ignore", "pipe", "pipe"] });
3044
+ const child = spawn4("kvbox-server", args, { stdio: ["ignore", "pipe", "pipe"] });
2930
3045
  let out = "";
2931
3046
  let err = "";
2932
3047
  child.stdout.on("data", (chunk) => out += chunk.toString());
@@ -3780,7 +3895,7 @@ var nodeTemplate = {
3780
3895
  };
3781
3896
 
3782
3897
  // src/commands/deploy/templates/react.ts
3783
- import { spawn as spawn4 } from "child_process";
3898
+ import { spawn as spawn5 } from "child_process";
3784
3899
  import { access as access2 } from "fs/promises";
3785
3900
  import { join as join3 } from "path";
3786
3901
  var OUT_DIRS = ["dist", "build"];
@@ -3788,7 +3903,7 @@ async function runBuild(dir, pm) {
3788
3903
  const args = runScript(pm, "build");
3789
3904
  info(`${color.dim("$")} ${pm} ${args.join(" ")}`);
3790
3905
  const status2 = await new Promise((resolve3, reject) => {
3791
- const child = spawn4(pm, args, { cwd: dir, stdio: ["ignore", process.stderr, process.stderr], shell: process.platform === "win32" });
3906
+ const child = spawn5(pm, args, { cwd: dir, stdio: ["ignore", process.stderr, process.stderr], shell: process.platform === "win32" });
3792
3907
  child.once("error", (err) => reject(new KvboxError(`could not run ${pm}: ${err.message}`)));
3793
3908
  child.once("close", (code) => resolve3(code ?? 1));
3794
3909
  });
@@ -3910,7 +4025,7 @@ function subdomainFor(name) {
3910
4025
  }
3911
4026
 
3912
4027
  // src/commands/deploy/ship.ts
3913
- import { spawn as spawn5 } from "child_process";
4028
+ import { spawn as spawn6 } from "child_process";
3914
4029
  import { readdir, stat as stat2 } from "fs/promises";
3915
4030
  import { join as join5 } from "path";
3916
4031
  var IMAGE_TOO_OLD = 3;
@@ -3932,8 +4047,8 @@ async function measure(dir, exclude = []) {
3932
4047
  return total;
3933
4048
  }
3934
4049
  async function ship(ep, dir, remote, exclude = []) {
3935
- const tar = spawn5("tar", ["-cf", "-", ...exclude.map((e) => `--exclude=${e}`), "-C", dir, "."], { stdio: ["ignore", "pipe", "pipe"] });
3936
- const ssh = spawn5("ssh", [...sshArgs(ep), remote], { stdio: ["pipe", "pipe", "pipe"] });
4050
+ const tar = spawn6("tar", ["-cf", "-", ...exclude.map((e) => `--exclude=${e}`), "-C", dir, "."], { stdio: ["ignore", "pipe", "pipe"] });
4051
+ const ssh = spawn6("ssh", [...sshArgs(ep), remote], { stdio: ["pipe", "pipe", "pipe"] });
3937
4052
  tar.stdout.pipe(ssh.stdin);
3938
4053
  const chunks = [];
3939
4054
  ssh.stdout.on("data", (c) => chunks.push(c));