64 lines
1.8 KiB
Python
64 lines
1.8 KiB
Python
import json
|
|
import logging
|
|
import subprocess
|
|
from pathlib import Path
|
|
from threading import Thread
|
|
from queue import Queue
|
|
|
|
class V2RayManager:
|
|
def __init__(self, config_path, log_path):
|
|
self.config_path = Path(config_path)
|
|
self.log_path = Path(log_path)
|
|
self.process = None
|
|
self.log_queue = Queue()
|
|
self.running = False
|
|
|
|
def start(self):
|
|
"""启动v2ray核心"""
|
|
if self.running:
|
|
return True
|
|
|
|
v2ray_bin = get_v2ray_binary_path()
|
|
cmd = [str(v2ray_bin), "-config", str(self.config_path)]
|
|
|
|
try:
|
|
self.process = subprocess.Popen(
|
|
cmd,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.STDOUT,
|
|
universal_newlines=True
|
|
)
|
|
self.running = True
|
|
|
|
# 启动日志监听线程
|
|
Thread(target=self._log_reader, daemon=True).start()
|
|
return True
|
|
except Exception as e:
|
|
logging.error(f"启动v2ray失败: {str(e)}")
|
|
return False
|
|
|
|
def stop(self):
|
|
"""停止v2ray核心"""
|
|
if not self.running:
|
|
return
|
|
|
|
if self.process:
|
|
self.process.terminate()
|
|
try:
|
|
self.process.wait(timeout=5)
|
|
except subprocess.TimeoutExpired:
|
|
self.process.kill()
|
|
|
|
self.running = False
|
|
|
|
def _log_reader(self):
|
|
"""读取v2ray日志"""
|
|
while self.running and self.process:
|
|
line = self.process.stdout.readline()
|
|
if not line:
|
|
break
|
|
self.log_queue.put(line.strip())
|
|
with open(self.log_path, 'a') as f:
|
|
f.write(line)
|
|
|
|
self.running = False |