Release 12.0 (full): one browser harness that converses, writes from held sources and builds what you describe, keeping each request through corrections and restarts. No language model. (part 5)
d9b105f verified Download workbench/machines.py from psiloceyeben/oracle7: direct link, hf CLI and curl.
- Browser
- Download file 11.9 kB
-
https://huggingface.co/psiloceyeben/oracle7/resolve/main/workbench/machines.py
- Command line
-
hf download hf://psiloceyeben/oracle7/workbench/machines.py
-
curl -L -o machines.py https://huggingface.co/psiloceyeben/oracle7/resolve/main/workbench/machines.py
11.9 kB
| """machines - the map of this computer and the machines it reaches (12.0). | |
| One place that shows the computer Oracle7 runs on and every server the user lists, read live and drawn as a map | |
| (static/machines.html, the page's Machines tab). The list is the user's own: workbench/local/machines.json (or | |
| ORACLE7_WORKBENCH_LOCAL/machines.json), which never ships in a pack. A machine is named by what the user's own ssh | |
| reaches it as: an ssh alias from their ~/.ssh/config ("research") or user@host. | |
| {"machines": [{"id": "web", "name": "Web server", "ssh": "root@203.0.113.7", "role": "sites", "color": "#0969da"}]} | |
| Reading is read-only. Each server is read by machine_probe.py piped over ssh stdin (it reads /proc, systemctl, ss, nginx | |
| -T, certificate files and fetches its own sites on 127.0.0.1; it writes nothing). ssh runs with BatchMode (keys only, no | |
| password prompt), StrictHostKeyChecking=yes (a host it has never seen is not trusted silently) and no forwarding. This | |
| computer is read with the standard library (and psutil when it is installed). Nothing is sent anywhere else. | |
| Would not solve: a machine that ssh cannot reach with a key; Windows servers (the probe reads Linux /proc). | |
| """ | |
| import json | |
| import os | |
| import platform | |
| import re | |
| import shutil | |
| import socket | |
| import subprocess | |
| import sys | |
| import time | |
| from concurrent.futures import ThreadPoolExecutor | |
| from pathlib import Path | |
| HERE = Path(__file__).resolve().parent | |
| PROBE = HERE / "machine_probe.py" | |
| ID = re.compile(r"^[A-Za-z0-9_-]{1,24}$") | |
| SSH_TARGET = re.compile(r"^(?:[A-Za-z0-9._-]{1,64}@)?[A-Za-z0-9._-]{1,253}$") | |
| COLOR = re.compile(r"^#[0-9a-fA-F]{6}$") | |
| PALETTE = ["#0969da", "#1a7f37", "#8250df", "#bf3989", "#e95420", "#9a6700", "#0a7ea4", "#cf222e"] | |
| DAY = 86400 | |
| def _local(): | |
| return Path(os.environ.get("ORACLE7_WORKBENCH_LOCAL") or (HERE / "local")) | |
| def _paths(): | |
| base = _local() | |
| return base / "machines.json", base / "machines_map.json", base / "machines_history.json" | |
| def config(): | |
| """the user's list: [{id, name, ssh, role, color}] (empty when none is kept)""" | |
| cfg, _m, _h = _paths() | |
| try: | |
| items = json.loads(cfg.read_text(encoding="utf-8")).get("machines") or [] | |
| except (OSError, ValueError): | |
| items = [] | |
| return [m for m in (_clean(x, i) for i, x in enumerate(items)) if m] | |
| def _clean(m, i=0): | |
| if not isinstance(m, dict): | |
| return None | |
| mid, ssh = str(m.get("id") or "").strip(), str(m.get("ssh") or "").strip() | |
| if not ID.match(mid) or not SSH_TARGET.match(ssh) or ssh.startswith("-"): | |
| return None | |
| color = str(m.get("color") or "") | |
| return {"id": mid, "name": str(m.get("name") or mid)[:40], "ssh": ssh, "role": str(m.get("role") or "")[:120], | |
| "color": color if COLOR.match(color) else PALETTE[i % len(PALETTE)]} | |
| def save(items): | |
| """keep the user's list (validated; ids unique). -> the list as kept""" | |
| kept, seen = [], set() | |
| for i, x in enumerate(items or []): | |
| m = _clean(x, i) | |
| if m and m["id"] not in seen: | |
| seen.add(m["id"]) | |
| kept.append(m) | |
| cfg, _m, _h = _paths() | |
| cfg.parent.mkdir(parents=True, exist_ok=True) | |
| tmp = cfg.with_suffix(".tmp") | |
| tmp.write_text(json.dumps({"machines": kept}, indent=1), encoding="utf-8") | |
| os.replace(tmp, cfg) | |
| return kept | |
| def probe_server(ssh, timeout=60): | |
| """one server's inventory, read by machine_probe.py over ssh (read-only). -> dict, or {"unreachable": True, "why"}""" | |
| if not SSH_TARGET.match(ssh) or ssh.startswith("-"): | |
| return {"unreachable": True, "why": "not an ssh target", "probed_at": int(time.time())} | |
| cmd = ["ssh", "-T", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", "-o", "ClearAllForwardings=yes", | |
| "-o", "ForwardAgent=no", "-o", "ForwardX11=no", "-o", "ConnectTimeout=10", ssh, "python3", "-"] | |
| try: | |
| r = subprocess.run(cmd, input=PROBE.read_text(encoding="utf-8"), capture_output=True, text=True, timeout=timeout) | |
| except FileNotFoundError: | |
| return {"unreachable": True, "why": "no ssh command on this computer", "probed_at": int(time.time())} | |
| except subprocess.TimeoutExpired: | |
| return {"unreachable": True, "why": "no answer within %d s" % timeout, "probed_at": int(time.time())} | |
| out = r.stdout.strip() | |
| try: | |
| sample = json.loads(out[out.index("{"):]) if "{" in out else None | |
| except ValueError: | |
| sample = None | |
| if not sample or not sample.get("cpus") or not (sample.get("disk") or {}).get("total"): | |
| why = (r.stderr.strip().splitlines() or ["no inventory returned"])[-1][:200] | |
| return {"unreachable": True, "why": why, "probed_at": int(time.time())} | |
| return sample | |
| def _mem(): | |
| try: | |
| import psutil # optional | |
| v = psutil.virtual_memory() | |
| return {"total": int(v.total), "used": int(v.total - v.available)} | |
| except Exception: # noqa: BLE001 | |
| pass | |
| if sys.platform == "win32": | |
| try: | |
| import ctypes | |
| class MS(ctypes.Structure): | |
| _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), | |
| ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), | |
| ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), | |
| ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), | |
| ("ullAvailExtendedVirtual", ctypes.c_ulonglong)] | |
| m = MS() | |
| m.dwLength = ctypes.sizeof(MS) | |
| ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m)) | |
| return {"total": int(m.ullTotalPhys), "used": int(m.ullTotalPhys - m.ullAvailPhys)} | |
| except Exception: # noqa: BLE001 | |
| return {"total": 0, "used": 0} | |
| try: | |
| info = {} | |
| for line in open("/proc/meminfo"): | |
| k, v = line.split(":", 1) | |
| info[k] = int(v.split()[0]) * 1024 | |
| return {"total": info["MemTotal"], "used": info["MemTotal"] - info.get("MemAvailable", info.get("MemFree", 0))} | |
| except Exception: # noqa: BLE001 | |
| return {"total": 0, "used": 0} | |
| def _uptime(): | |
| try: | |
| import psutil | |
| return int(time.time() - psutil.boot_time()) | |
| except Exception: # noqa: BLE001 | |
| pass | |
| if sys.platform == "win32": | |
| try: | |
| import ctypes | |
| return int(ctypes.windll.kernel32.GetTickCount64() // 1000) | |
| except Exception: # noqa: BLE001 | |
| return 0 | |
| try: | |
| return int(float(open("/proc/uptime").read().split()[0])) | |
| except Exception: # noqa: BLE001 | |
| return 0 | |
| def _cpu_pct(): | |
| try: | |
| import psutil | |
| return int(psutil.cpu_percent(interval=0.3)) | |
| except Exception: # noqa: BLE001 | |
| pass | |
| try: | |
| return int(100 * os.getloadavg()[0] / (os.cpu_count() or 1)) | |
| except Exception: # noqa: BLE001 | |
| return 0 | |
| def _drives(): | |
| """the computer's other drives (an external disk shows as one): [{mount, total, used, free}]""" | |
| mounts = [] | |
| if sys.platform == "win32": | |
| mounts = ["%s:\\" % c for c in "DEFGHIJKLMNOPQRSTUVWXYZ" if os.path.exists("%s:\\" % c)] | |
| else: | |
| for base in ("/media", "/mnt", "/Volumes"): | |
| try: | |
| mounts += [os.path.join(base, d) for d in os.listdir(base)] | |
| except OSError: | |
| pass | |
| out = [] | |
| for m in mounts[:6]: | |
| try: | |
| du = shutil.disk_usage(m) | |
| out.append({"mount": m, "total": du.total, "used": du.used, "free": du.free}) | |
| except OSError: | |
| pass | |
| return out | |
| def probe_local(): | |
| """this computer, read with the standard library (psutil when present)""" | |
| root = os.path.abspath(os.sep) if sys.platform != "win32" else os.environ.get("SystemDrive", "C:") + "\\" | |
| du = shutil.disk_usage(root) | |
| return {"hostname": socket.gethostname(), "model": platform.node(), "os": "%s %s" % (platform.system(), platform.release()), | |
| "cpu_model": platform.processor() or platform.machine(), "cpus": os.cpu_count() or 1, "cpu_pct": _cpu_pct(), | |
| "mem": _mem(), "disk": {"total": du.total, "used": du.used, "free": du.free}, "disk_name": root, | |
| "uptime_s": _uptime(), "battery": None, "on_power": True, "drives": _drives()} | |
| def collect(): | |
| """read every listed machine (in parallel) and this computer; keep the map and 24 h of history. -> the map""" | |
| items = config() | |
| with ThreadPoolExecutor(max_workers=max(1, min(8, len(items)))) as ex: | |
| found = dict(zip([m["id"] for m in items], ex.map(lambda m: probe_server(m["ssh"]), items))) | |
| laptop = probe_local() | |
| drives = laptop.get("drives") or [] | |
| drive = {"connected": bool(drives)} | |
| if drives: | |
| d = max(drives, key=lambda x: x["total"]) | |
| drive.update(label=d["mount"], fs="", model="", total=d["total"], used=d["used"], free=d["free"], folders=[]) | |
| now = int(time.time()) | |
| _cfg, map_path, hist_path = _paths() | |
| try: | |
| hist = json.loads(hist_path.read_text(encoding="utf-8")) | |
| except (OSError, ValueError): | |
| hist = {} | |
| hist = {k: [p for p in v if now - p[0] < DAY] for k, v in hist.items()} | |
| def point(key, disk, mem, load): | |
| hist.setdefault(key, []).append([now, round(disk, 1), round(mem, 1), round(load, 2)]) | |
| for mid, b in found.items(): | |
| if not b.get("unreachable"): | |
| point(mid, 100 * b["disk"]["used"] / b["disk"]["total"], 100 * b["mem"]["used"] / max(1, b["mem"]["total"]), | |
| 100 * (b.get("load") or [0])[0] / max(1, b.get("cpus") or 1)) | |
| point("laptop", 100 * laptop["disk"]["used"] / max(1, laptop["disk"]["total"]), | |
| 100 * laptop["mem"]["used"] / max(1, laptop["mem"]["total"]), laptop["cpu_pct"]) | |
| data = {"collected_at": now, "boxes": found, "laptop": laptop, "drive": drive, "history": hist} | |
| map_path.parent.mkdir(parents=True, exist_ok=True) | |
| for path, value in ((hist_path, hist), (map_path, data)): | |
| tmp = path.with_suffix(".tmp") | |
| tmp.write_text(json.dumps(value), encoding="utf-8") | |
| os.replace(tmp, path) | |
| return data | |
| def latest(): | |
| """the last map kept (None before the first reading) and the list it was drawn for""" | |
| _cfg, map_path, _h = _paths() | |
| try: | |
| data = json.loads(map_path.read_text(encoding="utf-8")) | |
| except (OSError, ValueError): | |
| data = None | |
| return {"meta": {m["id"]: m for m in config()}, "map": data} | |
| def summary(data=None): | |
| """the map in words, for a reply in the chat""" | |
| data = data or (latest().get("map") or {}) | |
| if not data: | |
| return "No machines have been read yet." | |
| meta = {m["id"]: m for m in config()} | |
| lines = [] | |
| lap = data.get("laptop") or {} | |
| if lap: | |
| lines.append("This computer (%s): %d%% CPU, memory %.0f%% used, disk %.0f%% used." % ( | |
| lap.get("hostname", ""), lap.get("cpu_pct", 0), 100 * lap["mem"]["used"] / max(1, lap["mem"]["total"]), | |
| 100 * lap["disk"]["used"] / max(1, lap["disk"]["total"]))) | |
| for mid, b in (data.get("boxes") or {}).items(): | |
| name = meta.get(mid, {}).get("name", mid) | |
| if b.get("unreachable"): | |
| lines.append("%s: not reached (%s)." % (name, b.get("why", "no answer"))) | |
| continue | |
| failed = b.get("failed") or [] | |
| lines.append("%s (%s): load %.2f on %d cores, memory %.0f%% used, disk %.0f%% used, %d services%s%s." % ( | |
| name, b.get("hostname", ""), (b.get("load") or [0])[0], b.get("cpus", 0), | |
| 100 * b["mem"]["used"] / max(1, b["mem"]["total"]), 100 * b["disk"]["used"] / max(1, b["disk"]["total"]), | |
| b.get("service_count", len(b.get("services") or [])), | |
| ("; failed: " + ", ".join(failed[:5])) if failed else "", | |
| "; reboot required" if b.get("reboot_required") else "")) | |
| return "\n".join(lines) | |