From 2d5c8d6c6d1f8e48bc666fe9f62a43b165818705 Mon Sep 17 00:00:00 2001 From: Joseph Woolley Date: Sat, 5 Dec 2026 09:32:10 -0500 Subject: [PATCH] Put Use the extra space back on every machine. Storage on this server and on a joined computer offers it when that computer's system drive has room to grow. It grows the last partition, its encryption, and the filesystem. Co-Authored-By: Grok 4.7 --- README.md | 5 +- connector/agent.py | 27 ++++- connector/helper.py | 205 +++++++++++++++++++++++++++++++++++- connector/test_helper.py | 167 +++++++++++++++++++++++++++++ omarchyd/connector.mjs | 28 +++++ omarchyd/server.mjs | 4 +- server/app.mjs | 4 +- test/storage-panel.test.mjs | 6 ++ test/swarm-storage.test.mjs | 3 + web/src/api.ts | 1 + web/src/screens/Storage.tsx | 81 +++++++++++++- 11 files changed, 518 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 3991873f..16cc7d0d 100644 --- a/README.md +++ b/README.md @@ -189,8 +189,9 @@ Ctrl, Alt and arrows. - Live CPU, memory, temperature, uptime and storage, with what each app and machine is using. - Storage pools with their space, drives, layout and errors. -- If a drive got bigger (a resized virtual disk, say), it shows the space that isn't in use yet and - the exact commands to grow into it. +- If the system drive got bigger (a resized virtual disk, say), Storage on this server or a joined + computer shows the space that isn’t in use yet. Use the extra space grows the partition, its + encryption and the filesystem. - Device name, Wi-Fi, logs, restart, shut down, factory reset, and a What's New after every update. ## Your other computers (Linux, Mac, Windows) diff --git a/connector/agent.py b/connector/agent.py index bc0f1879..14d5af40 100644 --- a/connector/agent.py +++ b/connector/agent.py @@ -5349,8 +5349,12 @@ def sync_connector_files(cfg, abilities, fetch_named=None, data_dir=None, helper return {"updated": updated, "skipped": skipped} -def helper(verb, *args): - r = subprocess.run(["sudo", "-n", HELPER, verb, *args], capture_output=True, text=True, timeout=600) +def helper(verb, *args, stdin=None): + kw = {} + # Pass stdin only when there is some, so other verbs keep the connector's own stdin. + if stdin is not None: + kw["input"] = stdin + r = subprocess.run(["sudo", "-n", HELPER, verb, *args], capture_output=True, text=True, timeout=600, **kw) if r.returncode: raise RuntimeError((r.stderr or r.stdout or "Storage helper failed").strip().split("\n")[-1][:300]) return r.stdout.strip() @@ -5447,6 +5451,23 @@ def storage_set_sleep(args): return True +def storage_grow_status(_args): + raw = helper("grow-status") + if not raw or raw == "null": + return None + return json.loads(raw) + + +def storage_grow(args): + pw = args.get("password") if isinstance(args, dict) else "" + if not isinstance(pw, str): + pw = "" + if len(pw) > 512 or re.search(r"[\r\n]", pw): + raise RuntimeError("Bad password") + # The disk password goes to the helper on stdin, then to cryptsetup. It is not an argument. + return json.loads(helper("grow-system", stdin=(pw + "\n") if pw else "")) + + STORAGE_ACTIONS = { "storage-status": storage_status, "storage-disks": storage_disks, @@ -5461,6 +5482,8 @@ def storage_set_sleep(args): "storage-forgetPool": storage_forget_pool, "storage-scrub": storage_scrub, "storage-setSleep": storage_set_sleep, + "storage-grow-status": storage_grow_status, + "storage-grow": storage_grow, } # Virtual machines (ability "vms"). Session libvirt as this user: no sudo, no shell. diff --git a/connector/helper.py b/connector/helper.py index 449c02b8..eaa3d09c 100644 --- a/connector/helper.py +++ b/connector/helper.py @@ -14,6 +14,8 @@ sleep DEV MIN spin-down time for a hard drive (0 = never) pool-* Btrfs pools at ~/Pools/NAME (create, add, import, forget, scrub, status) zfs-available is ZFS installed? + grow-status space on the system drive the filesystem does not use yet + grow-system grow that drive's last partition, its encryption and the filesystem """ import json import os @@ -101,14 +103,18 @@ def fail(message): raise HelperError(message) -def default_run(cmd, args): +def default_run(cmd, args, stdin=None): env = dict(os.environ) env["PATH"] = HELPER_PATH env["LC_ALL"] = "C" # A drive that never answers smartctl must not hold the disk list for the full command limit. timeout = 15 if cmd == "smartctl" else 600 + kw = dict(capture_output=True, text=True, timeout=timeout, env=env) + # The disk password is stdin for cryptsetup. Other commands leave this off. + if stdin is not None: + kw["input"] = stdin try: - r = subprocess.run([cmd, *args], capture_output=True, text=True, timeout=timeout, env=env) + r = subprocess.run([cmd, *args], **kw) except FileNotFoundError: raise HelperError("%s is not installed" % cmd) except subprocess.TimeoutExpired: @@ -147,7 +153,187 @@ def parse_smart(j): } -def handle(verb, args, run=None, user=None, realpath=None, fstab_text=None, files=None, chown=None, now=None): +MB = 1024 * 1024 + + +def _num(value): + if isinstance(value, bool) or value is None or value == "": + return 0 + try: + return int(value) + except (TypeError, ValueError): + try: + return int(float(value)) + except (TypeError, ValueError): + return 0 + + +def _fs_size(path, statvfs): + try: + st = statvfs(path) + except OSError: + return 0 + fr = getattr(st, "f_frsize", 0) or getattr(st, "f_bsize", 0) or 0 + blocks = getattr(st, "f_blocks", 0) or 0 + try: + return int(blocks) * int(fr) + except (TypeError, ValueError): + return 0 + + +def _unused_drive_bytes(disk_size, part_sizes, fs_partition_size, fs_size): + # Same thresholds as the server: unallocated space after the partitions, plus a filesystem + # that is meaningfully smaller than its own partition. Other partitions are in use. + parts = [n for n in part_sizes if n > 0] + part_lag = max(0, disk_size - sum(parts)) if parts else 0 + raw_fs = (fs_partition_size - fs_size) if fs_partition_size and fs_size else 0 + fs_threshold = max(1024 * MB, (fs_partition_size or 0) * 0.06) + fs_lag = raw_fs if raw_fs > fs_threshold else 0 + return (part_lag if part_lag > 256 * MB else 0) + fs_lag + + +def _system_layout(run, user, with_target): + cols = "SOURCE,FSTYPE,TARGET" if with_target else "SOURCE,FSTYPE" + fields = run("findmnt", ["-n", "-o", cols, "-T", user["home"]]).strip().split() + if len(fields) < (3 if with_target else 2): + fail("The system drive couldn’t be found") + source, fstype = fields[0], fields[1] + target = fields[2] if with_target else None + dev = re.sub(r"\[.*\]$", "", source) + if not dev.startswith("/dev/"): + fail("The system drive couldn’t be found") + parsed = json.loads(run("lsblk", ["-J", "-b", "-s", "-o", "NAME,PATH,SIZE,TYPE", dev]) or "{}") + node = (parsed.get("blockdevices") or [None])[0] + layers = [] + while isinstance(node, dict): + layers.append(node) + kids = node.get("children") or [] + node = kids[0] if kids else None + part = next((n for n in layers if n.get("type") == "part"), None) + crypt = next((n for n in layers if n.get("type") == "crypt"), None) + disk = next((n for n in layers if n.get("type") == "disk"), None) + if not disk: + fail("The system drive couldn’t be found") + tree = json.loads(run("lsblk", ["-J", "-b", "-o", "NAME,PATH,SIZE,TYPE,START", disk.get("path")]) or "{}") + root = (tree.get("blockdevices") or [None])[0] or {} + parts = [c for c in (root.get("children") or []) if c.get("type") == "part"] + last = None + best = -1 + for c in parts: + start = _num(c.get("start")) + if start > best: + best = start + last = c + return { + "dev": dev, + "fstype": fstype, + "target": target, + "layers": layers, + "part": part, + "crypt": crypt, + "disk": disk, + "parts": parts, + "last": last, + } + + +def _drive_report(info, user, statvfs): + disk, part, crypt, parts, last = info["disk"], info["part"], info["crypt"], info["parts"], info["last"] + fs_device = info["layers"][0] if info["layers"] else {} + fs_size = _fs_size(user["home"], statvfs) + part_lag = (_num(disk.get("size")) - sum(_num(c.get("size")) for c in parts)) if parts else 0 + steps = [] + if part and part_lag > 256 * MB: + steps.append("partition" if last and last.get("name") == part.get("name") else "partition-not-last") + if crypt and part and _num(part.get("size")) - _num(crypt.get("size")) > 256 * MB: + steps.append("encryption") + fs_dev_size = _num(fs_device.get("size")) + if fs_size and fs_dev_size - fs_size > max(1024 * MB, fs_dev_size * 0.06): + steps.append("filesystem") + if crypt and part and part_lag > 256 * MB and "encryption" not in steps: + steps.append("encryption") + if part and part_lag > 256 * MB and "filesystem" not in steps: + steps.append("filesystem") + seen = [] + for step in steps: + if step not in seen: + seen.append(step) + part_number = None + if part: + number = re.search(r"(\d+)$", str(part.get("name") or "")) + if number: + part_number = int(number.group(1)) + return { + "name": disk.get("path"), + "size": _num(disk.get("size")), + "notInUse": _unused_drive_bytes(_num(disk.get("size")), [_num(c.get("size")) for c in parts], _num(part.get("size")) if part else 0, fs_size), + "steps": seen, + "partition": part.get("path") if part else None, + "partitionNumber": part_number, + "encrypted": crypt.get("name") if crypt else None, + "filesystem": info["fstype"], + } + + +def _grow_system(run, user, stdin): + info = _system_layout(run, user, True) + layers = info["layers"] + if any(n.get("type") == "lvm" or re.match(r"^raid", str(n.get("type") or "")) for n in layers): + fail("The system is on LVM or RAID. Grow it with lvextend / mdadm instead.") + part, disk, crypt, parts, last = info["part"], info["disk"], info["crypt"], info["parts"], info["last"] + if not part or not disk: + fail("The system isn’t on a partition of a drive, so there’s nothing to grow") + if layers.index(part) != len(layers) - 2: + fail("This layout isn’t supported for growing") + if not last or last.get("path") != part.get("path"): + fail("%s isn’t the last partition on %s, so it can’t grow into the new space. Use a partition tool (GParted) from a live USB." % (part.get("path"), disk.get("path"))) + number = re.search(r"(\d+)$", str(part.get("name") or "")) + if not number: + fail("The partition number couldn’t be read") + number = number.group(1) + free = _num(disk.get("size")) - sum(_num(c.get("size")) for c in parts) + passphrase = stdin or "" + if passphrase.endswith("\n"): + passphrase = passphrase[:-1] + done = [] + # 1. The partition: move a GPT's backup header to the new end, then extend the last + # partition to the end of the drive and tell the kernel (works while it's mounted). + if free > 16 * MB: + dump = run("sfdisk", ["--dump", disk.get("path")]) + table = re.search(r"^label:\s*(\w+)", dump or "", re.M) + if table and table.group(1) == "gpt": + run("sfdisk", ["--relocate", "gpt-bak-std", disk.get("path")]) + run("sfdisk", ["--no-reread", "--force", "-N", number, disk.get("path")], ", +\n") + run("partx", ["-u", "-n", number, disk.get("path")]) + done.append("partition") + # 2. The encryption layer, if any. The password arrives on stdin and is not stored. + if crypt: + try: + if passphrase: + run("cryptsetup", ["resize", crypt.get("name"), "--key-file", "-"], passphrase) + else: + run("cryptsetup", ["resize", crypt.get("name")]) + except Exception as e: + if re.search(r"passphrase|key|No key available", str(e), re.I): + if passphrase: + fail("That disk password didn’t unlock the drive") + fail("NEEDS_PASSWORD: The drive is encrypted. Enter its disk password (the one you type when the computer starts).") + raise + done.append("encryption") + fstype, target, dev = info["fstype"], info["target"], info["dev"] + if fstype == "btrfs": + run("btrfs", ["filesystem", "resize", "max", target]) + elif fstype in ("ext4", "ext3"): + run("resize2fs", [dev]) + elif fstype == "xfs": + run("xfs_growfs", [target]) + else: + fail("Growing a %s filesystem isn’t supported" % fstype) + done.append("filesystem") + return {"grown": done, "disk": disk.get("path"), "partition": part.get("path")} + + +def handle(verb, args, run=None, user=None, realpath=None, fstab_text=None, files=None, chown=None, now=None, stdin=None, statvfs=None): run = run or default_run realpath = realpath or os.path.realpath now = now or time.time @@ -1055,12 +1241,23 @@ def virtual_of(real): for z in zfs_importable_data(): out.append({"kind": "zfs", "uuid": "zfs:%s" % z["name"], "label": z["name"], "devices": [], "state": z.get("state"), "otherSystem": z.get("otherSystem"), "note": z.get("note")}) return json.dumps(out) + # The drive the owner's home is on, after that disk was made bigger. + if verb == "grow-status": + try: + info = _system_layout(run, user, False) + except Exception: + return "null" + return json.dumps(_drive_report(info, user, statvfs or os.statvfs)) + if verb == "grow-system": + return json.dumps(_grow_system(run, user, stdin)) fail("Unknown action: %s" % verb) def main(): verb = sys.argv[1] if len(sys.argv) > 1 else "" args = sys.argv[2:] + # The disk password, only for a grow. It is never an argument. + stdin = sys.stdin.read() if verb == "grow-system" else None try: if os.geteuid() != 0: fail("Run this through sudo as the person who installed the connector") @@ -1077,7 +1274,7 @@ def main(): fail("Unknown user") if pw.pw_uid != uid: fail("Unknown user") - sys.stdout.write("%s\n" % handle(verb, args, user={"name": name, "uid": uid, "gid": pw.pw_gid, "home": pw.pw_dir})) + sys.stdout.write("%s\n" % handle(verb, args, user={"name": name, "uid": uid, "gid": pw.pw_gid, "home": pw.pw_dir}, stdin=stdin)) except HelperError as e: sys.stderr.write("%s\n" % e) sys.exit(2) diff --git a/connector/test_helper.py b/connector/test_helper.py index 6ddfa496..98999045 100644 --- a/connector/test_helper.py +++ b/connector/test_helper.py @@ -1047,5 +1047,172 @@ def test_path_exists_or_sbin(self): self.assertTrue(os.path.exists(p) or p == "/usr/sbin/hdparm") +class Grow(unittest.TestCase): + def setUp(self): + from helper import handle + self.handle = handle + self.user = {"name": "chris", "uid": 1000, "gid": 1000, "home": "/home/chris"} + self.G = 1024 ** 3 + + def stat(self, blocks): + return lambda _path: type("St", (), {"f_blocks": blocks, "f_frsize": 1, "f_bsize": 1})() + + def layout(self, crypt=True, last="vda2", fstype="btrfs", lvm=False): + G = self.G + disk = {"name": "vda", "path": "/dev/vda", "size": 200 * G, "type": "disk"} + part = {"name": "vda2", "path": "/dev/vda2", "size": 99 * G, "type": "part"} + if lvm: + chain = {"name": "root", "path": "/dev/mapper/root", "size": 98 * G, "type": "lvm", "children": [dict(part, children=[disk])]} + src = "/dev/mapper/root[/@home]" + elif crypt: + chain = {"name": "root", "path": "/dev/mapper/root", "size": 98 * G, "type": "crypt", "children": [dict(part, children=[disk])]} + src = "/dev/mapper/root[/@home]" + else: + chain = dict(part, children=[disk]) + src = "/dev/vda2[/@home]" + vda2_start = 2099200 if last == "vda2" else 1000 + tree = {"name": "vda", "path": "/dev/vda", "size": 200 * G, "type": "disk", "children": [ + {"name": "vda1", "path": "/dev/vda1", "size": G, "type": "part", "start": 2048}, + {"name": "vda2", "path": "/dev/vda2", "size": 99 * G, "type": "part", "start": vda2_start}, + ]} + return src, fstype, chain, tree + + def fake(self, crypt=True, last="vda2", fstype="btrfs", lvm=False, accept=None): + src, fs, chain, tree = self.layout(crypt, last, fstype, lvm) + log = [] + + def run(cmd, args, stdin=None): + log.append([cmd, *list(args)] + (["" % stdin] if stdin is not None else [])) + if cmd == "findmnt": + return "%s %s /home\n" % (src, fs) + if cmd == "lsblk": + return json.dumps({"blockdevices": [chain if "-s" in args else tree]}) + if cmd == "sfdisk" and args[:1] == ["--dump"]: + return "label: gpt\n" + if cmd == "cryptsetup": + if accept is not None and stdin != accept: + raise Exception("cryptsetup: No key available with this passphrase.") + return "" + return "" + + return log, run + + def test_grow_status_reports_unused_space_and_steps(self): + _log, run = self.fake() + drive = json.loads(self.handle("grow-status", [], run=run, user=self.user, statvfs=self.stat(99 * self.G))) + self.assertEqual(drive["name"], "/dev/vda") + self.assertEqual(drive["size"], 200 * self.G) + self.assertEqual(drive["notInUse"], 100 * self.G) + self.assertEqual(drive["steps"], ["partition", "encryption", "filesystem"]) + self.assertEqual(drive["encrypted"], "root") + self.assertEqual(drive["partitionNumber"], 2) + self.assertNotIn("partition-not-last", drive["steps"]) + + def test_grow_status_counts_a_filesystem_that_lags_its_partition(self): + G = self.G + # The partition already fills the disk. The filesystem is still half that size. + chain = {"name": "vda1", "path": "/dev/vda1", "size": 100 * G, "type": "part", "children": [ + {"name": "vda", "path": "/dev/vda", "size": 100 * G, "type": "disk"} + ]} + tree = {"name": "vda", "path": "/dev/vda", "size": 100 * G, "type": "disk", "children": [ + {"name": "vda1", "path": "/dev/vda1", "size": 100 * G, "type": "part", "start": 2048} + ]} + + def run(cmd, args, stdin=None): + if cmd == "findmnt": + return "/dev/vda1 ext4 /home\n" + if cmd == "lsblk": + return json.dumps({"blockdevices": [chain if "-s" in args else tree]}) + return "" + + drive = json.loads(self.handle("grow-status", [], run=run, user=self.user, statvfs=self.stat(50 * G))) + self.assertEqual(drive["notInUse"], 50 * G) + self.assertEqual(drive["steps"], ["filesystem"]) + self.assertIsNone(drive["encrypted"]) + + def test_grow_status_missing_drive_is_null(self): + def run(cmd, args, stdin=None): + if cmd == "findmnt": + return "overlay overlay /\n" + raise AssertionError(cmd) + + self.assertEqual(self.handle("grow-status", [], run=run, user=self.user, statvfs=self.stat(1)), "null") + + def test_grow_system_last_partition_then_encryption_then_filesystem(self): + from helper import HelperError + log, run = self.fake(accept="disk pass") + with self.assertRaisesRegex(HelperError, "NEEDS_PASSWORD"): + self.handle("grow-system", [], run=run, user=self.user, stdin="") + self.assertNotIn("secret", str(log)) + log, run = self.fake(accept="disk pass") + grown = json.loads(self.handle("grow-system", [], run=run, user=self.user, stdin="disk pass\n")) + self.assertEqual(grown["grown"], ["partition", "encryption", "filesystem"]) + cmds = [" ".join(c) for c in log] + self.assertIn("sfdisk --relocate gpt-bak-std /dev/vda", cmds) + self.assertIn("sfdisk --no-reread --force -N 2 /dev/vda ", cmds) + self.assertIn("partx -u -n 2 /dev/vda", cmds) + self.assertIn("cryptsetup resize root --key-file - ", cmds) + self.assertIn("btrfs filesystem resize max /home", cmds) + self.assertLess(cmds.index("partx -u -n 2 /dev/vda"), cmds.index("btrfs filesystem resize max /home")) + + def test_wrong_password_is_not_echoed(self): + from helper import HelperError + log, run = self.fake(accept="disk pass") + with self.assertRaisesRegex(HelperError, "didn’t unlock") as err: + self.handle("grow-system", [], run=run, user=self.user, stdin="secret-pass\n") + self.assertNotIn("secret-pass", str(err.exception)) + self.assertTrue(any(c[:3] == ["cryptsetup", "resize", "root"] for c in log)) + + def test_not_last_partition_is_refused(self): + log, run = self.fake(last="vda1") + drive = json.loads(self.handle("grow-status", [], run=run, user=self.user, statvfs=self.stat(99 * self.G))) + self.assertIn("partition-not-last", drive["steps"]) + log, run = self.fake(last="vda1", accept="disk pass") + from helper import HelperError + with self.assertRaisesRegex(HelperError, "isn’t the last partition"): + self.handle("grow-system", [], run=run, user=self.user, stdin="disk pass\n") + self.assertFalse(any(c[0] == "sfdisk" and c[1] != "--dump" for c in log)) + self.assertFalse(any(c[0] == "partx" for c in log)) + + def test_unencrypted_skips_cryptsetup(self): + log, run = self.fake(crypt=False) + grown = json.loads(self.handle("grow-system", [], run=run, user=self.user, stdin="")) + self.assertEqual(grown["grown"], ["partition", "filesystem"]) + self.assertFalse(any(c[0] == "cryptsetup" for c in log)) + + def test_lvm_is_refused(self): + from helper import HelperError + log, run = self.fake(lvm=True) + drive = json.loads(self.handle("grow-status", [], run=run, user=self.user, statvfs=self.stat(98 * self.G))) + self.assertGreater(drive["notInUse"], 0) + log.clear() + with self.assertRaisesRegex(HelperError, "LVM or RAID"): + self.handle("grow-system", [], run=run, user=self.user, stdin="") + self.assertFalse(any(c[0] in ("sfdisk", "partx", "cryptsetup", "btrfs") for c in log)) + + def test_default_run_passes_stdin_only_when_given(self): + import helper + seen = [] + + def fake_run(argv, **kw): + seen.append(kw.get("input", "absent")) + + class R: + returncode = 0 + stdout = "" + stderr = "" + + return R() + + orig = helper.subprocess.run + helper.subprocess.run = fake_run + try: + helper.default_run("lsblk", ["-J"]) + helper.default_run("sfdisk", ["--no-reread"], ", +\n") + finally: + helper.subprocess.run = orig + self.assertEqual(seen, ["absent", ", +\n"]) + + if __name__ == "__main__": unittest.main() diff --git a/omarchyd/connector.mjs b/omarchyd/connector.mjs index 4d516510..83562105 100644 --- a/omarchyd/connector.mjs +++ b/omarchyd/connector.mjs @@ -2179,6 +2179,34 @@ export function createConnector({dataDir, tlsDir, connectorDir = fileURLToPath(n } }, }, + // The joined computer's system drive, and how much of it the filesystem does not use yet. + 'swarm.storage.growStatus': { + kind: 'query', + run: async (input) => { + const a = await requireAgent(input, true) + try { + const drive = await call(a.id, 'storage-grow-status', {}) + return drive && typeof drive === 'object' ? drive : null + } catch (e) { + throw storageReadError(e, a.name) + } + }, + }, + // Grow that drive. The disk password, if any, is passed through to the connector and is not stored. + 'swarm.storage.growSystem': { + kind: 'mutation', + run: async (input) => { + const pw = typeof input?.password === 'string' ? input.password : '' + if (pw.length > 512 || /[\r\n]/.test(pw)) throw new RpcError('BAD_REQUEST', 'Bad password') + const a = await requireAgent(input, true) + try { + return await call(a.id, 'storage-grow', pw ? {password: pw} : {}) + } catch (e) { + if (/Unknown action/.test(e.message)) throw new RpcError('PRECONDITION_FAILED', `Run the connector install again on ${a.name}.`) + throw new RpcError('PRECONDITION_FAILED', e.message) + } + }, + }, // Before showing a computer's screen: can it, and if not, why (in words, not a socket code). 'swarm.desktopCheck': { kind: 'query', diff --git a/omarchyd/server.mjs b/omarchyd/server.mjs index 1bd33ce0..a2399ca2 100644 --- a/omarchyd/server.mjs +++ b/omarchyd/server.mjs @@ -392,9 +392,9 @@ export async function startOmarchyd({port = 2021, host = '127.0.0.1', dataDir, t 'omarchy.plugins': {kind: 'query', run: (input) => themeCall(() => omarchyPlugins.list(input ?? {}))}, // Local swarm (connector.mjs): owner only. ...Object.fromEntries( - ['swarm.list', 'swarm.history', 'swarm.alerts', 'swarm.wake', 'swarm.pair', 'swarm.reauthorize', 'swarm.updateConnector', 'swarm.updateAllConnectors', 'swarm.remove', 'swarm.rename', 'swarm.setAbilities', 'swarm.action', 'swarm.desktopCheck', 'swarm.storage.status', 'swarm.vms.status', 'swarm.storage.disks', 'swarm.storage.pools', 'swarm.storage.importable', 'swarm.storage.unmount', 'swarm.storage.mount', 'swarm.storage.format', 'swarm.storage.createPool', 'swarm.storage.addToPool', 'swarm.storage.importPool', 'swarm.storage.forgetPool', 'swarm.storage.scrub', 'swarm.storage.setSleep', 'swarm.services.list', 'swarm.services.logs', 'swarm.services.control', 'swarm.hostLogs', 'swarm.files.list', 'swarm.files.read', 'swarm.files.write', 'swarm.files.recents', 'swarm.files.mkdir', 'swarm.files.rename', 'swarm.files.trash', 'swarm.files.copyToServer', 'swarm.files.copyFromServer'].map((name) => [ + ['swarm.list', 'swarm.history', 'swarm.alerts', 'swarm.wake', 'swarm.pair', 'swarm.reauthorize', 'swarm.updateConnector', 'swarm.updateAllConnectors', 'swarm.remove', 'swarm.rename', 'swarm.setAbilities', 'swarm.action', 'swarm.desktopCheck', 'swarm.storage.status', 'swarm.vms.status', 'swarm.storage.disks', 'swarm.storage.pools', 'swarm.storage.importable', 'swarm.storage.unmount', 'swarm.storage.mount', 'swarm.storage.format', 'swarm.storage.createPool', 'swarm.storage.addToPool', 'swarm.storage.importPool', 'swarm.storage.forgetPool', 'swarm.storage.scrub', 'swarm.storage.setSleep', 'swarm.storage.growStatus', 'swarm.storage.growSystem', 'swarm.services.list', 'swarm.services.logs', 'swarm.services.control', 'swarm.hostLogs', 'swarm.files.list', 'swarm.files.read', 'swarm.files.write', 'swarm.files.recents', 'swarm.files.mkdir', 'swarm.files.rename', 'swarm.files.trash', 'swarm.files.copyToServer', 'swarm.files.copyFromServer'].map((name) => [ name, - {kind: ['swarm.list', 'swarm.history', 'swarm.alerts', 'swarm.desktopCheck', 'swarm.storage.status', 'swarm.vms.status', 'swarm.storage.disks', 'swarm.storage.pools', 'swarm.storage.importable', 'swarm.services.list', 'swarm.services.logs', 'swarm.hostLogs', 'swarm.files.list', 'swarm.files.read', 'swarm.files.recents'].includes(name) ? 'query' : 'mutation', run: (input, {auth}) => (ownerOnly(auth, 'manage the local swarm'), connector.procedures[name].run(input))}, + {kind: ['swarm.list', 'swarm.history', 'swarm.alerts', 'swarm.desktopCheck', 'swarm.storage.status', 'swarm.vms.status', 'swarm.storage.disks', 'swarm.storage.pools', 'swarm.storage.importable', 'swarm.storage.growStatus', 'swarm.services.list', 'swarm.services.logs', 'swarm.hostLogs', 'swarm.files.list', 'swarm.files.read', 'swarm.files.recents'].includes(name) ? 'query' : 'mutation', run: (input, {auth}) => (ownerOnly(auth, 'manage the local swarm'), connector.procedures[name].run(input))}, ]), ), 'omarchy.installPlugin': {kind: 'mutation', run: (input, {auth}) => (ownerOnly(auth, 'install Omarchy plugins'), themeCall(() => omarchyPlugins.install(input)))}, diff --git a/server/app.mjs b/server/app.mjs index e1550c9e..c1957c38 100644 --- a/server/app.mjs +++ b/server/app.mjs @@ -211,6 +211,8 @@ export const ALLOWED = { 'swarm.storage.forgetPool': 'mutation', 'swarm.storage.scrub': 'mutation', 'swarm.storage.setSleep': 'mutation', + 'swarm.storage.growStatus': 'query', + 'swarm.storage.growSystem': 'mutation', 'swarm.services.list': 'query', 'swarm.services.logs': 'query', 'swarm.services.control': 'mutation', @@ -503,7 +505,7 @@ export const ALLOWED = { } // Long-running mutations: omarchyd answers when the operation finishes. -export const SLOW = new Set(['containers.create', 'containers.images', 'containers.setRootPassword', 'containers.setNixosConfig', 'containers.applyNixosConfig', 'containers.installConnector', 'containers.templateFiles', 'containers.importTemplate', 'containers.downloadTemplate', 'machines.downloadIso', 'containers.files', 'containers.copyToServer', 'containers.rename', 'containers.trash', 'containers.mkdir', 'containers.setResources', 'containers.clone', 'containers.saveTemplate', 'containers.backup', 'containers.restoreBackup', 'containers.stop', 'containers.restart', 'containers.delete', 'containers.snapshot', 'containers.restoreSnapshot', 'hyprland.launch', 'hermes.connect', 'hermes.connectRemote', 'hermes.disconnect', 'hyprland.profileRun', 'unraid.connect', 'unraid.scan', 'unraid.preflight', 'unraid.resync', 'tailscale.login', 'tailscale.ping', 'oidc.setConfig', 'apps.setOidc', 'backups.configure', 'backups.shares', 'backups.restoreApp', 'backups.connectExisting', 'backups.snapshots', 'backups.computerSnapshots', 'backups.setComputer', 'backups.computerFolders', 'backups.gdrive.authFinish', 'backups.gdrive.configure', 'backups.gdrive.test', 'backups.gdrive.connectExisting', 'storage.growSystem', 'system.replaceCertificate', 'system.desktopSignIn', 'system.desktopShare', 'omarchy.removeTheme', 'storage.disks', 'storage.createPool', 'storage.addToPool', 'storage.importPool', 'storage.forgetPool', 'files.addShare', 'files.removeShare', 'files.copy', 'files.unarchive', 'files.getThumbnail', 'files.move', 'files.delete', 'files.emptyTrash', 'files.search', 'files.list', 'swarm.files.list', 'swarm.files.recents', 'files.transfer', 'files.fleetRecents', 'apps.install', 'apps.move', 'apps.update', 'apps.setPorts', 'apps.uninstall', 'apps.start', 'apps.stop', 'apps.restart', 'appStore.registry', 'appStore.app', 'appStore.addRepository', 'appStore.refresh', 'apps.importCompose', 'omarchy.plugins', 'omarchy.installPlugin', 'omarchy.updatePlugins', 'files.updateShare', 'files.setSharePassword', 'apps.logs', 'swarm.action', 'system.update', 'system.logs', 'machines.create', 'machines.installConnector', 'machines.uninstall', 'machines.snapshot', 'machines.revertSnapshot', 'machines.deleteSnapshot', 'machines.resizeDisk', 'machines.addDisk', 'machines.restart', 'machines.applyNixosConfig', 'machines.start', 'machines.hibernate', 'machines.updateCloudInit', 'machines.details', 'machines.node', 'wifi.connect', 'wifi.networks', 'system.setHostname', 'hardware.internalStorage.getDevices', 'hardware.raid.addDevice', 'hardware.raid.addMirror', 'hardware.raid.addAccelerator', 'hardware.raid.replaceDevice', 'hardware.raid.transitionToFailsafeRaidz', 'storage.unmount', 'storage.mount', 'storage.format', 'swarm.storage.disks', 'swarm.storage.unmount', 'swarm.storage.mount', 'swarm.storage.format', 'swarm.storage.pools', 'swarm.storage.importable', 'swarm.storage.createPool', 'swarm.storage.addToPool', 'swarm.storage.importPool', 'swarm.storage.forgetPool', 'swarm.storage.scrub', 'assistant.approve', 'clips.paste', 'clips.addFile', 'clips.fleetList', 'swarm.updateConnector', 'swarm.updateAllConnectors', 'swarm.services.list', 'swarm.services.logs', 'swarm.services.control', 'swarm.files.copyToServer', 'swarm.files.copyFromServer', 'machines.move', 'containers.move']) +export const SLOW = new Set(['containers.create', 'containers.images', 'containers.setRootPassword', 'containers.setNixosConfig', 'containers.applyNixosConfig', 'containers.installConnector', 'containers.templateFiles', 'containers.importTemplate', 'containers.downloadTemplate', 'machines.downloadIso', 'containers.files', 'containers.copyToServer', 'containers.rename', 'containers.trash', 'containers.mkdir', 'containers.setResources', 'containers.clone', 'containers.saveTemplate', 'containers.backup', 'containers.restoreBackup', 'containers.stop', 'containers.restart', 'containers.delete', 'containers.snapshot', 'containers.restoreSnapshot', 'hyprland.launch', 'hermes.connect', 'hermes.connectRemote', 'hermes.disconnect', 'hyprland.profileRun', 'unraid.connect', 'unraid.scan', 'unraid.preflight', 'unraid.resync', 'tailscale.login', 'tailscale.ping', 'oidc.setConfig', 'apps.setOidc', 'backups.configure', 'backups.shares', 'backups.restoreApp', 'backups.connectExisting', 'backups.snapshots', 'backups.computerSnapshots', 'backups.setComputer', 'backups.computerFolders', 'backups.gdrive.authFinish', 'backups.gdrive.configure', 'backups.gdrive.test', 'backups.gdrive.connectExisting', 'storage.growSystem', 'system.replaceCertificate', 'system.desktopSignIn', 'system.desktopShare', 'omarchy.removeTheme', 'storage.disks', 'storage.createPool', 'storage.addToPool', 'storage.importPool', 'storage.forgetPool', 'files.addShare', 'files.removeShare', 'files.copy', 'files.unarchive', 'files.getThumbnail', 'files.move', 'files.delete', 'files.emptyTrash', 'files.search', 'files.list', 'swarm.files.list', 'swarm.files.recents', 'files.transfer', 'files.fleetRecents', 'apps.install', 'apps.move', 'apps.update', 'apps.setPorts', 'apps.uninstall', 'apps.start', 'apps.stop', 'apps.restart', 'appStore.registry', 'appStore.app', 'appStore.addRepository', 'appStore.refresh', 'apps.importCompose', 'omarchy.plugins', 'omarchy.installPlugin', 'omarchy.updatePlugins', 'files.updateShare', 'files.setSharePassword', 'apps.logs', 'swarm.action', 'system.update', 'system.logs', 'machines.create', 'machines.installConnector', 'machines.uninstall', 'machines.snapshot', 'machines.revertSnapshot', 'machines.deleteSnapshot', 'machines.resizeDisk', 'machines.addDisk', 'machines.restart', 'machines.applyNixosConfig', 'machines.start', 'machines.hibernate', 'machines.updateCloudInit', 'machines.details', 'machines.node', 'wifi.connect', 'wifi.networks', 'system.setHostname', 'hardware.internalStorage.getDevices', 'hardware.raid.addDevice', 'hardware.raid.addMirror', 'hardware.raid.addAccelerator', 'hardware.raid.replaceDevice', 'hardware.raid.transitionToFailsafeRaidz', 'storage.unmount', 'storage.mount', 'storage.format', 'swarm.storage.disks', 'swarm.storage.unmount', 'swarm.storage.mount', 'swarm.storage.format', 'swarm.storage.growSystem', 'swarm.storage.pools', 'swarm.storage.importable', 'swarm.storage.createPool', 'swarm.storage.addToPool', 'swarm.storage.importPool', 'swarm.storage.forgetPool', 'swarm.storage.scrub', 'assistant.approve', 'clips.paste', 'clips.addFile', 'clips.fleetList', 'swarm.updateConnector', 'swarm.updateAllConnectors', 'swarm.services.list', 'swarm.services.logs', 'swarm.services.control', 'swarm.files.copyToServer', 'swarm.files.copyFromServer', 'machines.move', 'containers.move']) export const timeoutFor = (path) => (SLOW.has(path) ? 30 * 60 * 1000 : 20_000) // An IPv6 address in a URL needs brackets; req.hostname and URL.hostname may already have them. diff --git a/test/storage-panel.test.mjs b/test/storage-panel.test.mjs index 384df034..c3cdcfa1 100644 --- a/test/storage-panel.test.mjs +++ b/test/storage-panel.test.mjs @@ -10,6 +10,12 @@ test('storage and backups stay in the machine tab', async () => { assert.match(storage, //) assert.match(storage, //) + assert.doesNotMatch(storage, /\{!swarm && /) diff --git a/test/swarm-storage.test.mjs b/test/swarm-storage.test.mjs index f94bcd6c..1c9c43f3 100644 --- a/test/swarm-storage.test.mjs +++ b/test/swarm-storage.test.mjs @@ -48,6 +48,9 @@ test('swarm.storage.status: missing computer is NOT_FOUND, offline is PRECONDITI await assert.rejects(() => c.procedures['swarm.storage.forgetPool'].run({id, name: 'tank'}), /offline/) await assert.rejects(() => c.procedures['swarm.storage.scrub'].run({id, name: 'tank'}), /offline/) await assert.rejects(() => c.procedures['swarm.storage.setSleep'].run({id, device: '/dev/sda', minutes: 20}), /offline/) + await assert.rejects(() => c.procedures['swarm.storage.growStatus'].run({id}), /offline/) + await assert.rejects(() => c.procedures['swarm.storage.growSystem'].run({id}), /offline/) + await assert.rejects(() => c.procedures['swarm.storage.growSystem'].run({id, password: 'line\nbreak'}), /Bad password/) } finally { await rm(dataDir, {recursive: true, force: true}) } diff --git a/web/src/api.ts b/web/src/api.ts index 5aa1b9dd..f4fef1ad 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -38,6 +38,7 @@ const SLOW_RPC = new Set([ 'swarm.storage.unmount', 'swarm.storage.mount', 'swarm.storage.format', + 'swarm.storage.growSystem', 'swarm.storage.createPool', 'swarm.storage.addToPool', 'swarm.storage.importPool', diff --git a/web/src/screens/Storage.tsx b/web/src/screens/Storage.tsx index 15350a30..5009790c 100644 --- a/web/src/screens/Storage.tsx +++ b/web/src/screens/Storage.tsx @@ -8,7 +8,8 @@ import {useState, type CSSProperties, type ReactNode} from 'react' import {useQuery, useQueryClient} from '@tanstack/react-query' -import {mutate, query} from '../api' +import {mutate, query, type DiskUsage} from '../api' +import {useUser} from '../data' import {FilterBar} from '../FilterBar' import {poweredOnText} from '../plural' import {queryProblem, useBrowserOnline} from '../connection' @@ -128,6 +129,79 @@ function DriveRow({d, onClick, trailing, checked}: {d: Drive; onClick?: () => vo ) } +type GrowDrive = NonNullable + +// After a machine's system drive is made bigger, the partition, encryption and filesystem still have the old size. +function UnusedSpace({onDone, target}: {onDone: () => void; target: StorageTarget}) { + const toast = useToast() + const qc = useQueryClient() + const owner = useUser().data?.role === 'owner' + const swarm = target !== 'host' + const growKey = swarm ? ['swarm.storage.growStatus', target.agentId] : ['system.diskUsage'] + const disk = useQuery({ + queryKey: growKey, + queryFn: async (): Promise => { + if (target === 'host') return (await query('system.diskUsage')).drive ?? null + return query('swarm.storage.growStatus', {id: target.agentId}) + }, + refetchInterval: 60_000, + }) + const d = disk.data + const [asking, setAsking] = useState(false) + const [password, setPassword] = useState('') + const [busy, setBusy] = useState(false) + const [error, setError] = useState('') + if (!d || typeof d.notInUse !== 'number' || d.notInUse <= 0 || !Array.isArray(d.steps)) return null + const notLast = d.steps.includes('partition-not-last') + const grow = async () => { + setBusy(true) + setError('') + try { + if (target === 'host') await mutate('storage.growSystem', password ? {password} : {}) + else await mutate('swarm.storage.growSystem', password ? {id: target.agentId, password} : {id: target.agentId}) + setAsking(false) + setPassword('') + toast(`Done: the system now uses all ${bytes(d.size, 0)}`) + qc.invalidateQueries({queryKey: growKey}) + onDone() + } catch (e) { + const msg = (e as Error).message + if (/NEEDS_PASSWORD/.test(msg)) setAsking(true) + else setError(msg) + } finally { + setBusy(false) + } + } + return ( +
+ {bytes(d.notInUse, 0)} of your {bytes(d.size, 0)} drive isn’t in use yet + + {notLast + ? 'The drive got bigger, but the system’s partition isn’t the last one on it, so it can’t simply be grown. Use a partition tool (like GParted) from a live USB.' + : `The drive got bigger, but the system still has its old size. My Own Data Center can grow the partition${d.encrypted ? ', its encryption' : ''} and the filesystem into the new space while it runs. Only ever grows; nothing is erased.`} + + {asking && ( + setPassword(e.target.value)} + onKeyDown={(e) => e.key === 'Enter' && password && !busy && grow()} + /> + )} + {error && {error}} + {!notLast && owner && ( + + )} +
+ ) +} + export type StorageTarget = 'host' | {agentId: string; name: string} /** Storage is its own panel: a sheet on the phone, the machine pane on the desktop. Closing it returns to the machine that opened it. */ @@ -198,7 +272,8 @@ export function StoragePage({onBack, target = 'host'}: {onBack?: () => void; tar const refresh = () => { setRefreshing(true) - void Promise.all([rpc('disks'), rpc('pools'), rpc('importable'), 'system.diskUsage'].map((k) => qc.invalidateQueries({queryKey: [k]}))).finally(() => setRefreshing(false)) + const growKey = swarm ? 'swarm.storage.growStatus' : 'system.diskUsage' + void Promise.all([rpc('disks'), rpc('pools'), rpc('importable'), growKey].map((k) => qc.invalidateQueries({queryKey: [k]}))).finally(() => setRefreshing(false)) } const act = async (name: string, extra: object, done: string) => { setBusy(true) @@ -264,6 +339,8 @@ export function StoragePage({onBack, target = 'host'}: {onBack?: () => void; tar )} + + {ready === false && ( Storage tools aren’t set up