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:
+82
-166
@@ -1,4 +1,4 @@
|
||||
"""从 sing-box Clash API / V2Ray gRPC 采集节点连接与流量。"""
|
||||
"""从 sing-box Clash API 采集节点连接与流量(官方预编译包不含 v2ray_api)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
@@ -9,19 +9,15 @@ import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
import grpc
|
||||
|
||||
from db import connect, list_nodes
|
||||
|
||||
ROOT = Path(os.environ.get("JIEDIAN_ROOT", Path(__file__).resolve().parents[1]))
|
||||
ENV_FILE = ROOT / ".env"
|
||||
|
||||
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]] = {}
|
||||
_conn_cache: dict[str, dict[str, int | str]] = {}
|
||||
|
||||
|
||||
def _load_env() -> dict[str, str]:
|
||||
@@ -52,123 +48,6 @@ def format_speed(num: float) -> str:
|
||||
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]:
|
||||
env = _load_env()
|
||||
secret = env.get("CLASH_API_SECRET", "")
|
||||
@@ -184,10 +63,13 @@ def fetch_clash_connections() -> tuple[list[dict], bool]:
|
||||
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 {}
|
||||
user = str(meta.get("user") or meta.get("uid") or "")
|
||||
return user == uuid
|
||||
return str(meta.get("user") or meta.get("uid") or "")
|
||||
|
||||
|
||||
def _connection_id(conn: dict) -> str:
|
||||
return str(conn.get("id") or "")
|
||||
|
||||
|
||||
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()
|
||||
_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(
|
||||
"""
|
||||
UPDATE traffic_counters
|
||||
SET upload_total = ?, download_total = ?,
|
||||
snapshot_upload = ?, snapshot_download = ?,
|
||||
SET upload_total = upload_total + ?,
|
||||
download_total = download_total + ?,
|
||||
updated_at = datetime('now')
|
||||
WHERE node_id = ?
|
||||
""",
|
||||
(total_up, total_down, raw_up, raw_down, node_id),
|
||||
(upload, download, node_id),
|
||||
)
|
||||
conn.commit()
|
||||
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]:
|
||||
@@ -268,9 +182,9 @@ def _calc_speed(node_id: int, up: int, down: int) -> tuple[float, float]:
|
||||
|
||||
def collect_node_stats() -> dict:
|
||||
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()
|
||||
singbox_ok = v2ray_ok or clash_ok
|
||||
active_by_uuid = _sync_connections(connections, uuid_to_node)
|
||||
|
||||
result_nodes: dict[str, dict] = {}
|
||||
summary_online = 0
|
||||
@@ -280,11 +194,13 @@ def collect_node_stats() -> dict:
|
||||
for node in nodes:
|
||||
uid = node["uuid"]
|
||||
node_id = int(node["id"])
|
||||
raw_up, raw_down = v2ray.get(uid, (0, 0))
|
||||
total_up, total_down = _update_traffic_totals(node_id, raw_up, raw_down)
|
||||
up_speed, down_speed = _calc_speed(node_id, raw_up, raw_down)
|
||||
stored_up, stored_down = _get_stored_totals(node_id)
|
||||
session_up, session_down = active_by_uuid.get(uid, (0, 0))
|
||||
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
|
||||
|
||||
if online:
|
||||
@@ -297,17 +213,17 @@ def collect_node_stats() -> dict:
|
||||
"connections": len(matched),
|
||||
"upload_speed": round(up_speed),
|
||||
"download_speed": round(down_speed),
|
||||
"upload_total": total_up,
|
||||
"download_total": total_down,
|
||||
"upload_total": display_up,
|
||||
"download_total": display_down,
|
||||
"upload_speed_human": format_speed(up_speed),
|
||||
"download_speed_human": format_speed(down_speed),
|
||||
"upload_total_human": format_bytes(total_up),
|
||||
"download_total_human": format_bytes(total_down),
|
||||
"upload_total_human": format_bytes(display_up),
|
||||
"download_total_human": format_bytes(display_down),
|
||||
}
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"singbox": singbox_ok,
|
||||
"singbox": clash_ok,
|
||||
"nodes": result_nodes,
|
||||
"summary": {
|
||||
"online": summary_online,
|
||||
|
||||
Reference in New Issue
Block a user