refactor: 全栈代码审计修复 + 移除 NS-3.36/pybindgen 兼容

后端(25+ 修复):
- 移除死代码: `_add_yans_path_loss`/`_add_yans_fading`(77行)、不可达 mac_mode 分支
- 线程安全: sim.start() 用 asyncio.to_thread 包裹; wall-pacer 锁优化(I/O+FlowMonitor 移出锁)
- 安全: 拒绝 list 形式 sh -c 绕过 shell 元字符过滤
- PHY 缓存: stop() 时清除 `_phy_cache`,防止悬垂 ns-3 对象引用
- 验证: 拒绝负 node_id; BCD nibble range 校验; `_normalize_keys` 空 segment guard
- 资源: `_command_queue` maxsize=500; UDP subscriber 失败自动清理
- UDP 协议: 0x02AF 帧修复(去多余填充字节); encode() 纳入 try/except
- UDP 报告: 每 subscriber 独立 try/except,单点失败不饿死其余
- 功率映射: 反向匹配用最近邻(0.5dBm 公差),避免浮点精度 miss
- ws_radio: `_REPORT_CFG` 从模块全局移入 per-connection
- CppyyNsWrapper: 删除死代理缓存,非 module name 直接 raise AttributeError
- netns: 删除空桩 `host_netns_context()` 及未用导入
- 异常: ws_telemetry/ws_radio/state.py 裸 except 加 exc_info
- 清理: 4 个未用 import; CONFIG_FILE_PATH 环境变量化

前端:
- config.ts: 补全 6 字段(tapMode/tapPrefix/workMode/fhTableId/nodeMacId/softwareVersion)
- PRESET_NAMES: 补全 6 个 WiFi 测试预设中文名
- FALLBACK_CONFIG: ssid/nNodes 与 Python 默认值对齐
- useSimulation: connectWs 互斥 guard; unmount 清理 pendingRef
- App.tsx: handleIperf3/handleTraceroute 增加 res.ok 检查
- useSimConfig: 初始 load 增加 res.ok 检查 + 暴露 error state

构建:
- 移除 ns-allinone-3.36.tar.bz2 (43MB)
- docker-compose: 删除 controller-347 服务; build 切换为 Dockerfile.controller
- CI: dockerfile 路径切换为 Dockerfile.controller
- Dockerfile.controller.347: 清理 NS-3.36/pybindgen 残留注释
- Dockerfile.controller.pip: ns3==3.36 → ns3(去版本锁)
- main.py: 删除双路径兼容(pybindgen/cppyy) docstring

Co-Authored-By: Claude Opus 4.7 <[email protected]>
This commit is contained in:
adminandClaude Opus 4.7 committed 2026-05-16 17:56:39 +08:00
1 parent bf9ea83e8b
commit fb40527067
22 files changed
+257 -282

No files matched your search

+2 -2
View File
@@ -153,7 +153,7 @@ jobs:
cache-to: type=gha,mode=max,scope=host-manet-node
# ---------------------------------------------------------------------------
# 4. controller 多版本矩阵构建(3.36 pybindgen / 3.47 cppyy)
# 4. controller 镜像构建(NS-3.47 + cppyy)
# ---------------------------------------------------------------------------
controller-image:
name: Build controller (${{ matrix.ns3_version }})
@@ -165,7 +165,7 @@ jobs:
matrix:
include:
- ns3_version: "3.47"
dockerfile: controller/Dockerfile.controller.347
dockerfile: controller/Dockerfile.controller
image_name: manet-controller
steps:
- uses: actions/checkout@v4
@@ -1,6 +1,5 @@
# NS-3 MANET 控制器 Dockerfile(NS-3.47 源码编译 / linux/amd64)
# 与默认 Dockerfile.controller(NS-3.36 + pybindgen)并存。
# NS-3.37 起 pybindgen 已被移除,3.47 只剩 cppyy 一条 Python 绑定路径。
# NS-3.47 源码编译路线(与 Dockerfile.controller.pip pip 安装路线并存)。
#
# apt 源:中科大 mirrors.ustc.edu.cn
# pip 源:腾讯 mirrors.cloud.tencent.com
@@ -41,7 +40,7 @@ RUN pip3 config set global.index-url https://mirrors.cloud.tencent.com/pypi/simp
&& pip3 config set global.trusted-host mirrors.cloud.tencent.com
# --- 3. Python 运行时依赖 ---
# cppyy: NS-3.47 唯一支持的 Python 绑定后端(pybindgen 已在 3.37 移除)。
# cppyy: NS-3.47 Python 绑定后端。
# 严格 pin 3.1.2 — 与 ns-3.42–3.47 测过;ABI 在 minor 间不稳,升级 NS-3 时同步对照
# https://www.nsnam.org/docs/manual/html/python.html
RUN python3 -m pip install --no-cache-dir --upgrade pip setuptools wheel \
@@ -52,7 +51,7 @@ RUN python3 -m pip install --no-cache-dir --upgrade pip setuptools wheel \
docker==7.* pyroute2==0.7.* \
websockets==12.* httpx==0.27.*
# --- 4. ccache 加速(与 3.36 镜像共用 /ccache 卷时部分对象可复用) ---
# --- 4. ccache 加速 ---
ENV PATH="/usr/lib/ccache:$PATH"
ENV CCACHE_DIR=/ccache
RUN mkdir -p /ccache && ccache --max-size=10G
@@ -44,7 +44,7 @@ RUN pip3 config set global.index-url https://mirrors.cloud.tencent.com/pypi/simp
# - ns3:从 PyPI 拉取预编译 wheel,内含 cppyy 绑定 + 全模块 .so
# - 控制器运行时:FastAPI / pydantic / docker SDK / pyroute2
RUN python3 -m pip install --no-cache-dir --upgrade pip setuptools wheel \
&& python3 -m pip install --no-cache-dir ns3==3.36 \
&& python3 -m pip install --no-cache-dir ns3 \
&& python3 -m pip install --no-cache-dir \
fastapi==0.110.* "uvicorn[standard]"==0.29.* \
pydantic==2.* pydantic-settings==2.* \
+1 -4
View File
@@ -4,10 +4,7 @@
uvicorn controller.api.main:app --host 0.0.0.0 --port 8000
在控制器容器内由 /entrypoint.sh 启动。
PYTHONPATH 须包含 ns-3 Python 绑定目录(Docker:/opt/ns3/ns-3/build/bindings/python)。
导入双路径兼容:cppyy(pip install ns3)走 `from ns import ns`,
pybindgen(NS-3.36 源码编译)走 `import ns.core` 等显式子模块导入,
具体见 controller/orchestrator/sim_runner.py:_import_ns()。
使用 cppyy Python 绑定(NS-3.47+),`from ns import ns` 单一入口。
"""
from __future__ import annotations
@@ -52,6 +52,9 @@ def _validate_cmd(cmd: str | list[str]) -> None:
if not cmd:
raise HTTPException(400, "空命令")
name = cmd[0]
# 拒绝 list 形式的 shell -c 注入:sh -c / bash -c 可绕过元字符过滤
if name in ("sh", "bash") and "-c" in cmd:
raise HTTPException(400, "不允许通过 sh -c 执行命令")
if name not in _ALLOWED_CMDS:
raise HTTPException(400, f"命令 '{name}' 不在白名单内")
+4 -3
View File
@@ -21,7 +21,7 @@ import json
from pathlib import Path
from controller.orchestrator import SimConfig, NodeSpec, PRESETS
from controller.orchestrator.config import load_config, load_user_config, save_config_to_file
from controller.orchestrator.config import load_user_config, save_config_to_file
from controller.orchestrator.docker_mgr import CONTAINER_PREFIX, DockerMgr
from controller.orchestrator.netns import (
create_vxlan_on_controller,
@@ -59,13 +59,14 @@ def _get_controller_ip() -> str:
if p == "src" and i + 1 < len(parts):
return parts[i + 1]
except Exception:
pass
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()
@@ -198,7 +199,7 @@ class Session:
# 4. 启动 ns-3 仿真器(驱动所有 TAP)
sim = SimRunner(cfg)
try:
sim.start()
await asyncio.to_thread(sim.start)
except Exception:
docker_mgr.stop_all()
for mgr in remote_mgrs.values():
+35 -44
View File
@@ -236,53 +236,38 @@ async def _handle_set(cmd_code: int, extend: str, payload: dict[str, Any]) -> di
# ---------------------------------------------------------------------------
# 上报类配置与主动推送任务
# 上报配置辅助(per-connection,参数由调用方传入)
# ---------------------------------------------------------------------------
# 每个 /ws/radio 连接维护自己的上报配置副本
_REPORT_CFG: dict[str, Any] = {
"5002_enabled": True,
"5002_period": 2.0,
"5006_enabled": True,
"5006_period": 10.0,
}
def _get_report_cfg() -> dict[str, Any]:
"""返回当前上报配置快照。"""
return dict(_REPORT_CFG)
def _set_report_cfg(key: str, value: Any) -> bool:
def _set_report_cfg(cfg: dict[str, Any], key: str, value: Any) -> bool:
"""设置单个上报配置项。"""
if key not in _REPORT_CFG:
if key not in cfg:
return False
try:
if key.endswith("_enabled"):
_REPORT_CFG[key] = bool(value)
cfg[key] = bool(value)
elif key.endswith("_period"):
v = float(value)
_REPORT_CFG[key] = max(0.5, min(300.0, v))
cfg[key] = max(0.5, min(300.0, v))
else:
_REPORT_CFG[key] = value
cfg[key] = value
return True
except Exception:
return False
async def _push_5002(ws: WebSocket, stop_evt: asyncio.Event) -> None:
async def _push_5002(ws: WebSocket, stop_evt: asyncio.Event, report_cfg: dict[str, Any]) -> None:
"""5002 入网/断网状态变化上报任务。"""
prev_running: bool | None = None
while not stop_evt.is_set():
cfg = _get_report_cfg()
period = cfg["5002_period"]
period = report_cfg["5002_period"]
try:
await asyncio.wait_for(stop_evt.wait(), timeout=period)
except asyncio.TimeoutError:
pass
if stop_evt.is_set():
break
if not cfg["5002_enabled"]:
if not report_cfg["5002_enabled"]:
continue
sess = get_session()
@@ -300,19 +285,18 @@ async def _push_5002(ws: WebSocket, stop_evt: asyncio.Event) -> None:
break
async def _push_5006(ws: WebSocket, stop_evt: asyncio.Event) -> None:
async def _push_5006(ws: WebSocket, stop_evt: asyncio.Event, report_cfg: dict[str, Any]) -> None:
"""5006 在线信息上报任务。"""
prev_online: set[str] = set()
while not stop_evt.is_set():
cfg = _get_report_cfg()
period = cfg["5006_period"]
period = report_cfg["5006_period"]
try:
await asyncio.wait_for(stop_evt.wait(), timeout=period)
except asyncio.TimeoutError:
pass
if stop_evt.is_set():
break
if not cfg["5006_enabled"]:
if not report_cfg["5006_enabled"]:
continue
sess = get_session()
@@ -328,36 +312,35 @@ async def _push_5006(ws: WebSocket, stop_evt: asyncio.Event) -> None:
frame = _make_response(5006, "", netMode=1, groupMebsIP=online_ips)
await ws.send_json(frame)
except Exception:
pass
log.warning("_push_5006 failed", exc_info=True)
# ---------------------------------------------------------------------------
# 上报配置查询/设置
# ---------------------------------------------------------------------------
async def _handle_report_query(cmd_code: int, extend: str) -> dict[str, Any]:
async def _handle_report_query(cmd_code: int, extend: str, report_cfg: dict[str, Any]) -> dict[str, Any]:
"""9001 -> 9002: 查询上报配置。"""
cfg = _get_report_cfg()
return _make_response(
9002, extend,
report5002Enabled=1 if cfg["5002_enabled"] else 0,
report5002Period=int(cfg["5002_period"] * 1000), # ms
report5006Enabled=1 if cfg["5006_enabled"] else 0,
report5006Period=int(cfg["5006_period"] * 1000), # ms
report5002Enabled=1 if report_cfg["5002_enabled"] else 0,
report5002Period=int(report_cfg["5002_period"] * 1000), # ms
report5006Enabled=1 if report_cfg["5006_enabled"] else 0,
report5006Period=int(report_cfg["5006_period"] * 1000), # ms
)
async def _handle_report_set(cmd_code: int, extend: str, payload: dict[str, Any]) -> dict[str, Any]:
async def _handle_report_set(cmd_code: int, extend: str, payload: dict[str, Any], report_cfg: dict[str, Any]) -> dict[str, Any]:
"""9003 -> 9004: 设置上报配置。"""
ok = True
if "report5002Enabled" in payload:
ok = _set_report_cfg("5002_enabled", payload["report5002Enabled"]) and ok
ok = _set_report_cfg(report_cfg, "5002_enabled", payload["report5002Enabled"]) and ok
if "report5002Period" in payload:
ok = _set_report_cfg("5002_period", payload["report5002Period"] / 1000.0) and ok
ok = _set_report_cfg(report_cfg, "5002_period", payload["report5002Period"] / 1000.0) and ok
if "report5006Enabled" in payload:
ok = _set_report_cfg("5006_enabled", payload["report5006Enabled"]) and ok
ok = _set_report_cfg(report_cfg, "5006_enabled", payload["report5006Enabled"]) and ok
if "report5006Period" in payload:
ok = _set_report_cfg("5006_period", payload["report5006Period"] / 1000.0) and ok
ok = _set_report_cfg(report_cfg, "5006_period", payload["report5006Period"] / 1000.0) and ok
return _make_response(9004, extend, state=1 if ok else 0)
@@ -374,10 +357,18 @@ async def radio_ws(ws: WebSocket) -> None:
stop_evt = asyncio.Event()
tasks: list[asyncio.Task[None]] = []
# 每个连接独立的 report 配置,避免并发客户端互相覆盖
report_cfg: dict[str, Any] = {
"5002_enabled": True,
"5002_period": 2.0,
"5006_enabled": True,
"5006_period": 10.0,
}
try:
# 启动两个独立的上报任务,各自拥有独立的周期和开关
tasks.append(asyncio.create_task(_push_5002(ws, stop_evt), name="push-5002"))
tasks.append(asyncio.create_task(_push_5006(ws, stop_evt), name="push-5006"))
tasks.append(asyncio.create_task(_push_5002(ws, stop_evt, report_cfg), name="push-5002"))
tasks.append(asyncio.create_task(_push_5006(ws, stop_evt, report_cfg), name="push-5006"))
while True:
raw = await ws.receive_text()
@@ -395,7 +386,7 @@ async def radio_ws(ws: WebSocket) -> None:
# 查询类 (1xxx / 7xxx / 9xxx)
if cmd_code in (1001, 1025, 1071, 1049, 7001, 7003, 9001):
if cmd_code == 9001:
resp = await _handle_report_query(cmd_code, extend)
resp = await _handle_report_query(cmd_code, extend, report_cfg)
else:
resp = await _handle_query(cmd_code, extend, net_mode)
await ws.send_json(resp)
@@ -404,7 +395,7 @@ async def radio_ws(ws: WebSocket) -> None:
# 设置类 (2xxx / 8xxx / 9xxx)
if cmd_code in (2001, 2043, 2023, 8001, 8003, 9003):
if cmd_code == 9003:
resp = await _handle_report_set(cmd_code, extend, data)
resp = await _handle_report_set(cmd_code, extend, data, report_cfg)
else:
resp = await _handle_set(cmd_code, extend, data)
await ws.send_json(resp)
+1 -1
View File
@@ -105,7 +105,7 @@ async def telemetry_ws(ws: WebSocket) -> None:
task.cancel()
for task in done:
if task.exception():
log.debug("WebSocket task ended with %s", task.exception())
log.warning("WebSocket task ended with %s", task.exception())
except WebSocketDisconnect:
log.info("WebSocket 客户端断开")
@@ -563,8 +563,9 @@ def _normalize_keys(d: Mapping[str, Any]) -> dict[str, Any]:
for k, v in d.items():
if "_" in k:
# snake_case → camelCase alias
head, *rest = k.split("_")
ck = head + "".join(p.capitalize() for p in rest)
parts = k.split("_")
head = parts[0]
ck = head + "".join(p.capitalize() for p in parts[1:] if p)
out[ck] = v
else:
out[k] = v
@@ -762,7 +763,9 @@ _FIELD_GROUPS: list[tuple[str, list[str]]] = [
]),
]
CONFIG_FILE_PATH: Path = Path("/app/config/user_settings.conf")
CONFIG_FILE_PATH: Path = Path(
os.environ.get("MANET_CONFIG_FILE", "/app/config/user_settings.conf")
)
def save_config_to_file(cfg: SimConfig, path: str | Path | None = None) -> None:
@@ -27,8 +27,6 @@ import logging
import os
import re
import threading
from contextlib import contextmanager
from typing import Iterator
from pyroute2 import IPRoute, NetNS
@@ -342,16 +340,3 @@ def teardown(node_count: int) -> None:
delete_link(name)
# 3) 清理所有线程本地 IPRoute 实例
_close_ipr()
@contextmanager
def host_netns_context() -> Iterator[None]:
"""Context that pins the calling thread to the host netns. Useful when
pyroute2 ops are mixed with code that itself moves netns."""
fd = os.open("/proc/1/ns/net", os.O_RDONLY)
try:
# We don't actually setns() here; pyroute2 IPRoute() defaults to host.
# This stub exists to mark intent and could be extended with libc.setns().
yield
finally:
os.close(fd)
@@ -12,7 +12,7 @@ import asyncio
import logging
import threading
from dataclasses import dataclass
from typing import Any, Callable, Literal, Optional
from typing import Any, Callable, Literal
from controller.orchestrator.config import SimConfig, save_config_to_file
@@ -18,10 +18,8 @@ Frames from the container traverse: eth0 → veth → bridge → vxlan → UDP/4
"""
from __future__ import annotations
import json
import logging
import os
import socket
import threading
from dataclasses import dataclass
+96 -135
View File
@@ -36,12 +36,11 @@ def _to_ns3_address(inet_addr: Any) -> Any:
return inet_addr
class _CppyyModuleProxy:
"""让 cppyy 的扁平命名空间也能支持 `ns.core.Simulator` 这种子模块写法。
class _ModuleProxy:
"""代理已知子模块名,回退到 cppyy 根命名空间。
ns-3.47 cppyy 绑定中所有类都挂在 ns3 根命名空间下,但旧代码里大量出现
`ns.wifi.WifiHelper`、`ns.aodv.AodvHelper` 等子模块写法。本代理在子模块
命名空间找不到目标时,自动回退到扁平根命名空间,实现零改动兼容。
对已知的 ns-3 子模块名(如 wifi, mobility),cppyy 同时暴露为根属性。
若子模块路径未命中,代理回退到扁平根命名空间查找。
"""
def __init__(self, ns):
@@ -51,17 +50,20 @@ class _CppyyModuleProxy:
try:
return getattr(self._ns, name)
except AttributeError:
# 子模块命名空间(如 ns3::aodv)没有该类,回退到扁平根命名空间
pass
# 如果根命名空间也没有,让原始异常抛出
return getattr(self._ns, name)
class _CppyyNsWrapper:
"""包装 cppyy.gbl.ns3,优先返回扁平命名空间成员,缺失时回退到子模块代理。"""
"""包装 cppyy.gbl.ns3,配合 ns-3.47 cppyy 扁平命名空间实现子模块写法兼容。
ns-3.47 cppyy 绑定中所有类都挂在 ns3 根命名空间下,但旧代码里大量出现
`ns.wifi.WifiHelper`、`ns.aodv.AodvHelper` 等子模块写法。已知子模块名
(core, wifi, mobility 等) 走根命名空间二次回退;未知属性直接透传给底层。
"""
# ns-3 子模块名列表;cppyy 中这些名字同时是根命名空间属性(ns3::aodv 等),
# 但类实际挂在根下,因此必须走代理做二次回退。
# 但类实际挂在根下,因此必须做二次回退。
_MODULE_NAMES = frozenset({
"core", "network", "internet", "wifi", "mobility", "tap_bridge",
"flow_monitor", "propagation", "spectrum", "aodv", "olsr",
@@ -73,16 +75,16 @@ class _CppyyNsWrapper:
self._proxies: dict[str, Any] = {}
def __getattr__(self, name):
# 对已知子模块名一律走代理,让代理在"子模块空间 → 扁平根空间"回退;
# 其它名字若根命名空间有直接命中则立即返回。
if name in self._MODULE_NAMES:
if name not in self._proxies:
self._proxies[name] = _CppyyModuleProxy(self._ns)
self._proxies[name] = _ModuleProxy(self._ns)
return self._proxies[name]
if hasattr(self._ns, name):
return getattr(self._ns, name)
if name not in self._proxies:
self._proxies[name] = _CppyyModuleProxy(self._ns)
try:
val = getattr(self._ns, name)
except AttributeError:
raise AttributeError(f"ns3 has no attribute '{name}'") from None
self._proxies[name] = val
return self._proxies[name]
@@ -151,8 +153,8 @@ class SimRunner:
self._running = False
self._start_time: float | None = None
self._error: str | None = None
# 动态控制:线程安全命令队列 + ns-3 对象引用
self._command_queue: queue.Queue = queue.Queue()
# 动态控制:线程安全命令队列(maxsize 防无界增长) + ns-3 对象引用
self._command_queue: queue.Queue = queue.Queue(maxsize=500)
self._nodes_container: Any = None
self._wifi_devices: Any = None
self._spectrum_channel: Any = None
@@ -171,7 +173,8 @@ class SimRunner:
self._tap_bridge_helper: Any = None
# 当前活跃节点集合(remove 后元素被移除,但 ns-3 NodeContainer 不会缩容)
self._active_node_ids: set[int] = set()
# PHY 缓存:node_id → phy,避免动态命令时的四级回退
# PHY 缓存:node_id → phy,避免动态命令时的四级回退。
# 缓存生命周期绑定到单次仿真;节点增删时须调用 _invalidate_phy_cache()。
self._phy_cache: dict[int, Any] = {}
# 动态参数当前值(供遥测回传前端)
self._env_state = EnvState(
@@ -223,6 +226,7 @@ class SimRunner:
if self._wall_pacer_thread:
self._wall_pacer_thread.join(timeout=2.0)
self._wall_pacer_thread = None
self._phy_cache.clear()
self._running = False
@property
@@ -377,14 +381,8 @@ class SimRunner:
wifi.SetStandard(self._wifi_standard(ns, cfg.standard))
self._apply_rate_control(ns, wifi, cfg)
# 5. MAC:mac_mode="mesh" 启用 802.11s + HWMP,由 ns-3 mesh 模块在 L2
# 层完成多跳转发。NS-3.47 + cppyy 下 adhoc 模式会触发 Txop segfault,
# 因此强制使用 mesh 模式。
if cfg.mac_mode != "mesh":
log.warning(
"mac_mode='%s' 在 NS-3.47 + cppyy 下会导致 segfault,强制切换到 mesh",
cfg.mac_mode,
)
# 5. MAC:802.11s mesh + HWMP;mac_mode 由 config.py SimConfig validator
# 强制为 "mesh"(NS-3.47 + cppyy 下 adhoc 会触发 Txop segfault)。
devices = self._install_mesh(ns, cfg, phy, nodes)
# 6. Mobility
@@ -673,52 +671,6 @@ class SimRunner:
return m
return None
@staticmethod
def _add_yans_path_loss(ns: Any, ch: Any, cfg: SimConfig) -> None:
pl = cfg.path_loss_model
freq_hz = float(cfg.frequency_mhz) * 1e6
if pl == "LogDistance":
ch.AddPropagationLoss(
"ns3::LogDistancePropagationLossModel",
"Exponent", ns.core.DoubleValue(cfg.path_loss_exponent),
"ReferenceLoss", ns.core.DoubleValue(cfg.path_loss_ref_loss),
"ReferenceDistance", ns.core.DoubleValue(cfg.path_loss_ref_distance),
)
elif pl == "FreeSpace":
ch.AddPropagationLoss(
"ns3::FriisPropagationLossModel",
"Frequency", ns.core.DoubleValue(freq_hz),
"MinLoss", ns.core.DoubleValue(0.0),
)
elif pl == "TwoRayGround":
ch.AddPropagationLoss(
"ns3::TwoRayGroundPropagationLossModel",
"Frequency", ns.core.DoubleValue(freq_hz),
)
elif pl == "ThreeLogDistance":
ch.AddPropagationLoss("ns3::ThreeLogDistancePropagationLossModel")
elif pl == "Cost231":
ch.AddPropagationLoss("ns3::Cost231PropagationLossModel")
elif pl == "Range":
ch.AddPropagationLoss(
"ns3::RangePropagationLossModel",
"MaxRange", ns.core.DoubleValue(cfg.range_target_m),
)
@staticmethod
def _add_yans_fading(ns: Any, ch: Any, cfg: SimConfig) -> None:
if cfg.fading_model == "Nakagami":
ch.AddPropagationLoss(
"ns3::NakagamiPropagationLossModel",
"m0", ns.core.DoubleValue(cfg.nakagami_m0),
"m1", ns.core.DoubleValue(cfg.nakagami_m1),
"m2", ns.core.DoubleValue(cfg.nakagami_m2),
"Distance1", ns.core.DoubleValue(cfg.nakagami_d1),
"Distance2", ns.core.DoubleValue(cfg.nakagami_d2),
)
elif cfg.fading_model == "Jakes":
ch.AddPropagationLoss("ns3::JakesPropagationLossModel")
# ---- fading / shadowing / obstacle helpers ------------------------------
@staticmethod
def _make_fading_model(ns: Any, cfg: SimConfig) -> Any | None:
@@ -1201,7 +1153,7 @@ class SimRunner:
仅调用现有 MobilityModel 的 SetPosition,不替换对象,
避免与 Simulator::Run() 线程发生 race。
"""
if node_id >= self.config.n_nodes:
if node_id < 0 or node_id >= self.config.n_nodes:
return {"applied": False, "reason": "node_id out of range"}
def _do():
@@ -1224,7 +1176,7 @@ class SimRunner:
def set_tx_power(self, node_id: int, dbm: float) -> dict[str, Any]:
"""修改指定节点的发射功率(线程安全)。"""
if node_id >= self.config.n_nodes:
if node_id < 0 or node_id >= self.config.n_nodes:
return {"applied": False, "reason": "node_id out of range"}
def _do():
@@ -1246,7 +1198,7 @@ class SimRunner:
def set_rx_sensitivity(self, node_id: int, dbm: float) -> dict[str, Any]:
"""修改指定节点的接收灵敏度(线程安全)。"""
if node_id >= self.config.n_nodes:
if node_id < 0 or node_id >= self.config.n_nodes:
return {"applied": False, "reason": "node_id out of range"}
def _do():
@@ -1390,10 +1342,9 @@ class SimRunner:
cmd()
except Exception as e: # noqa: BLE001
log.warning("dynamic command failed: %s", e)
# 2. 刷新位置快照 + 邻居 + tap 接口计数器
# 2. 刷新位置快照 + 邻居(在锁内,快速操作)
with self._lock:
n_nodes = self.config.n_nodes
tap_prefix = self.config.tap_prefix
# 必须用 _env_state.range_target_m(动态控制可能已修改),
# 不能用 self.config.range_target_m(启动时的静态快照)。
max_range = self._env_state.range_target_m
@@ -1423,71 +1374,81 @@ class SimRunner:
if math.hypot(ni.x - nj.x, ni.y - nj.y) <= max_range:
neighbors.append(j)
ni.neighbors = neighbors
# 2c. tap 接口 RX/TX(真实容器流量,FlowMonitor 看不到)
for i in range(n_nodes):
nr = self._nodes_runtime.get(i)
if not nr:
continue
try:
with open(f"/sys/class/net/{tap_prefix}{i}/statistics/rx_packets") as fh:
nr.rx_packets = int(fh.read().strip())
with open(f"/sys/class/net/{tap_prefix}{i}/statistics/tx_packets") as fh:
nr.tx_packets = int(fh.read().strip())
except Exception: # noqa: BLE001
pass
# 2d. FlowMonitor 统计 (ns-3.47 cppyy 不支持 Simulator.Schedule
# 传入 Python callback,改在 wall-time 线程懒更新)
# 使用增量更新替代全量 clear+重建,减少 GC 压力
if self._fm is not None:
try:
self._fm.CheckForLostPackets()
stats = self._fm.GetFlowStats()
classifier = None
if hasattr(self._fm, "GetClassifier"):
classifier = self._fm.GetClassifier()
seen: set[int] = set()
for fid, st in stats:
seen.add(fid)
source, destination = "", ""
if classifier:
ft = classifier.FindFlow(fid)
source = str(ft.sourceAddress)
destination = str(ft.destinationAddress)
elapsed = max(
(st.timeLastRxPacket.GetSeconds()
- st.timeFirstTxPacket.GetSeconds()),
1e-9,
)
throughput_mbps = (st.rxBytes * 8.0) / elapsed / 1e6
avg_delay = (st.delaySum.GetSeconds() / st.rxPackets) \
if st.rxPackets else 0.0
# 2c. tap 接口 RX/TX(真实容器流量,FlowMonitor 看不到) —— 文件 I/O 在锁外
tap_prefix = self.config.tap_prefix
with self._lock:
node_ids = list(self._nodes_runtime.keys())
for i in node_ids:
try:
with open(f"/sys/class/net/{tap_prefix}{i}/statistics/rx_packets") as fh:
rx = int(fh.read().strip())
with open(f"/sys/class/net/{tap_prefix}{i}/statistics/tx_packets") as fh:
tx = int(fh.read().strip())
with self._lock:
nr = self._nodes_runtime.get(i)
if nr:
nr.rx_packets = rx
nr.tx_packets = tx
except Exception: # noqa: BLE001
pass
# 2d. FlowMonitor 统计 (ns-3.47 cppyy 不支持 Simulator.Schedule
# 传入 Python callback,改在 wall-time 线程懒更新)
# 使用增量更新替代全量 clear+重建,减少 GC 压力
if self._fm is not None:
try:
self._fm.CheckForLostPackets()
stats = self._fm.GetFlowStats()
classifier = None
if hasattr(self._fm, "GetClassifier"):
classifier = self._fm.GetClassifier()
# 在锁外构建新数据,锁内仅做交换
flows_batch: dict[int, FlowRuntime] = {}
seen: set[int] = set()
for fid, st in stats:
seen.add(fid)
source, destination = "", ""
if classifier:
ft = classifier.FindFlow(fid)
source = str(ft.sourceAddress)
destination = str(ft.destinationAddress)
elapsed = max(
(st.timeLastRxPacket.GetSeconds()
- st.timeFirstTxPacket.GetSeconds()),
1e-3, # 最小 1ms 避免溢出
)
throughput_mbps = (st.rxBytes * 8.0) / elapsed / 1e6
avg_delay = (st.delaySum.GetSeconds() / st.rxPackets) \
if st.rxPackets else 0.0
flows_batch[fid] = FlowRuntime(
flow_id=fid,
source=source,
destination=destination,
tx_packets=st.txPackets,
rx_packets=st.rxPackets,
lost_packets=st.lostPackets,
avg_delay=avg_delay,
throughput=throughput_mbps,
)
# 增量合并到共享存储
with self._lock:
for fid, fr in flows_batch.items():
existing = self._flows_runtime.get(fid)
if existing is not None:
# 增量更新已有对象,避免频繁创建新对象
existing.source = source
existing.destination = destination
existing.tx_packets = st.txPackets
existing.rx_packets = st.rxPackets
existing.lost_packets = st.lostPackets
existing.avg_delay = avg_delay
existing.throughput = throughput_mbps
existing.source = fr.source
existing.destination = fr.destination
existing.tx_packets = fr.tx_packets
existing.rx_packets = fr.rx_packets
existing.lost_packets = fr.lost_packets
existing.avg_delay = fr.avg_delay
existing.throughput = fr.throughput
else:
self._flows_runtime[fid] = FlowRuntime(
flow_id=fid,
source=source,
destination=destination,
tx_packets=st.txPackets,
rx_packets=st.rxPackets,
lost_packets=st.lostPackets,
avg_delay=avg_delay,
throughput=throughput_mbps,
)
self._flows_runtime[fid] = fr
# 删除已不存在的流
for dead_fid in list(self._flows_runtime):
if dead_fid not in seen:
del self._flows_runtime[dead_fid]
except Exception as e: # noqa: BLE001
log.warning("flow monitor poll failed: %s", e)
except Exception as e: # noqa: BLE001
log.warning("flow monitor poll failed: %s", e)
except Exception as e: # noqa: BLE001
log.warning("wall pacer iteration failed: %s", e)
# 自适应 sleep:测量本次迭代耗时,动态调整以维持目标频率
@@ -244,8 +244,20 @@ class UdpCommandHandler:
sess = get_session()
tx_power = sess.param_store.get("txPower").get("value", [33.0])
dbm = tx_power[0] if isinstance(tx_power, list) else tx_power
level = POWER_LEVEL_REVERSE.get(float(dbm), 0)
return UdpFrame(comm_type=1, cmd_id=0x0182, payload=bcd1_encode(level))
dbm = float(dbm)
# 最近匹配(公差 0.5 dBm 内),避免浮点精度导致反向查找 miss
best_level = 0
best_diff = float("inf")
for level, ref_dbm in POWER_LEVEL_MAP.items():
diff = abs(dbm - ref_dbm)
if diff < best_diff:
best_diff = diff
best_level = level
if best_diff > 0.5:
best_level = POWER_LEVEL_REVERSE.get(
min(POWER_LEVEL_REVERSE, key=lambda k: abs(k - dbm)), 0
)
return UdpFrame(comm_type=1, cmd_id=0x0182, payload=bcd1_encode(best_level))
# ------------------------------------------------------------------ 版本
@@ -65,21 +65,23 @@ def bcd4_to_mhz(data: bytes) -> float:
"""
if len(data) != 4:
raise ValueError(f"BCD4 需要 4 字节,收到 {len(data)}")
d1000m = data[0] & 0x0F
d100m = (data[1] >> 4) & 0x0F
d10m = data[1] & 0x0F
d1m = (data[2] >> 4) & 0x0F
d100k = data[2] & 0x0F
d10k = (data[3] >> 4) & 0x0F
d1k = data[3] & 0x0F
nibbles = [
data[0] & 0x0F,
(data[1] >> 4) & 0x0F, data[1] & 0x0F,
(data[2] >> 4) & 0x0F, data[2] & 0x0F,
(data[3] >> 4) & 0x0F, data[3] & 0x0F,
]
for n in nibbles:
if n > 9:
raise ValueError(f"无效 BCD nibble: {n}, 原始数据: {data.hex()}")
return (
d1000m * 1000.0
+ d100m * 100.0
+ d10m * 10.0
+ d1m
+ d100k * 0.1
+ d10k * 0.01
+ d1k * 0.001
nibbles[0] * 1000.0
+ nibbles[1] * 100.0
+ nibbles[2] * 10.0
+ nibbles[3]
+ nibbles[4] * 0.1
+ nibbles[5] * 0.01
+ nibbles[6] * 0.001
)
@@ -89,6 +91,9 @@ def mhz_to_bcd4(mhz: float) -> bytes:
whole = int(mhz)
frac = int(round((mhz - whole) * 1000))
if whole >= 10000:
raise ValueError(f"频率 {mhz} MHz 超出 BCD4 范围 (>= 10000 MHz)")
d1000m = (whole // 1000) & 0x0F
whole %= 1000
d100m = (whole // 100) & 0x0F
@@ -113,7 +118,11 @@ def bcd1_to_int(data: bytes) -> int:
"""1 字节压缩 BCD → int。"""
if len(data) != 1:
raise ValueError(f"BCD1 需要 1 字节,收到 {len(data)}")
return ((data[0] >> 4) & 0x0F) * 10 + (data[0] & 0x0F)
tens = (data[0] >> 4) & 0x0F
ones = data[0] & 0x0F
if tens > 9 or ones > 9:
raise ValueError(f"无效 BCD 字节: 0x{data[0]:02X}")
return tens * 10 + ones
def int_to_bcd1(val: int) -> bytes:
@@ -47,13 +47,11 @@ class UdpProtocol(asyncio.DatagramProtocol):
try:
response = await self.handler.handle(frame)
if response is not None and self.transport is not None:
self.transport.sendto(response.encode(), addr)
log.debug("UDP 响应 -> %s: %s", addr, response)
except Exception:
log.exception("UDP 命令处理异常 from %s", addr)
return
if response is not None and self.transport is not None:
self.transport.sendto(response.encode(), addr)
log.debug("UDP 响应 -> %s: %s", addr, response)
class UdpService:
@@ -125,8 +123,12 @@ class UdpService:
)
if topo_frame is not None:
raw = topo_frame.encode()
for addr in self._subscribers:
self._transport.sendto(raw, addr)
for addr in list(self._subscribers):
try:
self._transport.sendto(raw, addr)
except Exception:
self._subscribers.discard(addr)
log.debug("移除无响应订户 %s", addr)
except Exception:
log.exception("拓扑上报失败")
@@ -134,8 +136,11 @@ class UdpService:
try:
status_frame = self._build_status_report()
raw = status_frame.encode()
for addr in self._subscribers:
self._transport.sendto(raw, addr)
for addr in list(self._subscribers):
try:
self._transport.sendto(raw, addr)
except Exception:
self._subscribers.discard(addr)
except Exception:
log.exception("状态上报失败")
@@ -146,11 +151,11 @@ class UdpService:
BYTE[0] = 1 (消息类别: 节点状态信息)
BYTE[1] = 自组网状态 (0=未同步, 1=同步)
BYTE[2] = 测控链状态 (0=未同步, 1=同步)
BYTE[3]-BYTE[6] = 32 位无符号异常代码 (0=无异常)
BYTE[3]-BYTE[6] = 32 位无符号异常代码 (0=无异常) → 4 bytes
"""
from controller.api.state import get_session
sess = get_session()
sync = 1 if sess.running else 0
payload = struct.pack(">BBBBI", 1, sync, sync, 0, 0)
payload = struct.pack(">BBBI", 1, sync, sync, 0)
return UdpFrame(comm_type=1, cmd_id=0x02AF, payload=payload)
+1 -34
View File
@@ -25,7 +25,7 @@ services:
# 本地开发时取消注释 build 段,注释 image 行
# build:
# context: .
# dockerfile: controller/Dockerfile.controller.347
# dockerfile: controller/Dockerfile.controller
image: ghcr.io/clawdbuddy/manet-controller:latest
container_name: controller
privileged: true
@@ -52,39 +52,6 @@ services:
- ./config:/app/config
restart: unless-stopped
# NS-3.47 备用构建(cppyy 绑定,使用 Dockerfile.controller.347)。
# 默认 `docker compose up` 不拉取,必须用 profile 启用:
# docker compose --profile v347 build controller-347
# docker compose --profile v347 up -d controller-347
# 与 controller 共享 br-ns3 / tap / veth 这一套全局网络资源,
# 同一时刻只能让一个 controller 跑仿真,否则会互踩。
controller-347:
profiles: ["v347"]
build:
context: .
dockerfile: controller/Dockerfile.controller.347
image: controller:3.47
container_name: controller-347
privileged: true
network_mode: host
pid: host
cap_add:
- NET_ADMIN
- NET_RAW
- SYS_ADMIN
environment:
- LOG_LEVEL=INFO
- MANET_WEB_DIR=/app/dist
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- /var/run/netns:/var/run/netns
- ./results:/results
- ./config:/app/config
# 8000 已被 controller 占用;这里换 8001 以便并行起服。
command: ["uvicorn", "controller.api.main:app",
"--host", "0.0.0.0", "--port", "8001"]
restart: unless-stopped
# Build-only target. The controller spawns these containers at runtime via
# the Docker socket; we never start this service directly.
node-image-builder:
Binary file not shown.
+8
View File
@@ -72,6 +72,10 @@ function App() {
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ cmd: 'iperf3 -c 192.168.100.10 -p 5201 -t 5 -J' }),
});
if (!res.ok) {
const text = await res.text();
throw new Error(`iperf3 exec failed (${res.status}): ${text}`);
}
const data = await res.json();
addLog(`[iperf3] clientNode=${clientNode} exitCode=${data.exitCode}`);
if (data.output) {
@@ -130,6 +134,10 @@ function App() {
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ cmd: `traceroute -n -m 5 -w 1 ${targetIp}` }),
});
if (!res.ok) {
const text = await res.text();
throw new Error(`traceroute exec failed (${res.status}): ${text}`);
}
const data = await res.json();
if (data.exitCode === 0 && data.output) {
data.output.split('\n').slice(0, 8).forEach((line: string) => {
@@ -6,7 +6,7 @@ const API_BASE = '';
// 极小的本地 fallback,用于 API 尚未返回前的占位。
// 权威预设定义在后端 controller/orchestrator/config.py:PRESETS 中。
const FALLBACK_CONFIG: SimConfig = {
nNodes: 6, simulationTime: 300, seed: 1, run: 1, logComponents: '',
nNodes: 5, simulationTime: 300, seed: 1, run: 1, logComponents: '',
standard: '80211n-2.4GHz', phyModel: 'yans', frequencyMhz: 2412, channelWidthMhz: 20, rangeTargetM: 4000,
dataRate: 'HtMcs7',
txPowerStart: 30, txPowerEnd: 30, txPowerLevels: 1,
@@ -18,7 +18,7 @@ const FALLBACK_CONFIG: SimConfig = {
ricianK: 9.0,
enableObstacles: false, obstacleShadowingSigma: 4.0, obstaclePenetrationLoss: 10.0,
obstacleDiffractionEnabled: true, obstaclesJson: '[]',
ssid: 'mesh-network', bssid: '00:00:00:00:AD:H0',
ssid: 'adhoc-30ns3', bssid: '00:00:00:00:AD:H0',
macMode: 'mesh', rateControl: 'Constant', rtsCtsThreshold: 2200, fragmentationThreshold: 2200,
nonUnicastMode: false, beaconInterval: 100, cwMin: 15, cwMax: 1023,
routingProtocol: 'aodv', aodvHelloInterval: 1, aodvRreqRetries: 2,
@@ -32,6 +32,8 @@ const FALLBACK_CONFIG: SimConfig = {
pcapPrefix: 'manet-30nodes-adhoc', enableMobilityTrace: false,
trafficMode: 'tap', onoffDataRate: '6Mbps', onoffPacketSize: 1024,
onoffMaxBytes: 0, onoffStartTime: 1.0, onoffSinkPort: 5000,
tapMode: 'UseLocal', tapPrefix: 'mesh-tap-',
workMode: 0, fhTableId: 0, nodeMacId: 0, softwareVersion: 'V1.00.03',
};
// 按钮显示名映射(后端 /api/sim/presets 只返回扁平 SimConfig,没有 name 字段)
@@ -42,6 +44,12 @@ export const PRESET_NAMES: Record<string, string> = {
debug: '调试 / 最小配置',
tactical: '战术 / 10节点',
throughput: '极限吞吐 / 2节点',
'wifi-band-test-2.4g': 'WiFi 2.4GHz 频段',
'wifi-band-test-5g': 'WiFi 5GHz 频段',
'wifi-bandwidth-test-20m': 'WiFi 20MHz 带宽',
'wifi-bandwidth-test-40m': 'WiFi 40MHz 带宽',
'wifi-distance-test': 'WiFi 距离渐变',
'wifi-adhoc-multihop': 'WiFi 大规模拓扑',
};
interface SimApi {
@@ -52,6 +60,7 @@ interface SimApi {
export function useSimConfig(sim?: SimApi) {
const [presets, setPresets] = useState<Record<string, SimConfig> | null>(null);
const [ready, setReady] = useState(false);
const [error, setError] = useState<string | null>(null);
const [config, setConfig] = useState<SimConfig>({ ...FALLBACK_CONFIG });
const [activePreset, setActivePreset] = useState<string>('default');
const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
@@ -62,7 +71,7 @@ export function useSimConfig(sim?: SimApi) {
useEffect(() => {
Promise.all([
fetch(`${API_BASE}/api/config`).then(r => r.ok ? r.json() : null).catch(() => null),
fetch(`${API_BASE}/api/sim/presets`).then(r => r.json()).catch(() => ({} as Record<string, SimConfig>)),
fetch(`${API_BASE}/api/sim/presets`).then(r => r.ok ? r.json() : (() => { throw new Error(`HTTP ${r.status}`); })()).catch(() => ({} as Record<string, SimConfig>)),
]).then(([saved, presetData]) => {
setPresets(presetData);
if (saved && typeof saved === 'object' && !Array.isArray(saved)) {
@@ -70,7 +79,8 @@ export function useSimConfig(sim?: SimApi) {
setConfig(prev => ({ ...prev, ...saved }));
}
setReady(true);
}).catch(() => {
}).catch((e) => {
setError(`加载配置失败: ${(e as Error).message}`);
setReady(true);
});
}, []);
@@ -225,6 +235,7 @@ export function useSimConfig(sim?: SimApi) {
config,
activePreset,
ready,
error,
presets,
saveStatus,
updateConfig,
@@ -171,7 +171,16 @@ export function useSimulation(initialNnodes: number = 5) {
// ---- WebSocket subscription, with auto-reconnect ----
const connectWs = useCallback(() => {
if (wsRef.current) return;
// 互斥:清理旧连接和重连定时器
if (wsRef.current) {
wsRef.current.onclose = null; // 阻止旧 socket close 再次触发重连
wsRef.current.close();
wsRef.current = null;
}
if (reconnectTimerRef.current !== null) {
clearTimeout(reconnectTimerRef.current);
reconnectTimerRef.current = null;
}
const url = wsUrl('/ws/telemetry');
let ws: WebSocket;
try {
@@ -242,6 +251,12 @@ export function useSimulation(initialNnodes: number = 5) {
useEffect(() => {
connectWs();
return () => {
// 清理 pending requests,避免 setState on unmounted component
pendingRef.current.forEach(({ reject, timer }) => {
clearTimeout(timer);
reject(new Error('component unmounted'));
});
pendingRef.current.clear();
if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current);
if (wsRef.current) {
wsRef.current.onclose = null; // suppress reconnect on unmount
@@ -104,6 +104,16 @@ export interface SimConfig {
onoffMaxBytes: number;
onoffStartTime: number;
onoffSinkPort: number;
// --- TapBridge ---
tapMode: 'UseBridge' | 'UseLocal';
tapPrefix: string;
// --- UDP 协议扩展字段 ---
workMode: number;
fhTableId: number;
nodeMacId: number;
softwareVersion: string;
}
export interface NodeStatus {