Add Debian deployment, MariaDB storage and randomized proxy routing

This commit is contained in:
Codex
2026-10-11 19:07:27 +08:00
parent 2e3439dbb9
commit 915241a2fd
27 changed files with 896 additions and 32 deletions
+61
View File
@@ -0,0 +1,61 @@
"""Control only the two fixed, dedicated proxy-pool systemd units."""
import socket
import subprocess
from urllib.parse import urlparse
import requests
UNITS = ('kaoyan-proxy-api.service', 'kaoyan-proxy-scheduler.service')
class LinuxPoolService:
def __init__(self, settings):
self.settings = settings
self.session = requests.Session()
self.session.trust_env = False
def status(self, config=None):
config = config or self.settings.read()
api_ready, counts = False, {}
try:
response = self.session.get(config['pool_url'] + '/count/', timeout=2)
response.raise_for_status()
counts = response.json()
api_ready = isinstance(counts, dict) and type(counts.get('count')) is int
except (requests.RequestException, ValueError):
pass
items = []
for name, label, unit in zip(('server', 'schedule'), ('代理 API', '抓取与检测'), UNITS):
try:
result = subprocess.run(['/usr/bin/systemctl', 'show', unit, '--property=LoadState,ActiveState,MainPID'], capture_output=True, text=True, timeout=5)
facts = dict(line.split('=', 1) for line in result.stdout.splitlines() if '=' in line)
installed = facts.get('LoadState') == 'loaded'
active = installed and facts.get('ActiveState') == 'active'
items.append({'name': name, 'label': label, 'state': 'running' if active else 'stopped', 'pid': int(facts.get('MainPID', '0')) or None, 'verified': active, 'elevated': False, 'detail': 'systemd 运行中' if active else ('已停止' if installed else '未安装本项目 systemd 单元')})
except (OSError, subprocess.TimeoutExpired, ValueError):
items.append({'name': name, 'label': label, 'state': 'unknown', 'pid': None, 'verified': False, 'elevated': False, 'detail': '无法查询 systemd 状态'})
try:
with socket.create_connection(('127.0.0.1', 6381), timeout=1):
redis_ready = True
except OSError:
redis_ready = False
items.append({'name': 'redis', 'label': 'Redis', 'state': 'external' if redis_ready else 'stopped', 'pid': None, 'verified': False, 'elevated': False, 'detail': '独立 Redis 服务(127.0.0.1:6381)' if redis_ready else '未连接到本项目 Redis'})
local = urlparse(config['pool_url']).hostname in ('127.0.0.1', 'localhost', '::1')
return {'api_ready': api_ready, 'counts': counts if api_ready else {}, 'items': items, 'can_stop': local and any(item['verified'] for item in items[:2]), 'warning': '' if local else '当前使用外部代理池,请在其所在服务器管理服务', 'admin_command': '', 'manager': 'systemd'}
def manage(self, action):
if action not in ('start', 'stop', 'status'):
raise ValueError('代理池操作无效')
status = self.status()
result = {'ok': True, 'action': action, 'changed': False, 'status': status, 'message': '服务状态已更新', 'output': '\n'.join(item['label'] + ':' + item['detail'] for item in status['items'])}
if action == 'status':
return result
if status['warning']:
return {**result, 'ok': False, 'message': status['warning']}
if action == 'start' and all(item['state'] == 'running' for item in status['items'][:2]) and status['api_ready']:
return {**result, 'message': '代理池已在运行,已复用现有服务'}
try:
completed = subprocess.run(['/usr/bin/sudo', '-n', '/usr/bin/systemctl', action, *UNITS], capture_output=True, text=True, timeout=55)
message = '代理池启动完成' if action == 'start' else '代理池已停止'
return {**result, 'ok': completed.returncode == 0, 'changed': True, 'status': self.status(), 'message': message if completed.returncode == 0 else 'systemd 操作失败,请检查本项目 sudoers 与服务日志', 'output': (completed.stdout + completed.stderr)[-5000:] or message}
except (OSError, subprocess.TimeoutExpired):
return {**result, 'ok': False, 'message': '代理池管理超时或命令不可用,请检查 systemd 服务'}