214 lines
9.7 KiB
Python
214 lines
9.7 KiB
Python
|
|
from datetime import timedelta
|
||
|
|
from decimal import Decimal
|
||
|
|
|
||
|
|
from django.db.models import Count, Q
|
||
|
|
from django.utils import timezone
|
||
|
|
|
||
|
|
from .models import LearnedRouteRule, Node, RouteObservation, Subscription, VpnAiFinding, VpnAiRuntime
|
||
|
|
|
||
|
|
|
||
|
|
LEARNING_WINDOW = timedelta(days=7)
|
||
|
|
RULE_LIFETIME = timedelta(days=30)
|
||
|
|
|
||
|
|
|
||
|
|
def _open_finding(*, fingerprint, category, severity, title, summary, evidence):
|
||
|
|
finding, _ = VpnAiFinding.objects.update_or_create(
|
||
|
|
fingerprint=fingerprint,
|
||
|
|
defaults={
|
||
|
|
"category": category,
|
||
|
|
"severity": severity,
|
||
|
|
"status": VpnAiFinding.Status.OPEN,
|
||
|
|
"title": title,
|
||
|
|
"summary": summary,
|
||
|
|
"evidence": evidence,
|
||
|
|
"resolved_at": None,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
return finding
|
||
|
|
|
||
|
|
|
||
|
|
def _resolve_missing_findings(category, active_fingerprints, now):
|
||
|
|
VpnAiFinding.objects.filter(category=category, status=VpnAiFinding.Status.OPEN).exclude(
|
||
|
|
fingerprint__in=active_fingerprints
|
||
|
|
).update(status=VpnAiFinding.Status.RESOLVED, resolved_at=now)
|
||
|
|
|
||
|
|
|
||
|
|
def _learning_confidence(failures, devices, proxy_successes):
|
||
|
|
failure_score = min(1.0, failures / 6) * 0.45
|
||
|
|
device_score = min(1.0, devices / 2) * 0.40
|
||
|
|
success_score = min(1.0, proxy_successes / 2) * 0.15
|
||
|
|
return Decimal(str(round(failure_score + device_score + success_score, 4)))
|
||
|
|
|
||
|
|
|
||
|
|
def evaluate_route_learning(now):
|
||
|
|
since = now - LEARNING_WINDOW
|
||
|
|
aggregates = (
|
||
|
|
RouteObservation.objects.filter(received_at__gte=since, scope="public")
|
||
|
|
.values("target_type", "target")
|
||
|
|
.annotate(
|
||
|
|
failures=Count("id", filter=Q(outcome=RouteObservation.Outcome.DIRECT_FAILED)),
|
||
|
|
proxy_successes=Count("id", filter=Q(outcome=RouteObservation.Outcome.PROXY_SUCCEEDED)),
|
||
|
|
devices=Count("device_id", distinct=True),
|
||
|
|
verified_devices=Count("device_id", distinct=True, filter=Q(
|
||
|
|
outcome=RouteObservation.Outcome.PROXY_SUCCEEDED, evidence_kind="tls", related_report_id__isnull=False)),
|
||
|
|
)
|
||
|
|
)
|
||
|
|
active_route_findings = set()
|
||
|
|
for item in aggregates:
|
||
|
|
failures = item["failures"]
|
||
|
|
devices = item["devices"]
|
||
|
|
successes = item["proxy_successes"]
|
||
|
|
confidence = _learning_confidence(failures, devices, successes)
|
||
|
|
rule, _ = LearnedRouteRule.objects.get_or_create(
|
||
|
|
target_type=item["target_type"],
|
||
|
|
target=item["target"],
|
||
|
|
defaults={
|
||
|
|
"source": LearnedRouteRule.Source.AI,
|
||
|
|
"match_mode": LearnedRouteRule.MatchMode.EXACT,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
rule.failure_reports = failures
|
||
|
|
rule.proxy_success_reports = successes
|
||
|
|
rule.distinct_devices = devices
|
||
|
|
rule.confidence = confidence
|
||
|
|
rule.last_evaluated_at = now
|
||
|
|
if rule.source == LearnedRouteRule.Source.PRESET and rule.manually_locked:
|
||
|
|
# Preset rules are trusted company baselines. vpn-ai may attach
|
||
|
|
# observation counters for visibility, but must not relearn,
|
||
|
|
# expire, or rewrite their reason and status.
|
||
|
|
rule.save(
|
||
|
|
update_fields=[
|
||
|
|
"failure_reports",
|
||
|
|
"proxy_success_reports",
|
||
|
|
"distinct_devices",
|
||
|
|
"confidence",
|
||
|
|
"last_evaluated_at",
|
||
|
|
"updated_at",
|
||
|
|
]
|
||
|
|
)
|
||
|
|
continue
|
||
|
|
rule.reason = (
|
||
|
|
f"近 7 天:直连失败 {failures} 次、涉及 {devices} 台设备、"
|
||
|
|
f"代理成功确认 {successes} 次;置信度 {confidence}."
|
||
|
|
)
|
||
|
|
if not rule.manually_locked:
|
||
|
|
# Company rules still require independent evidence from at least two
|
||
|
|
# devices. A direct failure followed by a successful proxy probe on
|
||
|
|
# both devices is stronger evidence than repeated failures alone.
|
||
|
|
# Failure-only reports can be a local outage, a dead website or DNS
|
||
|
|
# policy. Require correlated, certificate-verified proxy TLS on two
|
||
|
|
# devices; legacy unverified reports remain visible but cannot promote.
|
||
|
|
should_activate = item["verified_devices"] >= 2 and failures >= 2
|
||
|
|
rule.status = LearnedRouteRule.Status.ACTIVE if should_activate else LearnedRouteRule.Status.PENDING
|
||
|
|
rule.valid_until = now + RULE_LIFETIME if should_activate else None
|
||
|
|
rule.save()
|
||
|
|
|
||
|
|
if rule.status == LearnedRouteRule.Status.ACTIVE:
|
||
|
|
fingerprint = f"route:{rule.target_type}:{rule.target}"
|
||
|
|
active_route_findings.add(fingerprint)
|
||
|
|
_open_finding(
|
||
|
|
fingerprint=fingerprint,
|
||
|
|
category=VpnAiFinding.Category.ROUTING,
|
||
|
|
severity=VpnAiFinding.Severity.INFO,
|
||
|
|
title=f"已学习代理目标:{rule.target}",
|
||
|
|
summary="vpn-ai 已依据多设备连接结果启用公司级智能代理规则。",
|
||
|
|
evidence={
|
||
|
|
"target_type": rule.target_type,
|
||
|
|
"target": rule.target,
|
||
|
|
"confidence": str(confidence),
|
||
|
|
"failures": failures,
|
||
|
|
"devices": devices,
|
||
|
|
"proxy_successes": successes,
|
||
|
|
"valid_until": rule.valid_until.isoformat() if rule.valid_until else None,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
|
||
|
|
LearnedRouteRule.objects.filter(
|
||
|
|
status=LearnedRouteRule.Status.ACTIVE,
|
||
|
|
manually_locked=False,
|
||
|
|
valid_until__lte=now,
|
||
|
|
).update(status=LearnedRouteRule.Status.PENDING, valid_until=None)
|
||
|
|
_resolve_missing_findings(VpnAiFinding.Category.ROUTING, active_route_findings, now)
|
||
|
|
|
||
|
|
|
||
|
|
def diagnose_nodes(now):
|
||
|
|
stale_before = now - timedelta(minutes=10)
|
||
|
|
offline_before = now - timedelta(minutes=15)
|
||
|
|
active_fingerprints = set()
|
||
|
|
nodes = Node.objects.filter(active=True, subscription_enabled=True).exclude(status=Node.Status.MAINTENANCE)
|
||
|
|
for node in nodes:
|
||
|
|
if not node.last_seen_at or node.last_seen_at < stale_before:
|
||
|
|
fingerprint = f"node:stale:{node.pk}"
|
||
|
|
active_fingerprints.add(fingerprint)
|
||
|
|
minutes = None if not node.last_seen_at else round((now - node.last_seen_at).total_seconds() / 60)
|
||
|
|
_open_finding(
|
||
|
|
fingerprint=fingerprint,
|
||
|
|
category=VpnAiFinding.Category.NODE,
|
||
|
|
severity=(
|
||
|
|
VpnAiFinding.Severity.CRITICAL
|
||
|
|
if not node.last_seen_at or node.last_seen_at < offline_before
|
||
|
|
else VpnAiFinding.Severity.WARNING
|
||
|
|
),
|
||
|
|
title=f"节点心跳异常:{node.name}",
|
||
|
|
summary="节点代理未在预期时间内上报,vpn-ai 已记录并持续复查。",
|
||
|
|
evidence={
|
||
|
|
"node": node.slug,
|
||
|
|
"last_seen_at": node.last_seen_at.isoformat() if node.last_seen_at else None,
|
||
|
|
"minutes_since_seen": minutes,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
if node.status == Node.Status.ONLINE and (not node.last_seen_at or node.last_seen_at < offline_before):
|
||
|
|
Node.objects.filter(pk=node.pk, status=Node.Status.ONLINE).update(status=Node.Status.OFFLINE)
|
||
|
|
_resolve_missing_findings(VpnAiFinding.Category.NODE, active_fingerprints, now)
|
||
|
|
|
||
|
|
|
||
|
|
def diagnose_subscriptions(now):
|
||
|
|
active_fingerprints = set()
|
||
|
|
subscriptions = Subscription.objects.select_related("user", "plan").filter(status=Subscription.Status.ACTIVE)
|
||
|
|
for subscription in subscriptions:
|
||
|
|
if subscription.traffic_limit_bytes:
|
||
|
|
percent = subscription.used_bytes * 100 / subscription.traffic_limit_bytes
|
||
|
|
if percent >= 90:
|
||
|
|
fingerprint = f"subscription:quota:{subscription.pk}"
|
||
|
|
active_fingerprints.add(fingerprint)
|
||
|
|
_open_finding(
|
||
|
|
fingerprint=fingerprint,
|
||
|
|
category=VpnAiFinding.Category.SUBSCRIPTION,
|
||
|
|
severity=VpnAiFinding.Severity.WARNING,
|
||
|
|
title=f"订阅流量接近上限:{subscription.user}",
|
||
|
|
summary="当前周期流量使用率已达到或超过 90%。",
|
||
|
|
evidence={"subscription_id": subscription.pk, "usage_percent": round(percent, 2)},
|
||
|
|
)
|
||
|
|
if subscription.expires_at and subscription.expires_at <= now + timedelta(days=3):
|
||
|
|
fingerprint = f"subscription:expiry:{subscription.pk}"
|
||
|
|
active_fingerprints.add(fingerprint)
|
||
|
|
_open_finding(
|
||
|
|
fingerprint=fingerprint,
|
||
|
|
category=VpnAiFinding.Category.SUBSCRIPTION,
|
||
|
|
severity=VpnAiFinding.Severity.WARNING,
|
||
|
|
title=f"订阅即将到期:{subscription.user}",
|
||
|
|
summary="订阅将在 3 天内到期,请管理员确认续期或停用安排。",
|
||
|
|
evidence={"subscription_id": subscription.pk, "expires_at": subscription.expires_at.isoformat()},
|
||
|
|
)
|
||
|
|
_resolve_missing_findings(VpnAiFinding.Category.SUBSCRIPTION, active_fingerprints, now)
|
||
|
|
|
||
|
|
|
||
|
|
def run_vpn_ai_cycle(runtime):
|
||
|
|
from .dispatch import build_dispatch_snapshot
|
||
|
|
now = timezone.now()
|
||
|
|
evaluate_route_learning(now)
|
||
|
|
diagnose_nodes(now)
|
||
|
|
diagnose_subscriptions(now)
|
||
|
|
since = now - LEARNING_WINDOW
|
||
|
|
runtime.last_heartbeat_at = now
|
||
|
|
runtime.last_cycle_at = now
|
||
|
|
runtime.cycle_count += 1
|
||
|
|
runtime.observations_7d = RouteObservation.objects.filter(received_at__gte=since).count()
|
||
|
|
runtime.active_rules = LearnedRouteRule.objects.filter(
|
||
|
|
status=LearnedRouteRule.Status.ACTIVE
|
||
|
|
).filter(Q(valid_until__isnull=True) | Q(valid_until__gt=now)).count()
|
||
|
|
runtime.open_findings = VpnAiFinding.objects.filter(status=VpnAiFinding.Status.OPEN).count()
|
||
|
|
runtime.last_error = ""
|
||
|
|
runtime.dispatch_snapshot = build_dispatch_snapshot(now)
|
||
|
|
runtime.save()
|