- Pins, exklusive Nutzung und Modellzeitfenster liegen in einem gemeinsamen Zeitplan (Tabelle schedule; bestehende Pins werden übernommen) und werden mit omega-proxy schedule pin|exclusive|window|list|remove verwaltet - Exklusiv: nur die genannten Keys dürfen das System nutzen; Modellzeitfenster: nur die genannten Modelle sind verfügbar; andere Anfragen erhalten 403 mit Ende und Anlass - Super-Keys (key create --super) dürfen trotz beider Einschränkungen alles - Beim Anlegen werden Speicher der Pins, Überschneidungen exklusiver Einträge und Modellzeitfenster sowie Pins außerhalb ihres Fensters geprüft - Wöchentliche Zeiten dürfen über Mitternacht reichen (z. B. 22:00-02:00) - Unit-Tests und tests/multispark/schedule_test.py Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
147 lines
4.8 KiB
Python
147 lines
4.8 KiB
Python
"""Gemeinsame Hilfen für die Tests mit drei simulierten Sparks."""
|
|
|
|
import json
|
|
import os
|
|
import random
|
|
import signal
|
|
import sqlite3
|
|
import threading
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
T = "run"
|
|
KEY = open(f"{T}/key.txt").read().strip()
|
|
P = "http://127.0.0.1:8000"
|
|
BUDGET = {"spark1": 1200, "spark2": 1000, "spark3": 800}
|
|
OLLAMA = {"spark1": 11441, "spark2": 11442, "spark3": 11443}
|
|
LLAMA = {"spark1": 8181}
|
|
LLAMA_MB = {"qwen3-0.6b": 600, "smollm2-135m": 300}
|
|
AGENT = {"spark1": (9201, "t1"), "spark2": (9202, "t2")}
|
|
PIDS = dict(line.split() for line in open(f"{T}/pids"))
|
|
|
|
failures = []
|
|
|
|
|
|
def check(ok, text):
|
|
print(f" {'OK ' if ok else 'FEHLER'} {text}")
|
|
if not ok:
|
|
failures.append(text)
|
|
|
|
|
|
def http(url, body=None, headers=None, timeout=240):
|
|
data = json.dumps(body).encode() if body is not None else None
|
|
req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json", **(headers or {})})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
return r.status, r.read()
|
|
except urllib.error.HTTPError as e:
|
|
return e.code, e.read()
|
|
except Exception as e:
|
|
return 0, str(e).encode()
|
|
|
|
|
|
def ground_truth():
|
|
"""Belegter Speicher je Spark laut den Engines selbst, nicht laut Proxy"""
|
|
used = {n: 0 for n in BUDGET}
|
|
models = {n: [] for n in BUDGET}
|
|
for n, port in OLLAMA.items():
|
|
st, b = http(f"http://127.0.0.1:{port}/api/ps", timeout=2)
|
|
if st == 200:
|
|
for m in json.loads(b)["models"]:
|
|
used[n] += (m["size_vram"] or m["size"]) // 2**20
|
|
models[n].append(f"ollama:{m['name']}")
|
|
for n, port in LLAMA.items():
|
|
st, b = http(f"http://127.0.0.1:{port}/models", timeout=2)
|
|
if st == 200:
|
|
for m in json.loads(b)["data"]:
|
|
if m["status"]["value"] in ("loaded", "loading"):
|
|
used[n] += LLAMA_MB[m["id"]]
|
|
models[n].append(f"llamacpp:{m['id']}")
|
|
for n, (port, tok) in AGENT.items():
|
|
st, b = http(f"http://127.0.0.1:{port}/v1/vllm", headers={"Authorization": f"Bearer {tok}"}, timeout=2)
|
|
if st == 200:
|
|
for i in json.loads(b):
|
|
if i["state"] in ("starting", "running", "stopping"):
|
|
used[n] += i["memory_mb"]
|
|
models[n].append(f"vllm:{i['name']}")
|
|
return used, models
|
|
|
|
|
|
class Monitor(threading.Thread):
|
|
def __init__(self):
|
|
super().__init__(daemon=True)
|
|
self.max_used = {n: 0 for n in BUDGET}
|
|
self.violations = []
|
|
self.running = True
|
|
|
|
def run(self):
|
|
while self.running:
|
|
used, models = ground_truth()
|
|
for n in BUDGET:
|
|
self.max_used[n] = max(self.max_used[n], used[n])
|
|
if used[n] > BUDGET[n]:
|
|
self.violations.append((time.strftime("%H:%M:%S"), n, used[n], models[n]))
|
|
time.sleep(0.15)
|
|
|
|
|
|
def ask(engine, model, tokens=3, key=None):
|
|
t = time.time()
|
|
if engine == "ollama":
|
|
url, body = f"{P}/api/generate", {"model": model, "prompt": "hi", "stream": False, "think": False,
|
|
"options": {"num_predict": tokens}}
|
|
else:
|
|
prefix = "/llamacpp" if engine == "llamacpp" else "/vllm"
|
|
url, body = f"{P}{prefix}/v1/chat/completions", {"model": model, "max_tokens": tokens,
|
|
"messages": [{"role": "user", "content": "hi"}]}
|
|
st, b = http(url, body, {"Authorization": f"Bearer {key or KEY}"})
|
|
return st, time.time() - t, b
|
|
|
|
|
|
def status():
|
|
_, b = http(f"{P}/omega/status", headers={"Authorization": f"Bearer {KEY}"})
|
|
return json.loads(b)["nodes"]
|
|
|
|
|
|
def where(engine, model):
|
|
return [n["name"] for n in status() for m in n["models"]
|
|
if m["engine"] == engine and m["model"] == model and m["state"] == "loaded"]
|
|
|
|
|
|
def show_status():
|
|
for n in status():
|
|
models = ", ".join(f"{m['engine']}:{m['model']} {m['mb']}" for m in sorted(n["models"], key=lambda m: m["model"]))
|
|
print(f" {n['name']}: {n['used_mb']:>4}/{n['budget_mb']} MB {models}")
|
|
|
|
|
|
def audit(since_id=0):
|
|
db = sqlite3.connect(f"{T}/test.db")
|
|
rows = db.execute("SELECT id, action, detail FROM audit_log WHERE id > ? AND action LIKE 'model.%'",
|
|
(since_id,)).fetchall()
|
|
db.close()
|
|
return rows
|
|
|
|
|
|
def last_audit_id():
|
|
db = sqlite3.connect(f"{T}/test.db")
|
|
(i,) = db.execute("SELECT coalesce(max(id), 0) FROM audit_log").fetchone()
|
|
db.close()
|
|
return i
|
|
|
|
|
|
def parallel(jobs):
|
|
results = [None] * len(jobs)
|
|
|
|
def run(i, job, delay):
|
|
time.sleep(delay)
|
|
results[i] = ask(*job)
|
|
|
|
threads = [threading.Thread(target=run, args=(i, job, i * 0.3)) for i, job in enumerate(jobs)]
|
|
for t in threads:
|
|
t.start()
|
|
for t in threads:
|
|
t.join()
|
|
return results
|
|
|
|
|