spatial-computing 0.12.2__tar.gz → 0.14.0__tar.gz
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.
- {spatial_computing-0.12.2/spatial_computing.egg-info → spatial_computing-0.14.0}/PKG-INFO +2 -2
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/README.md +1 -1
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/pyproject.toml +1 -1
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/__init__.py +1 -1
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/cli.py +59 -6
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/core/registry.py +2 -2
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/fabric/metal.py +6 -4
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/fabric/metal_run.swift +20 -11
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/fleet/agent.py +8 -3
- spatial_computing-0.14.0/spatial/fleet/alerts.py +46 -0
- spatial_computing-0.14.0/spatial/fleet/dashboard.py +160 -0
- spatial_computing-0.14.0/spatial/fleet/ha.py +334 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/fleet/hub.py +85 -14
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/kernel/dsl.py +72 -21
- {spatial_computing-0.12.2 → spatial_computing-0.14.0/spatial_computing.egg-info}/PKG-INFO +2 -2
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial_computing.egg-info/SOURCES.txt +6 -0
- spatial_computing-0.14.0/tests/test_dashboard.py +112 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/tests/test_fleet.py +17 -0
- spatial_computing-0.14.0/tests/test_ha.py +106 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/tests/test_kernel.py +41 -0
- spatial_computing-0.14.0/tests/test_quorum.py +188 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/LICENSE +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/setup.cfg +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/ai/__init__.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/ai/kvcache.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/compute/__init__.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/compute/cost.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/compute/detect.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/compute/monitor.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/compute/scheduler.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/compute/taskqueue.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/compute/worker.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/compute/workloads.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/core/__init__.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/core/auth.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/core/energy.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/core/ledger.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/core/model.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/core/protocol.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/fabric/__init__.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/fabric/cuda.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/fabric/devices.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/fabric/metal_mandel.swift +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/fleet/__init__.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/holographic/__init__.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/holographic/cgh.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/holographic/model.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/intelligence/__init__.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/intelligence/predictor.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/interconnect/__init__.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/interconnect/collectives.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/interconnect/comm.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/interconnect/model.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/interconnect/tasks.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/kernel/__init__.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/kernel/library.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/memory/__init__.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/memory/fararray.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/memory/pageserver.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/memory/secure.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/memory/shared.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/memory/tiered.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/q/__init__.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/q/__main__.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/q/backends/__init__.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/q/codegen.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/q/compiler.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/q/ir.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/q/lexer.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/q/parser.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/q/qir.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/q/runtime.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/q/sim.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/runtime/__init__.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/runtime/envs.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/runtime/inspect.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/runtime/microvm.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/runtime/planner.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/runtime/runner.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/runtime/toolchain.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/scientific/__init__.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/scientific/jobs.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/simulation/__init__.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/simulation/heat.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/simulation/nbody.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/unified/__init__.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/unified/model.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/unified/planner.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial/unified/providers.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial_computing.egg-info/dependency_links.txt +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial_computing.egg-info/entry_points.txt +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial_computing.egg-info/requires.txt +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/spatial_computing.egg-info/top_level.txt +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/tests/test_auth.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/tests/test_compute.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/tests/test_core.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/tests/test_domains.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/tests/test_engines.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/tests/test_fabric.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/tests/test_hardening.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/tests/test_interconnect.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/tests/test_memory.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/tests/test_optimizer.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/tests/test_q.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/tests/test_runtime.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/tests/test_unified.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/tests/test_v02.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/tests/test_v03.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/tests/test_v05.py +0 -0
- {spatial_computing-0.12.2 → spatial_computing-0.14.0}/tests/test_v07.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: spatial-computing
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.14.0
|
|
4
4
|
Summary: Spatial Computing: open-source infrastructure efficiency toolkit. Measure, decide, prove (compute, tiered memory, runtime routing, hybrid quantum language)
|
|
5
5
|
Author: Spatial Computing contributors
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -37,7 +37,7 @@ Dynamic: license-file
|
|
|
37
37
|
|
|
38
38
|
One objective for the whole infrastructure: get every job done correctly at the lowest cost, and prove it. Spatial Computing prices every way to run a job across compute, memory, runtime, quantum, AI, science and a fleet of machines, picks the cheapest, and records the estimate next to what really happened. A gain is claimed only when it is measured. It does not add RAM, cores or GPUs: it compares execution strategies on the hardware you have, trades one resource for another in numbers, and says plainly what it cannot do.
|
|
39
39
|
|
|
40
|
-
> **Status: v0.
|
|
40
|
+
> **Status: v0.14.0, early-stage open-source toolkit.** Everything here was built and measured on a single 2017 MacBook Pro (Intel i7-7660U, 2 cores, 16 GB). Nothing has been proven on a second machine, a data-center GPU or a real quantum computer. See [Limitations](docs/LIMITATIONS.md) and the [site](https://spatial-computing-ecru.vercel.app).
|
|
41
41
|
|
|
42
42
|
[Français](README.fr.md)
|
|
43
43
|
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
One objective for the whole infrastructure: get every job done correctly at the lowest cost, and prove it. Spatial Computing prices every way to run a job across compute, memory, runtime, quantum, AI, science and a fleet of machines, picks the cheapest, and records the estimate next to what really happened. A gain is claimed only when it is measured. It does not add RAM, cores or GPUs: it compares execution strategies on the hardware you have, trades one resource for another in numbers, and says plainly what it cannot do.
|
|
6
6
|
|
|
7
|
-
> **Status: v0.
|
|
7
|
+
> **Status: v0.14.0, early-stage open-source toolkit.** Everything here was built and measured on a single 2017 MacBook Pro (Intel i7-7660U, 2 cores, 16 GB). Nothing has been proven on a second machine, a data-center GPU or a real quantum computer. See [Limitations](docs/LIMITATIONS.md) and the [site](https://spatial-computing-ecru.vercel.app).
|
|
8
8
|
|
|
9
9
|
[Français](README.fr.md)
|
|
10
10
|
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "spatial-computing"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.14.0"
|
|
8
8
|
description = "Spatial Computing: open-source infrastructure efficiency toolkit. Measure, decide, prove (compute, tiered memory, runtime routing, hybrid quantum language)"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "Apache-2.0"
|
|
@@ -4,6 +4,7 @@ from __future__ import annotations
|
|
|
4
4
|
import argparse
|
|
5
5
|
import json
|
|
6
6
|
import subprocess
|
|
7
|
+
import time
|
|
7
8
|
import sys
|
|
8
9
|
from pathlib import Path
|
|
9
10
|
|
|
@@ -89,21 +90,60 @@ def _read_token(path: str) -> bytes:
|
|
|
89
90
|
|
|
90
91
|
|
|
91
92
|
def _hub_client(a):
|
|
92
|
-
from .
|
|
93
|
-
|
|
94
|
-
return RpcClient(host or "127.0.0.1", int(port), _read_token(a.token_file), timeout=30)
|
|
93
|
+
from .fleet.ha import connect_active
|
|
94
|
+
return connect_active(a.hub, _read_token(a.token_file), timeout=30) # a.hub may be "h1:p,h2:p": the active one is used
|
|
95
95
|
|
|
96
96
|
|
|
97
97
|
def cmd_agent(a):
|
|
98
98
|
from .fleet import Agent
|
|
99
|
-
|
|
100
|
-
ag = Agent(host or "127.0.0.1", int(port), _read_token(a.token_file), name=a.name, interval_s=a.interval,
|
|
99
|
+
ag = Agent(a.hub, None, _read_token(a.token_file), name=a.name, interval_s=a.interval,
|
|
101
100
|
usd_per_hour=a.usd_per_hour, labels=[x for x in a.labels.split(",") if x], run_tasks=not a.no_tasks)
|
|
102
|
-
print(f"agent '{ag.name}' reporting to {a.hub} every {a.interval:g} s" + ("" if a.no_tasks else "; accepts allow-listed tasks"))
|
|
101
|
+
print(f"agent '{ag.name}' reporting to {a.hub} every {a.interval:g} s" + ("" if a.no_tasks else "; accepts allow-listed tasks"), flush=True)
|
|
103
102
|
ag.run_forever()
|
|
104
103
|
return 0
|
|
105
104
|
|
|
106
105
|
|
|
106
|
+
def cmd_dashboard(a):
|
|
107
|
+
from .fleet.dashboard import Dashboard
|
|
108
|
+
d = Dashboard(a.hub, _read_token(a.token_file), port=a.port, min_severity=a.min_severity, webhook=a.webhook).start()
|
|
109
|
+
print(f"dashboard (read-only, this machine only): {d.url}", flush=True)
|
|
110
|
+
if a.webhook:
|
|
111
|
+
print(f"alert events are POSTed to {a.webhook}")
|
|
112
|
+
try:
|
|
113
|
+
while True:
|
|
114
|
+
time.sleep(3600)
|
|
115
|
+
except KeyboardInterrupt:
|
|
116
|
+
d.stop()
|
|
117
|
+
return 0
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def cmd_watch(a):
|
|
121
|
+
from .fleet.alerts import AlertEngine, post_webhook
|
|
122
|
+
eng, cli = AlertEngine(a.min_severity), None
|
|
123
|
+
print(f"watching {a.hub} every {a.interval:g} s (alert level: {a.min_severity} and above)", flush=True)
|
|
124
|
+
while True:
|
|
125
|
+
try:
|
|
126
|
+
cli = cli or _hub_client(a)
|
|
127
|
+
events = eng.update(cli.call({"op": "advise", "window_s": a.window})[0]["recommendations"])
|
|
128
|
+
except Exception as e:
|
|
129
|
+
cli = None
|
|
130
|
+
events = [{"event": "hub_unreachable", "key": "hub", "ts": time.time(), "severity": "high", "text": f"{type(e).__name__}: {e}"}] if "hub" not in eng.firing else []
|
|
131
|
+
eng.firing.setdefault("hub", {"since": time.time(), "severity": "high", "text": "hub unreachable"})
|
|
132
|
+
else:
|
|
133
|
+
if "hub" in eng.firing:
|
|
134
|
+
eng.firing.pop("hub"); events.append({"event": "resolved", "key": "hub", "ts": time.time(), "severity": "high", "text": "hub reachable again"})
|
|
135
|
+
for e in events:
|
|
136
|
+
print(f"{time.strftime('%H:%M:%S', time.localtime(e['ts']))} {e['event']:<9} [{e['severity']}] {e['text']}", flush=True)
|
|
137
|
+
if a.webhook:
|
|
138
|
+
try:
|
|
139
|
+
post_webhook(a.webhook, e)
|
|
140
|
+
except Exception as err:
|
|
141
|
+
print(f"webhook failed: {err}", flush=True)
|
|
142
|
+
if a.once:
|
|
143
|
+
return 0
|
|
144
|
+
time.sleep(a.interval)
|
|
145
|
+
|
|
146
|
+
|
|
107
147
|
def cmd_fleet(a):
|
|
108
148
|
cli = _hub_client(a)
|
|
109
149
|
if a.action == "status":
|
|
@@ -273,6 +313,19 @@ def main(argv=None):
|
|
|
273
313
|
p.add_argument("--workload"); p.add_argument("--params", default="{}"); p.add_argument("--needs", default="{}")
|
|
274
314
|
p.add_argument("--task-id", type=int)
|
|
275
315
|
p.set_defaults(fn=cmd_fleet)
|
|
316
|
+
p = sub.add_parser("dashboard", help="read-only fleet dashboard in your browser (served on 127.0.0.1 only, behind a random key)")
|
|
317
|
+
p.add_argument("--hub", required=True, help="host:port, or h1:p,h2:p for a hub pair")
|
|
318
|
+
p.add_argument("--token-file", required=True, help="scoped token with fleet:read")
|
|
319
|
+
p.add_argument("--port", type=int, default=0)
|
|
320
|
+
p.add_argument("--min-severity", default="high", choices=["low", "medium", "high"])
|
|
321
|
+
p.add_argument("--webhook", help="POST each alert event (JSON) to this http(s) URL: this sends fleet data off the machine")
|
|
322
|
+
p.set_defaults(fn=cmd_dashboard)
|
|
323
|
+
p = sub.add_parser("watch", help="print alerts as they fire and clear; optional webhook")
|
|
324
|
+
p.add_argument("--hub", required=True); p.add_argument("--token-file", required=True)
|
|
325
|
+
p.add_argument("--interval", type=float, default=10.0); p.add_argument("--window", type=float, default=60.0)
|
|
326
|
+
p.add_argument("--min-severity", default="high", choices=["low", "medium", "high"])
|
|
327
|
+
p.add_argument("--webhook"); p.add_argument("--once", action="store_true")
|
|
328
|
+
p.set_defaults(fn=cmd_watch)
|
|
276
329
|
p = sub.add_parser("token", help="scoped credentials: `init` a master key, `issue` a tenant token")
|
|
277
330
|
p.add_argument("action", choices=["init", "issue"])
|
|
278
331
|
p.add_argument("--master-key-file", required=True)
|
|
@@ -37,13 +37,13 @@ ENGINES: list[Engine] = [
|
|
|
37
37
|
"N = 4 and 8 processes on one machine over loopback; no real network, RDMA or GPU memory; about 3,000x slower than NVLink 5 (vendor figure); no fault tolerance"),
|
|
38
38
|
Engine("kernel", "Portable kernels", "spatial.kernel", Status.FIRST_COMPONENTS,
|
|
39
39
|
"tests/test_kernel.py, benchmarks/bench_kernel.py (planner right 4 of 6; integer kernel bit-identical CPU vs Metal)",
|
|
40
|
-
"CUDA C generated, never compiled or run;
|
|
40
|
+
"CUDA C and HIP generated, never compiled or run; two kernel shapes (2-D map, whole-grid sum with shared memory), no tiling or tensor cores"),
|
|
41
41
|
Engine("planner", "Spatial Planner (the one objective)", "spatial.unified", Status.OPERATIONAL_PROTOTYPE,
|
|
42
42
|
"tests/test_unified.py",
|
|
43
43
|
"estimates come from probes and measured constants on one machine; calibration is a median of past ratios; no learned model; fleet and QPU pricing need the caller's prices"),
|
|
44
44
|
Engine("fleet", "Spatial Fleet (agent + hub)", "spatial.fleet", Status.OPERATIONAL_PROTOTYPE,
|
|
45
45
|
"tests/test_fleet.py, benchmarks/bench_fleet.py",
|
|
46
|
-
"validated on one machine (agents on loopback); no dashboard
|
|
46
|
+
"validated on one machine (agents on loopback); HA: active/standby for two hubs, majority election (election safety, no replicated log) for three or more, tested on one machine with simulated clocks; dashboard is read-only and local; recommendations are estimates; never applies changes by itself"),
|
|
47
47
|
Engine("runtime", "Spatial Runtime Engine", "spatial.runtime", Status.OPERATIONAL_PROTOTYPE,
|
|
48
48
|
"tests/test_runtime.py, benchmarks/bench_runtime.py",
|
|
49
49
|
"Windows apps not demonstrated (no Wine / Windows image); no containers; no GUI streaming"),
|
|
@@ -62,16 +62,16 @@ def _ensure_run_binary() -> Path:
|
|
|
62
62
|
return RUN_BIN
|
|
63
63
|
|
|
64
64
|
|
|
65
|
-
def run_kernel(k, n: int, params: dict, reps: int = 1, timing: dict | None = None):
|
|
66
|
-
"""Run a portable Kernel (spatial.kernel) on the Metal GPU; returns the (n, n) uint32 output.
|
|
65
|
+
def run_kernel(k, n: int, params: dict, reps: int = 1, timing: dict | None = None, reduce: bool = False):
|
|
66
|
+
"""Run a portable Kernel (spatial.kernel) on the Metal GPU; returns the (n, n) uint32 output, or with reduce=True the sum of all outputs (computed in threadgroup shared memory, partial sums added on the host).
|
|
67
67
|
`timing`, if given, receives the GPU-side median seconds."""
|
|
68
68
|
import numpy as np
|
|
69
69
|
import tempfile
|
|
70
70
|
binary = _ensure_run_binary()
|
|
71
71
|
with tempfile.TemporaryDirectory() as d:
|
|
72
72
|
msl, out = Path(d) / "k.metal", Path(d) / "out.bin"
|
|
73
|
-
msl.write_text(k.to_metal())
|
|
74
|
-
args = [str(binary), str(msl), k.name, str(n), str(reps), str(out)]
|
|
73
|
+
msl.write_text(k.to_metal(reduce=reduce))
|
|
74
|
+
args = [str(binary), str(msl), k.name + ("_sum" if reduce else ""), str(n), str(reps), str(out), "sum" if reduce else "map"]
|
|
75
75
|
args += [f"{t}:{float(params[p]) if t == 'float' else int(params[p])}" for p, t in k.params]
|
|
76
76
|
r = subprocess.run(args, capture_output=True, text=True, timeout=600)
|
|
77
77
|
try:
|
|
@@ -82,4 +82,6 @@ def run_kernel(k, n: int, params: dict, reps: int = 1, timing: dict | None = Non
|
|
|
82
82
|
raise RuntimeError(info.get("error", "Metal error"))
|
|
83
83
|
if timing is not None:
|
|
84
84
|
timing.update(info)
|
|
85
|
+
if reduce:
|
|
86
|
+
return int(np.fromfile(out, dtype=np.uint64).sum())
|
|
85
87
|
return np.fromfile(out, dtype=np.uint32).reshape(n, n)
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Generic Metal host for portable kernels generated by spatial.kernel.
|
|
2
|
-
// usage: metal_run <msl_file> <kernel_name> <n> <reps> <out_file> [int:<v> | float:<v> ...]
|
|
3
|
-
// Buffers: 0 = output
|
|
2
|
+
// usage: metal_run <msl_file> <kernel_name> <n> <reps> <out_file> <map|sum> [int:<v> | float:<v> ...]
|
|
3
|
+
// Buffers: 0 = output, 1 = n (int), 2.. = parameters in order.
|
|
4
|
+
// map: output uint[n*n]. sum: one uint64 partial sum per 16x16 threadgroup (the kernel reduces in threadgroup memory).
|
|
4
5
|
import Foundation
|
|
5
6
|
import Metal
|
|
6
7
|
|
|
@@ -8,9 +9,11 @@ func now() -> Double { return Double(DispatchTime.now().uptimeNanoseconds) / 1e9
|
|
|
8
9
|
func fail(_ m: String) -> Never { print("{\"ok\": false, \"error\": \"\(m)\"}"); exit(1) }
|
|
9
10
|
|
|
10
11
|
let a = CommandLine.arguments
|
|
11
|
-
if a.count <
|
|
12
|
+
if a.count < 7 { fail("usage") }
|
|
12
13
|
guard let src = try? String(contentsOfFile: a[1], encoding: .utf8) else { fail("cannot read msl") }
|
|
13
|
-
let name = a[2], n = Int(a[3])!, reps = max(1, Int(a[4])!), outPath = a[5]
|
|
14
|
+
let name = a[2], n = Int(a[3])!, reps = max(1, Int(a[4])!), outPath = a[5], mode = a[6]
|
|
15
|
+
let sumMode = (mode == "sum")
|
|
16
|
+
let gx = (n + 15) / 16
|
|
14
17
|
guard let dev = MTLCreateSystemDefaultDevice() ?? MTLCopyAllDevices().first else { fail("no Metal device") }
|
|
15
18
|
let t0 = now()
|
|
16
19
|
let lib: MTLLibrary
|
|
@@ -21,7 +24,9 @@ do { lib = try dev.makeLibrary(source: src, options: nil) } catch {
|
|
|
21
24
|
guard let fn = lib.makeFunction(name: name) else { fail("kernel not found") }
|
|
22
25
|
let pipe = try! dev.makeComputePipelineState(function: fn)
|
|
23
26
|
let setupS = now() - t0
|
|
24
|
-
|
|
27
|
+
if sumMode && pipe.maxTotalThreadsPerThreadgroup < 256 { fail("device allows fewer than 256 threads per threadgroup") }
|
|
28
|
+
let outLen = sumMode ? gx * gx * 8 : n * n * 4
|
|
29
|
+
let out = dev.makeBuffer(length: outLen, options: .storageModeShared)!
|
|
25
30
|
let queue = dev.makeCommandQueue()!
|
|
26
31
|
var nn = Int32(n)
|
|
27
32
|
|
|
@@ -32,21 +37,25 @@ func run() -> Double {
|
|
|
32
37
|
enc.setComputePipelineState(pipe)
|
|
33
38
|
enc.setBuffer(out, offset: 0, index: 0)
|
|
34
39
|
enc.setBytes(&nn, length: 4, index: 1)
|
|
35
|
-
for (k, spec) in a[
|
|
40
|
+
for (k, spec) in a[7...].enumerated() {
|
|
36
41
|
let parts = spec.split(separator: ":", maxSplits: 1).map(String.init)
|
|
37
42
|
if parts[0] == "int" { var v = Int32(parts[1])!; enc.setBytes(&v, length: 4, index: 2 + k) }
|
|
38
43
|
else { var v = Float(parts[1])!; enc.setBytes(&v, length: 4, index: 2 + k) }
|
|
39
44
|
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
45
|
+
if sumMode {
|
|
46
|
+
enc.dispatchThreadgroups(MTLSize(width: gx, height: gx, depth: 1), threadsPerThreadgroup: MTLSize(width: 16, height: 16, depth: 1))
|
|
47
|
+
} else {
|
|
48
|
+
let w = pipe.threadExecutionWidth
|
|
49
|
+
let h = pipe.maxTotalThreadsPerThreadgroup / w
|
|
50
|
+
enc.dispatchThreadgroups(MTLSize(width: (n + w - 1) / w, height: (n + h - 1) / h, depth: 1),
|
|
51
|
+
threadsPerThreadgroup: MTLSize(width: w, height: h, depth: 1))
|
|
52
|
+
}
|
|
44
53
|
enc.endEncoding(); cb.commit(); cb.waitUntilCompleted()
|
|
45
54
|
return now() - t
|
|
46
55
|
}
|
|
47
56
|
var times: [Double] = []
|
|
48
57
|
for _ in 0..<reps { times.append(run()) }
|
|
49
|
-
let data = Data(bytes: out.contents(), count:
|
|
58
|
+
let data = Data(bytes: out.contents(), count: outLen)
|
|
50
59
|
do { try data.write(to: URL(fileURLWithPath: outPath)) } catch { fail("cannot write output") }
|
|
51
60
|
times.sort()
|
|
52
61
|
print("{\"ok\": true, \"device\": \"\(dev.name)\", \"gpu_s_median\": \(times[times.count / 2]), \"setup_s\": \(setupS)}")
|
|
@@ -18,13 +18,16 @@ from ..compute import workloads
|
|
|
18
18
|
from ..compute.detect import _nvidia_gpus, detect_node
|
|
19
19
|
from ..compute.monitor import snapshot
|
|
20
20
|
from ..core.protocol import RpcClient
|
|
21
|
+
from .ha import connect_active, parse_addrs
|
|
21
22
|
|
|
22
23
|
|
|
23
24
|
class Agent:
|
|
24
|
-
def __init__(self, host: str, port: int, token: bytes, name: str | None = None, interval_s: float = 5.0,
|
|
25
|
+
def __init__(self, host: "str | list", port: int | None, token: bytes, name: str | None = None, interval_s: float = 5.0,
|
|
25
26
|
usd_per_hour: float | None = None, labels: list | None = None, run_tasks: bool = True,
|
|
26
27
|
poll_s: float = 1.0, buffer: int = 720):
|
|
27
|
-
|
|
28
|
+
# one hub, or several (host as a list or "h1:p,h2:p"): the agent talks to whichever reports itself active
|
|
29
|
+
self.hubs = parse_addrs(host) if port is None else [(host, port)]
|
|
30
|
+
self.host, self.port, self.token = self.hubs[0][0], self.hubs[0][1], token
|
|
28
31
|
self.name = name or socket.gethostname()
|
|
29
32
|
self.interval_s, self.poll_s = interval_s, poll_s
|
|
30
33
|
self.usd_per_hour, self.labels, self.run_tasks = usd_per_hour, labels or [], run_tasks
|
|
@@ -46,7 +49,9 @@ class Agent:
|
|
|
46
49
|
|
|
47
50
|
# ---------------------------------------------------------------- loops
|
|
48
51
|
def _connect(self) -> RpcClient:
|
|
49
|
-
|
|
52
|
+
if len(self.hubs) == 1:
|
|
53
|
+
return RpcClient(self.host, self.port, self.token, timeout=30)
|
|
54
|
+
return connect_active(self.hubs, self.token, timeout=30)
|
|
50
55
|
|
|
51
56
|
def _report_loop(self):
|
|
52
57
|
cli = None
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Alerts from the hub's recommendations: edge-triggered (a condition alerts once when it appears and
|
|
2
|
+
once when it clears), optional webhook. Nothing leaves this machine unless a webhook URL is given."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
import urllib.parse
|
|
8
|
+
import urllib.request
|
|
9
|
+
|
|
10
|
+
RANK = {"low": 0, "medium": 1, "high": 2}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def key_of(r: dict) -> str:
|
|
14
|
+
return f"{r['kind']}:{r.get('node') or ','.join(r.get('nodes_to_free', []))}"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class AlertEngine:
|
|
18
|
+
def __init__(self, min_severity: str = "high", clock=time.time):
|
|
19
|
+
if min_severity not in RANK:
|
|
20
|
+
raise ValueError("min_severity must be low, medium or high")
|
|
21
|
+
self.min_rank, self.clock = RANK[min_severity], clock
|
|
22
|
+
self.firing: dict[str, dict] = {}
|
|
23
|
+
self.history: list[dict] = [] # newest last, capped
|
|
24
|
+
|
|
25
|
+
def update(self, recommendations: list[dict]) -> list[dict]:
|
|
26
|
+
"""Feed the current recommendations; returns the events produced by this update."""
|
|
27
|
+
now, events = self.clock(), []
|
|
28
|
+
current = {key_of(r): r for r in recommendations if RANK.get(r.get("severity"), 0) >= self.min_rank}
|
|
29
|
+
for k, r in current.items():
|
|
30
|
+
if k not in self.firing:
|
|
31
|
+
self.firing[k] = {"since": now, **r}
|
|
32
|
+
events.append({"event": "firing", "key": k, "ts": now, "severity": r["severity"], "text": r["text"]})
|
|
33
|
+
for k in [k for k in self.firing if k not in current]:
|
|
34
|
+
old = self.firing.pop(k)
|
|
35
|
+
events.append({"event": "resolved", "key": k, "ts": now, "severity": old["severity"], "text": old["text"],
|
|
36
|
+
"lasted_s": now - old["since"]})
|
|
37
|
+
self.history = (self.history + events)[-200:]
|
|
38
|
+
return events
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def post_webhook(url: str, event: dict, timeout: float = 5.0) -> None:
|
|
42
|
+
u = urllib.parse.urlparse(url)
|
|
43
|
+
if u.scheme not in ("http", "https") or not u.netloc:
|
|
44
|
+
raise ValueError("webhook must be an http(s) URL")
|
|
45
|
+
req = urllib.request.Request(url, data=json.dumps(event).encode(), headers={"Content-Type": "application/json"}, method="POST")
|
|
46
|
+
urllib.request.urlopen(req, timeout=timeout).read()
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Fleet dashboard: a local, read-only web page over the hub.
|
|
2
|
+
|
|
3
|
+
The process holds the hub credential and serves HTTP on 127.0.0.1 ONLY (no option to bind elsewhere).
|
|
4
|
+
Every request needs a random key printed at start; the Host header must be loopback (blocks DNS
|
|
5
|
+
rebinding); only GET is accepted; the page can read the fleet and cannot change anything.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import http.server
|
|
10
|
+
import json
|
|
11
|
+
import secrets
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
from urllib.parse import parse_qs, urlparse
|
|
15
|
+
|
|
16
|
+
from .alerts import AlertEngine, post_webhook
|
|
17
|
+
from .ha import connect_active
|
|
18
|
+
|
|
19
|
+
PAGE = r"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
20
|
+
<title>Spatial Fleet</title><style>
|
|
21
|
+
:root{--paper:#f6f4ec;--ink:#12233f;--mute:#4f5f7a;--mark:#ffd84a;--ok:#2f8f3a;--bad:#c0392b;--warn:#b7791f;--grid:#12233f14;
|
|
22
|
+
--serif:"Instrument Serif",Georgia,serif;--mono:"DM Mono",ui-monospace,Menlo,monospace}
|
|
23
|
+
@media (prefers-color-scheme:dark){:root{--paper:#0e1a30;--ink:#f6f4ec;--mute:#9fb0cc;--grid:#f6f4ec14;--ok:#b8f171;--bad:#ff8a7a;--warn:#ffd84a}}
|
|
24
|
+
*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font:14px/1.5 var(--mono);
|
|
25
|
+
background-image:linear-gradient(var(--grid) 1px,transparent 1px),linear-gradient(90deg,var(--grid) 1px,transparent 1px);background-size:24px 24px}
|
|
26
|
+
header{display:flex;justify-content:space-between;align-items:baseline;padding:18px 24px;border-bottom:1px solid var(--ink);background:var(--paper)}
|
|
27
|
+
h1{font:400 32px var(--serif);margin:0}h2{font:400 22px var(--serif);margin:0 0 8px}
|
|
28
|
+
main{max-width:1180px;margin:0 auto;padding:16px 24px;display:grid;gap:16px}
|
|
29
|
+
section{background:var(--paper);border:1px solid var(--ink);padding:14px 16px;overflow-x:auto}
|
|
30
|
+
table{border-collapse:collapse;width:100%}th,td{text-align:left;padding:4px 10px 4px 0;white-space:nowrap}th{color:var(--mute);font-weight:400}
|
|
31
|
+
.bar{display:inline-block;width:90px;height:8px;border:1px solid var(--ink);vertical-align:middle;margin-right:6px}.bar i{display:block;height:100%;background:var(--ink)}
|
|
32
|
+
.tag{padding:1px 6px;border:1px solid currentColor}.ok{color:var(--ok)}.bad{color:var(--bad)}.warn{color:var(--warn)}.mute{color:var(--mute)}
|
|
33
|
+
#banner{display:none;background:var(--bad);color:#fff;padding:10px 24px}
|
|
34
|
+
.kpis{display:flex;gap:28px;flex-wrap:wrap}.kpis b{font:400 30px var(--serif);display:block}
|
|
35
|
+
</style></head><body>
|
|
36
|
+
<div id="banner" role="alert"></div>
|
|
37
|
+
<header><h1>Spatial Fleet</h1><span id="meta" class="mute">connecting…</span></header>
|
|
38
|
+
<main>
|
|
39
|
+
<section><div class="kpis" id="kpis"></div></section>
|
|
40
|
+
<section><h2>Alerts</h2><div id="alerts" class="mute">none</div></section>
|
|
41
|
+
<section><h2>Nodes</h2><table id="nodes"></table></section>
|
|
42
|
+
<section><h2>Recommendations</h2><div id="recs" class="mute">none</div></section>
|
|
43
|
+
<section><h2>Tenants and queue</h2><table id="tenants"></table><p></p><table id="tasks"></table></section>
|
|
44
|
+
</main>
|
|
45
|
+
<script>
|
|
46
|
+
const key=new URLSearchParams(location.search).get("key")||"";
|
|
47
|
+
const esc=s=>String(s??"-").replace(/[&<>"']/g,c=>({"&":"&","<":"<",">":">",'"':""","'":"'"}[c]));
|
|
48
|
+
const f=(v,n=0)=>v==null?"-":Number(v).toFixed(n);
|
|
49
|
+
const bar=v=>`<span class="bar"><i style="width:${Math.max(0,Math.min(100,v||0))}%"></i></span>${f(v)}%`;
|
|
50
|
+
async function tick(){
|
|
51
|
+
try{
|
|
52
|
+
const r=await fetch("api/state?key="+encodeURIComponent(key),{cache:"no-store"});
|
|
53
|
+
if(!r.ok) throw new Error(r.status);
|
|
54
|
+
const s=await r.json();
|
|
55
|
+
document.getElementById("meta").textContent=`hub ${s.hub.name} · ${s.hub.role} · epoch ${s.hub.epoch} · updated ${new Date(s.ts*1000).toLocaleTimeString()}`;
|
|
56
|
+
const u=s.utilization;
|
|
57
|
+
document.getElementById("kpis").innerHTML=[["nodes",u.nodes],["cores",u.cores],["CPU",u.cpu_utilization_pct==null?"-":f(u.cpu_utilization_pct,1)+"%"],
|
|
58
|
+
["queued",s.queue.counts.queued||0],["running",s.queue.counts.running||0],["done",s.queue.counts.done||0],["failed",s.queue.counts.failed||0]].map(([k,v])=>`<div><b>${esc(v)}</b>${k}</div>`).join("");
|
|
59
|
+
document.getElementById("nodes").innerHTML="<tr><th>node</th><th>up</th><th>cores</th><th>cpu</th><th>ram free</th><th>gpus</th><th>$/h</th><th>samples</th></tr>"+
|
|
60
|
+
s.nodes.map(n=>`<tr><td>${esc(n.node)}</td><td class="${n.alive?"ok":"bad"}">${n.alive?"yes":"NO"}</td><td>${f(n.cores)}</td><td>${bar(n.cpu_avg)}</td><td>${f(n.ram_avail_pct)}%</td><td>${esc(n.gpu_count)}</td><td>${f(n.usd_per_hour,2)}</td><td>${esc(n.samples)}</td></tr>`).join("");
|
|
61
|
+
const firing=Object.values(s.alerts.firing);
|
|
62
|
+
const b=document.getElementById("banner");b.style.display=firing.length?"block":"none";b.textContent=firing.map(a=>a.text).join(" · ");
|
|
63
|
+
document.getElementById("alerts").innerHTML=(firing.length?firing.map(a=>`<div class="bad">● ${esc(a.severity)} ${esc(a.text)}</div>`).join(""):"<span class='ok'>nothing firing</span>")+
|
|
64
|
+
s.alerts.history.slice(-5).reverse().map(e=>`<div class="mute">${new Date(e.ts*1000).toLocaleTimeString()} ${esc(e.event)} ${esc(e.key)}</div>`).join("");
|
|
65
|
+
document.getElementById("recs").innerHTML=s.recommendations.length?s.recommendations.map(r=>`<p><span class="tag ${r.severity=="high"?"bad":"warn"}">${esc(r.severity)}</span> <b>${esc(r.kind)}</b> ${esc(r.text)}${r.est_saving_usd_per_month?` <span class="mute">(estimated saving ${f(r.est_saving_usd_per_month)} $/month: an estimate, not a result)</span>`:""}</p>`).join(""):"no recommendation: nothing in the measurements justifies a change";
|
|
66
|
+
document.getElementById("tenants").innerHTML="<tr><th>tenant</th><th>weight</th><th>finished s</th><th>weighted load</th><th>queued</th><th>running</th></tr>"+
|
|
67
|
+
s.tenants.map(t=>`<tr><td>${esc(t.tenant)}</td><td>${f(t.weight,1)}</td><td>${f(t.finished_s,1)}</td><td>${f(t.weighted_load,1)}</td><td>${esc(t.queued)}</td><td>${esc(t.running)}</td></tr>`).join("");
|
|
68
|
+
document.getElementById("tasks").innerHTML="<tr><th>task</th><th>workload</th><th>state</th><th>node</th><th>tenant</th><th>wall s</th></tr>"+
|
|
69
|
+
s.queue.recent.map(t=>`<tr><td>${esc(t.id)}${t.gang?" (gang)":""}</td><td>${esc(t.workload)}</td><td class="${t.state=="failed"?"bad":t.state=="done"?"ok":""}">${esc(t.state)}</td><td>${esc(t.node)}</td><td>${esc(t.tenant)}</td><td>${f(t.wall_s,2)}</td></tr>`).join("");
|
|
70
|
+
}catch(e){document.getElementById("meta").textContent="no data: "+e.message}
|
|
71
|
+
}
|
|
72
|
+
tick();setInterval(tick,3000);
|
|
73
|
+
</script></body></html>"""
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class Dashboard:
|
|
77
|
+
def __init__(self, hubs, token: bytes, port: int = 0, interval_s: float = 3.0, window_s: float = 60.0,
|
|
78
|
+
min_severity: str = "high", webhook: str | None = None):
|
|
79
|
+
self.hubs, self.token, self.interval_s, self.window_s, self.webhook = hubs, token, interval_s, window_s, webhook
|
|
80
|
+
self.alerts = AlertEngine(min_severity)
|
|
81
|
+
self.key = secrets.token_urlsafe(16)
|
|
82
|
+
self.state: dict = {"error": "starting"}
|
|
83
|
+
self._cli = None
|
|
84
|
+
self._stop = threading.Event()
|
|
85
|
+
dash = self
|
|
86
|
+
|
|
87
|
+
class H(http.server.BaseHTTPRequestHandler):
|
|
88
|
+
def log_message(self, *a):
|
|
89
|
+
pass
|
|
90
|
+
|
|
91
|
+
def _deny(self, code, msg):
|
|
92
|
+
self.send_response(code); self.send_header("Content-Type", "text/plain"); self.end_headers(); self.wfile.write(msg.encode())
|
|
93
|
+
|
|
94
|
+
def do_GET(self):
|
|
95
|
+
host = (self.headers.get("Host") or "").rsplit(":", 1)[0].strip("[]")
|
|
96
|
+
if host not in ("127.0.0.1", "localhost", "::1"):
|
|
97
|
+
return self._deny(403, "bad host") # DNS rebinding
|
|
98
|
+
u = urlparse(self.path)
|
|
99
|
+
k = (parse_qs(u.query).get("key") or [""])[0]
|
|
100
|
+
if not secrets.compare_digest(k, dash.key):
|
|
101
|
+
return self._deny(403, "missing or wrong key")
|
|
102
|
+
if u.path == "/api/state":
|
|
103
|
+
body = json.dumps(dash.state).encode(); ctype = "application/json"
|
|
104
|
+
elif u.path in ("/", "/index.html"):
|
|
105
|
+
body = PAGE.encode(); ctype = "text/html; charset=utf-8"
|
|
106
|
+
else:
|
|
107
|
+
return self._deny(404, "not found")
|
|
108
|
+
self.send_response(200)
|
|
109
|
+
self.send_header("Content-Type", ctype); self.send_header("Cache-Control", "no-store")
|
|
110
|
+
self.send_header("X-Frame-Options", "DENY"); self.send_header("Referrer-Policy", "no-referrer")
|
|
111
|
+
self.send_header("Content-Security-Policy", "default-src 'self'; style-src 'unsafe-inline'; script-src 'unsafe-inline'")
|
|
112
|
+
self.end_headers(); self.wfile.write(body)
|
|
113
|
+
|
|
114
|
+
do_POST = do_PUT = do_DELETE = lambda self: self._deny(405, "read-only")
|
|
115
|
+
|
|
116
|
+
self._http = http.server.ThreadingHTTPServer(("127.0.0.1", port), H) # loopback only, by construction
|
|
117
|
+
self.port = self._http.server_address[1]
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def url(self) -> str:
|
|
121
|
+
return f"http://127.0.0.1:{self.port}/?key={self.key}"
|
|
122
|
+
|
|
123
|
+
def refresh(self) -> dict:
|
|
124
|
+
try:
|
|
125
|
+
if self._cli is None:
|
|
126
|
+
self._cli = connect_active(self.hubs, self.token, timeout=10)
|
|
127
|
+
c = self._cli
|
|
128
|
+
role = c.call({"op": "role"})[0]
|
|
129
|
+
nodes = c.call({"op": "nodes", "window_s": self.window_s})[0]
|
|
130
|
+
recs = c.call({"op": "advise", "window_s": self.window_s})[0]["recommendations"]
|
|
131
|
+
events = self.alerts.update(recs)
|
|
132
|
+
self.state = {"ts": time.time(), "hub": role, "nodes": nodes["nodes"], "utilization": nodes["utilization"],
|
|
133
|
+
"recommendations": recs, "tenants": c.call({"op": "tenants"})[0]["tenants"], "queue": c.call({"op": "queue"})[0],
|
|
134
|
+
"alerts": {"firing": self.alerts.firing, "history": self.alerts.history}}
|
|
135
|
+
if self.webhook:
|
|
136
|
+
for e in events:
|
|
137
|
+
try:
|
|
138
|
+
post_webhook(self.webhook, e)
|
|
139
|
+
except Exception:
|
|
140
|
+
pass
|
|
141
|
+
except Exception as e: # keep serving; reconnect (and fail over) next round
|
|
142
|
+
if self._cli is not None:
|
|
143
|
+
try: self._cli.close()
|
|
144
|
+
except Exception: pass
|
|
145
|
+
self._cli = None
|
|
146
|
+
self.state = {**{k: v for k, v in self.state.items() if k != "error"}, "error": f"{type(e).__name__}: {e}"} if "nodes" in self.state else {"error": f"{type(e).__name__}: {e}"}
|
|
147
|
+
return self.state
|
|
148
|
+
|
|
149
|
+
def start(self) -> "Dashboard":
|
|
150
|
+
def loop():
|
|
151
|
+
while not self._stop.is_set():
|
|
152
|
+
self.refresh()
|
|
153
|
+
self._stop.wait(self.interval_s)
|
|
154
|
+
threading.Thread(target=loop, daemon=True).start()
|
|
155
|
+
threading.Thread(target=self._http.serve_forever, daemon=True).start()
|
|
156
|
+
return self
|
|
157
|
+
|
|
158
|
+
def stop(self) -> None:
|
|
159
|
+
self._stop.set()
|
|
160
|
+
self._http.shutdown(); self._http.server_close()
|