Files
buryan-infra/ops/work/web/services/svc_draw.py
T

153 lines
6.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Сервис СХЕМА и КАБЕЛИ (8104): interconnect-diagram + кабельный журнал."""
import sys
sys.path.insert(0, "/root/buryan-infra/ops/work/web")
from svc_base import serve # noqa
import combine_core as cc # noqa
C = cc.Core()
COLOR = {"HDMI": "#2f81f7", "USB": "#3fb950", "USB-C": "#3fb950", "VCH": "#a371f7",
"LAN": "#d29922", "3.5mm": "#8b949e", "DP": "#a371f7", "RJ-9": "#8b949e",
"—": "#484f58"}
def _items(q):
out = []
for raw in (q.get("item") or []):
if ":" in raw:
m, n = raw.rsplit(":", 1)
try:
out.append([m, int(n)])
except ValueError:
pass
else:
out.append([raw, 1])
return out
def _esc(s):
return str(s).replace("<", "&lt;").replace(">", "&gt;").replace("&", "&amp;")
def diagram(q, body):
"""SVG-схема: порты хоста слева/справа, устройства вокруг, связи по разъёмам."""
hk = cc.norm((q.get("host") or [""])[0])
if hk not in C.devices:
return {"error": "хост не найден"}
host = C.devices[hk]["name"]
items = _items(q)
plan = C.port_plan(hk, items)
W, H = 1100, 620
cx, cy, bw, bh = 550, 310, 210, 110
parts = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" '
f'width="{W}" height="{H}" style="background:#0a0e13">']
# хост
parts.append(f'<rect x="{cx-bw//2}" y="{cy-bh//2}" width="{bw}" height="{bh}" rx="12" '
f'fill="#132239" stroke="#2f81f7" stroke-width="2"/>')
parts.append(f'<text x="{cx-bw//2+14}" y="{cy-bh//2+24}" fill="#e6edf3" '
f'font-size="14" font-weight="600">{_esc(host)[:26]}</text>')
parts.append(f'<text x="{cx-bw//2+14}" y="{cy-bh//2+40}" fill="#8b949e" '
f'font-size="10">ports: {plan["source"]}</text>')
for i, p in enumerate(plan["host_in"][:5]):
y = cy - bh//2 + 60 + i*14
used = "•" if p in plan["used_in"] else "○"
parts.append(f'<text x="{cx-bw//2+14}" y="{y}" fill="{COLOR.get(p,"#8b949e")}" '
f'font-size="10">in {_esc(p)} {used}</text>')
for i, p in enumerate(plan["host_out"][:5]):
y = cy - bh//2 + 60 + i*14
used = "•" if p in plan["used_out"] else "○"
parts.append(f'<text x="{cx+bw//2-14}" y="{y}" fill="{COLOR.get(p,"#8b949e")}" '
f'font-size="10" text-anchor="end">{used} out {_esc(p)}</text>')
# устройства
rows = [r for r in plan["rows"] if r["device"] not in ("", None)]
n = max(len(rows), 1)
for i, r in enumerate(rows):
a_top = 60
step = (H - 120) / n
y = a_top + step * i + step/2
x = 175 if i % 2 == 0 else 925
col = COLOR.get(r["needs_port"], "#484f58") if r["ok"] else "#f85149"
dash = "" if r["ok"] else ' stroke-dasharray="6 4"'
parts.append(f'<path d="M {cx} {cy} L {x} {y}" stroke="{col}" stroke-width="2" '
f'opacity="0.75"{dash} fill="none"/>')
parts.append(f'<rect x="{x-105}" y="{y-30}" width="210" height="60" rx="10" '
f'fill="#161b22" stroke="{col}" stroke-width="1.4"/>')
parts.append(f'<text x="{x}" y="{y-8}" text-anchor="middle" fill="#e6edf3" '
f'font-size="12" font-weight="600">{_esc(r["device"])[:24]}</text>')
parts.append(f'<text x="{x}" y="{y+8}" text-anchor="middle" fill="#8b949e" '
f'font-size="9.5">{("→ "+_esc(r["host_port"])) if r["ok"] else "нет порта"}'
f'{" ×"+str(r["qty"]) if r["qty"]>1 else ""}</text>')
parts.append(f'<text x="{x}" y="{y+21}" text-anchor="middle" fill="#8b949e" '
f'font-size="9">{_esc(r["needs_port"] or "?")}</text>')
parts.append("</svg>")
return {"host": host, "svg": "".join(parts),
"unresolved": plan["unresolved"],
"free_in": plan["free_in"], "free_out": plan["free_out"]}
def cables(q, body):
return C.cable_schedule((q.get("host") or [""])[0], _items(q))
def rack(q, body):
"""Чертёж стойки (EIA-310: 1U = 44.45 мм)."""
items = _items(q)
U = 44.45
u = 1
rows = []
for r in items:
h = 1
name = r[0]
if any(x in name.lower() for x in ("mcore", "codec", "dsp", "ap08")):
h = 1
rows.append({"device": name, "qty": r[1], "u": h, "start_u": u})
u += h * r[1]
total_u = u + 1
W, px = 420, 70
H = int(total_u * px + 80)
parts = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}">',
f'<rect x="0" y="0" width="{W}" height="{H}" fill="#0a0e13"/>',
f'<text x="14" y="24" fill="#e6edf3" font-size="13" font-weight="600">'
f'Стойка: {total_u}U (EIA-310, 1U=44.45 мм)</text>']
for r in rows:
y = 60 + (r["start_u"] - 1) * px
for n in range(r["qty"]):
yy = y + n * r["u"] * px
parts.append(f'<rect x="24" y="{yy}" width="{W-48}" height="{px-4}" rx="4" '
f'fill="#161b22" stroke="#2e4a6b"/>')
parts.append(f'<text x="34" y="{yy+26}" fill="#e6edf3" font-size="12">'
f'{_esc(r["device"])[:38]}</text>')
parts.append(f'<text x="{W-34}" y="{yy+26}" fill="#8b949e" font-size="10" '
f'text-anchor="end">U{r["start_u"]+n}</text>')
parts.append("</svg>")
return {"svg": "".join(parts), "total_u": total_u,
"height_mm": round(total_u * U, 1)}
def ipplan(q, body):
"""IP-план: выдаёт адреса по порядку для сетевых устройств."""
base = (q.get("net") or ["10.10.20."])[0]
start = int((q.get("start") or ["10"])[0])
items = _items(q)
rows, n = [], start
for r in items:
name, qty = r[0], r[1]
ins, outs, src = C.ports(name)
if "LAN" not in (ins + outs):
continue
for _ in range(qty):
rows.append({"device": name, "ip": "%s%d" % (base, n),
"purpose": "управление", "vlan": (q.get("vlan") or ["20"])[0]})
n += 1
return {"base": base, "rows": rows, "count": len(rows)}
serve({
"/diagram": diagram,
"/cables": cables,
"/rack": rack,
"/ipplan": ipplan,
}, int(sys.argv[1]) if len(sys.argv) > 1 else 8104, "draw")