Publish Zonghengjia Windows 0.4.0 client source
This commit is contained in:
@@ -15,6 +15,12 @@ FRESHNESS = timedelta(minutes=3)
|
||||
RESERVATION_BYTES_PER_SECOND = 128 * 1024
|
||||
|
||||
|
||||
def lock_vpn_ai_runtime():
|
||||
"""Lock the one row shared by dispatch and topology-changing operations."""
|
||||
runtime, _ = VpnAiRuntime.objects.get_or_create(service_name="vpn-ai")
|
||||
return VpnAiRuntime.objects.select_for_update().get(pk=runtime.pk)
|
||||
|
||||
|
||||
def build_dispatch_snapshot(now=None):
|
||||
now = now or timezone.now()
|
||||
reservations = dict(ClientSession.objects.filter(
|
||||
@@ -46,8 +52,7 @@ def build_dispatch_snapshot(now=None):
|
||||
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)
|
||||
lock_vpn_ai_runtime()
|
||||
session = ClientSession.objects.select_for_update().get(pk=session.pk)
|
||||
now = timezone.now()
|
||||
snapshot = build_dispatch_snapshot(now)
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
from django.db import transaction
|
||||
from django.utils import timezone
|
||||
|
||||
from control.dispatch import FRESHNESS, lock_vpn_ai_runtime
|
||||
from control.models import ClientSession, Node, NodeDeployment, Subscription
|
||||
|
||||
|
||||
TARGET_SLUG = "racknerd-newyork-004"
|
||||
LEGACY_SLUGS = ("aliyun-tokyo-002", "aliyun-siliconvalley-003")
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = "Safely drain and retire legacy VPN nodes after migrating access to VPN004."
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument(
|
||||
"--phase",
|
||||
choices=("drain", "finalize"),
|
||||
default="drain",
|
||||
help="drain migrates access and revokes desired credentials; finalize disables acknowledged nodes.",
|
||||
)
|
||||
|
||||
@transaction.atomic
|
||||
def handle(self, *args, **options):
|
||||
# choose_node takes this same lock before assigning sessions. Holding it
|
||||
# through the retirement transaction prevents a concurrent reservation
|
||||
# from writing a legacy node back after sessions have been migrated.
|
||||
lock_vpn_ai_runtime()
|
||||
target = Node.objects.select_for_update().filter(slug=TARGET_SLUG).first()
|
||||
if not target or not (
|
||||
target.active
|
||||
and target.subscription_enabled
|
||||
and target.status == Node.Status.ONLINE
|
||||
and target.protocol == Node.Protocol.VLESS_REALITY
|
||||
and not target.office_only
|
||||
):
|
||||
raise CommandError(
|
||||
f"replacement node {TARGET_SLUG} must be an active, subscribed, online public VLESS node"
|
||||
)
|
||||
if not target.last_seen_at or target.last_seen_at < timezone.now() - FRESHNESS:
|
||||
raise CommandError(
|
||||
f"replacement node {TARGET_SLUG} must have a fresh heartbeat within {FRESHNESS}"
|
||||
)
|
||||
|
||||
legacy_by_slug = {
|
||||
node.slug: node
|
||||
for node in Node.objects.select_for_update().filter(slug__in=LEGACY_SLUGS)
|
||||
}
|
||||
if set(legacy_by_slug) != set(LEGACY_SLUGS):
|
||||
missing = sorted(set(LEGACY_SLUGS) - set(legacy_by_slug))
|
||||
raise CommandError(
|
||||
"both legacy node records are required; missing: " + ", ".join(missing)
|
||||
)
|
||||
legacy_nodes = [legacy_by_slug[slug] for slug in LEGACY_SLUGS]
|
||||
if options["phase"] == "finalize":
|
||||
not_drained = [node.slug for node in legacy_nodes if node.subscription_enabled]
|
||||
if not_drained:
|
||||
raise CommandError(
|
||||
"legacy nodes must be drained before finalization: " + ", ".join(not_drained)
|
||||
)
|
||||
still_deployed = sorted(
|
||||
{
|
||||
deployment.node.slug
|
||||
for deployment in NodeDeployment.objects.select_for_update()
|
||||
.select_related("node")
|
||||
.filter(node__in=legacy_nodes, deployed=True)
|
||||
}
|
||||
)
|
||||
if still_deployed:
|
||||
raise CommandError(
|
||||
"legacy nodes still report deployed credentials: " + ", ".join(still_deployed)
|
||||
)
|
||||
missing_empty_ack = [
|
||||
node.slug
|
||||
for node in legacy_nodes
|
||||
if node.retirement_drain_started_at is None
|
||||
or node.retirement_empty_ack_at is None
|
||||
or node.retirement_empty_ack_at < node.retirement_drain_started_at
|
||||
]
|
||||
if missing_empty_ack:
|
||||
raise CommandError(
|
||||
"post-drain empty authorization acknowledgement is required from: "
|
||||
+ ", ".join(missing_empty_ack)
|
||||
)
|
||||
for node in legacy_nodes:
|
||||
node.active = False
|
||||
node.subscription_enabled = False
|
||||
node.status = Node.Status.OFFLINE
|
||||
node.save(
|
||||
update_fields=["active", "subscription_enabled", "status", "updated_at"]
|
||||
)
|
||||
self.stdout.write(
|
||||
self.style.SUCCESS(
|
||||
f"Finalize complete: {len(legacy_nodes)} legacy nodes disabled; records retained."
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
affected_subscriptions = list(
|
||||
Subscription.objects.select_for_update()
|
||||
.filter(allowed_nodes__in=legacy_nodes)
|
||||
.distinct()
|
||||
)
|
||||
for subscription in affected_subscriptions:
|
||||
subscription.allowed_nodes.remove(*legacy_nodes)
|
||||
subscription.allowed_nodes.add(target)
|
||||
|
||||
now = timezone.now()
|
||||
active_sessions = ClientSession.objects.filter(
|
||||
assigned_node__in=legacy_nodes,
|
||||
revoked_at__isnull=True,
|
||||
expires_at__gt=now,
|
||||
).update(assigned_node=target, dispatch_decision={})
|
||||
|
||||
drain_started_at = timezone.now()
|
||||
for node in legacy_nodes:
|
||||
update_fields = ["subscription_enabled", "status", "updated_at"]
|
||||
if node.subscription_enabled or node.retirement_drain_started_at is None:
|
||||
node.retirement_drain_started_at = drain_started_at
|
||||
node.retirement_empty_ack_at = None
|
||||
update_fields.extend(
|
||||
["retirement_drain_started_at", "retirement_empty_ack_at"]
|
||||
)
|
||||
node.subscription_enabled = False
|
||||
node.status = Node.Status.MAINTENANCE
|
||||
node.save(update_fields=update_fields)
|
||||
|
||||
self.stdout.write(
|
||||
self.style.SUCCESS(
|
||||
"Drain complete: "
|
||||
f"{len(legacy_nodes)} legacy nodes, "
|
||||
f"{len(affected_subscriptions)} subscriptions, "
|
||||
f"{active_sessions} active sessions migrated to {target.slug}."
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,28 @@
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [("control", "0015_learning_delivery")]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="node",
|
||||
name="retirement_drain_started_at",
|
||||
field=models.DateTimeField(
|
||||
blank=True,
|
||||
editable=False,
|
||||
null=True,
|
||||
verbose_name="退役排空开始时间",
|
||||
),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="node",
|
||||
name="retirement_empty_ack_at",
|
||||
field=models.DateTimeField(
|
||||
blank=True,
|
||||
editable=False,
|
||||
null=True,
|
||||
verbose_name="节点空授权确认时间",
|
||||
),
|
||||
),
|
||||
]
|
||||
@@ -224,6 +224,12 @@ class Node(models.Model):
|
||||
agent_token_digest = models.CharField("节点令牌摘要", max_length=64, blank=True, editable=False)
|
||||
total_upload_bytes = models.PositiveBigIntegerField("累计上传", default=0)
|
||||
total_download_bytes = models.PositiveBigIntegerField("累计下载", default=0)
|
||||
retirement_drain_started_at = models.DateTimeField(
|
||||
"退役排空开始时间", null=True, blank=True, editable=False
|
||||
)
|
||||
retirement_empty_ack_at = models.DateTimeField(
|
||||
"节点空授权确认时间", null=True, blank=True, editable=False
|
||||
)
|
||||
created_at = models.DateTimeField("创建时间", auto_now_add=True)
|
||||
updated_at = models.DateTimeField("更新时间", auto_now=True)
|
||||
|
||||
|
||||
@@ -11,7 +11,12 @@ def desired_subscriptions_for_node(node):
|
||||
# on an office relay. The legacy node-sync protocol carries no enrolled-site
|
||||
# proof or per-device lease; leave office provisioning fail-closed until that
|
||||
# separate protocol is implemented and accepted.
|
||||
if node.office_only:
|
||||
if (
|
||||
not node.active
|
||||
or not node.subscription_enabled
|
||||
or node.status != node.Status.ONLINE
|
||||
or node.office_only
|
||||
):
|
||||
return Subscription.objects.none()
|
||||
return (
|
||||
Subscription.objects.select_related("user", "plan")
|
||||
|
||||
@@ -16,7 +16,7 @@ from django.utils import timezone
|
||||
|
||||
class CandidateUpgradeCompatibilityTests(TransactionTestCase):
|
||||
old_target = [("control", "0010_plan_billing_months_plan_online_payment_required")]
|
||||
candidate_target = [("control", "0015_learning_delivery")]
|
||||
candidate_target = [("control", "0016_node_retirement_ack")]
|
||||
|
||||
@contextmanager
|
||||
def baseline(self):
|
||||
@@ -114,6 +114,8 @@ class CandidateUpgradeCompatibilityTests(TransactionTestCase):
|
||||
self.assertFalse(new_node.office_only)
|
||||
self.assertEqual(new_node.office_access_scope, "explicit_users")
|
||||
self.assertFalse(new_node.office_users.exists())
|
||||
self.assertIsNone(new_node.retirement_drain_started_at)
|
||||
self.assertIsNone(new_node.retirement_empty_ack_at)
|
||||
new_sub = current.get_model("control", "Subscription").objects.get(pk=sub.pk)
|
||||
self.assertEqual(list(new_sub.allowed_nodes.values_list("pk", flat=True)), [node.pk])
|
||||
observations = current.get_model("control", "RouteObservation").objects
|
||||
|
||||
@@ -155,7 +155,15 @@ class EmployeeBillingTests(TestCase):
|
||||
# still must not accept this row as proof that money was received.
|
||||
sub.save()
|
||||
self.assertFalse(sub.is_usable)
|
||||
node = Node.objects.create(name="fixture", slug="node-fixture", server="example.invalid", port=11082)
|
||||
node = Node.objects.create(
|
||||
name="fixture",
|
||||
slug="node-fixture",
|
||||
server="example.invalid",
|
||||
port=11082,
|
||||
status=Node.Status.ONLINE,
|
||||
active=True,
|
||||
subscription_enabled=True,
|
||||
)
|
||||
self.assertNotIn(sub, desired_subscriptions_for_node(node))
|
||||
employee_sub = Subscription.objects.create(user=self.employee, plan=self.plan, status="active", provisioning_state="active")
|
||||
self.assertTrue(employee_sub.is_usable)
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from io import StringIO
|
||||
from threading import Event
|
||||
from unittest.mock import patch
|
||||
import uuid
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.management import call_command
|
||||
from django.db import close_old_connections, connection, connections, transaction
|
||||
from django.test import Client, TransactionTestCase, skipUnlessDBFeature
|
||||
from django.utils import timezone
|
||||
|
||||
from control.dispatch import lock_vpn_ai_runtime
|
||||
from control.models import (
|
||||
ClientSession,
|
||||
Device,
|
||||
Node,
|
||||
NodeDeployment,
|
||||
Plan,
|
||||
Subscription,
|
||||
VpnAiRuntime,
|
||||
)
|
||||
|
||||
|
||||
@skipUnlessDBFeature("has_select_for_update")
|
||||
class RetirementDispatchConcurrencyTests(TransactionTestCase):
|
||||
"""PostgreSQL regression: retirement and dispatch serialize on one row."""
|
||||
|
||||
def setUp(self):
|
||||
user = get_user_model().objects.create_user(
|
||||
username="retirement-concurrency",
|
||||
account_status="active",
|
||||
)
|
||||
plan = Plan.objects.create(name="Retirement concurrency", slug="retirement-concurrency")
|
||||
self.subscription = Subscription.objects.create(
|
||||
user=user,
|
||||
plan=plan,
|
||||
status=Subscription.Status.ACTIVE,
|
||||
provisioning_state=Subscription.ProvisioningState.ACTIVE,
|
||||
)
|
||||
self.target = self.create_node("racknerd-newyork-004", 11084)
|
||||
self.legacy_nodes = (
|
||||
self.create_node("aliyun-tokyo-002", 10803),
|
||||
self.create_node("aliyun-siliconvalley-003", 11083),
|
||||
)
|
||||
device = Device.objects.create(
|
||||
subscription=self.subscription,
|
||||
device_id="retirement-concurrency",
|
||||
)
|
||||
self.session, _ = ClientSession.issue(self.subscription, device)
|
||||
ClientSession.objects.filter(pk=self.session.pk).update(assigned_node=self.legacy_nodes[0])
|
||||
VpnAiRuntime.objects.create(service_name="vpn-ai")
|
||||
|
||||
@staticmethod
|
||||
def create_node(slug, port):
|
||||
return Node.objects.create(
|
||||
name=slug,
|
||||
slug=slug,
|
||||
region="test",
|
||||
server=f"{slug}.example.invalid",
|
||||
port=port,
|
||||
protocol=Node.Protocol.VLESS_REALITY,
|
||||
status=Node.Status.ONLINE,
|
||||
active=True,
|
||||
subscription_enabled=True,
|
||||
last_seen_at=timezone.now(),
|
||||
sni="www.example.com",
|
||||
reality_public_key="test",
|
||||
reality_short_id="0123456789abcdef",
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def in_thread(action):
|
||||
close_old_connections()
|
||||
try:
|
||||
return action()
|
||||
finally:
|
||||
connections.close_all()
|
||||
|
||||
def test_retirement_waits_for_dispatch_runtime_lock_before_reassigning_session(self):
|
||||
holder_ready = Event()
|
||||
release_holder = Event()
|
||||
retirement_reached_lock = Event()
|
||||
|
||||
def hold_dispatch_lock():
|
||||
with transaction.atomic():
|
||||
lock_vpn_ai_runtime()
|
||||
holder_ready.set()
|
||||
self.assertTrue(release_holder.wait(10), "retirement did not reach the shared lock")
|
||||
|
||||
def retire_nodes():
|
||||
self.assertTrue(holder_ready.wait(10), "dispatch lock was not acquired")
|
||||
|
||||
def observe(execute, sql, params, many, context):
|
||||
upper = sql.upper()
|
||||
if '"CONTROL_VPNAIRUNTIME"' in upper and "FOR UPDATE" in upper:
|
||||
retirement_reached_lock.set()
|
||||
return execute(sql, params, many, context)
|
||||
|
||||
with connection.execute_wrapper(observe):
|
||||
call_command("retire_legacy_nodes", phase="drain", stdout=StringIO())
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
holder = pool.submit(self.in_thread, hold_dispatch_lock)
|
||||
retirement = pool.submit(self.in_thread, retire_nodes)
|
||||
self.assertTrue(
|
||||
retirement_reached_lock.wait(10),
|
||||
"retirement did not attempt the dispatch runtime row lock",
|
||||
)
|
||||
self.session.refresh_from_db()
|
||||
self.assertEqual(self.session.assigned_node, self.legacy_nodes[0])
|
||||
release_holder.set()
|
||||
holder.result(timeout=15)
|
||||
retirement.result(timeout=15)
|
||||
|
||||
self.session.refresh_from_db()
|
||||
self.assertEqual(self.session.assigned_node, self.target)
|
||||
|
||||
def test_report_started_before_finalize_cannot_restore_a_deployment_after_finalize(self):
|
||||
node = self.legacy_nodes[0]
|
||||
node.set_agent_token("retire-race-token")
|
||||
node.save(update_fields=["agent_token_digest"])
|
||||
call_command("retire_legacy_nodes", phase="drain", stdout=StringIO())
|
||||
deployment = NodeDeployment.objects.create(
|
||||
node=node,
|
||||
subscription=self.subscription,
|
||||
deployed=False,
|
||||
revoked_at=timezone.now(),
|
||||
)
|
||||
for legacy in self.legacy_nodes:
|
||||
legacy.refresh_from_db()
|
||||
legacy.retirement_empty_ack_at = timezone.now()
|
||||
legacy.save(update_fields=["retirement_empty_ack_at", "updated_at"])
|
||||
|
||||
report_reached_parse = Event()
|
||||
finalize_finished = Event()
|
||||
original_json_loads = json.loads
|
||||
payload = json.dumps(
|
||||
{
|
||||
"report_id": str(uuid.uuid4()),
|
||||
"success": True,
|
||||
"applied_subscription_ids": [self.subscription.pk],
|
||||
"usage": [],
|
||||
}
|
||||
)
|
||||
|
||||
def delayed_json_loads(*args, **kwargs):
|
||||
report_reached_parse.set()
|
||||
self.assertTrue(finalize_finished.wait(10), "finalize did not complete")
|
||||
return original_json_loads(*args, **kwargs)
|
||||
|
||||
def submit_stale_report():
|
||||
client = Client()
|
||||
with patch("control.views.json.loads", side_effect=delayed_json_loads):
|
||||
return client.post(
|
||||
"/api/v1/node/sync/",
|
||||
data=payload,
|
||||
content_type="application/json",
|
||||
HTTP_X_NODE_SLUG=node.slug,
|
||||
HTTP_AUTHORIZATION=(
|
||||
"Bearer retire-race-token"
|
||||
),
|
||||
)
|
||||
|
||||
def finalize_nodes():
|
||||
self.assertTrue(report_reached_parse.wait(10), "report did not reach parsing")
|
||||
try:
|
||||
call_command("retire_legacy_nodes", phase="finalize", stdout=StringIO())
|
||||
finally:
|
||||
finalize_finished.set()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
report_future = pool.submit(self.in_thread, submit_stale_report)
|
||||
finalize_future = pool.submit(self.in_thread, finalize_nodes)
|
||||
response = report_future.result(timeout=20)
|
||||
finalize_future.result(timeout=20)
|
||||
|
||||
self.assertEqual(response.status_code, 409)
|
||||
deployment.refresh_from_db()
|
||||
self.assertFalse(deployment.deployed)
|
||||
node.refresh_from_db()
|
||||
self.assertFalse(node.active)
|
||||
self.assertEqual(node.status, Node.Status.OFFLINE)
|
||||
@@ -0,0 +1,465 @@
|
||||
import json
|
||||
import uuid
|
||||
from datetime import timedelta
|
||||
from io import StringIO
|
||||
from unittest.mock import patch
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.management import call_command, get_commands
|
||||
from django.core.management.base import CommandError
|
||||
from django.test import TestCase
|
||||
from django.utils import timezone
|
||||
|
||||
from control import dispatch
|
||||
from control.models import (
|
||||
ClientSession,
|
||||
Device,
|
||||
Node,
|
||||
NodeDeployment,
|
||||
Plan,
|
||||
Subscription,
|
||||
UsageRecord,
|
||||
)
|
||||
from control.services import desired_subscriptions_for_node
|
||||
|
||||
|
||||
class RetiredNodeProvisioningTests(TestCase):
|
||||
def setUp(self):
|
||||
User = get_user_model()
|
||||
self.user = User.objects.create_user(
|
||||
username="retirement-user",
|
||||
email="retirement@example.com",
|
||||
password="retirement-test-password",
|
||||
display_name="Retirement Test",
|
||||
identity_type=User.IdentityType.EMPLOYEE,
|
||||
account_status=User.AccountStatus.ACTIVE,
|
||||
)
|
||||
self.plan = Plan.objects.create(
|
||||
name="Retirement Test Plan",
|
||||
slug="retirement-test-plan",
|
||||
audience=Plan.Audience.EMPLOYEE,
|
||||
employee_benefit=True,
|
||||
duration_days=0,
|
||||
)
|
||||
self.subscription = Subscription.objects.create(
|
||||
user=self.user,
|
||||
plan=self.plan,
|
||||
status=Subscription.Status.ACTIVE,
|
||||
provisioning_state=Subscription.ProvisioningState.ACTIVE,
|
||||
)
|
||||
self.node = Node.objects.create(
|
||||
name="Legacy Node",
|
||||
slug="legacy-node",
|
||||
region="Legacy",
|
||||
server="legacy.example.invalid",
|
||||
port=11082,
|
||||
protocol=Node.Protocol.VLESS_REALITY,
|
||||
status=Node.Status.ONLINE,
|
||||
active=True,
|
||||
subscription_enabled=True,
|
||||
sni="www.example.com",
|
||||
reality_public_key="test-public-key",
|
||||
reality_short_id="0123456789abcdef",
|
||||
)
|
||||
|
||||
def test_disabled_or_unavailable_node_never_receives_subscription_credentials(self):
|
||||
self.assertIn(self.subscription, desired_subscriptions_for_node(self.node))
|
||||
|
||||
unavailable_states = (
|
||||
{"active": False},
|
||||
{"subscription_enabled": False},
|
||||
{"status": Node.Status.PREPARING},
|
||||
{"status": Node.Status.MAINTENANCE},
|
||||
{"status": Node.Status.OFFLINE},
|
||||
)
|
||||
for changes in unavailable_states:
|
||||
with self.subTest(changes=changes):
|
||||
Node.objects.filter(pk=self.node.pk).update(
|
||||
active=True,
|
||||
subscription_enabled=True,
|
||||
status=Node.Status.ONLINE,
|
||||
)
|
||||
Node.objects.filter(pk=self.node.pk).update(**changes)
|
||||
self.node.refresh_from_db()
|
||||
self.assertFalse(desired_subscriptions_for_node(self.node).exists())
|
||||
|
||||
def test_profile_and_config_exclude_retired_nodes(self):
|
||||
target = Node.objects.create(
|
||||
name="VPN004",
|
||||
slug="racknerd-newyork-004",
|
||||
region="New York",
|
||||
server="vpn004.example.invalid",
|
||||
port=11084,
|
||||
protocol=Node.Protocol.VLESS_REALITY,
|
||||
status=Node.Status.ONLINE,
|
||||
active=True,
|
||||
subscription_enabled=True,
|
||||
sort_order=1,
|
||||
sni="www.example.com",
|
||||
reality_public_key="target-public-key",
|
||||
reality_short_id="fedcba9876543210",
|
||||
)
|
||||
self.node.subscription_enabled = False
|
||||
self.node.save(update_fields=["subscription_enabled"])
|
||||
device = Device.objects.create(
|
||||
subscription=self.subscription,
|
||||
device_id="single-node-profile-device",
|
||||
)
|
||||
_, token = ClientSession.issue(self.subscription, device)
|
||||
headers = {"HTTP_AUTHORIZATION": f"Bearer {token}"}
|
||||
|
||||
profile_response = self.client.get("/api/v1/client/profile/", **headers)
|
||||
self.assertEqual(profile_response.status_code, 200)
|
||||
self.assertEqual(
|
||||
[node["slug"] for node in profile_response.json()["profile"]["nodes"]],
|
||||
[target.slug],
|
||||
)
|
||||
|
||||
config_response = self.client.get(
|
||||
"/api/v1/client/config/",
|
||||
{"route": "smart"},
|
||||
**headers,
|
||||
)
|
||||
self.assertEqual(config_response.status_code, 200)
|
||||
self.assertEqual(config_response.json()["node"]["slug"], target.slug)
|
||||
|
||||
retired_response = self.client.get(
|
||||
"/api/v1/client/config/",
|
||||
{"node": self.node.slug, "route": "smart"},
|
||||
**headers,
|
||||
)
|
||||
self.assertEqual(retired_response.status_code, 404)
|
||||
|
||||
def test_sync_preserves_administrative_state_and_returns_no_credentials(self):
|
||||
self.node.set_agent_token("offline-node-token")
|
||||
self.node.save(update_fields=["agent_token_digest"])
|
||||
|
||||
for status in (
|
||||
Node.Status.PREPARING,
|
||||
Node.Status.MAINTENANCE,
|
||||
Node.Status.OFFLINE,
|
||||
):
|
||||
with self.subTest(status=status):
|
||||
Node.objects.filter(pk=self.node.pk).update(
|
||||
status=status,
|
||||
active=True,
|
||||
subscription_enabled=True,
|
||||
last_seen_at=None,
|
||||
)
|
||||
response = self.client.get(
|
||||
"/api/v1/node/sync/",
|
||||
HTTP_X_NODE_SLUG=self.node.slug,
|
||||
HTTP_AUTHORIZATION="Bearer offline-node-token",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json()["clients"], [])
|
||||
self.node.refresh_from_db()
|
||||
self.assertEqual(self.node.status, status)
|
||||
self.assertIsNotNone(self.node.last_seen_at)
|
||||
|
||||
|
||||
class SharedDispatchLockRegistrationTests(TestCase):
|
||||
def test_dispatch_exposes_one_shared_runtime_lock_for_reservations_and_retirement(self):
|
||||
self.assertTrue(hasattr(dispatch, "lock_vpn_ai_runtime"))
|
||||
|
||||
|
||||
class SingleNodeRetirementCommandRegistrationTests(TestCase):
|
||||
def test_safe_retirement_command_is_registered(self):
|
||||
self.assertIn("retire_legacy_nodes", get_commands())
|
||||
|
||||
|
||||
class SingleNodeRetirementCommandTests(TestCase):
|
||||
legacy_slugs = ("aliyun-tokyo-002", "aliyun-siliconvalley-003")
|
||||
|
||||
@staticmethod
|
||||
def create_node(slug, port, *, sort_order=10):
|
||||
return Node.objects.create(
|
||||
name=slug,
|
||||
slug=slug,
|
||||
region=slug,
|
||||
server=f"{slug}.example.invalid",
|
||||
port=port,
|
||||
protocol=Node.Protocol.VLESS_REALITY,
|
||||
status=Node.Status.ONLINE,
|
||||
active=True,
|
||||
subscription_enabled=True,
|
||||
last_seen_at=timezone.now(),
|
||||
sort_order=sort_order,
|
||||
sni="www.example.com",
|
||||
reality_public_key=f"{slug}-public-key",
|
||||
reality_short_id=f"{port:016d}"[-16:],
|
||||
)
|
||||
|
||||
def setUp(self):
|
||||
User = get_user_model()
|
||||
user = User.objects.create_user(
|
||||
username="retirement-command-user",
|
||||
email="retirement-command@example.com",
|
||||
password="retirement-command-test-password",
|
||||
display_name="Retirement Command Test",
|
||||
identity_type=User.IdentityType.EMPLOYEE,
|
||||
account_status=User.AccountStatus.ACTIVE,
|
||||
)
|
||||
plan = Plan.objects.create(
|
||||
name="Retirement Command Plan",
|
||||
slug="retirement-command-plan",
|
||||
audience=Plan.Audience.EMPLOYEE,
|
||||
employee_benefit=True,
|
||||
duration_days=0,
|
||||
)
|
||||
self.subscription = Subscription.objects.create(
|
||||
user=user,
|
||||
plan=plan,
|
||||
status=Subscription.Status.ACTIVE,
|
||||
provisioning_state=Subscription.ProvisioningState.ACTIVE,
|
||||
route_mode=Subscription.RouteMode.DEDICATED,
|
||||
)
|
||||
self.target = self.create_node("racknerd-newyork-004", 11084, sort_order=1)
|
||||
self.legacy_nodes = (
|
||||
self.create_node(self.legacy_slugs[0], 10803),
|
||||
self.create_node(self.legacy_slugs[1], 11083),
|
||||
)
|
||||
for index, node in enumerate(self.legacy_nodes):
|
||||
node.set_agent_token(f"legacy-node-token-{index}")
|
||||
node.save(update_fields=["agent_token_digest"])
|
||||
self.subscription.allowed_nodes.set(self.legacy_nodes)
|
||||
self.device = Device.objects.create(
|
||||
subscription=self.subscription,
|
||||
device_id="retirement-command-device",
|
||||
)
|
||||
self.active_session, _ = ClientSession.issue(self.subscription, self.device)
|
||||
ClientSession.objects.filter(pk=self.active_session.pk).update(
|
||||
assigned_node=self.legacy_nodes[0],
|
||||
dispatch_decision={"node": self.legacy_nodes[0].slug},
|
||||
)
|
||||
self.expired_session, _ = ClientSession.issue(
|
||||
self.subscription,
|
||||
self.device,
|
||||
lifetime=timedelta(seconds=-1),
|
||||
)
|
||||
ClientSession.objects.filter(pk=self.expired_session.pk).update(
|
||||
assigned_node=self.legacy_nodes[1],
|
||||
dispatch_decision={"node": self.legacy_nodes[1].slug},
|
||||
)
|
||||
for node in self.legacy_nodes:
|
||||
NodeDeployment.objects.create(
|
||||
subscription=self.subscription,
|
||||
node=node,
|
||||
deployed=True,
|
||||
applied_at=timezone.now(),
|
||||
)
|
||||
self.usage = UsageRecord.objects.create(
|
||||
subscription=self.subscription,
|
||||
node=self.legacy_nodes[0],
|
||||
day=timezone.localdate(),
|
||||
upload_bytes=123,
|
||||
download_bytes=456,
|
||||
)
|
||||
|
||||
def run_retirement(self, phase):
|
||||
output = StringIO()
|
||||
args = () if phase == "drain" else ("--phase", phase)
|
||||
call_command("retire_legacy_nodes", *args, stdout=output)
|
||||
return output.getvalue()
|
||||
|
||||
def acknowledge_empty_authorization(self, node, index):
|
||||
response = self.client.post(
|
||||
"/api/v1/node/sync/",
|
||||
data=json.dumps(
|
||||
{
|
||||
"report_id": str(uuid.uuid4()),
|
||||
"success": True,
|
||||
"applied_subscription_ids": [],
|
||||
"usage": [],
|
||||
}
|
||||
),
|
||||
content_type="application/json",
|
||||
HTTP_X_NODE_SLUG=node.slug,
|
||||
HTTP_AUTHORIZATION=f"Bearer legacy-node-token-{index}",
|
||||
)
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
node.refresh_from_db()
|
||||
self.assertEqual(node.status, Node.Status.MAINTENANCE)
|
||||
|
||||
def test_drain_migrates_authorization_and_active_sessions_without_deleting_history(self):
|
||||
self.run_retirement("drain")
|
||||
self.run_retirement("drain")
|
||||
|
||||
self.subscription.refresh_from_db()
|
||||
self.assertEqual(
|
||||
list(self.subscription.allowed_nodes.values_list("slug", flat=True)),
|
||||
[self.target.slug],
|
||||
)
|
||||
self.active_session.refresh_from_db()
|
||||
self.assertEqual(self.active_session.assigned_node, self.target)
|
||||
self.assertEqual(self.active_session.dispatch_decision, {})
|
||||
self.expired_session.refresh_from_db()
|
||||
self.assertEqual(self.expired_session.assigned_node, self.legacy_nodes[1])
|
||||
|
||||
for node in self.legacy_nodes:
|
||||
node.refresh_from_db()
|
||||
self.assertTrue(node.active)
|
||||
self.assertFalse(node.subscription_enabled)
|
||||
self.assertEqual(node.status, Node.Status.MAINTENANCE)
|
||||
self.assertFalse(desired_subscriptions_for_node(node).exists())
|
||||
|
||||
self.assertEqual(Node.objects.filter(slug__in=self.legacy_slugs).count(), 2)
|
||||
self.assertTrue(UsageRecord.objects.filter(pk=self.usage.pk).exists())
|
||||
|
||||
def test_finalize_requires_agent_revocation_acknowledgement_then_is_idempotent(self):
|
||||
self.run_retirement("drain")
|
||||
|
||||
with self.assertRaisesMessage(CommandError, "still report deployed credentials"):
|
||||
self.run_retirement("finalize")
|
||||
|
||||
for index, node in enumerate(self.legacy_nodes):
|
||||
self.acknowledge_empty_authorization(node, index)
|
||||
self.run_retirement("finalize")
|
||||
self.run_retirement("finalize")
|
||||
|
||||
for node in self.legacy_nodes:
|
||||
node.refresh_from_db()
|
||||
self.assertFalse(node.active)
|
||||
self.assertFalse(node.subscription_enabled)
|
||||
self.assertEqual(node.status, Node.Status.OFFLINE)
|
||||
self.assertEqual(Node.objects.filter(slug__in=self.legacy_slugs).count(), 2)
|
||||
self.assertTrue(UsageRecord.objects.filter(pk=self.usage.pk).exists())
|
||||
|
||||
def test_get_authenticated_before_finalize_cannot_serve_a_retired_generation(self):
|
||||
stale_authenticated_node = Node.objects.get(pk=self.legacy_nodes[0].pk)
|
||||
Node.objects.filter(pk=stale_authenticated_node.pk).update(
|
||||
active=False,
|
||||
subscription_enabled=False,
|
||||
status=Node.Status.OFFLINE,
|
||||
)
|
||||
|
||||
with patch("control.views._authenticate_node", return_value=stale_authenticated_node):
|
||||
response = self.client.get("/api/v1/node/sync/")
|
||||
|
||||
self.assertEqual(response.status_code, 409)
|
||||
self.assertEqual(response.json(), {"error": "node retired"})
|
||||
|
||||
def test_post_authenticated_before_finalize_cannot_restore_a_deployment(self):
|
||||
self.run_retirement("drain")
|
||||
node = self.legacy_nodes[0]
|
||||
stale_authenticated_node = Node.objects.get(pk=node.pk)
|
||||
deployment = NodeDeployment.objects.get(node=node, subscription=self.subscription)
|
||||
deployment.deployed = False
|
||||
deployment.revoked_at = timezone.now()
|
||||
deployment.save(update_fields=["deployed", "revoked_at", "updated_at"])
|
||||
Node.objects.filter(pk=node.pk).update(
|
||||
active=False,
|
||||
subscription_enabled=False,
|
||||
status=Node.Status.OFFLINE,
|
||||
)
|
||||
|
||||
with patch("control.views._authenticate_node", return_value=stale_authenticated_node):
|
||||
response = self.client.post(
|
||||
"/api/v1/node/sync/",
|
||||
data=json.dumps(
|
||||
{
|
||||
"report_id": str(uuid.uuid4()),
|
||||
"success": True,
|
||||
"applied_subscription_ids": [self.subscription.pk],
|
||||
"usage": [],
|
||||
}
|
||||
),
|
||||
content_type="application/json",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 409)
|
||||
self.assertEqual(response.json(), {"error": "node retired"})
|
||||
deployment.refresh_from_db()
|
||||
self.assertFalse(deployment.deployed)
|
||||
node.refresh_from_db()
|
||||
self.assertFalse(node.active)
|
||||
self.assertEqual(node.status, Node.Status.OFFLINE)
|
||||
|
||||
def test_finalize_refuses_nodes_that_have_not_been_drained(self):
|
||||
NodeDeployment.objects.filter(node__in=self.legacy_nodes).update(
|
||||
deployed=False,
|
||||
revoked_at=timezone.now(),
|
||||
)
|
||||
|
||||
with self.assertRaisesMessage(CommandError, "must be drained"):
|
||||
self.run_retirement("finalize")
|
||||
|
||||
for node in self.legacy_nodes:
|
||||
node.refresh_from_db()
|
||||
self.assertTrue(node.active)
|
||||
self.assertTrue(node.subscription_enabled)
|
||||
self.assertEqual(node.status, Node.Status.ONLINE)
|
||||
|
||||
def test_finalize_refuses_false_deployments_without_post_drain_empty_acknowledgement(self):
|
||||
self.run_retirement("drain")
|
||||
NodeDeployment.objects.filter(node__in=self.legacy_nodes).update(
|
||||
deployed=False,
|
||||
revoked_at=timezone.now(),
|
||||
)
|
||||
|
||||
with self.assertRaisesMessage(CommandError, "empty authorization acknowledgement"):
|
||||
self.run_retirement("finalize")
|
||||
|
||||
for node in self.legacy_nodes:
|
||||
node.refresh_from_db()
|
||||
self.assertTrue(node.active)
|
||||
|
||||
def test_drain_refuses_an_unavailable_replacement_without_mutating_legacy_nodes(self):
|
||||
self.target.status = Node.Status.MAINTENANCE
|
||||
self.target.save(update_fields=["status"])
|
||||
|
||||
with self.assertRaisesMessage(CommandError, "replacement node"):
|
||||
self.run_retirement("drain")
|
||||
|
||||
for node in self.legacy_nodes:
|
||||
node.refresh_from_db()
|
||||
self.assertTrue(node.active)
|
||||
self.assertTrue(node.subscription_enabled)
|
||||
self.assertEqual(node.status, Node.Status.ONLINE)
|
||||
|
||||
def test_drain_refuses_replacement_without_a_fresh_heartbeat(self):
|
||||
for last_seen_at in (None, timezone.now() - dispatch.FRESHNESS - timedelta(seconds=1)):
|
||||
with self.subTest(last_seen_at=last_seen_at):
|
||||
Node.objects.filter(pk=self.target.pk).update(last_seen_at=last_seen_at)
|
||||
|
||||
with self.assertRaisesMessage(CommandError, "fresh heartbeat"):
|
||||
self.run_retirement("drain")
|
||||
|
||||
for node in self.legacy_nodes:
|
||||
node.refresh_from_db()
|
||||
self.assertTrue(node.active)
|
||||
self.assertTrue(node.subscription_enabled)
|
||||
self.assertEqual(node.status, Node.Status.ONLINE)
|
||||
|
||||
def test_drain_requires_both_named_legacy_rows(self):
|
||||
for retained_count in (0, 1):
|
||||
with self.subTest(retained_count=retained_count):
|
||||
for index, node in enumerate(self.legacy_nodes):
|
||||
node.slug = (
|
||||
self.legacy_slugs[index]
|
||||
if index < retained_count
|
||||
else f"renamed-legacy-{index}"
|
||||
)
|
||||
node.save(update_fields=["slug"])
|
||||
|
||||
with self.assertRaisesMessage(CommandError, "both legacy node records"):
|
||||
self.run_retirement("drain")
|
||||
|
||||
for index, node in enumerate(self.legacy_nodes):
|
||||
node.slug = self.legacy_slugs[index]
|
||||
node.save(update_fields=["slug"])
|
||||
|
||||
def test_drain_aborts_before_mutation_when_shared_dispatch_lock_is_unavailable(self):
|
||||
with patch(
|
||||
"control.management.commands.retire_legacy_nodes.lock_vpn_ai_runtime",
|
||||
side_effect=CommandError("dispatch lock unavailable"),
|
||||
):
|
||||
with self.assertRaisesMessage(CommandError, "dispatch lock unavailable"):
|
||||
self.run_retirement("drain")
|
||||
|
||||
self.active_session.refresh_from_db()
|
||||
self.assertEqual(self.active_session.assigned_node, self.legacy_nodes[0])
|
||||
for node in self.legacy_nodes:
|
||||
node.refresh_from_db()
|
||||
self.assertTrue(node.subscription_enabled)
|
||||
+68
-39
@@ -616,33 +616,38 @@ def node_sync(request):
|
||||
return JsonResponse({"error": "node authentication failed"}, status=401)
|
||||
|
||||
now = timezone.now()
|
||||
Node.objects.filter(pk=node.pk).update(
|
||||
last_seen_at=now,
|
||||
status=Node.Status.ONLINE,
|
||||
agent_version=request.headers.get("X-Agent-Version", "")[:64],
|
||||
)
|
||||
|
||||
desired = list(desired_subscriptions_for_node(node))
|
||||
agent_version = request.headers.get("X-Agent-Version", "")[:64]
|
||||
if request.method == "GET":
|
||||
NodeDeployment.objects.bulk_create(
|
||||
[NodeDeployment(node=node, subscription=subscription) for subscription in desired],
|
||||
ignore_conflicts=True,
|
||||
)
|
||||
return JsonResponse(
|
||||
{
|
||||
"node": node.slug,
|
||||
"generated_at": now.isoformat(),
|
||||
"clients": [
|
||||
{
|
||||
"subscription_id": subscription.pk,
|
||||
"email": f"sub-{subscription.pk}",
|
||||
"uuid": str(subscription.credential_uuid),
|
||||
"flow": "xtls-rprx-vision",
|
||||
}
|
||||
for subscription in desired
|
||||
],
|
||||
}
|
||||
)
|
||||
# Keep the eligibility snapshot, deployment rows and serialized response
|
||||
# in the same row-lock transaction. Finalize therefore orders strictly
|
||||
# before or after this generation; it cannot interleave after the snapshot.
|
||||
with transaction.atomic():
|
||||
node = Node.objects.select_for_update(**non_key_lock_options()).get(pk=node.pk)
|
||||
if not node.active:
|
||||
return JsonResponse({"error": "node retired"}, status=409)
|
||||
node.last_seen_at = now
|
||||
node.agent_version = agent_version
|
||||
node.save(update_fields=["last_seen_at", "agent_version", "updated_at"])
|
||||
desired = list(desired_subscriptions_for_node(node))
|
||||
NodeDeployment.objects.bulk_create(
|
||||
[NodeDeployment(node=node, subscription=subscription) for subscription in desired],
|
||||
ignore_conflicts=True,
|
||||
)
|
||||
return JsonResponse(
|
||||
{
|
||||
"node": node.slug,
|
||||
"generated_at": now.isoformat(),
|
||||
"clients": [
|
||||
{
|
||||
"subscription_id": subscription.pk,
|
||||
"email": f"sub-{subscription.pk}",
|
||||
"uuid": str(subscription.credential_uuid),
|
||||
"flow": "xtls-rprx-vision",
|
||||
}
|
||||
for subscription in desired
|
||||
],
|
||||
}
|
||||
)
|
||||
|
||||
try:
|
||||
payload = json.loads(request.body or b"{}")
|
||||
@@ -656,8 +661,6 @@ def node_sync(request):
|
||||
except (KeyError, TypeError, ValueError, json.JSONDecodeError):
|
||||
return JsonResponse({"error": "invalid report payload"}, status=400)
|
||||
|
||||
desired_ids = {subscription.pk for subscription in desired}
|
||||
|
||||
normalized_usage = []
|
||||
try:
|
||||
for item in usage:
|
||||
@@ -672,18 +675,37 @@ def node_sync(request):
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return JsonResponse({"error": "invalid usage item"}, status=400)
|
||||
|
||||
known_deployment_ids = set(
|
||||
NodeDeployment.objects.filter(node=node).values_list("subscription_id", flat=True)
|
||||
) | desired_ids
|
||||
if not applied_ids.issubset(known_deployment_ids):
|
||||
return JsonResponse({"error": "applied subscription is not associated with this node"}, status=400)
|
||||
if any(subscription_id not in known_deployment_ids for subscription_id, _, _ in normalized_usage):
|
||||
return JsonResponse({"error": "usage item is not associated with this node"}, status=400)
|
||||
|
||||
with transaction.atomic():
|
||||
# Serialize first reports as well as existing deployment rows. Otherwise
|
||||
# two first reports can both try to create the same NodeDeployment.
|
||||
Node.objects.select_for_update(**non_key_lock_options()).get(pk=node.pk)
|
||||
# Re-read every mutable eligibility field under the one row lock used by
|
||||
# drain/finalize. A request authenticated before finalization must never
|
||||
# restore deployments or acknowledge an obsolete authorization generation.
|
||||
node = Node.objects.select_for_update(**non_key_lock_options()).get(pk=node.pk)
|
||||
if not node.active or node.status == Node.Status.OFFLINE:
|
||||
return JsonResponse({"error": "node retired"}, status=409)
|
||||
node.last_seen_at = now
|
||||
node.agent_version = agent_version
|
||||
node.save(update_fields=["last_seen_at", "agent_version", "updated_at"])
|
||||
desired = list(desired_subscriptions_for_node(node))
|
||||
desired_ids = {subscription.pk for subscription in desired}
|
||||
known_deployment_ids = set(
|
||||
NodeDeployment.objects.filter(node=node).values_list("subscription_id", flat=True)
|
||||
) | desired_ids
|
||||
if not applied_ids.issubset(known_deployment_ids):
|
||||
return JsonResponse(
|
||||
{"error": "applied subscription is not associated with this node"},
|
||||
status=400,
|
||||
)
|
||||
if any(
|
||||
subscription_id not in known_deployment_ids
|
||||
for subscription_id, _, _ in normalized_usage
|
||||
):
|
||||
return JsonResponse(
|
||||
{"error": "usage item is not associated with this node"},
|
||||
status=400,
|
||||
)
|
||||
|
||||
# Serialize first reports as well as existing deployment rows. Otherwise
|
||||
# two first reports can both try to create the same NodeDeployment.
|
||||
report, created = NodeReport.objects.get_or_create(node=node, report_id=report_id)
|
||||
if not created:
|
||||
return JsonResponse({"status": "already_processed"})
|
||||
@@ -714,6 +736,13 @@ def node_sync(request):
|
||||
deployment.revoked_at = now
|
||||
deployment.last_error = ""
|
||||
deployment.save()
|
||||
if (
|
||||
not desired_ids
|
||||
and not applied_ids
|
||||
and not node.subscription_enabled
|
||||
and node.retirement_drain_started_at is not None
|
||||
):
|
||||
Node.objects.filter(pk=node.pk).update(retirement_empty_ack_at=now)
|
||||
else:
|
||||
for subscription_id in desired_ids:
|
||||
deployment = deployments[subscription_id]
|
||||
|
||||
Reference in New Issue
Block a user