Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4ea05e5b3 | ||
|
|
f03cb13c87 | ||
|
|
33ed6d2c12 | ||
|
|
7c2b5a95c9 | ||
|
|
3faa1fb570 | ||
|
|
d6ab25c363 |
No files matched your search
BIN
Binary file not shown.
@@ -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"
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
import shlex
|
||||
from typing import Any
|
||||
@@ -11,6 +12,8 @@ from pydantic import BaseModel, field_validator
|
||||
|
||||
from controller.api.state import get_session
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(tags=["nodes"])
|
||||
|
||||
# 允许在节点内执行的命令白名单。
|
||||
@@ -95,7 +98,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 +113,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 +136,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 +150,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:
|
||||
|
||||
@@ -57,7 +57,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,
|
||||
|
||||
@@ -31,6 +31,7 @@ from controller.orchestrator.netns import (
|
||||
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 +41,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 +121,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 +150,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 +208,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 +282,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 +311,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
|
||||
|
||||
@@ -230,7 +339,7 @@ class Session:
|
||||
docker_mgr.start_status_refresh(interval=1.0)
|
||||
|
||||
# 6. 启动遥测泵 (5 Hz)
|
||||
# 统一的状态检查函数,覆盖本地和远端节点
|
||||
# 统一的状态检查函数,覆盖本地、host、远端节点
|
||||
specs_by_id = {s.id: s for s in specs}
|
||||
|
||||
def _is_running(node_id: int) -> bool:
|
||||
@@ -239,6 +348,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 +361,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 +374,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 +401,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 +411,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
|
||||
|
||||
@@ -115,9 +115,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,328 @@
|
||||
"""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 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_path: str) -> Optional["paramiko.PKey"]:
|
||||
"""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 _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:
|
||||
connect_kwargs["key_filename"] = self.ssh_key
|
||||
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)
|
||||
# If spec.image is the default container image, use the host-specific one.
|
||||
# Otherwise trust the caller's image choice (e.g. GHCR path).
|
||||
if spec.image == "manet-node:latest":
|
||||
image = "ghcr.io/clawdbuddy/host-manet-node:main"
|
||||
else:
|
||||
image = spec.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_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]:
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
#!/usr/bin/env python3
|
||||
"""UDP 二进制协议测试脚本(api_54.docx)。
|
||||
|
||||
用法:
|
||||
python3 test_udp_protocol.py [--host 127.0.0.1] [--port 62450]
|
||||
|
||||
测试项:
|
||||
1. 静态参数查询 (0x0041~0x0045)
|
||||
2. 静态参数设置 (0x0001~0x0005) + ACK/NACK
|
||||
3. 动态参数查询 (0x0141~0x0142)
|
||||
4. 动态参数设置 (0x0101~0x0102) + ACK/NACK
|
||||
5. 版本查询 (0x0203)
|
||||
6. 拓扑查询 (0x0310) — 仿真未运行时预期返回 NACK
|
||||
7. 周期上报 — 订阅后等待 5~6 秒接收 0x0310 / 0x02AF
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
|
||||
|
||||
def build_frame(cmd_id: int, payload: bytes = b"", comm_type: int = 1) -> bytes:
|
||||
"""构造 UDP 协议帧。"""
|
||||
header = struct.pack(">BBBH", comm_type, 0, 0, cmd_id)
|
||||
length = struct.pack(">H", len(payload))
|
||||
return header + length + payload
|
||||
|
||||
|
||||
def parse_frame(data: bytes) -> tuple[int, int, bytes]:
|
||||
"""解析 UDP 协议帧,返回 (comm_type, cmd_id, payload)。"""
|
||||
if len(data) < 7:
|
||||
raise ValueError(f"帧太短: {len(data)}")
|
||||
comm_type, _, _, cmd_id = struct.unpack(">BBBH", data[:5])
|
||||
length, = struct.unpack(">H", data[5:7])
|
||||
payload = data[7 : 7 + length]
|
||||
return comm_type, cmd_id, payload
|
||||
|
||||
|
||||
def hex_bytes(data: bytes) -> str:
|
||||
return " ".join(f"{b:02X}" for b in data)
|
||||
|
||||
|
||||
class UdpTester:
|
||||
def __init__(self, host: str, port: int, timeout: float = 3.0):
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
self.sock.settimeout(timeout)
|
||||
self.sock.bind(("0.0.0.0", 0)) # 任意源端口
|
||||
|
||||
def send_recv(self, cmd_id: int, payload: bytes = b"", comm_type: int = 1) -> tuple[int, int, bytes] | None:
|
||||
"""发送一帧并等待响应。返回 (comm_type, cmd_id, payload) 或 None(超时)。"""
|
||||
req = build_frame(cmd_id, payload, comm_type)
|
||||
self.sock.sendto(req, (self.host, self.port))
|
||||
try:
|
||||
data, addr = self.sock.recvfrom(2048)
|
||||
return parse_frame(data)
|
||||
except socket.timeout:
|
||||
return None
|
||||
|
||||
# ------------------------------------------------------------------ 测试用例
|
||||
|
||||
def test_static_query(self) -> bool:
|
||||
"""测试静态参数查询。"""
|
||||
print("\n[1] 静态参数查询")
|
||||
ok = True
|
||||
queries = [
|
||||
(0x0041, 0x0081, "网络规模"),
|
||||
(0x0042, 0x0082, "工作模式"),
|
||||
(0x0043, 0x0083, "MAC 地址"),
|
||||
(0x0044, 0x0084, "定频频率"),
|
||||
(0x0045, 0x0085, "跳频表号"),
|
||||
]
|
||||
for req_cmd, expected_resp_cmd, name in queries:
|
||||
resp = self.send_recv(req_cmd)
|
||||
if resp is None:
|
||||
print(f" FAIL [{name}] 超时")
|
||||
ok = False
|
||||
continue
|
||||
_, resp_cmd, payload = resp
|
||||
if resp_cmd == expected_resp_cmd:
|
||||
print(f" PASS [{name}] 0x{resp_cmd:04X} payload={hex_bytes(payload)}")
|
||||
else:
|
||||
print(f" FAIL [{name}] 期望 0x{expected_resp_cmd:04X}, 收到 0x{resp_cmd:04X}")
|
||||
ok = False
|
||||
return ok
|
||||
|
||||
def test_static_set(self) -> bool:
|
||||
"""测试静态参数设置 + ACK/NACK。"""
|
||||
print("\n[2] 静态参数设置")
|
||||
ok = True
|
||||
|
||||
# 2.1 设置网络规模 = 8 (0x0008)
|
||||
resp = self.send_recv(0x0001, struct.pack(">H", 8))
|
||||
ok = self._check_ack(resp, 0x0001, "设置网络规模=8") and ok
|
||||
|
||||
# 2.2 设置工作模式 = 2 (FCS)
|
||||
resp = self.send_recv(0x0002, bytes([2]))
|
||||
ok = self._check_ack(resp, 0x0002, "设置工作模式=2") and ok
|
||||
|
||||
# 2.3 设置 MAC 地址 = 10
|
||||
resp = self.send_recv(0x0003, struct.pack(">H", 10))
|
||||
ok = self._check_ack(resp, 0x0003, "设置 MAC 地址=10") and ok
|
||||
|
||||
# 2.4 设置定频频率 = 505.54 MHz (BCD: 00 50 55 40)
|
||||
resp = self.send_recv(0x0004, bytes([0x00, 0x50, 0x55, 0x40]))
|
||||
ok = self._check_ack(resp, 0x0004, "设置频率=505.54MHz") and ok
|
||||
|
||||
# 2.5 设置跳频表号 = 5
|
||||
resp = self.send_recv(0x0005, bytes([5]))
|
||||
ok = self._check_ack(resp, 0x0005, "设置跳频表号=5") and ok
|
||||
|
||||
# 2.6 查询验证写入值
|
||||
print(" 查询验证...")
|
||||
resp = self.send_recv(0x0041)
|
||||
if resp and resp[1] == 0x0081:
|
||||
val = struct.unpack(">H", resp[2])[0]
|
||||
print(f" 网络规模 = {val} {'PASS' if val == 8 else 'FAIL'}")
|
||||
ok = ok and (val == 8)
|
||||
|
||||
resp = self.send_recv(0x0044)
|
||||
if resp and resp[1] == 0x0084:
|
||||
# BCD 解码简单验证
|
||||
print(f" 频率 payload = {hex_bytes(resp[2])}")
|
||||
|
||||
return ok
|
||||
|
||||
def test_dynamic_query(self) -> bool:
|
||||
"""测试动态参数查询。"""
|
||||
print("\n[3] 动态参数查询")
|
||||
ok = True
|
||||
queries = [
|
||||
(0x0141, 0x0181, "传输速率"),
|
||||
(0x0142, 0x0182, "发射功率"),
|
||||
]
|
||||
for req_cmd, expected_resp_cmd, name in queries:
|
||||
resp = self.send_recv(req_cmd)
|
||||
if resp is None:
|
||||
print(f" FAIL [{name}] 超时")
|
||||
ok = False
|
||||
continue
|
||||
_, resp_cmd, payload = resp
|
||||
if resp_cmd == expected_resp_cmd:
|
||||
print(f" PASS [{name}] 0x{resp_cmd:04X} payload={hex_bytes(payload)}")
|
||||
else:
|
||||
print(f" FAIL [{name}] 期望 0x{expected_resp_cmd:04X}, 收到 0x{resp_cmd:04X}")
|
||||
ok = False
|
||||
return ok
|
||||
|
||||
def test_dynamic_set(self) -> bool:
|
||||
"""测试动态参数设置。"""
|
||||
print("\n[4] 动态参数设置")
|
||||
ok = True
|
||||
|
||||
# 4.1 设置速率档位 = 5 (宽 4Mbps)
|
||||
resp = self.send_recv(0x0101, bytes([0x05]))
|
||||
ok = self._check_ack(resp, 0x0101, "设置速率档位=5") and ok
|
||||
|
||||
# 4.2 设置功率档位 = 2 (小功率)
|
||||
resp = self.send_recv(0x0102, bytes([0x02]))
|
||||
ok = self._check_ack(resp, 0x0102, "设置功率档位=2") and ok
|
||||
|
||||
# 4.3 查询验证
|
||||
resp = self.send_recv(0x0141)
|
||||
if resp and resp[1] == 0x0181 and len(resp[2]) == 1:
|
||||
level = resp[2][0]
|
||||
print(f" 速率档位 = {level} {'PASS' if level == 5 else 'FAIL'}")
|
||||
ok = ok and (level == 5)
|
||||
|
||||
resp = self.send_recv(0x0142)
|
||||
if resp and resp[1] == 0x0182 and len(resp[2]) == 1:
|
||||
level = resp[2][0]
|
||||
print(f" 功率档位 = {level} {'PASS' if level == 2 else 'FAIL'}")
|
||||
ok = ok and (level == 2)
|
||||
|
||||
return ok
|
||||
|
||||
def test_version(self) -> bool:
|
||||
"""测试版本查询。"""
|
||||
print("\n[5] 版本查询")
|
||||
resp = self.send_recv(0x0203)
|
||||
if resp is None:
|
||||
print(" FAIL 超时")
|
||||
return False
|
||||
_, resp_cmd, payload = resp
|
||||
if resp_cmd == 0x02A3:
|
||||
version = payload.decode("ascii", errors="replace")
|
||||
print(f" PASS 版本 = {version}")
|
||||
return True
|
||||
else:
|
||||
print(f" FAIL 期望 0x02A3, 收到 0x{resp_cmd:04X}")
|
||||
return False
|
||||
|
||||
def test_topology(self) -> bool:
|
||||
"""测试拓扑查询 — 仿真未运行时预期返回 NACK。"""
|
||||
print("\n[6] 拓扑查询(仿真未运行)")
|
||||
resp = self.send_recv(0x0310)
|
||||
if resp is None:
|
||||
print(" FAIL 超时")
|
||||
return False
|
||||
_, resp_cmd, payload = resp
|
||||
if resp_cmd == 0x02A1: # NACK
|
||||
acked_cmd = struct.unpack(">H", payload)[0]
|
||||
print(f" PASS 返回 NACK (仿真未运行), acked_cmd=0x{acked_cmd:04X}")
|
||||
return True
|
||||
elif resp_cmd == 0x0310:
|
||||
print(f" INFO 返回拓扑数据 payload={hex_bytes(payload)}")
|
||||
return True
|
||||
else:
|
||||
print(f" FAIL 期望 NACK 或 0x0310, 收到 0x{resp_cmd:04X}")
|
||||
return False
|
||||
|
||||
def test_periodic_report(self) -> bool:
|
||||
"""测试周期上报 — 等待 6 秒接收自动推送。"""
|
||||
print("\n[7] 周期上报(等待 6 秒)")
|
||||
print(" 先发送一帧以激活订阅...")
|
||||
self.send_recv(0x0041) # 任意合法帧,使控制器记录源地址
|
||||
|
||||
print(" 等待 0x0310 拓扑 / 0x02AF 状态上报...")
|
||||
self.sock.settimeout(6.5)
|
||||
found_topo = False
|
||||
found_status = False
|
||||
deadline = time.time() + 6.0
|
||||
while time.time() < deadline:
|
||||
remaining = deadline - time.time()
|
||||
if remaining <= 0:
|
||||
break
|
||||
self.sock.settimeout(max(0.1, remaining))
|
||||
try:
|
||||
data, addr = self.sock.recvfrom(2048)
|
||||
_, cmd_id, payload = parse_frame(data)
|
||||
if cmd_id == 0x0310:
|
||||
print(f" 收到拓扑上报 0x0310 payload_len={len(payload)}")
|
||||
found_topo = True
|
||||
elif cmd_id == 0x02AF:
|
||||
print(f" 收到状态上报 0x02AF payload={hex_bytes(payload)}")
|
||||
found_status = True
|
||||
except socket.timeout:
|
||||
pass
|
||||
|
||||
ok = found_topo or found_status
|
||||
if not ok:
|
||||
print(" WARN 未收到周期上报(仿真未运行时不发送)")
|
||||
return ok
|
||||
|
||||
# ------------------------------------------------------------------ 辅助
|
||||
|
||||
def _check_ack(self, resp: tuple | None, expected_ack_cmd: int, desc: str) -> bool:
|
||||
if resp is None:
|
||||
print(f" FAIL [{desc}] 超时")
|
||||
return False
|
||||
_, resp_cmd, payload = resp
|
||||
if resp_cmd == 0x02A0: # ACK
|
||||
acked = struct.unpack(">H", payload)[0]
|
||||
if acked == expected_ack_cmd:
|
||||
print(f" PASS [{desc}] ACK")
|
||||
return True
|
||||
else:
|
||||
print(f" FAIL [{desc}] ACK 了错误的命令 0x{acked:04X}")
|
||||
return False
|
||||
elif resp_cmd == 0x02A1: # NACK
|
||||
acked = struct.unpack(">H", payload)[0]
|
||||
print(f" FAIL [{desc}] NACK (acked=0x{acked:04X})")
|
||||
return False
|
||||
else:
|
||||
print(f" FAIL [{desc}] 意外响应 0x{resp_cmd:04X}")
|
||||
return False
|
||||
|
||||
def close(self) -> None:
|
||||
self.sock.close()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="UDP 二进制协议测试")
|
||||
parser.add_argument("--host", default="127.0.0.1", help="控制器地址")
|
||||
parser.add_argument("--port", type=int, default=62450, help="UDP 端口")
|
||||
parser.add_argument("--skip-periodic", action="store_true", help="跳过周期上报测试")
|
||||
args = parser.parse_args()
|
||||
|
||||
tester = UdpTester(args.host, args.port)
|
||||
all_ok = True
|
||||
try:
|
||||
all_ok = tester.test_static_query() and all_ok
|
||||
all_ok = tester.test_static_set() and all_ok
|
||||
all_ok = tester.test_dynamic_query() and all_ok
|
||||
all_ok = tester.test_dynamic_set() and all_ok
|
||||
all_ok = tester.test_version() and all_ok
|
||||
all_ok = tester.test_topology() and all_ok
|
||||
if not args.skip_periodic:
|
||||
tester.test_periodic_report() # 不影响总结果
|
||||
finally:
|
||||
tester.close()
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
if all_ok:
|
||||
print("所有测试通过!")
|
||||
return 0
|
||||
else:
|
||||
print("部分测试失败,请检查日志。")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -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