fix: use Clash API only for traffic stats on stock sing-box builds
Official sing-box binaries lack v2ray_api, so drop that config and grpcio and track per-node traffic from Clash connection stats instead. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
+1
-1
@@ -90,7 +90,7 @@ bash scripts/install.sh
|
|||||||
| 复制链接 | VLESS Reality + Hysteria2 分享链接 |
|
| 复制链接 | VLESS Reality + Hysteria2 分享链接 |
|
||||||
| 删除节点 | 至少保留 1 个节点 |
|
| 删除节点 | 至少保留 1 个节点 |
|
||||||
| 连接状态 | 在线/离线、当前连接数(Clash API) |
|
| 连接状态 | 在线/离线、当前连接数(Clash API) |
|
||||||
| 流量统计 | 实时速率 + 累计上下行(V2Ray 统计,重启 sing-box 后继续累计) |
|
| 流量统计 | 实时速率 + 累计上下行(Clash API 连接统计) |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
+23
-4
@@ -37,25 +37,44 @@ curl -I "http://66.hyf2.cc/$(grep ^PANEL_PATH= /opt/jiedian/.env | cut -d= -f2)/
|
|||||||
|
|
||||||
> 443 端口已被 sing-box Reality 占用,面板走 80 端口子路径。请妥善保管 `PANEL_PATH`,相当于隐藏入口。
|
> 443 端口已被 sing-box Reality 占用,面板走 80 端口子路径。请妥善保管 `PANEL_PATH`,相当于隐藏入口。
|
||||||
|
|
||||||
面板可查看每个节点的 **在线状态、连接数、实时速率、累计流量**(数据来自 sing-box Clash API + V2Ray 统计,仅监听 127.0.0.1)。
|
面板可查看每个节点的 **在线状态、连接数、实时速率、累计流量**(数据来自 sing-box Clash API,仅监听 127.0.0.1)。
|
||||||
|
|
||||||
|
> **注意**:GitHub 官方 sing-box 预编译包**不含** `v2ray_api`,配置里不要启用 `experimental.v2ray_api`,否则 sing-box 无法启动。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 常见问题
|
## 常见问题
|
||||||
|
|
||||||
|
### sing-box 报错 v2ray api is not included in this build
|
||||||
|
|
||||||
|
GitHub 下载的官方 sing-box **默认不带** `v2ray_api` 模块。若配置里写了 `experimental.v2ray_api`,启动时会直接失败:
|
||||||
|
|
||||||
|
```
|
||||||
|
FATAL create v2ray-server: v2ray api is not included in this build, rebuild with -tags with_v2ray_api
|
||||||
|
```
|
||||||
|
|
||||||
|
**处理**:重新生成配置(已移除 v2ray_api,改用 Clash API 统计)并重启:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /opt/jiedian
|
||||||
|
git pull
|
||||||
|
python3 scripts/render-server.py
|
||||||
|
systemctl restart sing-box jiedian-panel
|
||||||
|
```
|
||||||
|
|
||||||
### 面板流量/在线状态显示「不可用」
|
### 面板流量/在线状态显示「不可用」
|
||||||
|
|
||||||
sing-box 统计 API 未就绪,按顺序检查:
|
sing-box Clash API 未就绪,按顺序检查:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
systemctl is-active sing-box
|
systemctl is-active sing-box
|
||||||
ss -tlnp | grep -E '9090|9091' # Clash API / V2Ray gRPC
|
ss -tlnp | grep 9090 # Clash API
|
||||||
grep CLASH_API_SECRET /opt/jiedian/.env
|
grep CLASH_API_SECRET /opt/jiedian/.env
|
||||||
python3 /opt/jiedian/scripts/render-server.py
|
python3 /opt/jiedian/scripts/render-server.py
|
||||||
systemctl restart sing-box jiedian-panel
|
systemctl restart sing-box jiedian-panel
|
||||||
```
|
```
|
||||||
|
|
||||||
升级后若未重装,需重新生成 sing-box 配置并重启服务,才会启用 `experimental.clash_api` 与 `v2ray_api`。
|
升级后若未重装,需重新生成 sing-box 配置并重启服务,才会启用 `experimental.clash_api`。
|
||||||
|
|
||||||
### 在线状态始终离线但客户端能连
|
### 在线状态始终离线但客户端能连
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,2 @@
|
|||||||
flask>=3.0,<4
|
flask>=3.0,<4
|
||||||
werkzeug>=3.0,<4
|
werkzeug>=3.0,<4
|
||||||
grpcio>=1.60,<2
|
|
||||||
|
|||||||
+82
-166
@@ -1,4 +1,4 @@
|
|||||||
"""从 sing-box Clash API / V2Ray gRPC 采集节点连接与流量。"""
|
"""从 sing-box Clash API 采集节点连接与流量(官方预编译包不含 v2ray_api)。"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
@@ -9,19 +9,15 @@ import urllib.error
|
|||||||
import urllib.request
|
import urllib.request
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import grpc
|
|
||||||
|
|
||||||
from db import connect, list_nodes
|
from db import connect, list_nodes
|
||||||
|
|
||||||
ROOT = Path(os.environ.get("JIEDIAN_ROOT", Path(__file__).resolve().parents[1]))
|
ROOT = Path(os.environ.get("JIEDIAN_ROOT", Path(__file__).resolve().parents[1]))
|
||||||
ENV_FILE = ROOT / ".env"
|
ENV_FILE = ROOT / ".env"
|
||||||
|
|
||||||
CLASH_ADDR = "127.0.0.1:9090"
|
CLASH_ADDR = "127.0.0.1:9090"
|
||||||
V2RAY_ADDR = "127.0.0.1:9091"
|
|
||||||
GRPC_METHOD = "/v2ray.core.app.stats.command.StatsService/QueryStats"
|
|
||||||
|
|
||||||
_grpc_channel: grpc.Channel | None = None
|
|
||||||
_speed_cache: dict[int, tuple[float, int, int]] = {}
|
_speed_cache: dict[int, tuple[float, int, int]] = {}
|
||||||
|
_conn_cache: dict[str, dict[str, int | str]] = {}
|
||||||
|
|
||||||
|
|
||||||
def _load_env() -> dict[str, str]:
|
def _load_env() -> dict[str, str]:
|
||||||
@@ -52,123 +48,6 @@ def format_speed(num: float) -> str:
|
|||||||
return f"{format_bytes(num)}/s"
|
return f"{format_bytes(num)}/s"
|
||||||
|
|
||||||
|
|
||||||
def _varint_encode(n: int) -> bytes:
|
|
||||||
out = bytearray()
|
|
||||||
while n > 0x7F:
|
|
||||||
out.append((n & 0x7F) | 0x80)
|
|
||||||
n >>= 7
|
|
||||||
out.append(n)
|
|
||||||
return bytes(out)
|
|
||||||
|
|
||||||
|
|
||||||
def _varint_decode(data: bytes, i: int) -> tuple[int, int]:
|
|
||||||
shift = 0
|
|
||||||
result = 0
|
|
||||||
while i < len(data):
|
|
||||||
b = data[i]
|
|
||||||
i += 1
|
|
||||||
result |= (b & 0x7F) << shift
|
|
||||||
if not (b & 0x80):
|
|
||||||
return result, i
|
|
||||||
shift += 7
|
|
||||||
raise ValueError("truncated varint")
|
|
||||||
|
|
||||||
|
|
||||||
def _skip_field(data: bytes, i: int, wire_type: int) -> int:
|
|
||||||
if wire_type == 0:
|
|
||||||
_, i = _varint_decode(data, i)
|
|
||||||
elif wire_type == 1:
|
|
||||||
i += 8
|
|
||||||
elif wire_type == 2:
|
|
||||||
length, i = _varint_decode(data, i)
|
|
||||||
i += length
|
|
||||||
elif wire_type == 5:
|
|
||||||
i += 4
|
|
||||||
else:
|
|
||||||
raise ValueError(f"unsupported wire type {wire_type}")
|
|
||||||
return i
|
|
||||||
|
|
||||||
|
|
||||||
def _encode_query_stats(name: str) -> bytes:
|
|
||||||
if not name:
|
|
||||||
return b""
|
|
||||||
payload = name.encode("utf-8")
|
|
||||||
return bytes([0x0A]) + _varint_encode(len(payload)) + payload
|
|
||||||
|
|
||||||
|
|
||||||
def _decode_stat_message(data: bytes) -> tuple[str, int | None]:
|
|
||||||
name: str | None = None
|
|
||||||
value: int | None = None
|
|
||||||
i = 0
|
|
||||||
while i < len(data):
|
|
||||||
tag = data[i]
|
|
||||||
i += 1
|
|
||||||
field = tag >> 3
|
|
||||||
wire = tag & 0x07
|
|
||||||
if field == 1 and wire == 2:
|
|
||||||
length, i = _varint_decode(data, i)
|
|
||||||
name = data[i : i + length].decode("utf-8")
|
|
||||||
i += length
|
|
||||||
elif field == 2 and wire == 0:
|
|
||||||
value, i = _varint_decode(data, i)
|
|
||||||
else:
|
|
||||||
i = _skip_field(data, i, wire)
|
|
||||||
return name or "", value
|
|
||||||
|
|
||||||
|
|
||||||
def _decode_query_stats_response(data: bytes) -> dict[str, int]:
|
|
||||||
stats: dict[str, int] = {}
|
|
||||||
i = 0
|
|
||||||
while i < len(data):
|
|
||||||
tag = data[i]
|
|
||||||
i += 1
|
|
||||||
field = tag >> 3
|
|
||||||
wire = tag & 0x07
|
|
||||||
if field == 1 and wire == 2:
|
|
||||||
length, i = _varint_decode(data, i)
|
|
||||||
name, value = _decode_stat_message(data[i : i + length])
|
|
||||||
i += length
|
|
||||||
if name and value is not None:
|
|
||||||
stats[name] = value
|
|
||||||
else:
|
|
||||||
i = _skip_field(data, i, wire)
|
|
||||||
return stats
|
|
||||||
|
|
||||||
|
|
||||||
def _grpc_channel_get() -> grpc.Channel:
|
|
||||||
global _grpc_channel
|
|
||||||
if _grpc_channel is None:
|
|
||||||
_grpc_channel = grpc.insecure_channel(V2RAY_ADDR)
|
|
||||||
return _grpc_channel
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_v2ray_user_stats() -> tuple[dict[str, tuple[int, int]], bool]:
|
|
||||||
"""返回 ({uuid: (upload_bytes, download_bytes)}, ok)。"""
|
|
||||||
channel = _grpc_channel_get()
|
|
||||||
method = channel.unary_unary(
|
|
||||||
GRPC_METHOD,
|
|
||||||
request_serializer=_encode_query_stats,
|
|
||||||
response_deserializer=_decode_query_stats_response,
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
raw = method(b"user>>>")
|
|
||||||
except grpc.RpcError:
|
|
||||||
return {}, False
|
|
||||||
|
|
||||||
users: dict[str, tuple[int, int]] = {}
|
|
||||||
for name, value in raw.items():
|
|
||||||
parts = name.split(">>>")
|
|
||||||
if len(parts) != 4 or parts[0] != "user" or parts[2] != "traffic":
|
|
||||||
continue
|
|
||||||
uid, direction = parts[1], parts[3]
|
|
||||||
up, down = users.get(uid, (0, 0))
|
|
||||||
if direction == "uplink":
|
|
||||||
users[uid] = (value, down)
|
|
||||||
elif direction == "downlink":
|
|
||||||
users[uid] = (up, value)
|
|
||||||
return users, True
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_clash_connections() -> tuple[list[dict], bool]:
|
def fetch_clash_connections() -> tuple[list[dict], bool]:
|
||||||
env = _load_env()
|
env = _load_env()
|
||||||
secret = env.get("CLASH_API_SECRET", "")
|
secret = env.get("CLASH_API_SECRET", "")
|
||||||
@@ -184,10 +63,13 @@ def fetch_clash_connections() -> tuple[list[dict], bool]:
|
|||||||
return payload.get("connections") or [], True
|
return payload.get("connections") or [], True
|
||||||
|
|
||||||
|
|
||||||
def _match_connection(conn: dict, uuid: str) -> bool:
|
def _connection_user(conn: dict) -> str:
|
||||||
meta = conn.get("metadata") or {}
|
meta = conn.get("metadata") or {}
|
||||||
user = str(meta.get("user") or meta.get("uid") or "")
|
return str(meta.get("user") or meta.get("uid") or "")
|
||||||
return user == uuid
|
|
||||||
|
|
||||||
|
def _connection_id(conn: dict) -> str:
|
||||||
|
return str(conn.get("id") or "")
|
||||||
|
|
||||||
|
|
||||||
def _ensure_traffic_schema(conn: sqlite3.Connection) -> None:
|
def _ensure_traffic_schema(conn: sqlite3.Connection) -> None:
|
||||||
@@ -211,46 +93,78 @@ def _ensure_traffic_schema(conn: sqlite3.Connection) -> None:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _update_traffic_totals(node_id: int, raw_up: int, raw_down: int) -> tuple[int, int]:
|
def _add_closed_traffic(node_id: int, upload: int, download: int) -> None:
|
||||||
|
if upload <= 0 and download <= 0:
|
||||||
|
return
|
||||||
conn = connect()
|
conn = connect()
|
||||||
_ensure_traffic_schema(conn)
|
_ensure_traffic_schema(conn)
|
||||||
row = conn.execute(
|
|
||||||
"SELECT upload_total, download_total, snapshot_upload, snapshot_download "
|
|
||||||
"FROM traffic_counters WHERE node_id = ?",
|
|
||||||
(node_id,),
|
|
||||||
).fetchone()
|
|
||||||
if row is None:
|
|
||||||
conn.execute("INSERT INTO traffic_counters (node_id) VALUES (?)", (node_id,))
|
|
||||||
conn.commit()
|
|
||||||
total_up, total_down, snap_up, snap_down = 0, 0, 0, 0
|
|
||||||
else:
|
|
||||||
total_up = int(row["upload_total"])
|
|
||||||
total_down = int(row["download_total"])
|
|
||||||
snap_up = int(row["snapshot_upload"])
|
|
||||||
snap_down = int(row["snapshot_download"])
|
|
||||||
|
|
||||||
if raw_up < snap_up or raw_down < snap_down:
|
|
||||||
total_up += snap_up
|
|
||||||
total_down += snap_down
|
|
||||||
snap_up = 0
|
|
||||||
snap_down = 0
|
|
||||||
|
|
||||||
total_up += max(0, raw_up - snap_up)
|
|
||||||
total_down += max(0, raw_down - snap_down)
|
|
||||||
|
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"""
|
"""
|
||||||
UPDATE traffic_counters
|
UPDATE traffic_counters
|
||||||
SET upload_total = ?, download_total = ?,
|
SET upload_total = upload_total + ?,
|
||||||
snapshot_upload = ?, snapshot_download = ?,
|
download_total = download_total + ?,
|
||||||
updated_at = datetime('now')
|
updated_at = datetime('now')
|
||||||
WHERE node_id = ?
|
WHERE node_id = ?
|
||||||
""",
|
""",
|
||||||
(total_up, total_down, raw_up, raw_down, node_id),
|
(upload, download, node_id),
|
||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
conn.close()
|
conn.close()
|
||||||
return total_up, total_down
|
|
||||||
|
|
||||||
|
def _get_stored_totals(node_id: int) -> tuple[int, int]:
|
||||||
|
conn = connect()
|
||||||
|
_ensure_traffic_schema(conn)
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT upload_total, download_total FROM traffic_counters WHERE node_id = ?",
|
||||||
|
(node_id,),
|
||||||
|
).fetchone()
|
||||||
|
conn.close()
|
||||||
|
if row is None:
|
||||||
|
return 0, 0
|
||||||
|
return int(row["upload_total"]), int(row["download_total"])
|
||||||
|
|
||||||
|
|
||||||
|
def _sync_connections(
|
||||||
|
connections: list[dict], uuid_to_node: dict[str, int]
|
||||||
|
) -> dict[str, tuple[int, int]]:
|
||||||
|
"""同步连接缓存,断开连接时写入累计流量,返回各用户当前活跃会话流量。"""
|
||||||
|
seen: set[str] = set()
|
||||||
|
active: dict[str, tuple[int, int]] = {}
|
||||||
|
|
||||||
|
for conn in connections:
|
||||||
|
user = _connection_user(conn)
|
||||||
|
if user not in uuid_to_node:
|
||||||
|
continue
|
||||||
|
cid = _connection_id(conn)
|
||||||
|
if not cid:
|
||||||
|
continue
|
||||||
|
|
||||||
|
upload = int(conn.get("upload") or 0)
|
||||||
|
download = int(conn.get("download") or 0)
|
||||||
|
seen.add(cid)
|
||||||
|
|
||||||
|
prev = _conn_cache.get(cid)
|
||||||
|
if prev and prev["uuid"] == user:
|
||||||
|
prev_up = int(prev["upload"])
|
||||||
|
prev_down = int(prev["download"])
|
||||||
|
if upload < prev_up or download < prev_down:
|
||||||
|
_add_closed_traffic(uuid_to_node[user], prev_up, prev_down)
|
||||||
|
_conn_cache[cid] = {"uuid": user, "upload": upload, "download": download}
|
||||||
|
|
||||||
|
cur_up, cur_down = active.get(user, (0, 0))
|
||||||
|
active[user] = (cur_up + upload, cur_down + download)
|
||||||
|
|
||||||
|
for cid in list(_conn_cache.keys()):
|
||||||
|
if cid in seen:
|
||||||
|
continue
|
||||||
|
info = _conn_cache.pop(cid)
|
||||||
|
user = str(info["uuid"])
|
||||||
|
node_id = uuid_to_node.get(user)
|
||||||
|
if node_id:
|
||||||
|
_add_closed_traffic(node_id, int(info["upload"]), int(info["download"]))
|
||||||
|
|
||||||
|
return active
|
||||||
|
|
||||||
|
|
||||||
def _calc_speed(node_id: int, up: int, down: int) -> tuple[float, float]:
|
def _calc_speed(node_id: int, up: int, down: int) -> tuple[float, float]:
|
||||||
@@ -268,9 +182,9 @@ def _calc_speed(node_id: int, up: int, down: int) -> tuple[float, float]:
|
|||||||
|
|
||||||
def collect_node_stats() -> dict:
|
def collect_node_stats() -> dict:
|
||||||
nodes = list_nodes()
|
nodes = list_nodes()
|
||||||
v2ray, v2ray_ok = fetch_v2ray_user_stats()
|
uuid_to_node = {node["uuid"]: int(node["id"]) for node in nodes}
|
||||||
connections, clash_ok = fetch_clash_connections()
|
connections, clash_ok = fetch_clash_connections()
|
||||||
singbox_ok = v2ray_ok or clash_ok
|
active_by_uuid = _sync_connections(connections, uuid_to_node)
|
||||||
|
|
||||||
result_nodes: dict[str, dict] = {}
|
result_nodes: dict[str, dict] = {}
|
||||||
summary_online = 0
|
summary_online = 0
|
||||||
@@ -280,11 +194,13 @@ def collect_node_stats() -> dict:
|
|||||||
for node in nodes:
|
for node in nodes:
|
||||||
uid = node["uuid"]
|
uid = node["uuid"]
|
||||||
node_id = int(node["id"])
|
node_id = int(node["id"])
|
||||||
raw_up, raw_down = v2ray.get(uid, (0, 0))
|
stored_up, stored_down = _get_stored_totals(node_id)
|
||||||
total_up, total_down = _update_traffic_totals(node_id, raw_up, raw_down)
|
session_up, session_down = active_by_uuid.get(uid, (0, 0))
|
||||||
up_speed, down_speed = _calc_speed(node_id, raw_up, raw_down)
|
display_up = stored_up + session_up
|
||||||
|
display_down = stored_down + session_down
|
||||||
|
up_speed, down_speed = _calc_speed(node_id, display_up, display_down)
|
||||||
|
|
||||||
matched = [c for c in connections if _match_connection(c, uid)]
|
matched = [c for c in connections if _connection_user(c) == uid]
|
||||||
online = len(matched) > 0 or (up_speed + down_speed) > 512
|
online = len(matched) > 0 or (up_speed + down_speed) > 512
|
||||||
|
|
||||||
if online:
|
if online:
|
||||||
@@ -297,17 +213,17 @@ def collect_node_stats() -> dict:
|
|||||||
"connections": len(matched),
|
"connections": len(matched),
|
||||||
"upload_speed": round(up_speed),
|
"upload_speed": round(up_speed),
|
||||||
"download_speed": round(down_speed),
|
"download_speed": round(down_speed),
|
||||||
"upload_total": total_up,
|
"upload_total": display_up,
|
||||||
"download_total": total_down,
|
"download_total": display_down,
|
||||||
"upload_speed_human": format_speed(up_speed),
|
"upload_speed_human": format_speed(up_speed),
|
||||||
"download_speed_human": format_speed(down_speed),
|
"download_speed_human": format_speed(down_speed),
|
||||||
"upload_total_human": format_bytes(total_up),
|
"upload_total_human": format_bytes(display_up),
|
||||||
"download_total_human": format_bytes(total_down),
|
"download_total_human": format_bytes(display_down),
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"ok": True,
|
"ok": True,
|
||||||
"singbox": singbox_ok,
|
"singbox": clash_ok,
|
||||||
"nodes": result_nodes,
|
"nodes": result_nodes,
|
||||||
"summary": {
|
"summary": {
|
||||||
"online": summary_online,
|
"online": summary_online,
|
||||||
|
|||||||
@@ -58,7 +58,6 @@ def build_config(env: dict[str, str], nodes: list[dict]) -> dict:
|
|||||||
hy2_users = [
|
hy2_users = [
|
||||||
{"name": n["uuid"], "password": n["hy2_password"]} for n in nodes
|
{"name": n["uuid"], "password": n["hy2_password"]} for n in nodes
|
||||||
]
|
]
|
||||||
user_ids = [n["uuid"] for n in nodes]
|
|
||||||
clash_secret = env.get("CLASH_API_SECRET", "")
|
clash_secret = env.get("CLASH_API_SECRET", "")
|
||||||
|
|
||||||
config = {
|
config = {
|
||||||
@@ -109,14 +108,6 @@ def build_config(env: dict[str, str], nodes: list[dict]) -> dict:
|
|||||||
"clash_api": {
|
"clash_api": {
|
||||||
"external_controller": "127.0.0.1:9090",
|
"external_controller": "127.0.0.1:9090",
|
||||||
},
|
},
|
||||||
"v2ray_api": {
|
|
||||||
"listen": "127.0.0.1:9091",
|
|
||||||
"stats": {
|
|
||||||
"enabled": True,
|
|
||||||
"inbounds": ["vless-reality-in", "hysteria2-in"],
|
|
||||||
"users": user_ids,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
if clash_secret:
|
if clash_secret:
|
||||||
experimental["clash_api"]["secret"] = clash_secret
|
experimental["clash_api"]["secret"] = clash_secret
|
||||||
|
|||||||
Reference in New Issue
Block a user