185 lines
6.9 KiB
Python
185 lines
6.9 KiB
Python
|
|
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)
|