supercomputer-console 1.3.0__py3-none-any.whl

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.
supercomputer.py ADDED
@@ -0,0 +1,1156 @@
1
+ #!/usr/bin/env python3
2
+ """supercomputer — a retro mainframe operator console for your terminal.
3
+
4
+ Linux and macOS, Python 3.9+, standard library only. Read-only: it reads
5
+ system statistics and never changes anything. The blinking lamps are
6
+ decorative, but how many are lit follows real load: per-core CPU, per-disk
7
+ I/O, network traffic and the busiest processes.
8
+
9
+ https://github.com/rdubar/supercomputer
10
+ """
11
+ import argparse
12
+ import ctypes
13
+ import curses
14
+ import hashlib
15
+ import json
16
+ import math
17
+ import os
18
+ import platform
19
+ import random
20
+ import re
21
+ import shutil
22
+ import subprocess
23
+ import sys
24
+ import threading
25
+ import time
26
+ import urllib.error
27
+ import urllib.request
28
+ import uuid
29
+
30
+ __version__ = "1.3.0"
31
+ REPO_URL = "github.com/rdubar/supercomputer"
32
+ PYPI_NAME = "supercomputer-console"
33
+ PYPI_URL = f"https://pypi.org/pypi/{PYPI_NAME}/json"
34
+
35
+ THEMES = ["AMBER", "GREEN", "CYAN"]
36
+ CONFIG_DIR = os.path.expanduser("~/.config/supercomputer")
37
+ THEME_FILE = os.path.join(CONFIG_DIR, "theme")
38
+ SERVICES_FILE = os.path.join(CONFIG_DIR, "services")
39
+ IS_MAC = sys.platform == "darwin"
40
+
41
+ # Shown on the SUBSYSTEMS row only if installed (Linux: systemd units) or
42
+ # running (macOS: process names). Override with ~/.config/supercomputer/services.
43
+ LINUX_SERVICES = [("PLEX", "plexmediaserver"), ("JELLY", "jellyfin"), ("SMB", "smbd"),
44
+ ("XMIT", "transmission-daemon"), ("VNC", "wayvnc"), ("SSH", "ssh"),
45
+ ("TSNET", "tailscaled"), ("DOCKR", "docker"), ("NGINX", "nginx")]
46
+ MAC_SERVICES = [("PLEX", "Plex Media Server"), ("DOCKR", "com.docker.backend"),
47
+ ("TSNET", "Tailscale"), ("DBOX", "Dropbox"), ("SYNC", "Syncthing"),
48
+ ("OLLMA", "ollama")]
49
+
50
+
51
+ # ================================================================ helpers
52
+ def read(path, default=""):
53
+ try:
54
+ with open(path) as f:
55
+ return f.read()
56
+ except OSError:
57
+ return default
58
+
59
+
60
+ def run(*cmd, timeout=3):
61
+ try:
62
+ return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout
63
+ except (OSError, subprocess.SubprocessError):
64
+ return ""
65
+
66
+
67
+ def human(n):
68
+ for unit in ("B", "K", "M", "G", "T"):
69
+ if n < 1024 or unit == "T":
70
+ return f"{n:.0f}{unit}" if unit == "B" else f"{n:.1f}{unit}"
71
+ n /= 1024
72
+
73
+
74
+ def uptime_str(seconds):
75
+ s = int(seconds)
76
+ d, s = divmod(s, 86400)
77
+ h, s = divmod(s, 3600)
78
+ return f"{d}D {h:02d}H {s // 60:02d}M"
79
+
80
+
81
+ def disk_usage(path):
82
+ try:
83
+ st = os.statvfs(path)
84
+ total = st.f_blocks * st.f_frsize
85
+ free = st.f_bavail * st.f_frsize
86
+ return total, (1 - free / total) if total else 0
87
+ except OSError:
88
+ return 0, 0
89
+
90
+
91
+ def load_services(defaults):
92
+ """[(label, target)] from the services file, else the platform defaults."""
93
+ text = read(SERVICES_FILE)
94
+ if not text:
95
+ return defaults
96
+ out = []
97
+ for line in text.splitlines():
98
+ line = line.split("#", 1)[0].strip()
99
+ if line:
100
+ label, _, target = line.partition(" ")
101
+ out.append((label.upper()[:6], target.strip() or label))
102
+ return out
103
+
104
+
105
+ # ================================================================ Linux
106
+ class LinuxProbe:
107
+ def __init__(self):
108
+ self.disks = self._disks()
109
+ self.services = self._installed(load_services(LINUX_SERVICES))
110
+
111
+ def chip(self):
112
+ for part in read("/proc/device-tree/compatible").split("\0"):
113
+ m = re.match(r"brcm,(bcm\d+)", part)
114
+ if m:
115
+ return m.group(1).upper()
116
+ for line in read("/proc/cpuinfo").splitlines():
117
+ if line.lower().startswith("model name"):
118
+ return line.split(":", 1)[1].strip().upper()[:24]
119
+ return platform.machine().upper()
120
+
121
+ def cpu_times(self):
122
+ out = {}
123
+ for line in read("/proc/stat").splitlines():
124
+ if line.startswith("cpu") and line[3:4].isdigit():
125
+ parts = line.split()
126
+ vals = list(map(int, parts[1:]))
127
+ idle = vals[3] + (vals[4] if len(vals) > 4 else 0)
128
+ out[int(parts[0][3:])] = (sum(vals), idle)
129
+ return out
130
+
131
+ @staticmethod
132
+ def _whole_disk(dev):
133
+ name = os.path.basename(os.path.realpath(dev))
134
+ sys_path = os.path.realpath(f"/sys/class/block/{name}")
135
+ if os.path.exists(os.path.join(sys_path, "partition")):
136
+ return os.path.basename(os.path.dirname(sys_path))
137
+ return name
138
+
139
+ def _disks(self):
140
+ seen, disks = set(), []
141
+ for line in read("/proc/mounts").splitlines():
142
+ dev, mnt = line.split()[:2]
143
+ mnt = mnt.replace("\\040", " ")
144
+ if not re.match(r"/dev/(sd|nvme|mmcblk|vd|xvd|hd|mapper/)", dev):
145
+ continue
146
+ if mnt.startswith("/boot") or dev in seen:
147
+ continue
148
+ seen.add(dev)
149
+ label = "SYS" if mnt == "/" else os.path.basename(mnt).upper()[:6] or "DISK"
150
+ disks.append((label, self._whole_disk(dev), mnt, mnt))
151
+ disks.sort(key=lambda d: (d[2] != "/", d[2]))
152
+ return disks[:6]
153
+
154
+ def disk_bytes(self):
155
+ out = {}
156
+ for line in read("/proc/diskstats").splitlines():
157
+ p = line.split()
158
+ if len(p) >= 10:
159
+ out[p[2]] = (int(p[5]) * 512, int(p[9]) * 512)
160
+ return out
161
+
162
+ def net_bytes(self):
163
+ rx = tx = 0
164
+ for line in read("/proc/net/dev").splitlines()[2:]:
165
+ name, data = line.split(":", 1)
166
+ name = name.strip()
167
+ if re.match(r"(lo|docker|veth|br-|virbr|tailscale|tun|tap|wg)", name):
168
+ continue
169
+ v = data.split()
170
+ rx += int(v[0])
171
+ tx += int(v[8])
172
+ return rx, tx
173
+
174
+ def memory(self):
175
+ m = {}
176
+ for line in read("/proc/meminfo").splitlines():
177
+ k, v = line.split(":", 1)
178
+ m[k] = int(v.split()[0]) * 1024
179
+ return m.get("MemTotal", 1), m.get("MemAvailable", 0)
180
+
181
+ def temperature(self):
182
+ raw = read("/sys/class/thermal/thermal_zone0/temp").strip()
183
+ return int(raw) / 1000 if raw.isdigit() else None
184
+
185
+ def uptime(self):
186
+ try:
187
+ return float(read("/proc/uptime", "0").split()[0])
188
+ except ValueError:
189
+ return 0
190
+
191
+ def swap(self):
192
+ m = {}
193
+ for line in read("/proc/meminfo").splitlines():
194
+ k, v = line.split(":", 1)
195
+ m[k] = int(v.split()[0]) * 1024
196
+ total = m.get("SwapTotal", 0)
197
+ return total, total - m.get("SwapFree", 0)
198
+
199
+ def swap_pages(self):
200
+ n = 0
201
+ for line in read("/proc/vmstat").splitlines():
202
+ k, _, v = line.partition(" ")
203
+ if k in ("pswpin", "pswpout"):
204
+ n += int(v)
205
+ return n
206
+
207
+ def mem_pressure(self):
208
+ return None
209
+
210
+ def throttled(self):
211
+ """Raspberry Pi firmware throttle flags, or None elsewhere."""
212
+ if not shutil.which("vcgencmd"):
213
+ return None
214
+ m = re.search(r"throttled=(0x[0-9a-fA-F]+)", run("vcgencmd", "get_throttled"))
215
+ return int(m.group(1), 16) if m else None
216
+
217
+ def proc_cpu(self):
218
+ """{pid: (name, cpu seconds)}."""
219
+ tck = os.sysconf("SC_CLK_TCK")
220
+ out = {}
221
+ for pid in os.listdir("/proc"):
222
+ if not pid.isdigit():
223
+ continue
224
+ data = read(f"/proc/{pid}/stat")
225
+ try:
226
+ name = data[data.index("(") + 1: data.rindex(")")]
227
+ fields = data[data.rindex(")") + 2:].split()
228
+ out[int(pid)] = (name, (int(fields[11]) + int(fields[12])) / tck)
229
+ except (ValueError, IndexError):
230
+ continue
231
+ return out
232
+
233
+ def _installed(self, services):
234
+ if not services:
235
+ return []
236
+ out = run("systemctl", "show", "-p", "Id", "-p", "LoadState",
237
+ *[t for _, t in services])
238
+ missing = set()
239
+ for block in out.strip().split("\n\n"):
240
+ props = dict(l.split("=", 1) for l in block.splitlines() if "=" in l)
241
+ if props.get("LoadState") == "not-found":
242
+ missing.add(props.get("Id", "").replace(".service", ""))
243
+ return [(l, t) for l, t in services if t not in missing]
244
+
245
+ def service_states(self):
246
+ if not self.services:
247
+ return []
248
+ states = run("systemctl", "is-active", *[t for _, t in self.services]).split()
249
+ states += ["unknown"] * (len(self.services) - len(states))
250
+ return [(label, st == "active") for (label, _), st in zip(self.services, states)]
251
+
252
+
253
+ # ================================================================ macOS
254
+ class MacProbe:
255
+ def __init__(self):
256
+ self.lib = ctypes.CDLL("/usr/lib/libSystem.dylib")
257
+ self.lib.mach_host_self.restype = ctypes.c_uint
258
+ self.lib.host_processor_info.argtypes = [
259
+ ctypes.c_uint, ctypes.c_int, ctypes.POINTER(ctypes.c_uint),
260
+ ctypes.POINTER(ctypes.POINTER(ctypes.c_uint)), ctypes.POINTER(ctypes.c_uint)]
261
+ self.lib.vm_deallocate.argtypes = [ctypes.c_uint, ctypes.c_size_t, ctypes.c_size_t]
262
+ self.host = self.lib.mach_host_self()
263
+ self.task = ctypes.c_uint.in_dll(self.lib, "mach_task_self_").value
264
+ self.mem_total = int(run("sysctl", "-n", "hw.memsize").strip() or 1)
265
+ m = re.search(r"sec = (\d+)", run("sysctl", "-n", "kern.boottime"))
266
+ self.boot = int(m.group(1)) if m else time.time()
267
+ self.disks = self._disks()
268
+ wanted = load_services(MAC_SERVICES)
269
+ if read(SERVICES_FILE):
270
+ self.services = wanted
271
+ else: # defaults: only what is running now
272
+ names = {n for n, _ in self.proc_cpu().values()}
273
+ self.services = [(l, t) for l, t in wanted if t[:16] in names]
274
+
275
+ def chip(self):
276
+ return run("sysctl", "-n", "machdep.cpu.brand_string").strip().upper() or "APPLE SILICON"
277
+
278
+ def cpu_times(self):
279
+ count = ctypes.c_uint(0)
280
+ info = ctypes.POINTER(ctypes.c_uint)()
281
+ n = ctypes.c_uint(0)
282
+ # flavor 2 = PROCESSOR_CPU_LOAD_INFO: user, system, idle, nice ticks per CPU
283
+ if self.lib.host_processor_info(self.host, 2, ctypes.byref(count),
284
+ ctypes.byref(info), ctypes.byref(n)) != 0:
285
+ return {}
286
+ out = {}
287
+ for i in range(count.value):
288
+ user, system, idle, nice = (info[i * 4 + k] for k in range(4))
289
+ out[i] = (user + system + idle + nice, idle)
290
+ self.lib.vm_deallocate(self.task, ctypes.cast(info, ctypes.c_void_p).value,
291
+ n.value * ctypes.sizeof(ctypes.c_uint))
292
+ return out
293
+
294
+ def _disks(self):
295
+ disks = []
296
+ for line in run("mount").splitlines():
297
+ m = re.match(r"(/dev/(disk\d+)\S*) on (.+) \((.*)\)$", line)
298
+ if not m:
299
+ continue
300
+ _, whole, mnt, opts = m.groups()
301
+ if mnt == "/":
302
+ usage = "/System/Volumes/Data" if os.path.isdir("/System/Volumes/Data") else "/"
303
+ disks.append(("SYS", "disk0", mnt, usage)) # internal SSD
304
+ elif mnt.startswith("/Volumes/") and "nobrowse" not in opts:
305
+ label = os.path.basename(mnt).upper().replace(" ", "")[:6]
306
+ disks.append((label, whole, mnt, mnt))
307
+ return disks[:6]
308
+
309
+ def disk_bytes(self):
310
+ out, pending = {}, None
311
+ text = run("ioreg", "-r", "-c", "IOBlockStorageDriver", "-k", "Statistics",
312
+ "-d", "3", "-l", "-w", "0")
313
+ for line in text.splitlines():
314
+ if '"Statistics"' in line:
315
+ r = re.search(r'"Bytes \(Read\)"=(\d+)', line)
316
+ w = re.search(r'"Bytes \(Write\)"=(\d+)', line)
317
+ pending = (int(r.group(1)) if r else 0, int(w.group(1)) if w else 0)
318
+ elif '"BSD Name"' in line and pending:
319
+ m = re.search(r'"BSD Name" = "(disk\d+)"', line)
320
+ if m:
321
+ out[m.group(1)] = pending
322
+ pending = None
323
+ return out
324
+
325
+ def net_bytes(self):
326
+ rx = tx = 0
327
+ for line in run("netstat", "-ibn").splitlines()[1:]:
328
+ p = line.split()
329
+ if len(p) >= 10 and p[0].startswith("en") and "<Link#" in line:
330
+ rx += int(p[-5])
331
+ tx += int(p[-2])
332
+ return rx, tx
333
+
334
+ def memory(self):
335
+ text = run("vm_stat")
336
+ page = re.search(r"page size of (\d+)", text)
337
+ page = int(page.group(1)) if page else 4096
338
+ pages = dict((k.strip(), int(v.strip().rstrip("."))) for k, v in
339
+ (l.split(":", 1) for l in text.splitlines()[1:] if ":" in l)
340
+ if v.strip().rstrip(".").isdigit())
341
+ avail = sum(pages.get(k, 0) for k in
342
+ ("Pages free", "Pages inactive", "Pages speculative")) * page
343
+ return self.mem_total, avail
344
+
345
+ def temperature(self):
346
+ return None # needs root (powermetrics); not worth it
347
+
348
+ def uptime(self):
349
+ return time.time() - self.boot
350
+
351
+ def swap(self):
352
+ text = run("sysctl", "-n", "vm.swapusage")
353
+ vals = dict(re.findall(r"(total|used) = ([\d.]+)M", text))
354
+ return int(float(vals.get("total", 0)) * 2**20), int(float(vals.get("used", 0)) * 2**20)
355
+
356
+ def swap_pages(self):
357
+ m = re.findall(r"Swap(?:ins|outs):\s+(\d+)", run("vm_stat"))
358
+ return sum(int(x) for x in m)
359
+
360
+ def mem_pressure(self):
361
+ """macOS memory pressure: 1 normal, 2 warning, 4 critical."""
362
+ v = run("sysctl", "-n", "kern.memorystatus_vm_pressure_level").strip()
363
+ return int(v) if v.isdigit() else None
364
+
365
+ def throttled(self):
366
+ return None
367
+
368
+ def proc_cpu(self):
369
+ out = {}
370
+ for line in run("ps", "-A", "-o", "pid=,time=,comm=").splitlines():
371
+ p = line.split(None, 2)
372
+ if len(p) < 3:
373
+ continue
374
+ days, t = 0, p[1] # [dd-][hh:]mm:ss.ss
375
+ if "-" in t:
376
+ d, t = t.split("-", 1)
377
+ days = int(d)
378
+ secs = 0.0
379
+ try:
380
+ for part in t.split(":"):
381
+ secs = secs * 60 + float(part)
382
+ except ValueError:
383
+ continue
384
+ out[int(p[0])] = (os.path.basename(p[2])[:16], days * 86400 + secs)
385
+ return out
386
+
387
+ def service_states(self):
388
+ if not self.services:
389
+ return []
390
+ names = {n for n, _ in self.proc_cpu().values()}
391
+ return [(label, target[:16] in names) for label, target in self.services]
392
+
393
+
394
+ def make_probe():
395
+ return MacProbe() if IS_MAC else LinuxProbe()
396
+
397
+
398
+ # ================================================================ strain
399
+ WARN, CRIT = 1, 2
400
+
401
+
402
+ def assess(probe, swap_rate=None, cpu_pinned=False):
403
+ """Current alarms as [(level, key, text)]. Cheap: a few reads, no sleeping.
404
+
405
+ swap_rate (pages/s) and cpu_pinned need a time window, so only callers
406
+ that sample over time (the console, --check) pass them.
407
+ """
408
+ alarms = []
409
+
410
+ def add(level, key, text):
411
+ alarms.append((level, key, text))
412
+
413
+ ncores = len(probe.cpu_times()) or os.cpu_count() or 1
414
+ load5 = os.getloadavg()[1] / ncores
415
+ if load5 > 3:
416
+ add(CRIT, "load", f"JOB QUEUE OVERLOADED: LOAD {load5:.1f}x CAPACITY")
417
+ elif load5 > 1.5:
418
+ add(WARN, "load", f"JOB QUEUE BACKLOG: LOAD {load5:.1f}x CAPACITY")
419
+ if cpu_pinned:
420
+ add(WARN, "cpu", "ALL PROCESSORS SATURATED FOR 30 S")
421
+
422
+ total, avail = probe.memory()
423
+ pressure = probe.mem_pressure()
424
+ if pressure is not None:
425
+ if pressure >= 4:
426
+ add(CRIT, "mem", "CORE STORAGE PRESSURE CRITICAL")
427
+ elif pressure >= 2:
428
+ add(WARN, "mem", "CORE STORAGE PRESSURE ELEVATED")
429
+ elif total:
430
+ free = avail / total
431
+ if free < 0.05:
432
+ add(CRIT, "mem", f"CORE STORAGE EXHAUSTED: {free * 100:.0f}% FREE")
433
+ elif free < 0.10:
434
+ add(WARN, "mem", f"CORE STORAGE LOW: {free * 100:.0f}% FREE")
435
+
436
+ stotal, sused = probe.swap()
437
+ if stotal and sused / stotal > 0.8:
438
+ add(WARN, "swap", f"DRUM STORAGE {sused / stotal * 100:.0f}% COMMITTED")
439
+ if swap_rate is not None and swap_rate > 250:
440
+ add(WARN, "paging", f"HEAVY PAGING TO DRUM: {swap_rate:.0f} PAGES/S")
441
+
442
+ t = probe.temperature()
443
+ if t is not None:
444
+ if t >= 85:
445
+ add(CRIT, "temp", f"COOLANT CRITICAL: CORE {t:.0f} C")
446
+ elif t >= 80:
447
+ add(WARN, "temp", f"COOLANT HOT: CORE {t:.0f} C")
448
+
449
+ th = probe.throttled()
450
+ if th:
451
+ if th & 0x1:
452
+ add(CRIT, "volt", "POWER BROWNOUT: UNDER-VOLTAGE NOW")
453
+ elif th & 0x10000:
454
+ add(WARN, "volt", "BROWNOUT RECORDED SINCE BOOT")
455
+ if th & 0x6:
456
+ add(WARN, "throttle", "PROCESSORS THROTTLED BY FIRMWARE")
457
+ elif th & 0x8:
458
+ add(WARN, "throttle", "SOFT TEMPERATURE LIMIT ACTIVE")
459
+
460
+ for label, _, _, path in probe.disks:
461
+ _, frac = disk_usage(path)
462
+ if frac >= 0.98:
463
+ add(CRIT, f"disk:{label}", f"STORAGE UNIT {label} {frac * 100:.0f}% FULL")
464
+ elif frac >= 0.95:
465
+ add(WARN, f"disk:{label}", f"STORAGE UNIT {label} {frac * 100:.0f}% FULL")
466
+
467
+ for label, ok in probe.service_states():
468
+ if not ok:
469
+ add(WARN, f"svc:{label}", f"SUBSYSTEM {label} OFFLINE")
470
+
471
+ alarms.sort(key=lambda a: -a[0])
472
+ return alarms
473
+
474
+
475
+ # ================================================================ demo
476
+ DEMO_SCRIPT = [ # (seconds, alarms) — replayed in a loop by --demo
477
+ (8, []),
478
+ (10, [(WARN, "cpu", "ALL PROCESSORS SATURATED FOR 30 S")]),
479
+ (10, [(WARN, "cpu", "ALL PROCESSORS SATURATED FOR 30 S"),
480
+ (WARN, "temp", "COOLANT HOT: CORE 82 C")]),
481
+ (10, [(CRIT, "temp", "COOLANT CRITICAL: CORE 86 C"),
482
+ (WARN, "throttle", "PROCESSORS THROTTLED BY FIRMWARE")]),
483
+ (8, [(CRIT, "volt", "POWER BROWNOUT: UNDER-VOLTAGE NOW")]),
484
+ (8, [(WARN, "mem", "CORE STORAGE LOW: 7% FREE"),
485
+ (WARN, "paging", "HEAVY PAGING TO DRUM: 900 PAGES/S")]),
486
+ (8, [(WARN, "disk:SYS", "STORAGE UNIT SYS 96% FULL"),
487
+ (WARN, "svc:PLEX", "SUBSYSTEM PLEX OFFLINE")]),
488
+ ]
489
+
490
+
491
+ def demo_state(elapsed):
492
+ """(alarms, load level 0..1) for the demo at a given time."""
493
+ total = sum(d for d, _ in DEMO_SCRIPT)
494
+ t = elapsed % total
495
+ for i, (dur, alarms) in enumerate(DEMO_SCRIPT):
496
+ if t < dur:
497
+ load = 0.15 if i == 0 else (0.98 if i in (1, 2, 3) else 0.6)
498
+ return alarms, load
499
+ t -= dur
500
+ return [], 0.1
501
+
502
+
503
+ # ================================================================ sampler
504
+ class Sampler:
505
+ def __init__(self, probe):
506
+ self.p = probe
507
+ self.disks = probe.disks
508
+ self.prev_cpu = probe.cpu_times()
509
+ self.prev_disk = probe.disk_bytes()
510
+ self.prev_net = probe.net_bytes()
511
+ self.prev_t = time.monotonic()
512
+ self.cpu = {k: 0.0 for k in self.prev_cpu}
513
+ self.dio = {}
514
+ self.net = (0.0, 0.0)
515
+ self.services = probe.service_states()
516
+ self.usage = {d[3]: disk_usage(d[3]) for d in self.disks}
517
+ self.mem = probe.memory()
518
+ self.temp = probe.temperature()
519
+ self.prev_proc = probe.proc_cpu()
520
+ self.prev_proc_t = time.monotonic()
521
+ self.jobs = []
522
+ self.prev_swap = (probe.swap_pages(), time.monotonic())
523
+ self.swap_rate = 0.0
524
+ self.hot_secs = 0
525
+ self.alarms = assess(probe)
526
+ self.tick = 0
527
+ self.demo = False
528
+ self.demo_start = time.monotonic()
529
+
530
+ def update(self):
531
+ now = time.monotonic()
532
+ dt = max(now - self.prev_t, 1e-3)
533
+ cur = self.p.cpu_times()
534
+ for k, (tot, idle) in cur.items():
535
+ pt, pi = self.prev_cpu.get(k, (tot, idle))
536
+ dtot = tot - pt
537
+ self.cpu[k] = 0.0 if dtot <= 0 else max(0.0, min(1.0, 1 - (idle - pi) / dtot))
538
+ self.prev_cpu = cur
539
+ ds = self.p.disk_bytes()
540
+ for key, (r, w) in ds.items():
541
+ pr, pw = self.prev_disk.get(key, (r, w))
542
+ self.dio[key] = (max(0, r - pr) / dt, max(0, w - pw) / dt)
543
+ self.prev_disk = ds
544
+ rx, tx = self.p.net_bytes()
545
+ prx, ptx = self.prev_net
546
+ self.net = (max(0, rx - prx) / dt, max(0, tx - ptx) / dt)
547
+ self.prev_net = (rx, tx)
548
+ self.prev_t = now
549
+ self.mem = self.p.memory()
550
+ self.temp = self.p.temperature()
551
+ self.tick += 1
552
+ if self.tick % 3 == 0:
553
+ self.update_jobs()
554
+ avg = sum(self.cpu.values()) / max(len(self.cpu), 1)
555
+ self.hot_secs = self.hot_secs + 1 if avg > 0.95 else 0
556
+ if self.tick % 5 == 0:
557
+ self.services = self.p.service_states()
558
+ pages, pt = self.p.swap_pages(), time.monotonic()
559
+ self.swap_rate = max(0, pages - self.prev_swap[0]) / max(pt - self.prev_swap[1], 1e-3)
560
+ self.prev_swap = (pages, pt)
561
+ self.alarms = assess(self.p, self.swap_rate, self.hot_secs >= 30)
562
+ if self.demo:
563
+ self.alarms, load = demo_state(now - self.demo_start)
564
+ for k in self.cpu:
565
+ self.cpu[k] = max(0.0, min(1.0, load + random.uniform(-0.08, 0.04)))
566
+ for _, key, _, _ in self.disks[:2]:
567
+ self.dio[key] = (load * random.uniform(20e6, 160e6), load * random.uniform(1e6, 40e6))
568
+ self.net = (load * random.uniform(5e6, 40e6), load * random.uniform(1e6, 10e6))
569
+ self.temp = 60 + 27 * load if self.temp is not None else None
570
+ if self.tick % 30 == 0:
571
+ self.usage = {d[3]: disk_usage(d[3]) for d in self.disks}
572
+
573
+ def update_jobs(self):
574
+ now = time.monotonic()
575
+ dt = max(now - self.prev_proc_t, 1e-3)
576
+ cur = self.p.proc_cpu()
577
+ jobs = []
578
+ for pid, (name, secs) in cur.items():
579
+ prev = self.prev_proc.get(pid)
580
+ if prev and prev[0] == name:
581
+ pct = (secs - prev[1]) / dt * 100
582
+ if pct >= 0.5:
583
+ jobs.append((pid, name, pct))
584
+ jobs.sort(key=lambda j: -j[2])
585
+ self.jobs = jobs[:8]
586
+ self.prev_proc, self.prev_proc_t = cur, now
587
+
588
+
589
+ def rate_level(bps, full=150e6):
590
+ """Map bytes/s to 0..1 on a log scale so small activity still shows."""
591
+ if bps <= 0:
592
+ return 0.0
593
+ return min(1.0, math.log10(1 + bps) / math.log10(1 + full))
594
+
595
+
596
+ # ================================================================ themes
597
+ def load_theme(argv_theme):
598
+ if argv_theme:
599
+ return THEMES.index(argv_theme.upper())
600
+ try:
601
+ return THEMES.index(read(THEME_FILE).strip().upper())
602
+ except ValueError:
603
+ return 0
604
+
605
+
606
+ def save_theme(i):
607
+ try:
608
+ os.makedirs(CONFIG_DIR, exist_ok=True)
609
+ with open(THEME_FILE, "w") as f:
610
+ f.write(THEMES[i] + "\n")
611
+ except OSError:
612
+ pass
613
+
614
+
615
+ def identity(probe):
616
+ host = platform.node().split(".")[0].upper() or "MAINFRAME"
617
+ serial = hashlib.sha1(str(uuid.getnode()).encode()).hexdigest()[:12].upper()
618
+ return host, probe.chip(), serial
619
+
620
+
621
+ # ================================================================ panel
622
+ class Panel:
623
+ def __init__(self, scr, probe, theme, bell=False, demo=False):
624
+ self.scr = scr
625
+ self.theme = theme
626
+ self.paused = False
627
+ self.overlay = None # "help" | "credits"
628
+ self.s = Sampler(probe)
629
+ self.s.demo = demo
630
+ self.host, self.chip, self.serial = identity(probe)
631
+ self.log = []
632
+ self.last_log = 0
633
+ self.lamps = {}
634
+ self.known_alarms = {}
635
+ self.bell = bell
636
+ self.frame = 0
637
+ curses.curs_set(0)
638
+ scr.nodelay(True)
639
+ curses.start_color()
640
+ self.set_theme()
641
+ self.say(f"{self.host} COLD START COMPLETE. ALL UNITS NOMINAL.")
642
+ self.say("PRESS H FOR OPERATOR CONTROLS, A FOR CREDITS.")
643
+ if demo:
644
+ self.say("DEMONSTRATION MODE: SIMULATED LOAD AND ALARMS. NOTHING IS WRONG.")
645
+
646
+ def set_theme(self):
647
+ bright = (curses.COLOR_YELLOW, curses.COLOR_GREEN, curses.COLOR_CYAN)[self.theme]
648
+ black = curses.COLOR_BLACK
649
+ curses.init_pair(1, bright, black)
650
+ curses.init_pair(2, curses.COLOR_RED, black)
651
+ curses.init_pair(3, curses.COLOR_WHITE, black)
652
+ curses.init_pair(4, black, bright)
653
+ self.MAIN = curses.color_pair(1) | curses.A_BOLD
654
+ self.DIM = curses.color_pair(1) | curses.A_DIM
655
+ self.WARN = curses.color_pair(2) | curses.A_BOLD
656
+ self.LABEL = curses.color_pair(3)
657
+ self.HEAD = curses.color_pair(4) | curses.A_BOLD
658
+ self.scr.bkgd(" ", curses.color_pair(1))
659
+
660
+ def say(self, msg):
661
+ self.log.append(f"{time.strftime('%H:%M:%S')} {msg}")
662
+ self.log = self.log[-50:]
663
+
664
+ def put(self, y, x, text, attr=0):
665
+ h, w = self.scr.getmaxyx()
666
+ if 0 <= y < h and 0 <= x < w:
667
+ try:
668
+ self.scr.addstr(y, x, text[: max(0, w - x - 1)], attr)
669
+ except curses.error:
670
+ pass
671
+
672
+ def lamp_row(self, y, x, key, n, level):
673
+ """Row of n lamps; about level*n lit, reshuffled each refresh."""
674
+ bits = [random.random() < level * (0.6 + 0.8 * random.random()) for _ in range(n)]
675
+ self.lamps[key] = bits
676
+ for i, on in enumerate(bits):
677
+ self.put(y, x, "●" if on else "·", self.MAIN if on else self.DIM)
678
+ x += 2 + (1 if (i + 1) % 4 == 0 else 0)
679
+ return x
680
+
681
+ def bar(self, y, x, width, frac, warn_at=0.9):
682
+ filled = int(round(frac * width))
683
+ attr = self.WARN if frac >= warn_at else self.MAIN
684
+ self.put(y, x, " " * filled, attr | curses.A_REVERSE)
685
+ self.put(y, x + filled, "·" * (width - filled), self.DIM)
686
+
687
+ def box(self, y, x, h, w, title):
688
+ self.put(y, x, "╔" + "═" * (w - 2) + "╗", self.DIM)
689
+ for i in range(1, h - 1):
690
+ self.put(y + i, x, "║", self.DIM)
691
+ self.put(y + i, x + w - 1, "║", self.DIM)
692
+ self.put(y + h - 1, x, "╚" + "═" * (w - 2) + "╝", self.DIM)
693
+ self.put(y, x + 2, f" {title} ", self.MAIN)
694
+
695
+ # ------------------------------------------------------------ events
696
+ def alarm_events(self):
697
+ current = {key: (lvl, text) for lvl, key, text in self.s.alarms}
698
+ for key, (lvl, text) in current.items():
699
+ if key not in self.known_alarms:
700
+ self.say(f"*** {'CRITICAL' if lvl == CRIT else 'ALARM'}: {text} ***")
701
+ if self.bell:
702
+ curses.beep()
703
+ for key, (_, text) in self.known_alarms.items():
704
+ if key not in current:
705
+ self.say(f"ALARM CLEARED: {text}")
706
+ self.known_alarms = current
707
+
708
+ def events(self):
709
+ s = self.s
710
+ self.alarm_events()
711
+ if time.monotonic() - self.last_log < 4:
712
+ return
713
+ msgs = []
714
+ for label, key, _, _ in s.disks:
715
+ r, w = s.dio.get(key, (0, 0))
716
+ if r + w > 5e6:
717
+ msgs.append(f"STORAGE UNIT {label}: CHANNEL ACTIVE R {human(r)}/S W {human(w)}/S")
718
+ avg = sum(s.cpu.values()) / max(len(s.cpu), 1)
719
+ if avg > 0.6:
720
+ msgs.append(f"VECTOR PIPELINE AT {avg * 100:.0f}% — ALL PROCESSORS ENGAGED")
721
+ if s.net[0] + s.net[1] > 2e6:
722
+ msgs.append(f"DATA LINK: RX {human(s.net[0])}/S TX {human(s.net[1])}/S")
723
+ if not msgs and random.random() < 0.15:
724
+ coolant = f"CORE {s.temp:.1f} C." if s.temp is not None else "SENSORS SEALED."
725
+ msgs.append(random.choice([
726
+ "PARITY CHECK OK. CORE MEMORY CONSISTENT.",
727
+ "SCHEDULER IDLE. AWAITING JOB SUBMISSION.",
728
+ f"COOLANT LOOP NOMINAL. {coolant}",
729
+ "TAPE LIBRARY STANDING BY.",
730
+ "OPERATOR CONSOLE ONLINE.",
731
+ "PUNCH CARD READER EMPTY. INSERT DECK.",
732
+ ]))
733
+ for m in msgs[:2]:
734
+ self.say(m)
735
+ if msgs:
736
+ self.last_log = time.monotonic()
737
+
738
+ # ------------------------------------------------------------ draw
739
+ def draw(self):
740
+ s = self.s
741
+ scr = self.scr
742
+ scr.erase()
743
+ h, w = scr.getmaxyx()
744
+ if h < 24 or w < 80:
745
+ self.put(0, 0, "ENLARGE OPERATOR CONSOLE TO 80x24", self.WARN)
746
+ scr.refresh()
747
+ return
748
+ W = min(w - 1, 100)
749
+ title = f" {self.host} · {self.chip} VECTOR PROCESSING SYSTEM · SERIAL {self.serial} "
750
+ self.put(0, 0, title.center(W)[:W], self.HEAD)
751
+
752
+ tm, ta = s.mem
753
+ self.put(1, 1, f"UPTIME {uptime_str(self.s.p.uptime())}", self.MAIN)
754
+ self.put(1, 24, f"CORE MEMORY {tm // 2**20:,} MW", self.MAIN)
755
+ self.put(1, 48, "COOLANT ", self.LABEL)
756
+ if s.temp is None:
757
+ self.put(1, 56, " SEALED", self.DIM)
758
+ else:
759
+ self.put(1, 56, f"{s.temp:5.1f} C", self.WARN if s.temp > 75 else self.MAIN)
760
+ self.put(1, W - 9, time.strftime("%H:%M:%S"), self.MAIN)
761
+ self.frame += 1
762
+ if s.alarms:
763
+ worst = s.alarms[0][0]
764
+ flash = self.frame % 4 < 2 or worst == WARN
765
+ tag = " ▲ CRITICAL " if worst == CRIT else " ▲ ALARM "
766
+ self.put(2, 1, tag, (self.WARN | curses.A_REVERSE) if flash else self.WARN)
767
+ self.put(2, len(tag) + 2, " · ".join(a[2] for a in s.alarms)[: W - len(tag) - 3], self.WARN)
768
+ else:
769
+ self.put(2, 1, "ALARMS: NONE · ALL UNITS NOMINAL", self.DIM)
770
+
771
+ # Processors: one column up to 8 cores, two columns beyond that
772
+ y = 3
773
+ cpus = sorted(s.cpu)
774
+ if len(cpus) > 16: # fold big machines into 16 groups
775
+ groups = [cpus[i::16] for i in range(16)]
776
+ levels = [sum(s.cpu[c] for c in g) / len(g) for g in groups]
777
+ names = [f"G{i:<2}" for i in range(16)]
778
+ else:
779
+ levels = [s.cpu[c] for c in cpus]
780
+ names = [f"{c:<2}" for c in cpus]
781
+ cols = 1 if len(levels) <= 8 else 2
782
+ rows = math.ceil(len(levels) / cols)
783
+ lamps = 24 if cols == 1 else 12
784
+ self.box(y, 0, rows + 2, W, "CENTRAL PROCESSORS")
785
+ for i, (name, lvl) in enumerate(zip(names, levels)):
786
+ row, col = y + 1 + i % rows, i // rows
787
+ x = 2 + col * (W // 2 - 1)
788
+ self.put(row, x, f"CPU {name}", self.LABEL)
789
+ end = self.lamp_row(row, x + 8, f"cpu{i}", lamps, lvl)
790
+ self.put(row, end + 1, f"{lvl * 100:5.1f}%", self.WARN if lvl > 0.9 else self.MAIN)
791
+ y += rows + 2
792
+
793
+ # Memory
794
+ used = 1 - ta / tm
795
+ self.box(y, 0, 3, W, "CORE STORAGE")
796
+ self.put(y + 1, 2, "MEM", self.LABEL)
797
+ self.bar(y + 1, 9, 40, used)
798
+ self.put(y + 1, 51, f"{used * 100:4.1f}% {human(tm - ta)} OF {human(tm)}", self.MAIN)
799
+ y += 3
800
+
801
+ # Storage
802
+ if s.disks:
803
+ self.box(y, 0, len(s.disks) + 2, W, "MASS STORAGE UNITS")
804
+ for i, (label, key, _, usage_path) in enumerate(s.disks):
805
+ row = y + 1 + i
806
+ r, wr = s.dio.get(key, (0, 0))
807
+ total, frac = s.usage.get(usage_path, (0, 0))
808
+ self.put(row, 2, f"{label:6}", self.LABEL)
809
+ self.put(row, 9, "R", self.LABEL)
810
+ self.lamp_row(row, 11, f"{key}r{i}", 4, rate_level(r))
811
+ self.put(row, 21, "W", self.LABEL)
812
+ self.lamp_row(row, 23, f"{key}w{i}", 4, rate_level(wr))
813
+ self.bar(row, 34, 20, frac)
814
+ self.put(row, 56, f"{frac * 100:3.0f}% OF {human(total):>6}", self.MAIN)
815
+ self.put(row, 73, f"{human(r + wr):>7}/S", self.MAIN if r + wr > 1e6 else self.DIM)
816
+ y += len(s.disks) + 2
817
+
818
+ # Network + subsystems
819
+ self.box(y, 0, 3, W, "DATA LINK / SUBSYSTEMS")
820
+ rx, tx = s.net
821
+ self.put(y + 1, 2, "RX", self.LABEL)
822
+ self.lamp_row(y + 1, 5, "rx", 4, rate_level(rx, 100e6))
823
+ self.put(y + 1, 14, "TX", self.LABEL)
824
+ self.lamp_row(y + 1, 17, "tx", 4, rate_level(tx, 100e6))
825
+ x = 28
826
+ for label, ok in s.services:
827
+ if x + len(label) + 3 > W - 2:
828
+ break
829
+ self.put(y + 1, x, "■" if ok else "□", self.MAIN if ok else self.WARN)
830
+ self.put(y + 1, x + 2, label, self.MAIN if ok else self.WARN)
831
+ x += len(label) + 4
832
+ if not s.services:
833
+ self.put(y + 1, x, f"{human(rx)}/S IN {human(tx)}/S OUT", self.DIM)
834
+ y += 3
835
+
836
+ # Active jobs, only if 3 log lines still fit
837
+ njobs = min(5, h - y - 3 - 2 - 5)
838
+ if njobs > 0:
839
+ self.box(y, 0, njobs + 2, W, "ACTIVE JOBS")
840
+ jobs = s.jobs[:njobs]
841
+ if not jobs:
842
+ self.put(y + 1, 2, "NO JOBS IN EXECUTION" if s.tick >= 3 else "SCANNING JOB TABLE...",
843
+ self.DIM)
844
+ for i, (pid, name, pct) in enumerate(jobs):
845
+ row = y + 1 + i
846
+ self.put(row, 2, f"JOB {pid:>7}", self.LABEL)
847
+ self.put(row, 15, f"{name.upper()[:16]:16}", self.MAIN)
848
+ end = self.lamp_row(row, 33, f"job{i}", 16, min(pct / 100, 1.0))
849
+ self.put(row, end + 1, f"{pct:6.1f}%", self.WARN if pct > 90 else self.MAIN)
850
+ y += njobs + 2
851
+
852
+ # Teletype log
853
+ room = h - y - 3
854
+ if room > 0:
855
+ self.box(y, 0, room + 2, W, "OPERATOR LOG")
856
+ for i, line in enumerate(self.log[-room:]):
857
+ self.put(y + 1 + i, 2, line[: W - 4], self.WARN if "***" in line else self.MAIN)
858
+
859
+ footer = f"[H] HELP [A] CREDITS [C] PHOSPHOR: {THEMES[self.theme]} [Q] HALT"
860
+ if self.paused:
861
+ footer += " *** FROZEN — [P] RESUMES ***"
862
+ elif s.demo:
863
+ footer += " *** DEMO: SIMULATED ***"
864
+ self.put(h - 1, 0, footer, self.WARN if self.paused else self.DIM)
865
+ ver = f"SUPERCOMPUTER V{__version__}"
866
+ if len(footer) + len(ver) + 2 < W:
867
+ self.put(h - 1, W - len(ver), ver, self.DIM)
868
+ if self.overlay == "help":
869
+ self.card(h, W, "OPERATOR CONTROLS", [
870
+ "C CHANGE PHOSPHOR: AMBER / GREEN / CYAN",
871
+ "P SPACE FREEZE / RESUME THE PANEL",
872
+ "H ? THIS CARD",
873
+ "A CREDITS",
874
+ "Q HALT CONSOLE (ESC CLOSES A CARD)",
875
+ "",
876
+ "LAMP DENSITY FOLLOWS REAL LOAD:",
877
+ " CENTRAL PROCESSORS PER-CORE CPU",
878
+ " MASS STORAGE READ / WRITE PER DISK",
879
+ " DATA LINK NETWORK IN / OUT",
880
+ " ACTIVE JOBS BUSIEST PROCESSES (3 S)",
881
+ "",
882
+ "ALARM LINE (UNDER THE HEADER) TURNS RED UNDER",
883
+ "STRAIN: MEMORY, LOAD, HEAT, POWER, DISKS, SERVICES.",
884
+ "COLOUR IS REMEMBERED. START WITH --GREEN ETC.",
885
+ ])
886
+ elif self.overlay == "credits":
887
+ self.card(h, W, f"SUPERCOMPUTER V{__version__}", [
888
+ "A RETRO MAINFRAME OPERATOR CONSOLE",
889
+ "",
890
+ "CONCEIVED BY ........ ROGER DUBAR",
891
+ "BUILT BY ............ CLAUDE CODE (ANTHROPIC)",
892
+ f"RUNNING ON .......... {self.host[:22]}",
893
+ f"PROCESSOR ........... {self.chip[:22]}",
894
+ "",
895
+ REPO_URL.upper(),
896
+ "MIT LICENSE",
897
+ "",
898
+ "NO MAINFRAMES WERE HARMED IN THE MAKING",
899
+ "OF THIS CONSOLE.",
900
+ ])
901
+ scr.refresh()
902
+
903
+ def card(self, h, W, title, lines):
904
+ bw = max(max(len(l) for l in lines), len(title)) + 8
905
+ bh = len(lines) + 4
906
+ y0, x0 = max(0, (h - bh) // 2), max(0, (W - bw) // 2)
907
+ for i in range(bh):
908
+ self.put(y0 + i, x0, " " * bw, self.MAIN)
909
+ self.box(y0, x0, bh, bw, title)
910
+ for i, l in enumerate(lines):
911
+ attr = self.MAIN | curses.A_UNDERLINE if l == REPO_URL.upper() else self.LABEL
912
+ self.put(y0 + 2 + i, x0 + 4, l, attr)
913
+
914
+ def run(self):
915
+ next_sample = time.monotonic() + 1
916
+ while True:
917
+ key = self.scr.getch()
918
+ if key == 27 and self.overlay:
919
+ self.overlay = None
920
+ elif key in (ord("q"), ord("Q"), 27):
921
+ return
922
+ elif key in (ord("c"), ord("C")):
923
+ self.theme = (self.theme + 1) % len(THEMES)
924
+ self.set_theme()
925
+ save_theme(self.theme)
926
+ elif key in (ord("h"), ord("H"), ord("?")):
927
+ self.overlay = None if self.overlay == "help" else "help"
928
+ elif key in (ord("a"), ord("A")):
929
+ self.overlay = None if self.overlay == "credits" else "credits"
930
+ elif key in (ord("p"), ord("P"), ord(" ")):
931
+ self.paused = not self.paused
932
+ self.say("PANEL FROZEN BY OPERATOR." if self.paused else "PANEL RESUMED.")
933
+ if time.monotonic() >= next_sample:
934
+ self.s.update()
935
+ self.events()
936
+ next_sample = max(next_sample + 1, time.monotonic())
937
+ if not self.paused or key != -1:
938
+ self.draw()
939
+ time.sleep(0.2)
940
+
941
+
942
+ # ================================================================ banner
943
+ def banner(probe):
944
+ A, D, R = "\033[1;33m", "\033[2;33m", "\033[0m"
945
+ host, chip, _ = identity(probe)
946
+ tm, ta = probe.memory()
947
+ load = " ".join(f"{x:.2f}" for x in os.getloadavg())
948
+ t = probe.temperature()
949
+ coolant = f" COOLANT {t:.1f} C" if t is not None else ""
950
+ svc = " ".join(f"{'■' if ok else '□'} {n}" for n, ok in probe.service_states())
951
+ lamps = "".join(random.choice("●·") for _ in range(32))
952
+ print("\n".join([
953
+ f"{D}╔{'═' * 62}╗{R}",
954
+ f"{D}║{R}{A}{(' ' + host + ' · ' + chip + ' VECTOR PROCESSING SYSTEM')[:62].ljust(62)}{R}{D}║{R}",
955
+ f"{D}║{R}{A}{(' ' + lamps).ljust(48)}{R}{D}{('V' + __version__).rjust(12)} ║{R}",
956
+ f"{D}╚{'═' * 62}╝{R}",
957
+ f"{A} UPTIME {uptime_str(probe.uptime())} LOAD {load}{coolant}{R}",
958
+ f"{A} CORE MEMORY {(tm - ta) // 2**20:,} / {tm // 2**20:,} MW {svc}{R}",
959
+ ] + alarm_lines(assess(probe), A, R) + [
960
+ f"{D} TYPE 'supercomputer' FOR THE OPERATOR CONSOLE{R}",
961
+ "",
962
+ ]))
963
+
964
+
965
+ def alarm_lines(alarms, ok_colour, reset):
966
+ red = "\033[1;31m"
967
+ if not alarms:
968
+ return [f"{ok_colour} ■ ALARMS: NONE · ALL UNITS NOMINAL{reset}"]
969
+ return [f"{red} ▲ {'CRITICAL' if lvl == CRIT else 'ALARM '} {text}{reset}" for lvl, _, text in alarms]
970
+
971
+
972
+ # ================================================================ check
973
+ STATE_FILE = os.path.expanduser("~/.cache/supercomputer/alarms")
974
+
975
+
976
+ def notify(title, message):
977
+ if IS_MAC:
978
+ esc = message.replace("\\", "").replace('"', "'")
979
+ run("osascript", "-e", f'display notification "{esc}" with title "{title}"')
980
+ elif shutil.which("notify-send"):
981
+ run("notify-send", "-a", "supercomputer", title, message)
982
+
983
+
984
+ def check(probe, do_notify=False, quiet=False):
985
+ """One-shot health check. Exit code 0 nominal, 1 alarm, 2 critical."""
986
+ swap0, cpu0 = probe.swap_pages(), probe.cpu_times()
987
+ time.sleep(1)
988
+ swap_rate = max(0, probe.swap_pages() - swap0)
989
+ cpu1 = probe.cpu_times()
990
+ busy = [1 - (cpu1[k][1] - cpu0[k][1]) / max(cpu1[k][0] - cpu0[k][0], 1) for k in cpu1 if k in cpu0]
991
+ alarms = assess(probe, swap_rate, bool(busy) and min(busy) > 0.98)
992
+ host = identity(probe)[0]
993
+ keys = sorted(k for _, k, _ in alarms)
994
+ before = read(STATE_FILE).split()
995
+ changed = keys != before
996
+ # --quiet: silent when nominal; with --notify, also silent while unchanged
997
+ if not quiet or (alarms and not do_notify) or (do_notify and changed):
998
+ A, R = ("\033[1;33m", "\033[0m") if sys.stdout.isatty() else ("", "")
999
+ lines = alarm_lines(alarms, A, R)
1000
+ if not sys.stdout.isatty():
1001
+ lines = [re.sub(r"\033\[[0-9;]*m", "", l) for l in lines]
1002
+ print(f"{host} · SUPERCOMPUTER V{__version__} STATUS CHECK {time.strftime('%Y-%m-%d %H:%M:%S')}")
1003
+ print("\n".join(lines))
1004
+ if do_notify:
1005
+ if changed:
1006
+ new = [t for _, k, t in alarms if k not in before]
1007
+ if new:
1008
+ notify(f"{host} SUPERCOMPUTER ALARM", "; ".join(new))
1009
+ elif not alarms:
1010
+ notify(f"{host} SUPERCOMPUTER", "ALL ALARMS CLEARED. ALL UNITS NOMINAL.")
1011
+ try:
1012
+ os.makedirs(os.path.dirname(STATE_FILE), exist_ok=True)
1013
+ with open(STATE_FILE, "w") as f:
1014
+ f.write(" ".join(keys) + "\n")
1015
+ except OSError:
1016
+ pass
1017
+ return max((lvl for lvl, _, _ in alarms), default=0)
1018
+
1019
+
1020
+ def latest_release(timeout):
1021
+ """Newest version on PyPI as (version, None), or (None, reason).
1022
+
1023
+ Runs in a daemon thread with a hard deadline, so a slow DNS lookup or a
1024
+ dead network can't hold anything up: urlopen's own timeout doesn't cover
1025
+ name resolution.
1026
+ """
1027
+ result = {}
1028
+
1029
+ def fetch():
1030
+ try:
1031
+ req = urllib.request.Request(PYPI_URL, headers={
1032
+ "Accept": "application/json", "User-Agent": f"supercomputer/{__version__}"})
1033
+ with urllib.request.urlopen(req, timeout=timeout) as r:
1034
+ result["version"] = json.load(r)["info"]["version"]
1035
+ except urllib.error.HTTPError as e:
1036
+ result["error"] = "no release on PyPI yet" if e.code == 404 else f"PyPI said HTTP {e.code}"
1037
+ except (urllib.error.URLError, OSError):
1038
+ result["error"] = "no connection"
1039
+ except (ValueError, KeyError, TypeError):
1040
+ result["error"] = "unexpected reply from PyPI"
1041
+
1042
+ t = threading.Thread(target=fetch, daemon=True)
1043
+ t.start()
1044
+ t.join(timeout)
1045
+ if "version" in result:
1046
+ return result["version"], None
1047
+ return None, result.get("error", "no connection")
1048
+
1049
+
1050
+ def version_key(v):
1051
+ return tuple(int(n) for n in re.findall(r"\d+", v)[:3])
1052
+
1053
+
1054
+ def is_newer(latest):
1055
+ return version_key(latest) > version_key(__version__)
1056
+
1057
+
1058
+ def show_version():
1059
+ """--version: print the version at once, then a quick update check."""
1060
+ print(f"supercomputer {__version__}", flush=True)
1061
+ if os.environ.get("SUPERCOMPUTER_NO_UPDATE_CHECK"):
1062
+ return
1063
+ latest, err = latest_release(timeout=1.5)
1064
+ if err:
1065
+ msg = f"update check skipped: {err}"
1066
+ elif is_newer(latest):
1067
+ msg = f"update available: {latest} (run: supercomputer --update)"
1068
+ else:
1069
+ msg = "up to date"
1070
+ print(msg, file=sys.stderr)
1071
+
1072
+
1073
+ def install_method():
1074
+ """How this copy was installed: (kind, upgrade command or None)."""
1075
+ here = os.path.dirname(os.path.realpath(__file__))
1076
+ if os.path.isdir(os.path.join(here, ".git")):
1077
+ return "git checkout", ["git", "-C", here, "pull", "--ff-only"]
1078
+ prefix = sys.prefix.replace("\\", "/")
1079
+ if "/uv/tools/" in prefix and shutil.which("uv"):
1080
+ return "uv tool", ["uv", "tool", "upgrade", PYPI_NAME]
1081
+ if "/pipx/venvs/" in prefix and shutil.which("pipx"):
1082
+ return "pipx", ["pipx", "upgrade", PYPI_NAME]
1083
+ if sys.prefix != sys.base_prefix:
1084
+ return "virtualenv", [sys.executable, "-m", "pip", "install", "--upgrade", PYPI_NAME]
1085
+ return "unknown", None
1086
+
1087
+
1088
+ def update():
1089
+ """--update: upgrade this copy the way it was installed. Returns an exit code."""
1090
+ kind, cmd = install_method()
1091
+ print(f"supercomputer {__version__} · installed via {kind}")
1092
+ if kind != "git checkout":
1093
+ latest, err = latest_release(timeout=5)
1094
+ if err:
1095
+ print(f"Can't check for updates: {err}.", file=sys.stderr)
1096
+ return 1
1097
+ if not is_newer(latest):
1098
+ print(f"Up to date (latest is {latest}).")
1099
+ return 0
1100
+ print(f"Updating to {latest}.")
1101
+ if cmd is None:
1102
+ print("Not sure how this copy was installed, so not touching it. Try one of:\n"
1103
+ f" uv tool upgrade {PYPI_NAME}\n pipx upgrade {PYPI_NAME}", file=sys.stderr)
1104
+ return 1
1105
+ print("$ " + " ".join(cmd), flush=True)
1106
+ try:
1107
+ return subprocess.call(cmd)
1108
+ except OSError as e:
1109
+ print(f"Couldn't run {cmd[0]}: {e}", file=sys.stderr)
1110
+ return 1
1111
+
1112
+
1113
+ def main():
1114
+ ap = argparse.ArgumentParser(
1115
+ prog="supercomputer",
1116
+ description="A retro mainframe operator console for your terminal.",
1117
+ epilog=f"Keys: h help, a credits, c colour, p freeze, q quit. https://{REPO_URL}")
1118
+ colour = ap.add_mutually_exclusive_group()
1119
+ for t in THEMES:
1120
+ colour.add_argument(f"--{t.lower()}", dest="theme", action="store_const", const=t,
1121
+ help=f"start in {t.lower()} phosphor")
1122
+ ap.add_argument("--banner", action="store_true", help="print a short static banner and exit")
1123
+ ap.add_argument("--check", action="store_true",
1124
+ help="one-shot strain check; exit 0 nominal, 1 alarm, 2 critical")
1125
+ ap.add_argument("--notify", action="store_true",
1126
+ help="with --check: desktop notification when alarms change")
1127
+ ap.add_argument("--quiet", action="store_true", help="with --check: print nothing when nominal")
1128
+ ap.add_argument("--bell", action="store_true", help="console: ring the terminal bell on new alarms")
1129
+ ap.add_argument("--demo", action="store_true",
1130
+ help="console: simulate load and cycle through every alarm (harmless)")
1131
+ ap.add_argument("--version", action="store_true",
1132
+ help="show the version and check quickly for a newer release")
1133
+ ap.add_argument("--update", action="store_true",
1134
+ help="upgrade to the latest release (uv, pipx, venv or git checkout)")
1135
+ args = ap.parse_args()
1136
+ if args.version:
1137
+ show_version()
1138
+ return
1139
+ if args.update:
1140
+ sys.exit(update())
1141
+ probe = make_probe()
1142
+ if args.banner:
1143
+ banner(probe)
1144
+ return
1145
+ if args.check:
1146
+ sys.exit(check(probe, args.notify, args.quiet))
1147
+ os.environ.setdefault("ESCDELAY", "25")
1148
+ theme = load_theme(args.theme)
1149
+ curses.wrapper(lambda scr: Panel(scr, probe, theme, args.bell, args.demo).run())
1150
+
1151
+
1152
+ if __name__ == "__main__":
1153
+ try:
1154
+ main()
1155
+ except KeyboardInterrupt:
1156
+ pass