75 lines
2.7 KiB
Python
75 lines
2.7 KiB
Python
|
|
import os
|
||
|
|
import signal
|
||
|
|
import socket
|
||
|
|
import time
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
from django.core.management.base import BaseCommand
|
||
|
|
from django.db import close_old_connections, connection
|
||
|
|
from django.utils import timezone
|
||
|
|
|
||
|
|
from control.models import VpnAiRuntime
|
||
|
|
from control.vpn_ai import run_vpn_ai_cycle
|
||
|
|
|
||
|
|
|
||
|
|
class Command(BaseCommand):
|
||
|
|
help = "运行优创⁺纵横家专属 vpn-ai 学习、运维与诊断工作进程。"
|
||
|
|
|
||
|
|
def add_arguments(self, parser):
|
||
|
|
parser.add_argument("--interval", type=int, default=60)
|
||
|
|
parser.add_argument("--once", action="store_true")
|
||
|
|
|
||
|
|
def handle(self, *args, **options):
|
||
|
|
interval = max(15, min(options["interval"], 3600))
|
||
|
|
once = options["once"]
|
||
|
|
stopping = False
|
||
|
|
|
||
|
|
def request_stop(*_):
|
||
|
|
nonlocal stopping
|
||
|
|
stopping = True
|
||
|
|
|
||
|
|
signal.signal(signal.SIGTERM, request_stop)
|
||
|
|
signal.signal(signal.SIGINT, request_stop)
|
||
|
|
worker_id = f"{socket.gethostname()}:{os.getpid()}"
|
||
|
|
runtime, _ = VpnAiRuntime.objects.get_or_create(service_name="vpn-ai")
|
||
|
|
runtime.version = "0.2.0"
|
||
|
|
runtime.worker_id = worker_id
|
||
|
|
runtime.started_at = timezone.now()
|
||
|
|
runtime.last_heartbeat_at = timezone.now()
|
||
|
|
runtime.last_error = ""
|
||
|
|
runtime.save()
|
||
|
|
self.stdout.write(self.style.SUCCESS(f"vpn-ai 已启动:{worker_id}"))
|
||
|
|
|
||
|
|
while not stopping:
|
||
|
|
close_old_connections()
|
||
|
|
lock_acquired = False
|
||
|
|
try:
|
||
|
|
with connection.cursor() as cursor:
|
||
|
|
cursor.execute("SELECT pg_try_advisory_lock(%s)", [9262026])
|
||
|
|
lock_acquired = bool(cursor.fetchone()[0])
|
||
|
|
if lock_acquired:
|
||
|
|
runtime.refresh_from_db()
|
||
|
|
run_vpn_ai_cycle(runtime)
|
||
|
|
Path("/tmp/ucvl-vpn-ai-heartbeat").touch()
|
||
|
|
except Exception as exc:
|
||
|
|
runtime.last_heartbeat_at = timezone.now()
|
||
|
|
runtime.last_error = f"{type(exc).__name__}: {exc}"[:2000]
|
||
|
|
runtime.save(update_fields=["last_heartbeat_at", "last_error", "updated_at"])
|
||
|
|
self.stderr.write(self.style.ERROR(runtime.last_error))
|
||
|
|
finally:
|
||
|
|
if lock_acquired:
|
||
|
|
try:
|
||
|
|
with connection.cursor() as cursor:
|
||
|
|
cursor.execute("SELECT pg_advisory_unlock(%s)", [9262026])
|
||
|
|
except Exception:
|
||
|
|
pass
|
||
|
|
close_old_connections()
|
||
|
|
if once:
|
||
|
|
break
|
||
|
|
for _ in range(interval):
|
||
|
|
if stopping:
|
||
|
|
break
|
||
|
|
time.sleep(1)
|
||
|
|
|
||
|
|
self.stdout.write("vpn-ai 已停止。")
|