-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathweb_manager.py
More file actions
355 lines (289 loc) · 9.63 KB
/
Copy pathweb_manager.py
File metadata and controls
355 lines (289 loc) · 9.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
#!/usr/bin/env python3
"""
Light Browser Web 管理界面
提供简单的状态查看和手动重启功能
"""
import asyncio
import json
import os
import subprocess
import time
from pathlib import Path
from typing import Dict, Any
import psutil
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from loguru import logger
# 配置
CDP_PORT = int(os.environ.get("CAMOUFOX_PORT", "9222"))
NOVNC_PORT = int(os.environ.get("NOVNC_PORT", "6080"))
WEB_PORT = int(os.environ.get("WEB_MANAGER_PORT", "18888"))
app = FastAPI(title="Light Browser 管理界面", version="1.0.0")
# 静态文件和模板
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
# 全局变量
bb_daemon_process = None
service_status = {
"camoufox": False,
"novnc": False,
"bb_api": False,
"last_check": 0
}
def run_command(command: str, timeout: int = 10) -> tuple:
"""执行命令并返回结果"""
try:
result = subprocess.run(
command.split(),
capture_output=True,
text=True,
timeout=timeout
)
return result.returncode == 0, result.stdout, result.stderr
except subprocess.TimeoutExpired:
return False, "", "命令执行超时"
except Exception as e:
return False, "", str(e)
def check_port_listening(port: int) -> bool:
"""检查端口是否在监听"""
try:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
result = sock.connect_ex(('localhost', port))
sock.close()
return result == 0
except Exception:
return False
def check_bb_browser_api_status() -> bool:
"""检查 bb-browser-api 状态"""
try:
success, stdout, stderr = run_command("bb-browser-api daemon status")
if success and "CDP connected: yes" in stdout:
return True
return False
except Exception as e:
logger.error(f"检查 bb-browser-api 状态失败: {e}")
return False
def start_bb_browser_api() -> bool:
"""启动 bb-browser-api daemon"""
global bb_daemon_process
try:
# 先停止可能存在的进程
run_command("bb-browser-api daemon stop")
time.sleep(2)
# 启动 daemon
success, stdout, stderr = run_command(f"bb-browser-api daemon start http://localhost:{CDP_PORT}")
if success:
logger.info("bb-browser-api daemon 启动成功")
time.sleep(3) # 等待启动完成
return check_bb_browser_api_status()
else:
logger.error(f"bb-browser-api daemon 启动失败: {stderr}")
return False
except Exception as e:
logger.error(f"启动 bb-browser-api daemon 异常: {e}")
return False
def stop_bb_browser_api():
"""停止 bb-browser-api daemon"""
try:
run_command("bb-browser-api daemon stop")
logger.info("bb-browser-api daemon 已停止")
except Exception as e:
logger.error(f"停止 bb-browser-api daemon 异常: {e}")
def get_service_status() -> Dict[str, Any]:
"""获取服务状态"""
global service_status
current_time = time.time()
# 每 5 秒更新一次状态
if current_time - service_status["last_check"] < 5:
return service_status
# 检查 Camoufox (CDP) 状态
service_status["camoufox"] = check_port_listening(CDP_PORT)
# 检查 noVNC 状态
service_status["novnc"] = check_port_listening(NOVNC_PORT)
# 检查 bb-browser-api 状态
service_status["bb_api"] = check_bb_browser_api_status()
service_status["last_check"] = current_time
return service_status
def get_system_info() -> Dict[str, Any]:
"""获取系统信息"""
try:
# CPU 使用率
cpu_percent = psutil.cpu_percent(interval=1)
# 内存使用情况
memory = psutil.virtual_memory()
# 磁盘使用情况
disk = psutil.disk_usage('/')
return {
"cpu_percent": cpu_percent,
"memory": {
"total": memory.total,
"used": memory.used,
"percent": memory.percent
},
"disk": {
"total": disk.total,
"used": disk.used,
"percent": (disk.used / disk.total) * 100
}
}
except Exception as e:
logger.error(f"获取系统信息失败: {e}")
return {}
def restart_services() -> Dict[str, bool]:
"""重启所有服务"""
results = {}
try:
# 重启 bb-browser-api
stop_bb_browser_api()
time.sleep(2)
results["bb_api"] = start_bb_browser_api()
# 检查其他服务状态
time.sleep(3)
status = get_service_status()
results["camoufox"] = status["camoufox"]
results["novnc"] = status["novnc"]
return results
except Exception as e:
logger.error(f"重启服务失败: {e}")
return {"error": str(e)}
@app.get("/", response_class=HTMLResponse)
async def dashboard(request: Request):
"""主页面"""
status = get_service_status()
system_info = get_system_info()
return templates.TemplateResponse("dashboard.html", {
"request": request,
"status": status,
"system_info": system_info,
"cdp_port": CDP_PORT,
"novnc_port": NOVNC_PORT,
"web_port": WEB_PORT
})
@app.get("/api/status")
async def api_status():
"""获取服务状态 API"""
status = get_service_status()
system_info = get_system_info()
return JSONResponse({
"status": status,
"system_info": system_info,
"ports": {
"cdp": CDP_PORT,
"novnc": NOVNC_PORT,
"web": WEB_PORT
},
"timestamp": time.time()
})
@app.post("/api/restart")
async def api_restart():
"""重启服务 API"""
try:
logger.info("收到重启请求")
results = restart_services()
return JSONResponse({
"success": True,
"message": "服务重启完成",
"results": results,
"timestamp": time.time()
})
except Exception as e:
logger.error(f"重启服务失败: {e}")
return JSONResponse({
"success": False,
"message": f"重启失败: {str(e)}",
"timestamp": time.time()
}, status_code=500)
@app.post("/api/start-bb-api")
async def api_start_bb_api():
"""启动 bb-browser-api"""
try:
success = start_bb_browser_api()
return JSONResponse({
"success": success,
"message": "bb-browser-api 启动成功" if success else "bb-browser-api 启动失败"
})
except Exception as e:
return JSONResponse({
"success": False,
"message": f"启动失败: {str(e)}"
}, status_code=500)
@app.post("/api/stop-bb-api")
async def api_stop_bb_api():
"""停止 bb-browser-api"""
try:
stop_bb_browser_api()
return JSONResponse({
"success": True,
"message": "bb-browser-api 已停止"
})
except Exception as e:
return JSONResponse({
"success": False,
"message": f"停止失败: {str(e)}"
}, status_code=500)
@app.get("/api/logs")
async def api_logs():
"""获取日志"""
try:
# 读取最近的日志
log_files = list(Path("/app/logs").glob("light-browser_*.log"))
if not log_files:
return JSONResponse({"logs": "暂无日志文件"})
# 获取最新的日志文件
latest_log = max(log_files, key=lambda x: x.stat().st_mtime)
# 读取最后 100 行
with open(latest_log, 'r', encoding='utf-8') as f:
lines = f.readlines()
recent_lines = lines[-100:] if len(lines) > 100 else lines
return JSONResponse({
"logs": "".join(recent_lines),
"file": str(latest_log)
})
except Exception as e:
return JSONResponse({
"logs": f"读取日志失败: {str(e)}"
})
async def startup_bb_api():
"""启动时初始化 bb-browser-api"""
logger.info("初始化 bb-browser-api...")
# 等待 Camoufox 服务就绪
for i in range(30): # 最多等待 30 秒
if check_port_listening(CDP_PORT):
logger.info("Camoufox 服务已就绪,启动 bb-browser-api")
start_bb_browser_api()
break
await asyncio.sleep(1)
else:
logger.warning("Camoufox 服务未就绪,bb-browser-api 启动可能失败")
@app.on_event("startup")
async def startup_event():
"""应用启动事件"""
logger.info(f"Light Browser Web 管理界面启动,端口: {WEB_PORT}")
# 异步启动 bb-browser-api
asyncio.create_task(startup_bb_api())
@app.on_event("shutdown")
async def shutdown_event():
"""应用关闭事件"""
logger.info("关闭 Web 管理界面")
stop_bb_browser_api()
if __name__ == "__main__":
import uvicorn
# 配置日志
logger.add(
"/app/logs/web_manager_{time:YYYY-MM-DD}.log",
rotation="1 day",
retention="7 days",
level="INFO",
format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}"
)
logger.info(f"启动 Light Browser Web 管理界面,端口: {WEB_PORT}")
uvicorn.run(
app,
host="0.0.0.0",
port=WEB_PORT,
log_level="info"
)