Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf209e5236 | ||
|
|
b55a819067 | ||
|
|
f66fb6c122 | ||
|
|
577edbec79 | ||
|
|
f3bed57e4d | ||
|
|
71ca95d7ce | ||
|
|
29cff2321a | ||
|
|
8a804e782a | ||
|
|
f7194ab2e4 | ||
|
|
c015861147 | ||
|
|
4d3f67277f | ||
|
|
f4ea05e5b3 | ||
|
|
f03cb13c87 | ||
|
|
33ed6d2c12 | ||
|
|
7c2b5a95c9 | ||
|
|
3faa1fb570 |
No files matched your search
@@ -55,3 +55,5 @@ Thumbs.db
|
||||
|
||||
# Claude Code 本地状态(settings、定时任务锁等)
|
||||
.claude/
|
||||
host_key
|
||||
docs_dev/
|
||||
@@ -4,3 +4,7 @@ test-results/
|
||||
.env
|
||||
*.env
|
||||
!*.env.example
|
||||
|
||||
# 运行时持久化文件(自动生成)
|
||||
config/host_registry.json
|
||||
config/node_specs.json
|
||||
@@ -1,49 +1,28 @@
|
||||
{
|
||||
"preset": "debug",
|
||||
"preset": null,
|
||||
"positions": [
|
||||
{
|
||||
"x": 10.0,
|
||||
"y": 10.0,
|
||||
"x": 0.0,
|
||||
"y": 0.0,
|
||||
"z": 0.0
|
||||
},
|
||||
{
|
||||
"x": 60.0,
|
||||
"y": 10.0,
|
||||
"z": 0.0
|
||||
},
|
||||
{
|
||||
"x": 110.0,
|
||||
"y": 10.0,
|
||||
"z": 0.0
|
||||
},
|
||||
{
|
||||
"x": 160.0,
|
||||
"y": 10.0,
|
||||
"z": 0.0
|
||||
},
|
||||
{
|
||||
"x": 210.0,
|
||||
"y": 10.0,
|
||||
"x": 50.0,
|
||||
"y": 0.0,
|
||||
"z": 0.0
|
||||
}
|
||||
],
|
||||
"txPower": [
|
||||
30.0,
|
||||
30.0,
|
||||
30.0,
|
||||
30.0,
|
||||
30.0
|
||||
20.0,
|
||||
20.0
|
||||
],
|
||||
"rxSensitivity": [
|
||||
-92.0,
|
||||
-92.0,
|
||||
-92.0,
|
||||
-92.0,
|
||||
-92.0
|
||||
],
|
||||
"pathLossExponent": 2.0,
|
||||
"frequencyMhz": 2412,
|
||||
"channelWidthMhz": 20,
|
||||
"rangeTargetM": 200.0,
|
||||
"rangeTargetM": 500.0,
|
||||
"pathLossModel": "FreeSpace"
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
"""远端主机管理 API。
|
||||
|
||||
提供主机的注册、查询、注销接口。注册信息保存在内存中(进程级),
|
||||
重启控制器后需要重新注册。
|
||||
提供主机的注册、查询、注销接口。注册信息持久化到 JSON 文件,
|
||||
控制器重启后自动恢复。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
@@ -16,10 +18,47 @@ log = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/hosts", tags=["hosts"])
|
||||
|
||||
REGISTRY_PATH: Path = Path("/app/config/host_registry.json")
|
||||
|
||||
# 进程级内存存储:{host_ip: HostRegisterRequest}
|
||||
_registry: dict[str, HostRegisterRequest] = {}
|
||||
|
||||
|
||||
def _load_registry() -> None:
|
||||
"""从 JSON 文件加载主机注册表。"""
|
||||
if not REGISTRY_PATH.exists():
|
||||
return
|
||||
try:
|
||||
data = json.loads(REGISTRY_PATH.read_text(encoding="utf-8"))
|
||||
for item in data:
|
||||
req = HostRegisterRequest(**item)
|
||||
_registry[req.ip] = req
|
||||
if _registry:
|
||||
log.info("已从 %s 恢复 %d 台主机", REGISTRY_PATH, len(_registry))
|
||||
except Exception as e:
|
||||
log.warning("加载主机注册表失败: %s", e)
|
||||
|
||||
|
||||
def _save_registry() -> None:
|
||||
"""将主机注册表持久化到 JSON 文件。"""
|
||||
data = [
|
||||
{
|
||||
"ip": h.ip,
|
||||
"ssh_user": h.ssh_user,
|
||||
"ssh_key": h.ssh_key,
|
||||
"capacity": h.capacity,
|
||||
"labels": h.labels,
|
||||
}
|
||||
for h in _registry.values()
|
||||
]
|
||||
REGISTRY_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
REGISTRY_PATH.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
|
||||
# 模块导入时自动恢复
|
||||
_load_registry()
|
||||
|
||||
|
||||
@router.post("/register")
|
||||
async def register_host(req: HostRegisterRequest) -> dict[str, Any]:
|
||||
"""注册远端主机。
|
||||
@@ -27,6 +66,7 @@ async def register_host(req: HostRegisterRequest) -> dict[str, Any]:
|
||||
同一 IP 重复注册会覆盖旧记录。
|
||||
"""
|
||||
_registry[req.ip] = req
|
||||
_save_registry()
|
||||
log.info("注册远端主机 %s (user=%s capacity=%d)", req.ip, req.ssh_user, req.capacity)
|
||||
return {
|
||||
"ok": True,
|
||||
@@ -50,12 +90,33 @@ async def list_hosts() -> list[dict[str, Any]]:
|
||||
]
|
||||
|
||||
|
||||
@router.put("/{host_ip}")
|
||||
async def update_host(host_ip: str, req: HostRegisterRequest) -> dict[str, Any]:
|
||||
"""更新远端主机的 SSH 凭据、容量等信息。
|
||||
|
||||
调用时必须与现有 host_ip 一致(或使用 URL 中的 IP)。
|
||||
"""
|
||||
if host_ip not in _registry:
|
||||
raise HTTPException(404, f"主机 {host_ip} 未注册")
|
||||
updated = req.model_copy(update={"ip": host_ip})
|
||||
_registry[host_ip] = updated
|
||||
_save_registry()
|
||||
log.info("更新远端主机 %s (user=%s capacity=%d)", host_ip, updated.ssh_user, updated.capacity)
|
||||
return {
|
||||
"ok": True,
|
||||
"ip": host_ip,
|
||||
"ssh_user": updated.ssh_user,
|
||||
"capacity": updated.capacity,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/{host_ip}")
|
||||
async def deregister_host(host_ip: str) -> dict[str, Any]:
|
||||
"""注销远端主机。"""
|
||||
if host_ip not in _registry:
|
||||
raise HTTPException(404, f"主机 {host_ip} 未注册")
|
||||
del _registry[host_ip]
|
||||
_save_registry()
|
||||
log.info("注销远端主机 %s", host_ip)
|
||||
return {"ok": True, "ip": host_ip}
|
||||
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
"""节点操作路由:GET/POST /api/nodes、/api/flows、/api/logs。"""
|
||||
"""节点操作路由:GET/POST /api/nodes、/api/flows、/api/logs 以及节点配置持久化。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import shlex
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
@@ -11,6 +14,26 @@ from pydantic import BaseModel, field_validator
|
||||
|
||||
from controller.api.state import get_session
|
||||
|
||||
NODE_SPECS_PATH: Path = Path("/app/config/node_specs.json")
|
||||
|
||||
|
||||
def _load_node_specs() -> list[dict[str, Any]]:
|
||||
"""从 JSON 文件加载节点配置。"""
|
||||
if not NODE_SPECS_PATH.exists():
|
||||
return []
|
||||
try:
|
||||
return json.loads(NODE_SPECS_PATH.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def _save_node_specs(specs: list[dict[str, Any]]) -> None:
|
||||
"""将节点配置持久化到 JSON 文件。"""
|
||||
NODE_SPECS_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
NODE_SPECS_PATH.write_text(json.dumps(specs, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(tags=["nodes"])
|
||||
|
||||
# 允许在节点内执行的命令白名单。
|
||||
@@ -60,6 +83,24 @@ def _validate_cmd(cmd: str | list[str]) -> None:
|
||||
raise HTTPException(400, f"命令 '{name}' 不在白名单内")
|
||||
|
||||
|
||||
class NodeSpecsBody(BaseModel):
|
||||
"""节点配置列表的请求体。"""
|
||||
specs: list[dict[str, Any]]
|
||||
|
||||
|
||||
@router.get("/api/nodes/specs")
|
||||
async def get_node_specs() -> list[dict[str, Any]]:
|
||||
"""获取保存的节点配置列表。"""
|
||||
return _load_node_specs()
|
||||
|
||||
|
||||
@router.put("/api/nodes/specs")
|
||||
async def save_node_specs(body: NodeSpecsBody) -> dict[str, Any]:
|
||||
"""保存节点配置列表。"""
|
||||
_save_node_specs(body.specs)
|
||||
return {"ok": True, "count": len(body.specs)}
|
||||
|
||||
|
||||
class ExecBody(BaseModel):
|
||||
"""节点内执行命令的请求体。"""
|
||||
cmd: str | list[str]
|
||||
@@ -95,7 +136,7 @@ async def list_flows() -> list[dict[str, Any]]:
|
||||
async def exec_in_node(node_id: int, body: ExecBody) -> dict[str, Any]:
|
||||
"""在指定节点容器内执行命令。支持本地和远端节点。"""
|
||||
sess = get_session()
|
||||
if not sess.docker_mgr and not sess.remote_mgrs:
|
||||
if not sess.docker_mgr and not sess.remote_mgrs and not sess.host_mgrs:
|
||||
raise HTTPException(409, "没有正在运行的仿真")
|
||||
|
||||
# 查找节点所属主机
|
||||
@@ -110,6 +151,14 @@ async def exec_in_node(node_id: int, body: ExecBody) -> dict[str, Any]:
|
||||
rc, out = await asyncio.to_thread(sess.docker_mgr.exec_in, node_id, body.cmd)
|
||||
except KeyError as e:
|
||||
raise HTTPException(404, str(e)) from e
|
||||
elif spec.host_type == "host-manet":
|
||||
mgr = sess.host_mgrs.get(spec.host)
|
||||
if mgr is None:
|
||||
raise HTTPException(409, f"远端主机 {spec.host} 未连接")
|
||||
try:
|
||||
rc, out = await asyncio.to_thread(mgr.exec_in, node_id, body.cmd)
|
||||
except KeyError as e:
|
||||
raise HTTPException(404, str(e)) from e
|
||||
else:
|
||||
mgr = sess.remote_mgrs.get(spec.host)
|
||||
if mgr is None:
|
||||
@@ -125,7 +174,7 @@ async def exec_in_node(node_id: int, body: ExecBody) -> dict[str, Any]:
|
||||
async def get_logs(node: int, tail: int = 200) -> dict[str, Any]:
|
||||
"""获取指定节点容器的日志。支持本地和远端节点。"""
|
||||
sess = get_session()
|
||||
if not sess.docker_mgr and not sess.remote_mgrs:
|
||||
if not sess.docker_mgr and not sess.remote_mgrs and not sess.host_mgrs:
|
||||
raise HTTPException(409, "没有正在运行的仿真")
|
||||
|
||||
spec = next((s for s in sess.specs if s.id == node), None)
|
||||
@@ -139,6 +188,14 @@ async def get_logs(node: int, tail: int = 200) -> dict[str, Any]:
|
||||
text = await asyncio.to_thread(sess.docker_mgr.logs, node, tail=tail)
|
||||
except KeyError as e:
|
||||
raise HTTPException(404, str(e)) from e
|
||||
elif spec.host_type == "host-manet":
|
||||
mgr = sess.host_mgrs.get(spec.host)
|
||||
if mgr is None:
|
||||
raise HTTPException(409, f"远端主机 {spec.host} 未连接")
|
||||
try:
|
||||
text = await asyncio.to_thread(mgr.logs, node, tail=tail)
|
||||
except KeyError as e:
|
||||
raise HTTPException(404, str(e)) from e
|
||||
else:
|
||||
mgr = sess.remote_mgrs.get(spec.host)
|
||||
if mgr is None:
|
||||
|
||||
@@ -3,11 +3,15 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from controller.api.state import Session, get_session
|
||||
from controller.orchestrator import RunRequest, PRESETS
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/sim", tags=["sim"])
|
||||
|
||||
|
||||
@@ -28,6 +32,7 @@ async def start_sim(req: RunRequest | None = None) -> dict[str, Any]:
|
||||
except KeyError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
except Exception as e: # noqa: BLE001
|
||||
log.exception("仿真启动失败")
|
||||
raise HTTPException(500, f"启动失败: {e!r}") from e
|
||||
return {"ok": True, "running": sess.running, "nNodes": sess.config.n_nodes}
|
||||
|
||||
@@ -57,7 +62,8 @@ async def status() -> dict[str, Any]:
|
||||
1 for s in sess.specs
|
||||
if (
|
||||
(s.host == "local" and sess.docker_mgr and sess.docker_mgr.is_running(s.id))
|
||||
or (s.host != "local" and sess.remote_mgrs.get(s.host) and sess.remote_mgrs[s.host].is_running(s.id))
|
||||
or (s.host != "local" and s.host_type == "host-manet" and sess.host_mgrs.get(s.host) and sess.host_mgrs[s.host].is_running(s.id))
|
||||
or (s.host != "local" and s.host_type != "host-manet" and sess.remote_mgrs.get(s.host) and sess.remote_mgrs[s.host].is_running(s.id))
|
||||
)
|
||||
),
|
||||
"preset": sess.preset,
|
||||
|
||||
@@ -27,10 +27,12 @@ from controller.orchestrator.netns import (
|
||||
create_vxlan_on_controller,
|
||||
delete_link,
|
||||
list_stale_links,
|
||||
mesh_mac,
|
||||
node_bridge_name,
|
||||
teardown,
|
||||
)
|
||||
from controller.orchestrator.param_store import ParamStore
|
||||
from controller.orchestrator.host_node_mgr import HostNodeMgr
|
||||
from controller.orchestrator.remote_docker import RemoteDockerMgr
|
||||
from controller.orchestrator.sim_runner import SimRunner
|
||||
from controller.orchestrator.telemetry import Telemetry
|
||||
@@ -40,16 +42,76 @@ SNAPSHOT_PATH: Path = Path("/app/config/sim_snapshot.json")
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _get_controller_ip() -> str:
|
||||
"""Return the IP address the controller host uses for outbound traffic.
|
||||
def _remote_lan_ip(host_ip: str) -> str:
|
||||
"""SSH to *host_ip* and detect its LAN IP (src IP of default route).
|
||||
|
||||
First checks ``MANET_CONTROLLER_IP`` env var, then falls back to
|
||||
auto-detection via the default route.
|
||||
Looks up SSH credentials from the host registry.
|
||||
"""
|
||||
from controller.api.routes_hosts import get_host_registry
|
||||
reg = get_host_registry()
|
||||
entry = reg.get(host_ip)
|
||||
ssh_user = entry.ssh_user if entry else "root"
|
||||
ssh_key = entry.ssh_key if entry else None
|
||||
import paramiko
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
connect_kwargs: dict = {
|
||||
"hostname": host_ip,
|
||||
"username": ssh_user,
|
||||
"timeout": 15,
|
||||
"banner_timeout": 15,
|
||||
}
|
||||
if ssh_key:
|
||||
try:
|
||||
from controller.orchestrator.host_node_mgr import _load_pkey
|
||||
pkey = _load_pkey(ssh_key)
|
||||
if pkey is not None:
|
||||
connect_kwargs["pkey"] = pkey
|
||||
else:
|
||||
connect_kwargs["key_filename"] = ssh_key
|
||||
except Exception:
|
||||
connect_kwargs["key_filename"] = ssh_key
|
||||
try:
|
||||
client.connect(**connect_kwargs)
|
||||
_, stdout, _ = client.exec_command(
|
||||
"ip route get 8.8.8.8", timeout=15
|
||||
)
|
||||
out = stdout.read().decode()
|
||||
parts = out.strip().split()
|
||||
for i, p in enumerate(parts):
|
||||
if p == "src" and i + 1 < len(parts):
|
||||
return parts[i + 1]
|
||||
raise RuntimeError(f"Could not detect LAN IP on {host_ip}")
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
|
||||
def _get_controller_ip(remote_lan_ip: str | None = None) -> str:
|
||||
"""Return the controller IP to use as VXLAN tunnel endpoint.
|
||||
|
||||
If *remote_lan_ip* is given, finds the controller IP on the same
|
||||
/24 subnet (so VXLAN traffic stays on one L2 segment and avoids NAT).
|
||||
Falls back to the default-route source IP, then ``MANET_CONTROLLER_IP``,
|
||||
then 127.0.0.1.
|
||||
"""
|
||||
ip = __import__("os").environ.get("MANET_CONTROLLER_IP")
|
||||
if ip:
|
||||
return ip
|
||||
try:
|
||||
out = subprocess.check_output(
|
||||
["ip", "-4", "addr", "show", "scope", "global"],
|
||||
text=True,
|
||||
)
|
||||
if remote_lan_ip:
|
||||
remote_prefix = ".".join(remote_lan_ip.split(".")[:2]) + "."
|
||||
for line in out.splitlines():
|
||||
line = line.strip()
|
||||
if line.startswith("inet "):
|
||||
parts = line.split()
|
||||
addr = parts[1].split("/")[0]
|
||||
if addr.startswith(remote_prefix):
|
||||
return addr
|
||||
# Fallback: default-route source IP
|
||||
out = subprocess.check_output(
|
||||
["ip", "route", "get", "1.1.1.1"],
|
||||
text=True,
|
||||
@@ -60,16 +122,7 @@ def _get_controller_ip() -> str:
|
||||
return parts[i + 1]
|
||||
except Exception:
|
||||
log.debug("fallback IP detection failed (ip route)", exc_info=True)
|
||||
# Last resort: UDP socket trick
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
s.connect(("8.8.8.8", 80))
|
||||
return s.getsockname()[0]
|
||||
except Exception:
|
||||
log.debug("fallback IP detection failed (UDP socket)", exc_info=True)
|
||||
return "127.0.0.1"
|
||||
finally:
|
||||
s.close()
|
||||
return "127.0.0.1"
|
||||
|
||||
|
||||
def default_node_specs(config: SimConfig) -> list[NodeSpec]:
|
||||
@@ -98,6 +151,7 @@ class Session:
|
||||
sim: Optional[SimRunner] = None
|
||||
docker_mgr: Optional[DockerMgr] = None
|
||||
remote_mgrs: dict[str, RemoteDockerMgr] = field(default_factory=dict)
|
||||
host_mgrs: dict[str, HostNodeMgr] = field(default_factory=dict)
|
||||
telemetry: Optional[Telemetry] = None
|
||||
param_store: Optional[ParamStore] = None
|
||||
specs: list[NodeSpec] = field(default_factory=list)
|
||||
@@ -155,20 +209,68 @@ class Session:
|
||||
await asyncio.to_thread(docker_mgr.stop_all)
|
||||
raise
|
||||
|
||||
# 2. 启动远端节点容器
|
||||
# 2. First pass: detect remote LAN IPs and compute per-remote controller IPs
|
||||
# (before starting containers, so we can pass the correct controller IP)
|
||||
remote_controller_ips: dict[int, str] = {}
|
||||
for spec in remote_specs:
|
||||
remote_host = spec.host
|
||||
if spec.host_type == "host-manet":
|
||||
# SSH to detect the remote's LAN IP (e.g. 192.168.50.199)
|
||||
try:
|
||||
remote_lan = _remote_lan_ip(spec.host)
|
||||
except Exception:
|
||||
log.warning("LAN IP detection failed for %s, using host IP", spec.host)
|
||||
remote_lan = spec.host
|
||||
else:
|
||||
remote_lan = spec.host
|
||||
# Find a controller IP on the same /24 as the remote to avoid NAT
|
||||
local_ip = _get_controller_ip(remote_lan)
|
||||
remote_controller_ips[spec.id] = local_ip
|
||||
|
||||
# 3. 启动远端节点容器(分两类:host-manet-node 和 常规远端容器)
|
||||
remote_mgrs: dict[str, RemoteDockerMgr] = {}
|
||||
controller_ip = _get_controller_ip()
|
||||
host_mgrs: dict[str, HostNodeMgr] = {}
|
||||
try:
|
||||
for spec in remote_specs:
|
||||
mgr = remote_mgrs.get(spec.host)
|
||||
if mgr is None:
|
||||
mgr = RemoteDockerMgr(spec.host)
|
||||
remote_mgrs[spec.host] = mgr
|
||||
await asyncio.to_thread(
|
||||
mgr.start_one, spec, cfg, controller_ip
|
||||
)
|
||||
if spec.host_type == "host-manet":
|
||||
# host-manet-node: SSH 启动容器 + 创建 controller 侧 bridge/tap
|
||||
mgr = host_mgrs.get(spec.host)
|
||||
if mgr is None:
|
||||
from controller.api.routes_hosts import get_host_registry
|
||||
reg = get_host_registry()
|
||||
entry = reg.get(spec.host)
|
||||
if entry is not None:
|
||||
mgr = HostNodeMgr(
|
||||
spec.host,
|
||||
ssh_user=entry.ssh_user,
|
||||
ssh_key=entry.ssh_key,
|
||||
)
|
||||
else:
|
||||
mgr = HostNodeMgr(spec.host)
|
||||
host_mgrs[spec.host] = mgr
|
||||
await asyncio.to_thread(
|
||||
mgr.start_one, spec, cfg,
|
||||
remote_controller_ips.get(spec.id, spec.host),
|
||||
)
|
||||
else:
|
||||
mgr = remote_mgrs.get(spec.host)
|
||||
if mgr is None:
|
||||
mgr = RemoteDockerMgr(spec.host)
|
||||
remote_mgrs[spec.host] = mgr
|
||||
await asyncio.to_thread(
|
||||
mgr.start_one, spec, cfg,
|
||||
remote_controller_ips.get(spec.id, spec.host),
|
||||
)
|
||||
except Exception:
|
||||
# 清理已启动的远端节点和本地节点
|
||||
for mgr in host_mgrs.values():
|
||||
try:
|
||||
mgr.stop_all()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
mgr.close()
|
||||
except Exception:
|
||||
pass
|
||||
for mgr in remote_mgrs.values():
|
||||
try:
|
||||
mgr.stop_all()
|
||||
@@ -181,20 +283,26 @@ class Session:
|
||||
docker_mgr.stop_all()
|
||||
raise
|
||||
|
||||
# 3. 控制器主机为每个远端节点创建 VXLAN 接口
|
||||
# 4. 控制器主机为每个远端节点创建 VXLAN 接口
|
||||
for spec in remote_specs:
|
||||
remote_lan = spec.host
|
||||
if spec.host_type == "host-manet":
|
||||
try:
|
||||
remote_lan = _remote_lan_ip(spec.host)
|
||||
except Exception:
|
||||
log.warning("LAN IP detection failed for %s, using %s", spec.host, spec.host)
|
||||
local_ip = _get_controller_ip(remote_lan)
|
||||
try:
|
||||
create_vxlan_on_controller(
|
||||
spec.id,
|
||||
remote_ip=spec.host,
|
||||
local_ip=controller_ip,
|
||||
remote_ip=remote_lan,
|
||||
local_ip=local_ip,
|
||||
)
|
||||
except Exception:
|
||||
log.warning(
|
||||
"为远端节点 %d (host=%s) 创建 VXLAN 失败",
|
||||
spec.id, spec.host,
|
||||
)
|
||||
# 继续;ns-3 启动时会报错,但至少其他节点可以工作
|
||||
|
||||
# 4. 启动 ns-3 仿真器(驱动所有 TAP)
|
||||
sim = SimRunner(cfg)
|
||||
@@ -204,6 +312,8 @@ class Session:
|
||||
docker_mgr.stop_all()
|
||||
for mgr in remote_mgrs.values():
|
||||
mgr.stop_all()
|
||||
for mgr in host_mgrs.values():
|
||||
mgr.stop_all()
|
||||
teardown(cfg.n_nodes)
|
||||
raise
|
||||
|
||||
@@ -226,11 +336,43 @@ class Session:
|
||||
except Exception as e: # noqa: BLE001
|
||||
log.warning("恢复快照失败: %s", e)
|
||||
|
||||
# 5. 启动容器状态缓存刷新(本地节点)
|
||||
# 5. 注入静态 ARP 条目(避免 mesh+VXLAN 路径下广播 ARP 不可达)
|
||||
for spec in specs:
|
||||
for peer in specs:
|
||||
if spec.id >= peer.id:
|
||||
continue
|
||||
peer_mac = mesh_mac(peer.id)
|
||||
my_mac = mesh_mac(spec.id)
|
||||
if spec.host == "local":
|
||||
try:
|
||||
docker_mgr.exec_in(spec.id, f"arp -s {peer.ip} {peer_mac}")
|
||||
except Exception as e:
|
||||
log.warning("设置 ARP 失败 node %d -> %s: %s", spec.id, peer.ip, e)
|
||||
elif spec.host_type == "host-manet":
|
||||
mgr = host_mgrs.get(spec.host)
|
||||
if mgr:
|
||||
try:
|
||||
mgr.exec_on_host(f"sudo arp -s {peer.ip} {peer_mac} dev vxlan-{spec.id}")
|
||||
except Exception as e:
|
||||
log.warning("设置 ARP 失败 host-node %d -> %s: %s", spec.id, peer.ip, e)
|
||||
if peer.host == "local":
|
||||
try:
|
||||
docker_mgr.exec_in(peer.id, f"arp -s {spec.ip} {my_mac}")
|
||||
except Exception as e:
|
||||
log.warning("设置 ARP 失败 node %d -> %s: %s", peer.id, spec.ip, e)
|
||||
elif peer.host_type == "host-manet":
|
||||
mgr = host_mgrs.get(peer.host)
|
||||
if mgr:
|
||||
try:
|
||||
mgr.exec_on_host(f"sudo arp -s {spec.ip} {my_mac} dev vxlan-{peer.id}")
|
||||
except Exception as e:
|
||||
log.warning("设置 ARP 失败 host-node %d -> %s: %s", peer.id, spec.ip, e)
|
||||
|
||||
# 6. 启动容器状态缓存刷新(本地节点)
|
||||
docker_mgr.start_status_refresh(interval=1.0)
|
||||
|
||||
# 6. 启动遥测泵 (5 Hz)
|
||||
# 统一的状态检查函数,覆盖本地和远端节点
|
||||
# 7. 启动遥测泵 (5 Hz)
|
||||
# 统一的状态检查函数,覆盖本地、host、远端节点
|
||||
specs_by_id = {s.id: s for s in specs}
|
||||
|
||||
def _is_running(node_id: int) -> bool:
|
||||
@@ -239,6 +381,9 @@ class Session:
|
||||
return False
|
||||
if spec.host == "local":
|
||||
return docker_mgr.is_running(node_id)
|
||||
if spec.host_type == "host-manet":
|
||||
mgr = host_mgrs.get(spec.host)
|
||||
return mgr.is_running(node_id) if mgr else False
|
||||
mgr = remote_mgrs.get(spec.host)
|
||||
return mgr.is_running(node_id) if mgr else False
|
||||
|
||||
@@ -249,6 +394,7 @@ class Session:
|
||||
self.config = cfg
|
||||
self.docker_mgr = docker_mgr
|
||||
self.remote_mgrs = remote_mgrs
|
||||
self.host_mgrs = host_mgrs
|
||||
self.sim = sim
|
||||
self.telemetry = tele
|
||||
self.specs = specs
|
||||
@@ -261,13 +407,14 @@ class Session:
|
||||
把上一次仿真留下的 docker 容器/mesh-br/mesh-tap/mesh-veth 兜底删干净。
|
||||
"""
|
||||
with self._lock:
|
||||
sim, docker_mgr, remote_mgrs, tele, specs = (
|
||||
self.sim, self.docker_mgr, self.remote_mgrs, self.telemetry, self.specs
|
||||
sim, docker_mgr, remote_mgrs, host_mgrs, tele, specs = (
|
||||
self.sim, self.docker_mgr, self.remote_mgrs, self.host_mgrs, self.telemetry, self.specs
|
||||
)
|
||||
cfg = self.config
|
||||
last_preset = self.preset
|
||||
self.sim = self.docker_mgr = self.telemetry = None
|
||||
self.remote_mgrs = {}
|
||||
self.host_mgrs = {}
|
||||
self.specs = []
|
||||
self.preset = None
|
||||
|
||||
@@ -287,7 +434,7 @@ class Session:
|
||||
await asyncio.to_thread(docker_mgr.stop_all)
|
||||
except Exception as e: # noqa: BLE001
|
||||
log.warning("docker_mgr.stop_all() 抛异常: %s", e)
|
||||
# 停止所有远端节点
|
||||
# 停止所有远端 container 节点
|
||||
for host_ip, mgr in remote_mgrs.items():
|
||||
try:
|
||||
await asyncio.to_thread(mgr.stop_all)
|
||||
@@ -297,6 +444,16 @@ class Session:
|
||||
mgr.close()
|
||||
except Exception as e: # noqa: BLE001
|
||||
log.warning("remote_mgr %s close() 抛异常: %s", host_ip, e)
|
||||
# 停止所有 host-manet-node 节点
|
||||
for host_ip, mgr in host_mgrs.items():
|
||||
try:
|
||||
await asyncio.to_thread(mgr.stop_all)
|
||||
except Exception as e: # noqa: BLE001
|
||||
log.warning("host_mgr %s stop_all() 抛异常: %s", host_ip, e)
|
||||
try:
|
||||
mgr.close()
|
||||
except Exception as e: # noqa: BLE001
|
||||
log.warning("host_mgr %s close() 抛异常: %s", host_ip, e)
|
||||
# 用配置中的 n_nodes 而不是实际启动的容器数,
|
||||
# 确保 ns-3 创建的所有 tap 接口都被清理
|
||||
try:
|
||||
|
||||
@@ -10,6 +10,7 @@ and the React UI's exportConfig.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal, Mapping
|
||||
@@ -38,6 +39,7 @@ RwMode = Literal["Time", "Distance"]
|
||||
NodeRole = Literal["client", "server", "gateway"]
|
||||
UserAppMode = Literal["bind", "image", "exec"]
|
||||
TrafficMode = Literal["tap", "onoff"]
|
||||
HostType = Literal["container", "host-manet"]
|
||||
|
||||
|
||||
class _CamelModel(BaseModel):
|
||||
@@ -200,6 +202,17 @@ class SimConfig(_CamelModel):
|
||||
node_mac_id: int = Field(default=0, ge=0, le=127)
|
||||
software_version: str = Field(default="V1.00.03")
|
||||
|
||||
# --- Advanced / internal [全局] ---
|
||||
no_ip_node_indices: list[int] = Field(
|
||||
default_factory=list,
|
||||
description="节点索引列表,这些节点不会分配 IP 地址,用作纯 L2 mesh 转发节点",
|
||||
)
|
||||
node_external_macs: dict[str, list[str]] = Field(
|
||||
default_factory=dict,
|
||||
description="Per-node external MACs that should be announced as proxy entries, "
|
||||
"e.g. {\"1\": [\"02:00:00:ff:00:01\"]} for node 1 advertising an external MAC",
|
||||
)
|
||||
|
||||
# ----- helpers -----------------------------------------------------------
|
||||
def merged_with(self, partial: Mapping[str, Any]) -> "SimConfig":
|
||||
"""Return a copy with `partial` overrides (accepts camelCase or snake_case)."""
|
||||
@@ -215,6 +228,7 @@ class NodeSpec(_CamelModel):
|
||||
ip: str
|
||||
role: NodeRole = "client"
|
||||
image: str = "manet-node:latest"
|
||||
host_type: HostType = "container" # "container"→常规容器, "host-manet"→host-manet-node
|
||||
user_app_mode: UserAppMode = "exec"
|
||||
user_app_cmd: str | None = None
|
||||
user_app_bind_path: str | None = None # host path to bind-mount when mode=bind
|
||||
|
||||
@@ -103,6 +103,14 @@ class DockerMgr:
|
||||
log.info("启动 %s (镜像=%s 模式=%s IP=%s)",
|
||||
name, spec.image, spec.user_app_mode, spec.ip)
|
||||
|
||||
# 自动拉取镜像(如果本地不存在)
|
||||
try:
|
||||
self.client.images.get(spec.image)
|
||||
except docker.errors.ImageNotFound:
|
||||
log.info("镜像 %s 不存在,正在拉取...", spec.image)
|
||||
self.client.images.pull(spec.image)
|
||||
log.info("镜像 %s 拉取完成", spec.image)
|
||||
|
||||
container = self.client.containers.run(
|
||||
image=spec.image,
|
||||
name=name,
|
||||
@@ -115,9 +123,15 @@ class DockerMgr:
|
||||
volumes=volumes,
|
||||
)
|
||||
|
||||
# 刷新属性以读取 PID
|
||||
container.reload()
|
||||
pid = container.attrs["State"]["Pid"]
|
||||
# 刷新属性以读取 PID(容器启动可能需要时间,重试 3 次)
|
||||
pid = None
|
||||
for attempt in range(3):
|
||||
container.reload()
|
||||
pid = container.attrs["State"]["Pid"]
|
||||
if pid:
|
||||
break
|
||||
import time
|
||||
time.sleep(0.5)
|
||||
if not pid:
|
||||
raise RuntimeError(f"容器 {name} 启动后没有 PID")
|
||||
|
||||
|
||||
@@ -0,0 +1,337 @@
|
||||
"""Host Node Manager — manages physical hosts as MANET nodes.
|
||||
|
||||
Each physical host runs a `host-manet-node` container (--net=host) that
|
||||
creates a VXLAN tunnel back to the controller. The controller side
|
||||
creates a matching VXLAN + bridge + TAP for each host node.
|
||||
|
||||
Data path:
|
||||
|
||||
Host App → vxlan-{id} ── UDP/4789 ──► Controller vxlan-{id}
|
||||
|
|
||||
mesh-br-{id}
|
||||
├── mesh-tap-{id} → ns-3 PHY/MAC
|
||||
|
||||
Unlike RemoteDockerMgr (which creates `--net=none` containers + veth
|
||||
pairs), the host-manet-node container runs in the *host* network
|
||||
namespace and manages its own VXLAN interface — HostNodeMgr only needs
|
||||
to SSH-start the container and create the controller-side bridge + TAP.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import logging
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
from .config import NodeSpec, SimConfig
|
||||
from . import netns
|
||||
|
||||
try:
|
||||
import paramiko
|
||||
from paramiko import RSAKey, Ed25519Key, ECDSAKey
|
||||
except ImportError as _e:
|
||||
paramiko = None # type: ignore[assignment]
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
HOST_CONTAINER_PREFIX = "manet-host-node-"
|
||||
|
||||
|
||||
def _load_pkey(key_data: str) -> Optional["paramiko.PKey"]:
|
||||
"""Try loading a private key from its PEM/OpenSSH content string."""
|
||||
for cls in (RSAKey, Ed25519Key, ECDSAKey):
|
||||
try:
|
||||
return cls.from_private_key(io.StringIO(key_data))
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
@dataclass
|
||||
class _HostNode:
|
||||
spec: NodeSpec
|
||||
container_id: str
|
||||
|
||||
|
||||
class HostNodeMgr:
|
||||
"""Manages host-manet-node containers on a single remote physical host.
|
||||
|
||||
For each node:
|
||||
1. SSH to the remote host and run the host-manet-node container
|
||||
(which creates the remote-side VXLAN tunnel).
|
||||
2. On the *controller* host: create per-node bridge + TAP interface.
|
||||
3. The VXLAN tunnel on the controller side is created later by
|
||||
``Session.start()`` (calling ``create_vxlan_on_controller``)
|
||||
which also attaches it to the bridge created in step 2.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
host_ip: str,
|
||||
ssh_user: str = "root",
|
||||
ssh_key: str | None = None,
|
||||
ssh_password: str | None = None,
|
||||
):
|
||||
self.host_ip = host_ip
|
||||
self.ssh_user = ssh_user
|
||||
self.ssh_key = ssh_key
|
||||
self.ssh_password = ssh_password
|
||||
self._client: paramiko.SSHClient | None = None
|
||||
self._client_lock = threading.Lock()
|
||||
self._nodes: dict[int, _HostNode] = {}
|
||||
self._nodes_lock = threading.Lock()
|
||||
|
||||
# ------------------------------------------------------------------ SSH
|
||||
def _ssh(self) -> paramiko.SSHClient:
|
||||
"""Lazy-connect (and cache) a Paramiko SSHClient."""
|
||||
if paramiko is None:
|
||||
raise RuntimeError("paramiko is not installed")
|
||||
with self._client_lock:
|
||||
if self._client is not None:
|
||||
transport = self._client.get_transport()
|
||||
if transport is not None and transport.is_active():
|
||||
return self._client
|
||||
try:
|
||||
self._client.close()
|
||||
except Exception:
|
||||
pass
|
||||
self._client = None
|
||||
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
connect_kwargs: dict = {
|
||||
"hostname": self.host_ip,
|
||||
"username": self.ssh_user,
|
||||
"timeout": 30,
|
||||
"banner_timeout": 30,
|
||||
}
|
||||
if self.ssh_key:
|
||||
pkey = _load_pkey(self.ssh_key)
|
||||
if pkey is not None:
|
||||
connect_kwargs["pkey"] = pkey
|
||||
else:
|
||||
raise ValueError(f"无法解析 SSH 私钥 (host={self.host_ip})")
|
||||
elif self.ssh_password:
|
||||
connect_kwargs["password"] = self.ssh_password
|
||||
client.connect(**connect_kwargs)
|
||||
self._client = client
|
||||
log.info("SSH connected to %s@%s", self.ssh_user, self.host_ip)
|
||||
return client
|
||||
|
||||
def _exec(self, cmd: str, timeout: int = 60) -> tuple[int, str, str]:
|
||||
"""Execute a command on the remote host via SSH."""
|
||||
client = self._ssh()
|
||||
log.debug("[host %s] %s", self.host_ip, cmd)
|
||||
stdin, stdout, stderr = client.exec_command(cmd, timeout=timeout)
|
||||
exit_code = stdout.channel.recv_exit_status()
|
||||
out = stdout.read().decode("utf-8", errors="replace")
|
||||
err = stderr.read().decode("utf-8", errors="replace")
|
||||
return exit_code, out, err
|
||||
|
||||
def _exec_ok(self, cmd: str, timeout: int = 60) -> str:
|
||||
"""Execute a command and raise on non-zero exit."""
|
||||
rc, out, err = self._exec(cmd, timeout)
|
||||
if rc != 0:
|
||||
raise RuntimeError(
|
||||
f"Remote command failed on {self.host_ip} (rc={rc}): {cmd}\n"
|
||||
f"stdout: {out}\nstderr: {err}"
|
||||
)
|
||||
return out
|
||||
|
||||
# ------------------------------------------------------------------ container lifecycle
|
||||
def _detect_lan_ip(self) -> str:
|
||||
"""Detect the remote host's LAN IP by checking the default route."""
|
||||
rc, out, _ = self._exec("ip route get 8.8.8.8 2>/dev/null || ip route get 1.1.1.1 2>/dev/null")
|
||||
parts = out.strip().split()
|
||||
for i, p in enumerate(parts):
|
||||
if p == "src" and i + 1 < len(parts):
|
||||
return parts[i + 1]
|
||||
raise RuntimeError(f"Could not detect LAN IP on {self.host_ip}")
|
||||
|
||||
def _create_remote_vxlan(self, node_id: int, node_ip: str,
|
||||
controller_ip: str, remote_mac: str) -> None:
|
||||
"""Create VXLAN on the remote host for a host-manet-node.
|
||||
|
||||
The VXLAN MAC is set to mesh peer MAC so the 802.11s mesh can
|
||||
route frames to/from this remote endpoint.
|
||||
MTU is reduced to 1400 to accommodate VXLAN encapsulation overhead.
|
||||
"""
|
||||
vni = 100 + node_id
|
||||
remote_lan = self._detect_lan_ip()
|
||||
# Delete stale VXLAN if exists
|
||||
self._exec(f"sudo ip link delete vxlan-{node_id} 2>/dev/null || true")
|
||||
# Create VXLAN with correct parameters
|
||||
cmd = (
|
||||
f"sudo ip link add vxlan-{node_id} type vxlan "
|
||||
f"id {vni} local {remote_lan} remote {controller_ip} dstport 4789 && "
|
||||
f"sudo ip link set vxlan-{node_id} address {remote_mac} && "
|
||||
f"sudo ip link set vxlan-{node_id} mtu 1400 && "
|
||||
f"sudo ip addr add {node_ip}/24 dev vxlan-{node_id} && "
|
||||
f"sudo ip link set vxlan-{node_id} up"
|
||||
)
|
||||
self._exec_ok(cmd)
|
||||
log.info("Remote VXLAN vxlan-%d created (mac=%s ip=%s local=%s remote=%s)",
|
||||
node_id, remote_mac, node_ip, remote_lan, controller_ip)
|
||||
|
||||
def start_one(self, spec: NodeSpec, config: SimConfig,
|
||||
controller_ip: str) -> dict:
|
||||
"""Start a host-manet-node container on the remote host.
|
||||
|
||||
Steps:
|
||||
1. SSH to the remote host and pull + run host-manet-node.
|
||||
2. Create remote VXLAN tunnel with correct MAC/IP/MTU.
|
||||
3. On the controller host: create the per-node bridge and TAP.
|
||||
(Local VXLAN will be created by Session.start() later.)
|
||||
|
||||
Returns a dict with {container_id, host_ip, remote_lan_ip}.
|
||||
"""
|
||||
if paramiko is None:
|
||||
raise RuntimeError("paramiko is not installed")
|
||||
|
||||
name = f"{HOST_CONTAINER_PREFIX}{spec.id}"
|
||||
|
||||
# 1) Kill stale container
|
||||
self._exec(f"docker rm -f {name} 2>/dev/null || true")
|
||||
|
||||
# 2) Build env vars
|
||||
env_list = [
|
||||
f"-e NODE_ID={spec.id}",
|
||||
f"-e NODE_IP={spec.ip}",
|
||||
f"-e CONTROLLER_IP={controller_ip}",
|
||||
f"-e NODE_ROLE={spec.role}",
|
||||
f"-e SSH_ENABLE={'1' if spec.ssh_enable else '0'}",
|
||||
f"-e USER_APP_MODE={spec.user_app_mode}",
|
||||
]
|
||||
if spec.user_app_cmd:
|
||||
env_list.append(f"-e USER_APP_CMD='{spec.user_app_cmd}'")
|
||||
if spec.ssh_authorized_keys:
|
||||
env_list.append(f"-e SSH_AUTHORIZED_KEYS='{spec.ssh_authorized_keys}'")
|
||||
|
||||
# Pass the controller's view of the remote host IP as LOCAL_IP
|
||||
env_list.append(f"-e LOCAL_IP={self.host_ip}")
|
||||
|
||||
env_str = " ".join(env_list)
|
||||
|
||||
log.info("Host start %s on %s (image=%s IP=%s)",
|
||||
name, self.host_ip, spec.image, spec.ip)
|
||||
|
||||
# 3) docker run (--net=host, --privileged)
|
||||
# Map local image names to GHCR host-manet-node images.
|
||||
# If the caller specifies a custom image (e.g. GHCR path), use it as-is.
|
||||
image = spec.image or "manet-node:latest"
|
||||
if image in ("manet-node:latest", "host-manet-node:latest"):
|
||||
image = "ghcr.io/clawdbuddy/host-manet-node:main"
|
||||
# v1.1.4+ tagged images
|
||||
if image == "host-manet-node:1.1.4":
|
||||
image = "ghcr.io/clawdbuddy/host-manet-node:1.1.4"
|
||||
# Auto-pull if not present
|
||||
self._exec(f"docker images -q {image} 2>/dev/null | grep -q . || docker pull {image}")
|
||||
run_cmd = (
|
||||
f"docker run -d --name {name} --hostname host-manet-{spec.id} "
|
||||
f"--net=host --privileged --cap-add NET_ADMIN --cap-add SYS_ADMIN "
|
||||
f"{env_str} {image}"
|
||||
)
|
||||
out = self._exec_ok(run_cmd)
|
||||
container_id = out.strip()
|
||||
log.info("Host container %s started: %s", name, container_id)
|
||||
|
||||
# 4) Create remote VXLAN tunnel
|
||||
remote_mac = netns.mesh_mac(spec.id)
|
||||
self._create_remote_vxlan(spec.id, spec.ip, controller_ip, remote_mac)
|
||||
|
||||
# 5) Create controller-side bridge + TAP for this node
|
||||
# (Local VXLAN will be added by Session.start() -> create_vxlan_on_controller)
|
||||
netns.ensure_node_bridge(spec.id)
|
||||
tap_name = f"mesh-tap-{spec.id}"
|
||||
netns.create_tap(tap_name, spec.id)
|
||||
log.info("Controller-side bridge+tap ready for host node %s", spec.id)
|
||||
|
||||
with self._nodes_lock:
|
||||
self._nodes[spec.id] = _HostNode(spec=spec, container_id=container_id)
|
||||
|
||||
remote_lan_ip = self._detect_lan_ip()
|
||||
return {
|
||||
"container_id": container_id,
|
||||
"host_ip": self.host_ip,
|
||||
"remote_lan_ip": remote_lan_ip,
|
||||
}
|
||||
|
||||
def stop_one(self, node_id: int) -> None:
|
||||
"""Stop the host-manet-node container and clean up controller-side links."""
|
||||
with self._nodes_lock:
|
||||
hn = self._nodes.pop(node_id, None)
|
||||
name = f"{HOST_CONTAINER_PREFIX}{node_id}"
|
||||
|
||||
# Best-effort remote cleanup
|
||||
try:
|
||||
self._exec_ok(f"docker rm -f {name} 2>/dev/null || true")
|
||||
except Exception as e:
|
||||
log.warning("host stop: failed to remove %s on %s: %s", name, self.host_ip, e)
|
||||
|
||||
# Clean up remote VXLAN
|
||||
try:
|
||||
self._exec_ok(f"sudo ip link delete vxlan-{node_id} 2>/dev/null || true")
|
||||
except Exception as e:
|
||||
log.warning("host stop: failed to remove vxlan-%d on %s: %s", node_id, self.host_ip, e)
|
||||
|
||||
# Clean up controller-side bridge + tap
|
||||
netns.delete_link(f"mesh-tap-{node_id}")
|
||||
netns.delete_link(netns.node_bridge_name(node_id))
|
||||
log.info("Host node %d cleaned up on controller", node_id)
|
||||
|
||||
def stop_all(self) -> None:
|
||||
"""Stop all host-manet-node containers managed by this manager."""
|
||||
with self._nodes_lock:
|
||||
nids = list(self._nodes)
|
||||
for nid in nids:
|
||||
self.stop_one(nid)
|
||||
|
||||
# ------------------------------------------------------------------ exec / logs / status
|
||||
def exec_on_host(self, cmd: str, timeout: int = 30) -> tuple[int, str]:
|
||||
"""Execute a command directly on the remote host (not inside a container)."""
|
||||
return self._exec(cmd, timeout)
|
||||
|
||||
def exec_in(self, node_id: int, cmd: str | list[str]) -> tuple[int, str]:
|
||||
"""Execute a command inside the host-manet-node container."""
|
||||
hn = self._nodes.get(node_id)
|
||||
if hn is None:
|
||||
raise KeyError(f"Host node {node_id} not found on {self.host_ip}")
|
||||
if isinstance(cmd, list):
|
||||
cmd_str = " ".join(cmd)
|
||||
else:
|
||||
cmd_str = cmd
|
||||
docker_cmd = f"docker exec {hn.container_id} sh -c '{cmd_str}'"
|
||||
rc, out, err = self._exec(docker_cmd)
|
||||
return rc, out + err
|
||||
|
||||
def logs(self, node_id: int, *, tail: int | str = 200) -> str:
|
||||
"""Fetch container logs from the remote host."""
|
||||
hn = self._nodes.get(node_id)
|
||||
if hn is None:
|
||||
raise KeyError(f"Host node {node_id} not found on {self.host_ip}")
|
||||
rc, out, _ = self._exec(f"docker logs --tail {tail} {hn.container_id}")
|
||||
return out
|
||||
|
||||
def is_running(self, node_id: int) -> bool:
|
||||
"""Check whether the host-manet-node container is still running."""
|
||||
hn = self._nodes.get(node_id)
|
||||
if hn is None:
|
||||
return False
|
||||
try:
|
||||
rc, out, _ = self._exec(
|
||||
f"docker inspect -f '{{{{.State.Running}}}}' {hn.container_id}"
|
||||
)
|
||||
return out.strip().lower() == "true"
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def close(self) -> None:
|
||||
"""Close the SSH connection."""
|
||||
with self._client_lock:
|
||||
if self._client is not None:
|
||||
try:
|
||||
self._client.close()
|
||||
except Exception:
|
||||
pass
|
||||
self._client = None
|
||||
@@ -125,19 +125,24 @@ def ensure_bridge(
|
||||
ipr.link("set", index=idx, state="up")
|
||||
|
||||
|
||||
def create_veth(host_name: str, peer_name: str, node_id: int) -> None:
|
||||
def create_veth(host_name: str, peer_name: str, node_id: int, mtu: int = 1400) -> None:
|
||||
"""veth pair; host-side joins the per-node bridge and goes up.
|
||||
Peer-side is left in the host netns (caller moves it into the container)."""
|
||||
Peer-side is left in the host netns (caller moves it into the container).
|
||||
MTU is set to 1400 by default to account for VXLAN overhead."""
|
||||
bridge = node_bridge_name(node_id)
|
||||
ipr = _get_ipr()
|
||||
if _get_link_index(ipr, host_name) is None:
|
||||
ipr.link("add", ifname=host_name, kind="veth", peer={"ifname": peer_name})
|
||||
log.info("created veth pair %s ↔ %s", host_name, peer_name)
|
||||
host_idx = _get_link_index(ipr, host_name)
|
||||
peer_idx = _get_link_index(ipr, peer_name)
|
||||
br_idx = _get_link_index(ipr, bridge)
|
||||
if br_idx is None:
|
||||
raise RuntimeError(f"bridge {bridge} missing; call ensure_node_bridge({node_id}) first")
|
||||
ipr.link("set", index=host_idx, master=br_idx)
|
||||
ipr.link("set", index=host_idx, mtu=mtu)
|
||||
if peer_idx:
|
||||
ipr.link("set", index=peer_idx, mtu=mtu)
|
||||
ipr.link("set", index=host_idx, state="up")
|
||||
|
||||
|
||||
@@ -164,8 +169,12 @@ def move_to_netns(
|
||||
"""Move `peer_name` (host-side) into the netns identified by `pid`,
|
||||
rename it to `rename_to`, optionally set MAC / assign IP, and bring it up."""
|
||||
netns_path = f"/proc/{pid}/ns/net"
|
||||
if not os.path.exists(netns_path):
|
||||
raise RuntimeError(f"container pid {pid} has no /proc/<pid>/ns/net (already exited?)")
|
||||
# 直接尝试打开文件,而不是用 os.path.exists(容器内权限检查可能不准确)
|
||||
try:
|
||||
with open(netns_path) as f:
|
||||
pass
|
||||
except (OSError, PermissionError) as e:
|
||||
raise RuntimeError(f"container pid {pid} has no accessible /proc/<pid>/ns/net: {e}")
|
||||
# 1) move
|
||||
ipr = _get_ipr()
|
||||
idx = _get_link_index(ipr, peer_name)
|
||||
@@ -208,7 +217,7 @@ def move_to_netns(
|
||||
ns.link("set", index=peer_idx, state="up")
|
||||
|
||||
|
||||
def create_tap(name: str, node_id: int) -> None:
|
||||
def create_tap(name: str, node_id: int, mtu: int = 1400) -> None:
|
||||
"""ip tuntap add `name` mode tap; attach to per-node bridge; bring up."""
|
||||
bridge = node_bridge_name(node_id)
|
||||
ipr = _get_ipr()
|
||||
@@ -221,6 +230,7 @@ def create_tap(name: str, node_id: int) -> None:
|
||||
raise RuntimeError(f"bridge {bridge} missing")
|
||||
ipr.link("set", index=idx, master=br_idx)
|
||||
ipr.link("set", index=idx, state="up")
|
||||
ipr.link("set", index=idx, mtu=mtu)
|
||||
|
||||
|
||||
def create_vxlan(
|
||||
@@ -267,6 +277,7 @@ def create_vxlan_on_controller(
|
||||
per-node bridge mesh-br-{node_id}. The ns-3 tap mesh-tap-{node_id} is
|
||||
already (or will be) on the same bridge, so frames from the remote host
|
||||
flow: vxlan -> bridge -> tap -> ns-3.
|
||||
MTU is set to 1400 to accommodate VXLAN encapsulation overhead.
|
||||
"""
|
||||
name = f"vxlan-{node_id}"
|
||||
vni = 100 + node_id
|
||||
@@ -277,13 +288,14 @@ def create_vxlan_on_controller(
|
||||
if idx is None:
|
||||
raise RuntimeError(f"vxlan {name} missing after creation")
|
||||
ipr.link("set", index=idx, state="up")
|
||||
ipr.link("set", index=idx, mtu=1400)
|
||||
|
||||
bridge = node_bridge_name(node_id)
|
||||
br_idx = _get_link_index(ipr, bridge)
|
||||
if br_idx is None:
|
||||
raise RuntimeError(f"bridge {bridge} missing; call ensure_node_bridge({node_id}) first")
|
||||
ipr.link("set", index=idx, master=br_idx)
|
||||
log.info("attached %s to %s", name, bridge)
|
||||
log.info("attached %s (mtu=1400) to %s", name, bridge)
|
||||
|
||||
|
||||
def delete_link(name: str) -> None:
|
||||
|
||||
@@ -28,6 +28,7 @@ from . import netns
|
||||
|
||||
try:
|
||||
import paramiko
|
||||
from paramiko import RSAKey, Ed25519Key, ECDSAKey
|
||||
except ImportError as _e: # pragma: no cover
|
||||
paramiko = None # type: ignore[assignment]
|
||||
|
||||
@@ -36,6 +37,16 @@ log = logging.getLogger(__name__)
|
||||
CONTAINER_PREFIX = "manet-node-"
|
||||
|
||||
|
||||
def _load_pkey(key_path: str) -> "paramiko.PKey | None":
|
||||
"""Try loading a private key file, auto-detecting the type."""
|
||||
for cls in (RSAKey, Ed25519Key, ECDSAKey):
|
||||
try:
|
||||
return cls.from_private_key_file(key_path)
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
@dataclass
|
||||
class _RemoteNode:
|
||||
spec: NodeSpec
|
||||
@@ -88,7 +99,11 @@ class RemoteDockerMgr:
|
||||
"banner_timeout": 30,
|
||||
}
|
||||
if self.ssh_key:
|
||||
connect_kwargs["key_filename"] = self.ssh_key
|
||||
pkey = _load_pkey(self.ssh_key)
|
||||
if pkey is not None:
|
||||
connect_kwargs["pkey"] = pkey
|
||||
else:
|
||||
connect_kwargs["key_filename"] = self.ssh_key
|
||||
elif self.ssh_password:
|
||||
connect_kwargs["password"] = self.ssh_password
|
||||
client.connect(**connect_kwargs)
|
||||
|
||||
@@ -402,7 +402,15 @@ class SimRunner:
|
||||
ns.network.Ipv4Mask("255.255.255.0"),
|
||||
ns.network.Ipv4Address("0.0.0.10"),
|
||||
)
|
||||
ipv4.Assign(devices)
|
||||
if cfg.no_ip_node_indices:
|
||||
filtered = ns.network.NetDeviceContainer()
|
||||
for i in range(cfg.n_nodes):
|
||||
if i not in cfg.no_ip_node_indices:
|
||||
filtered.Add(devices.Get(i))
|
||||
if filtered.GetN() > 0:
|
||||
ipv4.Assign(filtered)
|
||||
else:
|
||||
ipv4.Assign(devices)
|
||||
|
||||
# 9. TapBridge or OnOff internal traffic
|
||||
if cfg.traffic_mode == "tap":
|
||||
@@ -413,6 +421,7 @@ class SimRunner:
|
||||
tb_helper.SetAttribute("DeviceName", ns.core.StringValue(tap_name))
|
||||
tb_helper.Install(nodes.Get(i), devices.Get(i))
|
||||
log.info("TapBridge node-%d ↔ %s", i, tap_name)
|
||||
|
||||
else:
|
||||
# onoff mode: ns-3 internal traffic for baseline throughput test
|
||||
sink_addr = _to_ns3_address(
|
||||
@@ -453,6 +462,10 @@ class SimRunner:
|
||||
cfg.n_nodes - 1, cfg.onoff_data_rate, cfg.onoff_packet_size, cfg.onoff_sink_port
|
||||
)
|
||||
|
||||
# 9b. Host-manet-nodes use the mesh peer MAC for the remote VXLAN,
|
||||
# so no proxy entries are needed — the 802.11s mesh treats the
|
||||
# remote container as a local mesh peer.
|
||||
|
||||
# 10. FlowMonitor
|
||||
if cfg.flow_monitor:
|
||||
fm_helper = ns.flow_monitor.FlowMonitorHelper()
|
||||
@@ -997,6 +1010,7 @@ class SimRunner:
|
||||
# -------------------------------------------------------------- routing
|
||||
@staticmethod
|
||||
def _install_routing(ns: Any, cfg: SimConfig, nodes: Any) -> None:
|
||||
no_ip_set = set(cfg.no_ip_node_indices or [])
|
||||
stack = ns.internet.InternetStackHelper()
|
||||
proto = cfg.routing_protocol
|
||||
if proto == "aodv":
|
||||
@@ -1024,15 +1038,19 @@ class SimRunner:
|
||||
ns.core.TimeValue(ns.core.Seconds(cfg.dsdv_settling_time)))
|
||||
stack.SetRoutingHelper(dsdv)
|
||||
elif proto == "dsr":
|
||||
# DSR requires a separate dsrMain.Install; follow that pattern strictly.
|
||||
stack.Install(nodes)
|
||||
dsr_helper = ns.dsr.DsrHelper()
|
||||
dsr_main = ns.dsr.DsrMainHelper()
|
||||
dsr_main.Install(dsr_helper, nodes)
|
||||
return # stack already installed
|
||||
if not no_ip_set:
|
||||
stack.Install(nodes)
|
||||
dsr_helper = ns.dsr.DsrHelper()
|
||||
dsr_main = ns.dsr.DsrMainHelper()
|
||||
dsr_main.Install(dsr_helper, nodes)
|
||||
return
|
||||
# else "none": IP stack with default static routing only
|
||||
|
||||
stack.Install(nodes)
|
||||
# Install stack per-node, skipping no-ip nodes
|
||||
for i in range(nodes.GetN()):
|
||||
if i in no_ip_set:
|
||||
continue
|
||||
stack.Install(nodes.Get(i))
|
||||
|
||||
# ------------------------------------------------- dynamic control
|
||||
def _inject_command(self, fn: Callable[[], None]) -> dict[str, Any]:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useSimConfig } from '@/hooks/useSimConfig';
|
||||
@@ -8,10 +8,10 @@ import { ConfigPanel } from '@/sections/ConfigPanel';
|
||||
import { TopologyView } from '@/sections/TopologyView';
|
||||
import { LogView } from '@/sections/LogView';
|
||||
import { DynamicControl } from '@/sections/DynamicControl';
|
||||
import { ProtoTest } from '@/sections/ProtoTest';
|
||||
import { NodeManager } from '@/sections/NodeManager';
|
||||
import type { NodeSpec } from '@/types/config';
|
||||
import {
|
||||
LayoutDashboard, Settings, Network, ScrollText, Zap, Radio,
|
||||
LayoutDashboard, Settings, Network, ScrollText, Zap, Server,
|
||||
Play, Square, RotateCw, Wifi, Route,
|
||||
} from 'lucide-react';
|
||||
import './App.css';
|
||||
@@ -24,7 +24,7 @@ const NAV_ITEMS = [
|
||||
{ key: 'dashboard', label: '仪表板', icon: LayoutDashboard },
|
||||
{ key: 'config', label: '配置', icon: Settings },
|
||||
{ key: 'dynamic', label: '动态控制', icon: Zap },
|
||||
{ key: 'proto', label: '协议测试', icon: Radio },
|
||||
{ key: 'nodes', label: '节点管理', icon: Server },
|
||||
{ key: 'logs', label: '日志', icon: ScrollText },
|
||||
] as const;
|
||||
|
||||
@@ -42,6 +42,14 @@ function App() {
|
||||
const [activePage, setActivePage] = useState<PageKey>('dashboard');
|
||||
const [nodeSpecs, setNodeSpecs] = useState<NodeSpec[] | undefined>(undefined);
|
||||
|
||||
// Load node specs from backend on mount (so Start always includes remote-host config)
|
||||
useEffect(() => {
|
||||
fetch('/api/nodes/specs')
|
||||
.then(r => r.ok ? r.json() : [])
|
||||
.then(data => { if (Array.isArray(data) && data.length > 0) setNodeSpecs(data); })
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
const handleStart = () => {
|
||||
startSimulation(config, undefined, nodeSpecs);
|
||||
};
|
||||
@@ -327,10 +335,8 @@ function App() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activePage === 'proto' && (
|
||||
<div className="h-full overflow-hidden animate-fade-in">
|
||||
<ProtoTest />
|
||||
</div>
|
||||
{activePage === 'nodes' && (
|
||||
<NodeManager onNodeSpecsChange={setNodeSpecs} />
|
||||
)}
|
||||
|
||||
{activePage === 'logs' && (
|
||||
|
||||
@@ -170,47 +170,53 @@ export function useSimConfig(sim?: SimApi) {
|
||||
setActivePreset('custom');
|
||||
}, []);
|
||||
|
||||
// ---- auto-save to backend via WebSocket (debounce 500ms) ----
|
||||
// ---- auto-save to backend via REST PUT /api/config (debounce 500ms) ----
|
||||
// 优先使用 REST 保存配置,可靠且不需要 WebSocket 连接。
|
||||
const saveConfig = useCallback(async (cfg: SimConfig) => {
|
||||
if (!sim) {
|
||||
// 无 WebSocket 时回退到 REST PUT
|
||||
setSaveStatus('saving');
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/api/config`, {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(cfg),
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
lastSavedJsonRef.current = JSON.stringify(cfg);
|
||||
setSaveStatus('saved');
|
||||
setTimeout(() => setSaveStatus('idle'), 2000);
|
||||
} catch {
|
||||
setSaveStatus('error');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
setSaveStatus('saving');
|
||||
try {
|
||||
const params: Record<string, unknown> = {};
|
||||
(Object.keys(cfg) as Array<keyof SimConfig>).forEach(key => {
|
||||
params[key] = cfg[key];
|
||||
const res = await fetch(`${API_BASE}/api/config`, {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(cfg),
|
||||
});
|
||||
const result = await sim.batchSetParams(params);
|
||||
// 忽略预期内的失败(如运行时不可修改的参数),只把真正异常视为错误
|
||||
const realFailures = (result.results || []).filter(
|
||||
(r: any) => !r.ok && !(r.reason || '').includes('requires simulator restart')
|
||||
);
|
||||
if (realFailures.length === 0) {
|
||||
lastSavedJsonRef.current = JSON.stringify(cfg);
|
||||
setSaveStatus('saved');
|
||||
setTimeout(() => setSaveStatus('idle'), 2000);
|
||||
} else {
|
||||
console.warn('save failed for keys:', realFailures.map((r: any) => r.key));
|
||||
setSaveStatus('error');
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const data = await res.json();
|
||||
if (data.ok === false) {
|
||||
const reasons = (data.results || [])
|
||||
.filter((r: { ok?: boolean }) => r.ok === false)
|
||||
.map((r: { key?: string; reason?: string }) => r.key || r.reason || 'unknown')
|
||||
.join(', ');
|
||||
if (reasons) console.warn('save partial failures:', reasons);
|
||||
}
|
||||
} catch {
|
||||
lastSavedJsonRef.current = JSON.stringify(cfg);
|
||||
setSaveStatus('saved');
|
||||
setTimeout(() => setSaveStatus('idle'), 2000);
|
||||
} catch (e) {
|
||||
console.warn('saveConfig REST failed:', e);
|
||||
|
||||
// 兜底:WebSocket 路径(仿真运行中需要实时下发的参数)
|
||||
if (sim) {
|
||||
try {
|
||||
const params: Record<string, unknown> = {};
|
||||
(Object.keys(cfg) as Array<keyof SimConfig>).forEach(key => {
|
||||
params[key] = cfg[key];
|
||||
});
|
||||
const result = await sim.batchSetParams(params);
|
||||
const realFailures = (result.results || []).filter(
|
||||
(r: { ok: boolean; reason?: string }) => !r.ok && !(r.reason || '').includes('requires simulator restart')
|
||||
);
|
||||
if (realFailures.length === 0) {
|
||||
lastSavedJsonRef.current = JSON.stringify(cfg);
|
||||
setSaveStatus('saved');
|
||||
setTimeout(() => setSaveStatus('idle'), 2000);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// WS 也失败,继续报 error
|
||||
}
|
||||
}
|
||||
|
||||
setSaveStatus('error');
|
||||
}
|
||||
}, [sim]);
|
||||
|
||||
@@ -0,0 +1,448 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { NodeSpec } from '@/types/config';
|
||||
import {
|
||||
Plus, Trash2, Server, Globe, Wifi,
|
||||
Loader2, RefreshCw, Network, Pencil, Save,
|
||||
} from 'lucide-react';
|
||||
|
||||
interface RemoteHost {
|
||||
ip: string;
|
||||
ssh_user: string;
|
||||
capacity: number;
|
||||
}
|
||||
|
||||
interface NodeManagerProps {
|
||||
onNodeSpecsChange?: (specs: NodeSpec[] | undefined) => void;
|
||||
}
|
||||
|
||||
export function NodeManager({ onNodeSpecsChange }: NodeManagerProps) {
|
||||
// ---- remote host management ----
|
||||
const [remoteHosts, setRemoteHosts] = useState<RemoteHost[]>([]);
|
||||
const [loadingHosts, setLoadingHosts] = useState(false);
|
||||
|
||||
const [newHostIp, setNewHostIp] = useState('');
|
||||
const [newHostUser, setNewHostUser] = useState('root');
|
||||
const [newHostKey, setNewHostKey] = useState('');
|
||||
const [newHostCapacity, setNewHostCapacity] = useState(4);
|
||||
const [registering, setRegistering] = useState(false);
|
||||
const [editingHost, setEditingHost] = useState<string | null>(null);
|
||||
const [editHostUser, setEditHostUser] = useState('');
|
||||
const [editHostKey, setEditHostKey] = useState('');
|
||||
const [editHostCapacity, setEditHostCapacity] = useState(4);
|
||||
|
||||
// ---- node configuration ----
|
||||
const [nodeSpecs, setNodeSpecs] = useState<NodeSpec[]>([]);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
// Load node specs from backend on mount
|
||||
const fetchNodeSpecs = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/nodes/specs');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (Array.isArray(data) && data.length > 0) {
|
||||
setNodeSpecs(data);
|
||||
} else {
|
||||
// Default fallback: 2 local nodes
|
||||
setNodeSpecs([
|
||||
{ id: 0, ip: '192.168.100.10', role: 'server', host: 'local' },
|
||||
{ id: 1, ip: '192.168.100.11', role: 'client', host: 'local' },
|
||||
]);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Save node specs to backend with debounce
|
||||
const saveNodeSpecs = useCallback(async (specs: NodeSpec[]) => {
|
||||
setSaving(true);
|
||||
try {
|
||||
await fetch('/api/nodes/specs', {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ specs }),
|
||||
});
|
||||
} catch {
|
||||
// ignore
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Debounced save: wait 500ms after last change
|
||||
const debouncedSave = useCallback((specs: NodeSpec[]) => {
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current);
|
||||
saveTimer.current = setTimeout(() => saveNodeSpecs(specs), 500);
|
||||
}, [saveNodeSpecs]);
|
||||
|
||||
const fetchHosts = useCallback(async () => {
|
||||
setLoadingHosts(true);
|
||||
try {
|
||||
const res = await fetch('/api/hosts');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setRemoteHosts(Array.isArray(data) ? data : []);
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
} finally {
|
||||
setLoadingHosts(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => { fetchHosts(); fetchNodeSpecs(); }, [fetchHosts, fetchNodeSpecs]);
|
||||
|
||||
const registerHost = async () => {
|
||||
if (!newHostIp.trim()) return;
|
||||
setRegistering(true);
|
||||
try {
|
||||
const body: Record<string, unknown> = {
|
||||
ip: newHostIp.trim(),
|
||||
ssh_user: newHostUser,
|
||||
capacity: newHostCapacity,
|
||||
};
|
||||
if (newHostKey.trim()) body.ssh_key = newHostKey.trim();
|
||||
const res = await fetch('/api/hosts/register', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (res.ok) {
|
||||
await fetchHosts();
|
||||
setNewHostIp('');
|
||||
setNewHostUser('root');
|
||||
setNewHostKey('');
|
||||
setNewHostCapacity(4);
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
} finally {
|
||||
setRegistering(false);
|
||||
}
|
||||
};
|
||||
|
||||
const unregisterHost = async (ip: string) => {
|
||||
try {
|
||||
await fetch(`/api/hosts/${ip}`, { method: 'DELETE' });
|
||||
await fetchHosts();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
};
|
||||
|
||||
const startEditHost = (host: RemoteHost) => {
|
||||
setEditingHost(host.ip);
|
||||
setEditHostUser(host.ssh_user);
|
||||
setEditHostKey('');
|
||||
setEditHostCapacity(host.capacity);
|
||||
};
|
||||
|
||||
const saveEditHost = async () => {
|
||||
if (!editingHost) return;
|
||||
try {
|
||||
const body: Record<string, unknown> = {
|
||||
ip: editingHost,
|
||||
ssh_user: editHostUser,
|
||||
capacity: editHostCapacity,
|
||||
};
|
||||
if (editHostKey.trim()) body.ssh_key = editHostKey.trim();
|
||||
const res = await fetch(`/api/hosts/${editingHost}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (res.ok) {
|
||||
await fetchHosts();
|
||||
setEditingHost(null);
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
};
|
||||
|
||||
const cancelEditHost = () => {
|
||||
setEditingHost(null);
|
||||
};
|
||||
|
||||
// ---- node spec management ----
|
||||
const addNode = () => {
|
||||
const maxId = nodeSpecs.reduce((max, n) => Math.max(max, n.id), -1);
|
||||
const newId = maxId + 1;
|
||||
const newIp = `192.168.100.${10 + newId}`;
|
||||
const updated = [...nodeSpecs, {
|
||||
id: newId,
|
||||
ip: newIp,
|
||||
role: 'client' as const,
|
||||
host: 'local' as const,
|
||||
}];
|
||||
setNodeSpecs(updated);
|
||||
debouncedSave(updated);
|
||||
};
|
||||
|
||||
const removeNode = (id: number) => {
|
||||
const updated = nodeSpecs.filter(n => n.id !== id);
|
||||
setNodeSpecs(updated);
|
||||
debouncedSave(updated);
|
||||
};
|
||||
|
||||
const updateNode = (id: number, field: keyof NodeSpec, value: string) => {
|
||||
const updated = nodeSpecs.map(n =>
|
||||
n.id === id ? { ...n, [field]: value } : n
|
||||
);
|
||||
setNodeSpecs(updated);
|
||||
debouncedSave(updated);
|
||||
};
|
||||
|
||||
// generate updated NodeSpec list whenever specs change
|
||||
const hasRemote = nodeSpecs.some(n => n.host !== 'local');
|
||||
useEffect(() => {
|
||||
if (onNodeSpecsChange) {
|
||||
onNodeSpecsChange(hasRemote ? nodeSpecs : undefined);
|
||||
}
|
||||
}, [nodeSpecs, hasRemote, onNodeSpecsChange]);
|
||||
|
||||
// Clean up debounce timer on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="h-full overflow-auto p-4 space-y-5 max-w-6xl mx-auto animate-fade-in">
|
||||
{/* ---- Remote Hosts ---- */}
|
||||
<Card>
|
||||
<CardHeader className="pb-3 flex flex-row items-center justify-between">
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
<Globe className="h-4 w-4 text-primary" />
|
||||
远端主机管理
|
||||
</CardTitle>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{remoteHosts.length} 台
|
||||
</Badge>
|
||||
<Button size="sm" variant="ghost" onClick={fetchHosts} disabled={loadingHosts} className="h-7 w-7 p-0">
|
||||
<RefreshCw className={cn('h-3.5 w-3.5', loadingHosts && 'animate-spin')} />
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{/* Add host form */}
|
||||
<div className="flex items-end gap-2 flex-wrap">
|
||||
<div className="flex-1 min-w-[140px]">
|
||||
<Label className="text-xs text-muted-foreground">IP 地址</Label>
|
||||
<Input
|
||||
value={newHostIp}
|
||||
onChange={e => setNewHostIp(e.target.value)}
|
||||
placeholder="192.168.1.100"
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="w-[100px]">
|
||||
<Label className="text-xs text-muted-foreground">SSH 用户</Label>
|
||||
<Input
|
||||
value={newHostUser}
|
||||
onChange={e => setNewHostUser(e.target.value)}
|
||||
placeholder="root"
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="w-[160px]">
|
||||
<Label className="text-xs text-muted-foreground">SSH 密钥路径</Label>
|
||||
<Input
|
||||
value={newHostKey}
|
||||
onChange={e => setNewHostKey(e.target.value)}
|
||||
placeholder="/path/to/key"
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="w-[80px]">
|
||||
<Label className="text-xs text-muted-foreground">容量</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={64}
|
||||
value={newHostCapacity}
|
||||
onChange={e => setNewHostCapacity(Number(e.target.value))}
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<Button onClick={registerHost} disabled={registering || !newHostIp.trim()} className="h-9 gap-1.5">
|
||||
{registering ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Plus className="h-3.5 w-3.5" />}
|
||||
注册
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Host list */}
|
||||
{remoteHosts.length === 0 ? (
|
||||
<div className="text-sm text-muted-foreground text-center py-6 border rounded-lg bg-muted/30">
|
||||
<Server className="h-6 w-6 mx-auto mb-2 opacity-30" />
|
||||
暂无已注册的远端主机
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1.5">
|
||||
{remoteHosts.map(host => (
|
||||
editingHost === host.ip ? (
|
||||
<div key={host.ip} className="flex items-end gap-2 px-3 py-2 rounded-lg border bg-accent/30 text-sm">
|
||||
<div className="min-w-0">
|
||||
<Label className="text-xs text-muted-foreground">SSH 用户</Label>
|
||||
<Input value={editHostUser} onChange={e => setEditHostUser(e.target.value)} className="h-8 text-xs mt-0.5" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<Label className="text-xs text-muted-foreground">SSH 密钥路径</Label>
|
||||
<Input value={editHostKey} onChange={e => setEditHostKey(e.target.value)} placeholder="留空不变" className="h-8 text-xs mt-0.5" />
|
||||
</div>
|
||||
<div className="w-[70px]">
|
||||
<Label className="text-xs text-muted-foreground">容量</Label>
|
||||
<Input type="number" min={1} max={64} value={editHostCapacity} onChange={e => setEditHostCapacity(Number(e.target.value))} className="h-8 text-xs mt-0.5" />
|
||||
</div>
|
||||
<Button size="sm" onClick={saveEditHost} className="h-8 gap-1">保存</Button>
|
||||
<Button size="sm" variant="ghost" onClick={cancelEditHost} className="h-8">取消</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
key={host.ip}
|
||||
className="flex items-center gap-3 px-3 py-2 rounded-lg border bg-card text-sm hover:bg-accent/50 transition-colors"
|
||||
>
|
||||
<Globe className="h-4 w-4 text-primary shrink-0" />
|
||||
<span className="font-mono font-medium">{host.ip}</span>
|
||||
<Badge variant="secondary" className="text-[10px]">{host.ssh_user}</Badge>
|
||||
<Badge variant="outline" className="text-[10px] ml-auto">容量 {host.capacity}</Badge>
|
||||
<Button size="sm" variant="ghost" onClick={() => startEditHost(host)} className="h-7 w-7 p-0">
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => unregisterHost(host.ip)} className="h-7 w-7 p-0 text-destructive hover:text-destructive">
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* ---- Node Configuration ---- */}
|
||||
<Card>
|
||||
<CardHeader className="pb-3 flex flex-row items-center justify-between">
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
<Network className="h-4 w-4 text-primary" />
|
||||
节点配置
|
||||
</CardTitle>
|
||||
<div className="flex items-center gap-2">
|
||||
{saving ? (
|
||||
<Badge variant="outline" className="text-xs text-muted-foreground gap-1">
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
保存中
|
||||
</Badge>
|
||||
) : nodeSpecs.length > 0 && (
|
||||
<Badge variant="outline" className="text-xs text-green-600 gap-1">
|
||||
<Save className="h-3 w-3" />
|
||||
已保存
|
||||
</Badge>
|
||||
)}
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{nodeSpecs.length} 节点
|
||||
</Badge>
|
||||
<Button size="sm" onClick={addNode} className="h-8 gap-1.5">
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
添加节点
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
{/* Header */}
|
||||
<div className="grid grid-cols-12 gap-2 px-3 py-1.5 text-xs font-medium text-muted-foreground border-b">
|
||||
<div className="col-span-1">ID</div>
|
||||
<div className="col-span-2">IP 地址</div>
|
||||
<div className="col-span-2">角色</div>
|
||||
<div className="col-span-3">主机</div>
|
||||
<div className="col-span-3">镜像版本</div>
|
||||
<div className="col-span-1" />
|
||||
</div>
|
||||
|
||||
{nodeSpecs.length === 0 ? (
|
||||
<div className="text-sm text-muted-foreground text-center py-8 border rounded-lg bg-muted/30">
|
||||
<Wifi className="h-6 w-6 mx-auto mb-2 opacity-30" />
|
||||
暂无节点,点击"添加节点"创建
|
||||
</div>
|
||||
) : (
|
||||
nodeSpecs.map((spec) => (
|
||||
<div
|
||||
key={spec.id}
|
||||
className="grid grid-cols-12 gap-2 items-center px-3 py-2 rounded-lg border bg-card hover:bg-accent/30 transition-colors"
|
||||
>
|
||||
<div className="col-span-1 font-mono text-sm font-medium">{spec.id}</div>
|
||||
<div className="col-span-2">
|
||||
<Input
|
||||
value={spec.ip}
|
||||
onChange={e => updateNode(spec.id, 'ip', e.target.value)}
|
||||
className="h-8 text-xs font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<select
|
||||
value={spec.role}
|
||||
onChange={e => updateNode(spec.id, 'role', e.target.value)}
|
||||
className="h-8 w-full rounded-lg border bg-background px-2 text-xs"
|
||||
>
|
||||
<option value="server">Server</option>
|
||||
<option value="client">Client</option>
|
||||
<option value="gateway">Gateway</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-span-3">
|
||||
<select
|
||||
value={spec.host}
|
||||
onChange={e => updateNode(spec.id, 'host', e.target.value)}
|
||||
className="h-8 w-full rounded-lg border bg-background px-2 text-xs"
|
||||
>
|
||||
<option value="local">本机 (Local)</option>
|
||||
{remoteHosts.map(h => (
|
||||
<option key={h.ip} value={h.ip}>{h.ip}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-span-3">
|
||||
<Input
|
||||
value={spec.image ?? 'manet-node:latest'}
|
||||
onChange={e => updateNode(spec.id, 'image' as keyof NodeSpec, e.target.value)}
|
||||
placeholder="manet-node:latest"
|
||||
className="h-8 text-xs font-mono"
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-1 flex justify-end">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => removeNode(spec.id)}
|
||||
disabled={nodeSpecs.length <= 1}
|
||||
className="h-8 w-8 p-0 text-destructive hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
|
||||
{hasRemote && (
|
||||
<div className="flex items-center gap-2 mt-2 px-3 py-2 rounded-lg bg-amber-50/80 border border-amber-200/60 text-xs text-amber-800">
|
||||
<Wifi className="h-3.5 w-3.5 shrink-0" />
|
||||
检测到远端节点,启动仿真时将自动创建对应 VXLAN 隧道
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,509 +0,0 @@
|
||||
import { useState, useRef, useCallback, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
Wifi, Send, Trash2, Radio, Settings, RefreshCw,
|
||||
ChevronDown, ChevronRight, Clock, Plug, Unplug,
|
||||
Cpu, Network, MessageSquare,
|
||||
} from 'lucide-react';
|
||||
|
||||
interface Message {
|
||||
id: number;
|
||||
direction: 'sent' | 'received';
|
||||
timestamp: string;
|
||||
payload: string;
|
||||
pretty?: string;
|
||||
}
|
||||
|
||||
const NET_MODE_OPTIONS = [
|
||||
{ value: 1, label: '自组网' },
|
||||
{ value: 2, label: 'LTE' },
|
||||
{ value: 3, label: '天通' },
|
||||
{ value: 4, label: '173RAP' },
|
||||
{ value: 5, label: '173PRN' },
|
||||
{ value: 6, label: '北斗' },
|
||||
{ value: 7, label: 'UV' },
|
||||
{ value: 12, label: '173FCS' },
|
||||
];
|
||||
|
||||
const POWER_OPTIONS = [
|
||||
{ value: 0, label: '值守' },
|
||||
{ value: 1, label: '低' },
|
||||
{ value: 2, label: '中' },
|
||||
{ value: 3, label: '高' },
|
||||
];
|
||||
|
||||
const RATE_OPTIONS = [
|
||||
{ value: 1, label: '9.6kb' },
|
||||
{ value: 2, label: '19.2kb' },
|
||||
{ value: 3, label: '38.4kb' },
|
||||
{ value: 4, label: '62.5kb' },
|
||||
];
|
||||
|
||||
function buildFrame(data: Record<string, unknown>) {
|
||||
return JSON.stringify({
|
||||
data,
|
||||
ident: '',
|
||||
mnemonic: 0,
|
||||
resWord: '',
|
||||
type: 0,
|
||||
version: 0,
|
||||
});
|
||||
}
|
||||
|
||||
export function ProtoTest() {
|
||||
const [wsUrl, setWsUrl] = useState('ws://100.100.100.3:8000/ws/radio');
|
||||
const [connected, setConnected] = useState(false);
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const [customPayload, setCustomPayload] = useState('');
|
||||
const [expandedGroups, setExpandedGroups] = useState<Record<string, boolean>>({
|
||||
query: true,
|
||||
set: true,
|
||||
report: false,
|
||||
reportCfg: false,
|
||||
});
|
||||
|
||||
const [report5002Enabled, setReport5002Enabled] = useState(1);
|
||||
const [report5002Period, setReport5002Period] = useState(2000);
|
||||
const [report5006Enabled, setReport5006Enabled] = useState(1);
|
||||
const [report5006Period, setReport5006Period] = useState(10000);
|
||||
const wsRef = useRef<WebSocket | null>(null);
|
||||
const msgIdRef = useRef(0);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const [netMode, setNetMode] = useState(1);
|
||||
const [ctrl, setCtrl] = useState(1);
|
||||
const [power, setPower] = useState(1);
|
||||
const [freqNum, setFreqNum] = useState(1);
|
||||
const [frequency, setFrequency] = useState(225);
|
||||
const [rate, setRate] = useState(2);
|
||||
const [extend, setExtend] = useState('KZ');
|
||||
|
||||
const [ns3Nodes, setNs3Nodes] = useState<Array<{ id: number; ip: string; status: string }>>([]);
|
||||
const [ns3Loading, setNs3Loading] = useState(false);
|
||||
|
||||
const fetchNs3Nodes = useCallback(async () => {
|
||||
setNs3Loading(true);
|
||||
try {
|
||||
const res = await fetch('/api/nodes');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setNs3Nodes(data);
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
} finally {
|
||||
setNs3Loading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchNs3Nodes();
|
||||
const timer = setInterval(fetchNs3Nodes, 5000);
|
||||
return () => clearInterval(timer);
|
||||
}, [fetchNs3Nodes]);
|
||||
|
||||
useEffect(() => {
|
||||
if (scrollRef.current) {
|
||||
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
|
||||
}
|
||||
}, [messages]);
|
||||
|
||||
const addMessage = useCallback((direction: 'sent' | 'received', payload: string) => {
|
||||
let pretty = '';
|
||||
try {
|
||||
pretty = JSON.stringify(JSON.parse(payload), null, 2);
|
||||
} catch {
|
||||
pretty = payload;
|
||||
}
|
||||
setMessages(prev => [...prev, {
|
||||
id: ++msgIdRef.current,
|
||||
direction,
|
||||
timestamp: new Date().toLocaleTimeString(),
|
||||
payload,
|
||||
pretty,
|
||||
}]);
|
||||
}, []);
|
||||
|
||||
const connect = useCallback(() => {
|
||||
if (wsRef.current?.readyState === WebSocket.OPEN) return;
|
||||
try {
|
||||
const ws = new WebSocket(wsUrl);
|
||||
ws.onopen = () => {
|
||||
setConnected(true);
|
||||
addMessage('received', `// 已连接到 ${wsUrl}`);
|
||||
};
|
||||
ws.onmessage = (ev) => {
|
||||
addMessage('received', ev.data);
|
||||
};
|
||||
ws.onclose = () => {
|
||||
setConnected(false);
|
||||
addMessage('received', `// 连接已关闭 ${wsUrl}`);
|
||||
wsRef.current = null;
|
||||
};
|
||||
ws.onerror = (e) => {
|
||||
setConnected(false);
|
||||
addMessage('received', `// 连接错误: ${(e as ErrorEvent).message || 'unknown'}`);
|
||||
wsRef.current = null;
|
||||
};
|
||||
wsRef.current = ws;
|
||||
} catch (e) {
|
||||
addMessage('received', `// 连接失败: ${(e as Error).message}`);
|
||||
}
|
||||
}, [wsUrl, addMessage]);
|
||||
|
||||
const disconnect = useCallback(() => {
|
||||
wsRef.current?.close();
|
||||
wsRef.current = null;
|
||||
setConnected(false);
|
||||
}, []);
|
||||
|
||||
const send = useCallback((payload: string) => {
|
||||
if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
|
||||
addMessage('received', '// 错误: WebSocket 未连接');
|
||||
return;
|
||||
}
|
||||
wsRef.current.send(payload);
|
||||
addMessage('sent', payload);
|
||||
}, [addMessage]);
|
||||
|
||||
const sendCmd = useCallback((cmdCode: number, extra: Record<string, unknown> = {}) => {
|
||||
const payload = buildFrame({ cmdCode, extend, ...extra });
|
||||
send(payload);
|
||||
}, [extend, send]);
|
||||
|
||||
const clearMessages = useCallback(() => setMessages([]), []);
|
||||
|
||||
const toggleGroup = (key: string) => {
|
||||
setExpandedGroups(prev => ({ ...prev, [key]: !prev[key] }));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col overflow-hidden p-4 gap-3">
|
||||
{/* 顶部连接栏 */}
|
||||
<div className="flex items-center gap-3 shrink-0 bg-card rounded-xl border border-slate-200/60 p-3 shadow-card">
|
||||
<div className={cn(
|
||||
'h-3 w-3 rounded-full shrink-0 ring-2 ring-offset-1 ring-offset-background transition-all',
|
||||
connected ? 'bg-success ring-success/30 status-glow-green' : 'bg-destructive ring-destructive/30'
|
||||
)} />
|
||||
<span className="text-sm font-semibold shrink-0">
|
||||
{connected ? '已连接' : '未连接'}
|
||||
</span>
|
||||
<Input
|
||||
value={wsUrl}
|
||||
onChange={e => setWsUrl(e.target.value)}
|
||||
placeholder="ws://host:port"
|
||||
className="flex-1 h-9 text-sm"
|
||||
disabled={connected}
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={connected ? disconnect : connect}
|
||||
variant={connected ? 'destructive' : 'default'}
|
||||
className="h-9 gap-1.5"
|
||||
>
|
||||
{connected ? <Unplug className="h-3.5 w-3.5" /> : <Plug className="h-3.5 w-3.5" />}
|
||||
{connected ? '断开' : '连接'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 主体 */}
|
||||
<div className="flex-1 min-h-0 flex gap-3">
|
||||
{/* 左侧面板:命令 */}
|
||||
<div className="w-[400px] shrink-0 flex flex-col gap-2 overflow-auto pr-1">
|
||||
{/* 公共参数 */}
|
||||
<div className="border border-slate-200/60 rounded-xl p-3 bg-card shadow-card space-y-2.5">
|
||||
<div className="text-xs font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-1.5">
|
||||
<Cpu className="h-3 w-3" /> 公共参数
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground block mb-1">extend</label>
|
||||
<Input value={extend} onChange={e => setExtend(e.target.value)} className="h-8 text-xs" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground block mb-1">netMode</label>
|
||||
<select
|
||||
value={netMode}
|
||||
onChange={e => setNetMode(Number(e.target.value))}
|
||||
className="h-8 w-full rounded-lg border bg-background px-2 text-xs"
|
||||
>
|
||||
{NET_MODE_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 查询类 */}
|
||||
<div className="border border-slate-200/60 rounded-xl bg-card shadow-card overflow-hidden">
|
||||
<button
|
||||
onClick={() => toggleGroup('query')}
|
||||
className="w-full flex items-center gap-2.5 px-3 py-2.5 text-sm font-medium hover:bg-accent/50 transition-colors"
|
||||
>
|
||||
{expandedGroups.query ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
|
||||
<Radio className="h-3.5 w-3.5 text-primary" />
|
||||
查询类
|
||||
</button>
|
||||
{expandedGroups.query && (
|
||||
<div className="px-3 pb-2.5 space-y-1.5">
|
||||
<CmdBtn label="网络模块开关 (1001)" onClick={() => sendCmd(1001)} />
|
||||
<CmdBtn label="入网状态 (1025)" onClick={() => sendCmd(1025, { netMode })} />
|
||||
<CmdBtn label="功率 (1071)" onClick={() => sendCmd(1071, { netMode })} />
|
||||
<CmdBtn label="频表 (1049)" onClick={() => sendCmd(1049, { netMode })} />
|
||||
<CmdBtn label="频率 (7001)" onClick={() => sendCmd(7001)} />
|
||||
<CmdBtn label="速率 (7003)" onClick={() => sendCmd(7003)} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 设置类 */}
|
||||
<div className="border border-slate-200/60 rounded-xl bg-card shadow-card overflow-hidden">
|
||||
<button
|
||||
onClick={() => toggleGroup('set')}
|
||||
className="w-full flex items-center gap-2.5 px-3 py-2.5 text-sm font-medium hover:bg-accent/50 transition-colors"
|
||||
>
|
||||
{expandedGroups.set ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
|
||||
<Settings className="h-3.5 w-3.5 text-amber-500" />
|
||||
设置类
|
||||
</button>
|
||||
{expandedGroups.set && (
|
||||
<div className="px-3 pb-2.5 space-y-2">
|
||||
<CmdBtn label={`网络模块开关 (2001) ctrl=${ctrl}`} onClick={() => sendCmd(2001, { netMode, ctrl })} />
|
||||
<div className="flex gap-2 items-center">
|
||||
<span className="text-xs text-muted-foreground">ctrl:</span>
|
||||
<select value={ctrl} onChange={e => setCtrl(Number(e.target.value))} className="h-7 rounded-lg border bg-background px-2 text-xs">
|
||||
<option value={0}>关</option>
|
||||
<option value={1}>开</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<CmdBtn label={`功率 (2043) power=${power}`} onClick={() => sendCmd(2043, { netMode, power })} />
|
||||
<div className="flex gap-2 items-center">
|
||||
<span className="text-xs text-muted-foreground">power:</span>
|
||||
<select value={power} onChange={e => setPower(Number(e.target.value))} className="h-7 rounded-lg border bg-background px-2 text-xs">
|
||||
{POWER_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<CmdBtn label={`频表 (2023) freqNum=${freqNum}`} onClick={() => sendCmd(2023, { netMode, freqNum })} />
|
||||
<div className="flex gap-2 items-center">
|
||||
<span className="text-xs text-muted-foreground">freqNum:</span>
|
||||
<Input type="number" min={0} max={20} value={freqNum} onChange={e => setFreqNum(Number(e.target.value))} className="h-7 w-16 text-xs" />
|
||||
</div>
|
||||
|
||||
<CmdBtn label={`频率 (8001) freq=${frequency}MHz`} onClick={() => sendCmd(8001, { frequency })} />
|
||||
<div className="flex gap-2 items-center">
|
||||
<span className="text-xs text-muted-foreground">frequency:</span>
|
||||
<Input type="number" min={225} max={512} value={frequency} onChange={e => setFrequency(Number(e.target.value))} className="h-7 w-20 text-xs" />
|
||||
<span className="text-xs text-muted-foreground">MHz</span>
|
||||
</div>
|
||||
|
||||
<CmdBtn label={`速率 (8003) rate=${rate}`} onClick={() => sendCmd(8003, { rate })} />
|
||||
<div className="flex gap-2 items-center">
|
||||
<span className="text-xs text-muted-foreground">rate:</span>
|
||||
<select value={rate} onChange={e => setRate(Number(e.target.value))} className="h-7 rounded-lg border bg-background px-2 text-xs">
|
||||
{RATE_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 上报类 */}
|
||||
<div className="border border-slate-200/60 rounded-xl bg-card shadow-card overflow-hidden">
|
||||
<button
|
||||
onClick={() => toggleGroup('report')}
|
||||
className="w-full flex items-center gap-2.5 px-3 py-2.5 text-sm font-medium hover:bg-accent/50 transition-colors"
|
||||
>
|
||||
{expandedGroups.report ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
|
||||
<Network className="h-3.5 w-3.5 text-emerald-500" />
|
||||
上报类(对接 控制器)
|
||||
</button>
|
||||
{expandedGroups.report && (
|
||||
<div className="px-3 pb-2.5 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
在线节点: {ns3Nodes.filter(n => n.status === 'online').length}/{ns3Nodes.length}
|
||||
</span>
|
||||
<Button size="sm" variant="ghost" onClick={fetchNs3Nodes} disabled={ns3Loading} className="h-7 gap-1 text-xs">
|
||||
<RefreshCw className={cn('h-3 w-3', ns3Loading && 'animate-spin')} />
|
||||
刷新
|
||||
</Button>
|
||||
</div>
|
||||
<CmdBtn
|
||||
label={`入网断网提示 (5002) state=${ns3Nodes.some(n => n.status === 'online') ? 1 : 0}`}
|
||||
onClick={() => {
|
||||
const state = ns3Nodes.some(n => n.status === 'online') ? 1 : 0;
|
||||
sendCmd(5002, { netMode, state });
|
||||
}}
|
||||
/>
|
||||
<CmdBtn
|
||||
label={`在线信息上报 (5006) IP数=${ns3Nodes.filter(n => n.status === 'online').length}`}
|
||||
onClick={() => {
|
||||
const onlineIps = ns3Nodes.filter(n => n.status === 'online').map(n => n.ip);
|
||||
sendCmd(5006, { netMode, groupMebsIP: onlineIps.length > 0 ? onlineIps : [] });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 上报配置 */}
|
||||
<div className="border border-slate-200/60 rounded-xl bg-card shadow-card overflow-hidden">
|
||||
<button
|
||||
onClick={() => toggleGroup('reportCfg')}
|
||||
className="w-full flex items-center gap-2.5 px-3 py-2.5 text-sm font-medium hover:bg-accent/50 transition-colors"
|
||||
>
|
||||
{expandedGroups.reportCfg ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
|
||||
<MessageSquare className="h-3.5 w-3.5 text-violet-500" />
|
||||
上报配置(开关与周期)
|
||||
</button>
|
||||
{expandedGroups.reportCfg && (
|
||||
<div className="px-3 pb-2.5 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground w-16 font-mono">5002:</span>
|
||||
<select
|
||||
value={report5002Enabled}
|
||||
onChange={e => setReport5002Enabled(Number(e.target.value))}
|
||||
className="h-7 rounded-lg border bg-background px-2 text-xs"
|
||||
>
|
||||
<option value={1}>开</option>
|
||||
<option value={0}>关</option>
|
||||
</select>
|
||||
<Input
|
||||
type="number"
|
||||
min={500}
|
||||
max={300000}
|
||||
step={100}
|
||||
value={report5002Period}
|
||||
onChange={e => setReport5002Period(Number(e.target.value))}
|
||||
className="h-7 w-20 text-xs"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">ms</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground w-16 font-mono">5006:</span>
|
||||
<select
|
||||
value={report5006Enabled}
|
||||
onChange={e => setReport5006Enabled(Number(e.target.value))}
|
||||
className="h-7 rounded-lg border bg-background px-2 text-xs"
|
||||
>
|
||||
<option value={1}>开</option>
|
||||
<option value={0}>关</option>
|
||||
</select>
|
||||
<Input
|
||||
type="number"
|
||||
min={500}
|
||||
max={300000}
|
||||
step={100}
|
||||
value={report5006Period}
|
||||
onChange={e => setReport5006Period(Number(e.target.value))}
|
||||
className="h-7 w-20 text-xs"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">ms</span>
|
||||
</div>
|
||||
<div className="flex gap-2 pt-1">
|
||||
<CmdBtn label="查询配置 (9001)" onClick={() => sendCmd(9001)} />
|
||||
<CmdBtn label="应用配置 (9003)" onClick={() =>
|
||||
sendCmd(9003, {
|
||||
report5002Enabled, report5002Period,
|
||||
report5006Enabled, report5006Period,
|
||||
})
|
||||
} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 右侧:消息日志 + 自定义发送 */}
|
||||
<div className="flex-1 min-w-0 flex flex-col gap-3">
|
||||
{/* 自定义发送 */}
|
||||
<div className="border border-slate-200/60 rounded-xl p-3 bg-card shadow-card shrink-0">
|
||||
<div className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2 flex items-center gap-1.5">
|
||||
<MessageSquare className="h-3 w-3" /> 自定义 JSON
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<textarea
|
||||
value={customPayload}
|
||||
onChange={e => setCustomPayload(e.target.value)}
|
||||
placeholder='{"data":{"cmdCode":1001,"extend":"KZ"},...}'
|
||||
className="flex-1 h-16 rounded-lg border bg-background px-3 py-2 text-xs font-mono resize-none focus:ring-2 focus:ring-primary/20 focus:border-primary outline-none transition-all"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => { send(customPayload); setCustomPayload(''); }}
|
||||
disabled={!connected || !customPayload.trim()}
|
||||
className="h-16 gap-1.5"
|
||||
>
|
||||
<Send className="h-3.5 w-3.5" />
|
||||
发送
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 消息日志 */}
|
||||
<div className="flex-1 min-h-0 border border-slate-200/60 rounded-xl bg-card shadow-card flex flex-col overflow-hidden">
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b shrink-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<Clock className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<span className="text-sm font-semibold">消息日志</span>
|
||||
<Badge variant="secondary" className="text-[10px] px-1.5 py-0 h-4 font-mono">{messages.length}</Badge>
|
||||
</div>
|
||||
<Button size="sm" variant="ghost" onClick={clearMessages} className="h-7 gap-1.5 text-xs">
|
||||
<Trash2 className="h-3 w-3" />
|
||||
清空
|
||||
</Button>
|
||||
</div>
|
||||
<div ref={scrollRef} className="flex-1 overflow-auto p-3 space-y-1.5 font-mono text-xs">
|
||||
{messages.length === 0 && (
|
||||
<div className="flex flex-col items-center justify-center text-muted-foreground py-16">
|
||||
<Wifi className="h-8 w-8 mb-3 opacity-20" />
|
||||
<p>暂无消息,连接后发送命令</p>
|
||||
</div>
|
||||
)}
|
||||
{messages.map(msg => (
|
||||
<div
|
||||
key={msg.id}
|
||||
className={cn(
|
||||
'rounded-lg px-3 py-2 border-l-2 transition-colors',
|
||||
msg.direction === 'sent'
|
||||
? 'bg-blue-50/70 border-l-blue-500 dark:bg-blue-950/30'
|
||||
: 'bg-emerald-50/70 border-l-emerald-500 dark:bg-emerald-950/30'
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className={cn(
|
||||
'text-[10px] font-bold px-1.5 py-0.5 rounded-md',
|
||||
msg.direction === 'sent' ? 'bg-blue-200 text-blue-800' : 'bg-emerald-200 text-emerald-800'
|
||||
)}>
|
||||
{msg.direction === 'sent' ? '→ 发送' : '← 接收'}
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground font-mono">{msg.timestamp}</span>
|
||||
</div>
|
||||
<pre className="whitespace-pre-wrap break-all text-[11px] leading-relaxed">{msg.pretty || msg.payload}</pre>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CmdBtn({ label, onClick }: { label: string; onClick: () => void }) {
|
||||
return (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={onClick}
|
||||
className="w-full h-8 justify-start text-xs gap-1.5 hover:bg-primary/5 hover:border-primary/30 transition-colors"
|
||||
>
|
||||
<Send className="h-3 w-3 shrink-0 text-primary" />
|
||||
{label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -157,6 +157,7 @@ export interface NodeSpec {
|
||||
ip: string;
|
||||
role: string;
|
||||
host: string;
|
||||
hostType?: string; // "container" | "host-manet"
|
||||
image?: string;
|
||||
userAppMode?: string;
|
||||
userAppCmd?: string;
|
||||
|
||||
Reference in new issue
Block a user