78 lines
4.5 KiB
Python
78 lines
4.5 KiB
Python
"""vpn-ai's bounded, telemetry-driven dispatcher; never moves a healthy live stream.
|
|
|
|
Traffic is an EWMA of real reports. Recent session reservations smooth arrivals
|
|
between report intervals; they are NOT presented as measured TCP connections.
|
|
"""
|
|
from datetime import timedelta
|
|
|
|
from django.db import transaction
|
|
from django.db.models import Count
|
|
from django.utils import timezone
|
|
|
|
from .models import ClientSession, Node, NodeTrafficSample, VpnAiRuntime
|
|
|
|
FRESHNESS = timedelta(minutes=3)
|
|
RESERVATION_BYTES_PER_SECOND = 128 * 1024
|
|
|
|
|
|
def build_dispatch_snapshot(now=None):
|
|
now = now or timezone.now()
|
|
reservations = dict(ClientSession.objects.filter(
|
|
assigned_node__isnull=False, revoked_at__isnull=True,
|
|
expires_at__gt=now, last_seen_at__gte=now - timedelta(minutes=5),
|
|
).values("assigned_node_id").annotate(total=Count("device_id", distinct=True)).values_list("assigned_node_id", "total"))
|
|
items = []
|
|
for node in Node.objects.filter(active=True, subscription_enabled=True, protocol=Node.Protocol.VLESS_REALITY):
|
|
samples = list(NodeTrafficSample.objects.filter(node=node, sampled_at__gte=now-FRESHNESS).order_by("-sampled_at")[:3])
|
|
rate = None
|
|
for sample in reversed(samples):
|
|
measured = sample.upload_bytes_per_second + sample.download_bytes_per_second
|
|
rate = measured if rate is None else 0.5 * measured + 0.5 * rate
|
|
healthy = bool(node.status == Node.Status.ONLINE and node.last_seen_at and node.last_seen_at >= now-FRESHNESS)
|
|
items.append({
|
|
"id": node.pk, "slug": node.slug, "name": node.name,
|
|
"healthy": healthy, "fallback_only": node.fallback_only,
|
|
"rate_bps": round(rate) if rate is not None else None,
|
|
"rate_text": f"{rate / 1024:.1f} KB/s" if rate is not None else "暂无新鲜采样",
|
|
"reservations": reservations.get(node.pk, 0),
|
|
"reason": "心跳过期或节点停用" if not healthy else ("最终备用" if node.fallback_only else "正常参与负载调度"),
|
|
})
|
|
return {"algorithm": "load-ewma-v1", "generated_at": now.isoformat(), "nodes": items,
|
|
"health_scope": "agent_heartbeat_not_end_to_end",
|
|
"policy": "启用的主节点按近期吞吐与会话预留分配;当前连接保持;仅标记为备用的节点在主池不可用时参与,不按国家判定。在线心跳不代表端到端出口已验证。"}
|
|
|
|
|
|
@transaction.atomic
|
|
def choose_node(session, excluded=(), new_connection=False):
|
|
# Lock one small shared row to serialize concurrent reservations. Never
|
|
# change account/node status on the strength of one client's failure.
|
|
runtime, _ = VpnAiRuntime.objects.get_or_create(service_name="vpn-ai")
|
|
VpnAiRuntime.objects.select_for_update().get(pk=runtime.pk)
|
|
session = ClientSession.objects.select_for_update().get(pk=session.pk)
|
|
now = timezone.now()
|
|
snapshot = build_dispatch_snapshot(now)
|
|
telemetry = {item["id"]: item for item in snapshot["nodes"]}
|
|
allowed = list(session.subscription.nodes_for_subscription().filter(protocol=Node.Protocol.VLESS_REALITY).exclude(slug__in=list(excluded)[:32]))
|
|
healthy = [node for node in allowed if telemetry.get(node.pk, {}).get("healthy")]
|
|
if not healthy:
|
|
return None, {"reason": "没有心跳正常且属于本订阅的可用节点。"}
|
|
current = next((node for node in healthy if node.pk == session.assigned_node_id), None)
|
|
if current and not new_connection:
|
|
return current, {**session.dispatch_decision, "sticky": True}
|
|
primary = [node for node in healthy if not node.fallback_only]
|
|
pool = primary or healthy
|
|
def score(node):
|
|
item = telemetry[node.pk]
|
|
# Unknown throughput is not zero. Prefer measured primary nodes, but
|
|
# an unmeasured healthy primary still precedes any emergency reserve.
|
|
rate = item["rate_bps"]
|
|
return (rate is None, (rate or 0) + item["reservations"] * RESERVATION_BYTES_PER_SECOND, node.sort_order, node.pk)
|
|
node = min(pool, key=score)
|
|
decision = {"at": now.isoformat(), "algorithm": snapshot["algorithm"], "sticky": False,
|
|
"reason": "主节点不可用,启用最终备用" if not primary else "主节点中按近期吞吐和会话预留分配",
|
|
"rate_bps": telemetry[node.pk]["rate_bps"], "reservations": telemetry[node.pk]["reservations"]}
|
|
session.assigned_node = node
|
|
session.dispatch_decision = decision
|
|
session.save(update_fields=["assigned_node", "dispatch_decision"])
|
|
return node, decision
|