461 lines
18 KiB
Python
461 lines
18 KiB
Python
"""FastAPI 服务端入口:设备/前端 WebSocket 端点、消息路由、静态调试页。"""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import base64
|
|
import binascii
|
|
import contextlib
|
|
import json
|
|
import logging
|
|
import os
|
|
import re
|
|
from contextvars import ContextVar
|
|
from pathlib import Path
|
|
|
|
import uvicorn
|
|
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
|
from fastapi.responses import FileResponse
|
|
|
|
from core.device import CommandDispatcher, CommandTimeoutError, DeviceOfflineError
|
|
from core.hub import DeviceConnection, Hub, UiSession
|
|
from core.protocol import (
|
|
ACTION_EVENT_HEARTBEAT,
|
|
TYPE_RESPONSE,
|
|
Envelope,
|
|
ErrorCode,
|
|
RegisterInfo,
|
|
error_payload,
|
|
)
|
|
from core.runlog import RunLog, ServerLogEntry, ServerLogHandler
|
|
from core.storage import Storage
|
|
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
|
)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
DEVICE_TOKEN = os.environ.get("DEVICE_TOKEN", "") # 为空 = 开发模式放行
|
|
DB_PATH = os.environ.get("DB_PATH", str(Path(__file__).parent / "data" / "cp_agent.db"))
|
|
WEB_DIR = Path(__file__).parent / "web"
|
|
|
|
storage = Storage(DB_PATH)
|
|
hub = Hub(storage)
|
|
dispatcher = CommandDispatcher(hub, storage)
|
|
runlog = RunLog()
|
|
server_log_handler = ServerLogHandler(runlog)
|
|
# Send tasks and deferred transport callbacks inherit this context, without
|
|
# suppressing unrelated application tasks on the same event-loop thread.
|
|
_log_broadcast_active = ContextVar("log_broadcast_active", default=False)
|
|
server_log_handler.addFilter(lambda record: not _log_broadcast_active.get())
|
|
log_queue: asyncio.Queue[ServerLogEntry] | None = None
|
|
log_broadcast_task: asyncio.Task[None] | None = None
|
|
log_loop: asyncio.AbstractEventLoop | None = None
|
|
LOGGERS_TO_CAPTURE = ("", "uvicorn", "uvicorn.error", "uvicorn.access")
|
|
LOG_QUEUE_SIZE = 500
|
|
LOG_BROADCAST_TIMEOUT = 1.0
|
|
_storage_closed = False
|
|
FILE_ACTIONS = {
|
|
"file.list", "file.mkdir", "file.rename", "file.delete",
|
|
"file.upload.start", "file.upload.chunk", "file.upload.finish",
|
|
"file.download.start", "file.download.chunk", "file.download.finish",
|
|
}
|
|
MAX_FILE_TRANSFER_BYTES = 512 * 1024 * 1024
|
|
MAX_TRANSFER_CHUNK_BYTES = 64 * 1024
|
|
TRANSFER_ID_RE = re.compile(r"^[A-Za-z0-9_-]{8,80}$")
|
|
PACKAGE_NAME_RE = re.compile(r"^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)+$")
|
|
|
|
|
|
def validate_download_relative_path(path: object) -> str:
|
|
"""Validate a path relative to /sdcard/Download; empty means the root."""
|
|
if not isinstance(path, str) or len(path) > 2048 or "\\" in path:
|
|
raise ValueError("文件路径无效")
|
|
if any(ord(char) < 32 or ord(char) == 127 for char in path):
|
|
raise ValueError("文件路径包含控制字符")
|
|
if path == "":
|
|
return ""
|
|
if path.startswith("/"):
|
|
raise ValueError("只能访问 /sdcard/Download")
|
|
parts = path.split("/")
|
|
if any(part in ("", ".", "..") for part in parts):
|
|
raise ValueError("文件路径不能包含空段、. 或 ..")
|
|
return "/".join(parts)
|
|
|
|
|
|
def validate_management_action(action: str, payload: object) -> None:
|
|
if not isinstance(payload, dict):
|
|
raise ValueError("请求参数无效")
|
|
if action in FILE_ACTIONS:
|
|
if action == "file.list":
|
|
validate_download_relative_path(payload.get("path", ""))
|
|
elif action in {"file.mkdir", "file.delete", "file.download.start", "file.upload.start"}:
|
|
if not validate_download_relative_path(payload.get("path")):
|
|
raise ValueError("文件路径不能为空")
|
|
elif action == "file.rename":
|
|
if not validate_download_relative_path(payload.get("path")) or not validate_download_relative_path(payload.get("newPath")):
|
|
raise ValueError("文件路径不能为空")
|
|
if action in {"file.upload.chunk", "file.download.chunk", "file.upload.finish", "file.download.finish"}:
|
|
transfer_id = payload.get("transferId")
|
|
if not isinstance(transfer_id, str) or not TRANSFER_ID_RE.fullmatch(transfer_id):
|
|
raise ValueError("传输 ID 无效")
|
|
if action == "file.upload.start":
|
|
size = payload.get("size")
|
|
if not isinstance(size, int) or isinstance(size, bool) or not 0 <= size <= MAX_FILE_TRANSFER_BYTES:
|
|
raise ValueError("文件超过 512 MiB 限制")
|
|
transfer_id = payload.get("transferId")
|
|
if not isinstance(transfer_id, str) or not TRANSFER_ID_RE.fullmatch(transfer_id):
|
|
raise ValueError("传输 ID 无效")
|
|
if action == "file.upload.finish":
|
|
checksum = payload.get("sha256")
|
|
if not isinstance(checksum, str) or not re.fullmatch(r"[a-fA-F0-9]{64}", checksum):
|
|
raise ValueError("SHA-256 无效")
|
|
if action == "file.upload.chunk":
|
|
data = payload.get("data")
|
|
offset = payload.get("offset")
|
|
if not isinstance(offset, int) or isinstance(offset, bool) or not 0 <= offset <= MAX_FILE_TRANSFER_BYTES:
|
|
raise ValueError("分块偏移无效")
|
|
if not isinstance(data, str) or len(data) > ((MAX_TRANSFER_CHUNK_BYTES + 2) // 3) * 4:
|
|
raise ValueError("文件分块无效或超过 64 KiB")
|
|
try:
|
|
decoded = base64.b64decode(data, validate=True)
|
|
except (binascii.Error, ValueError):
|
|
raise ValueError("文件分块不是合法 Base64") from None
|
|
if not decoded or len(decoded) > MAX_TRANSFER_CHUNK_BYTES:
|
|
raise ValueError("文件分块大小必须为 1-64 KiB")
|
|
if action == "file.download.start":
|
|
transfer_id = payload.get("transferId")
|
|
if not isinstance(transfer_id, str) or not TRANSFER_ID_RE.fullmatch(transfer_id):
|
|
raise ValueError("传输 ID 无效")
|
|
if action == "file.download.chunk":
|
|
offset, size = payload.get("offset"), payload.get("size", MAX_TRANSFER_CHUNK_BYTES)
|
|
if not isinstance(offset, int) or isinstance(offset, bool) or not 0 <= offset <= MAX_FILE_TRANSFER_BYTES:
|
|
raise ValueError("分块偏移无效")
|
|
if not isinstance(size, int) or isinstance(size, bool) or not 1 <= size <= MAX_TRANSFER_CHUNK_BYTES:
|
|
raise ValueError("分块大小无效")
|
|
return
|
|
if action in {"app.install", "app.uninstall"}:
|
|
if action == "app.install":
|
|
relative_path = validate_download_relative_path(payload.get("path"))
|
|
if not relative_path.lower().endswith(".apk"):
|
|
raise ValueError("只能安装 APK 文件")
|
|
else:
|
|
package_name = payload.get("package")
|
|
if not isinstance(package_name, str) or not PACKAGE_NAME_RE.fullmatch(package_name):
|
|
raise ValueError("应用包名无效")
|
|
if package_name == "com.cpagent.bridge":
|
|
raise ValueError("不能卸载 CP Bridge")
|
|
|
|
|
|
def enqueue_server_log(entry: ServerLogEntry) -> None:
|
|
loop, queue = log_loop, log_queue
|
|
if loop is None or queue is None or loop.is_closed():
|
|
return
|
|
|
|
def put_latest() -> None:
|
|
if queue is not log_queue:
|
|
return
|
|
# Runs atomically on the loop thread, including for threaded publishers.
|
|
if queue.full():
|
|
queue.get_nowait()
|
|
queue.task_done()
|
|
queue.put_nowait(entry)
|
|
|
|
# Shutdown can close the loop between the check above and scheduling.
|
|
with contextlib.suppress(RuntimeError):
|
|
loop.call_soon_threadsafe(put_latest)
|
|
|
|
|
|
def attach_server_log_handler() -> None:
|
|
for name in LOGGERS_TO_CAPTURE:
|
|
target = logging.getLogger(name)
|
|
if server_log_handler not in target.handlers:
|
|
target.addHandler(server_log_handler)
|
|
|
|
|
|
def detach_server_log_handler() -> None:
|
|
for name in LOGGERS_TO_CAPTURE:
|
|
logging.getLogger(name).removeHandler(server_log_handler)
|
|
|
|
|
|
async def broadcast_server_logs() -> None:
|
|
queue = log_queue
|
|
assert queue is not None
|
|
# Never log from this worker: those records would feed back into the queue.
|
|
while True:
|
|
entry = await queue.get()
|
|
token = _log_broadcast_active.set(True)
|
|
try:
|
|
await hub.broadcast_to_ui(
|
|
{"type": "event", "action": "event.log", "payload": entry},
|
|
timeout=LOG_BROADCAST_TIMEOUT,
|
|
)
|
|
finally:
|
|
_log_broadcast_active.reset(token)
|
|
queue.task_done()
|
|
|
|
|
|
app = FastAPI(title="ATX Agent Management Platform")
|
|
|
|
|
|
@app.on_event("startup")
|
|
async def startup() -> None:
|
|
global log_loop, log_queue, log_broadcast_task
|
|
# Storage is process-scoped; a fully shut down app cannot be restarted.
|
|
if _storage_closed:
|
|
raise RuntimeError("Cannot restart application: storage has been closed")
|
|
if log_loop is not None:
|
|
return
|
|
Path(DB_PATH).parent.mkdir(parents=True, exist_ok=True)
|
|
log_loop = asyncio.get_running_loop()
|
|
log_queue = asyncio.Queue(maxsize=LOG_QUEUE_SIZE)
|
|
server_log_handler.set_publish(enqueue_server_log)
|
|
attach_server_log_handler()
|
|
log_broadcast_task = log_loop.create_task(broadcast_server_logs())
|
|
hub.start_watchdog()
|
|
logger.info("服务启动完成, DB=%s", DB_PATH)
|
|
|
|
|
|
@app.on_event("shutdown")
|
|
async def shutdown() -> None:
|
|
global log_broadcast_task, log_queue, log_loop, _storage_closed
|
|
if _storage_closed:
|
|
return
|
|
await hub.shutdown()
|
|
server_log_handler.set_publish(None)
|
|
detach_server_log_handler()
|
|
if log_broadcast_task is not None:
|
|
log_broadcast_task.cancel()
|
|
with contextlib.suppress(asyncio.CancelledError):
|
|
await log_broadcast_task
|
|
log_broadcast_task = None
|
|
log_queue = None
|
|
log_loop = None
|
|
storage.close()
|
|
_storage_closed = True
|
|
|
|
|
|
# ---------------- 设备端 WS ----------------
|
|
|
|
@app.websocket("/ws/device")
|
|
async def device_ws(ws: WebSocket) -> None:
|
|
await ws.accept()
|
|
register = await _expect_register(ws)
|
|
if register is None:
|
|
return
|
|
|
|
if DEVICE_TOKEN and register.token != DEVICE_TOKEN:
|
|
await ws.send_text('{"type":"response","action":"register","status":"error","payload":{"code":3002,"message":"token 校验失败"}}')
|
|
await ws.close()
|
|
return
|
|
|
|
# 若同 deviceId 已有连接,先关闭旧的
|
|
old = hub.get_connection(register.device_id)
|
|
if old is not None:
|
|
try:
|
|
await old.ws.close()
|
|
except Exception:
|
|
pass
|
|
await hub.unregister_device(register.device_id)
|
|
|
|
conn = DeviceConnection(ws, register)
|
|
hub.register_device(conn)
|
|
await hub.broadcast_to_ui({"type": "event", "action": "device.online", "deviceId": register.device_id})
|
|
|
|
try:
|
|
while True:
|
|
raw = await ws.receive_text()
|
|
await _handle_device_message(conn, raw)
|
|
except WebSocketDisconnect:
|
|
pass
|
|
except Exception:
|
|
logger.exception("设备连接异常: %s", register.device_id)
|
|
finally:
|
|
# 只有当前注册的连接才标记离线
|
|
if hub.get_connection(register.device_id) is conn:
|
|
await hub.unregister_device(register.device_id)
|
|
|
|
|
|
async def _expect_register(ws: WebSocket) -> RegisterInfo | None:
|
|
try:
|
|
raw = await ws.receive_text()
|
|
data = json.loads(raw)
|
|
except WebSocketDisconnect:
|
|
return None
|
|
except Exception:
|
|
await ws.close()
|
|
return None
|
|
if data.get("type") != "register" or not data.get("deviceId"):
|
|
await ws.send_text('{"type":"response","action":"register","status":"error","payload":{"code":1001,"message":"首条消息必须是 register"}}')
|
|
await ws.close()
|
|
return None
|
|
return RegisterInfo.from_dict(data)
|
|
|
|
|
|
async def _handle_device_message(conn: DeviceConnection, raw: str) -> None:
|
|
try:
|
|
data = json.loads(raw)
|
|
except (json.JSONDecodeError, TypeError):
|
|
logger.warning("设备 %s 发送非法 JSON", conn.device_id)
|
|
return
|
|
|
|
try:
|
|
envelope = Envelope.from_dict(data)
|
|
except Exception:
|
|
logger.warning("设备 %s 发送无法解析的消息: %s", conn.device_id, raw[:200])
|
|
return
|
|
|
|
if envelope.type == TYPE_RESPONSE:
|
|
dispatcher.handle_response(conn, envelope)
|
|
return
|
|
|
|
if envelope.type == "event":
|
|
action = envelope.action
|
|
if action == ACTION_EVENT_HEARTBEAT:
|
|
hub.touch_heartbeat(conn.device_id, envelope.payload)
|
|
await hub.broadcast_to_ui({
|
|
"type": "event",
|
|
"action": "event.heartbeat",
|
|
"deviceId": conn.device_id,
|
|
"payload": envelope.payload,
|
|
})
|
|
else:
|
|
storage.add_event(conn.device_id, action, json.dumps(envelope.payload, ensure_ascii=False))
|
|
await hub.broadcast_to_ui({
|
|
"type": "event",
|
|
"action": action,
|
|
"deviceId": conn.device_id,
|
|
"payload": envelope.payload,
|
|
})
|
|
return
|
|
|
|
logger.warning("设备 %s 发送未知消息类型: %s", conn.device_id, envelope.type)
|
|
|
|
|
|
# ---------------- 前端 WS ----------------
|
|
|
|
@app.websocket("/ws/ui")
|
|
async def ui_ws(ws: WebSocket) -> None:
|
|
await ws.accept()
|
|
session = UiSession(ws, id(ws))
|
|
hub.register_ui(session)
|
|
|
|
async def send_device_list() -> None:
|
|
await session.send({"type": "event", "action": "device.list", "payload": hub.device_summaries()})
|
|
|
|
await send_device_list()
|
|
try:
|
|
while True:
|
|
raw = await ws.receive_text()
|
|
try:
|
|
data = json.loads(raw)
|
|
except json.JSONDecodeError:
|
|
await session.send({"type": "response", "action": "error", "status": "error",
|
|
"payload": error_payload(ErrorCode.BAD_REQUEST)})
|
|
continue
|
|
await _handle_ui_message(session, data)
|
|
except WebSocketDisconnect:
|
|
pass
|
|
finally:
|
|
hub.unregister_ui(session.session_id)
|
|
|
|
|
|
async def _handle_ui_message(session: UiSession, data: dict) -> None:
|
|
action = data.get("action", "")
|
|
request_id = data.get("id", "")
|
|
payload = data.get("payload") or {}
|
|
device_id = data.get("deviceId") or payload.get("deviceId") or ""
|
|
|
|
async def reply(status: str, result: dict) -> None:
|
|
await session.send({
|
|
"id": request_id, "type": "response", "action": action, "status": status, "payload": result,
|
|
})
|
|
|
|
if action == "device.list":
|
|
await reply("success", {"devices": hub.device_summaries()})
|
|
return
|
|
|
|
if action == "log.list":
|
|
await reply("success", {"logs": runlog.entries()})
|
|
return
|
|
|
|
if not device_id:
|
|
await reply("error", error_payload(ErrorCode.BAD_REQUEST, "缺少 deviceId"))
|
|
return
|
|
|
|
if action == "device.detail":
|
|
row = storage.get_device(device_id)
|
|
conn = hub.get_connection(device_id)
|
|
if row is None:
|
|
await reply("error", error_payload(ErrorCode.FILE_NOT_FOUND, "设备不存在"))
|
|
return
|
|
info = dict(row)
|
|
info["online"] = conn is not None
|
|
if conn is not None:
|
|
info["heartbeat"] = conn.last_heartbeat
|
|
info["connectedAt"] = conn.connected_at
|
|
await reply("success", {"device": info})
|
|
return
|
|
|
|
# ---- 以下为转发到设备的指令 ----
|
|
timeout = float(payload.get("timeout", 0)) or None
|
|
try:
|
|
# atx.* 命名空间:通用直通到设备(由 Bridge 映射 atx-agent HTTP 接口)
|
|
if action in FILE_ACTIONS or action in {"app.install", "app.uninstall"}:
|
|
try:
|
|
validate_management_action(action, payload)
|
|
except ValueError as e:
|
|
await reply("error", error_payload(ErrorCode.BAD_REQUEST, str(e)))
|
|
return
|
|
result = await dispatcher.send_command(device_id, action, payload, timeout or 120)
|
|
await reply("success", result)
|
|
elif action.startswith("atx."):
|
|
result = await dispatcher.send_command(device_id, action, payload, timeout or 60)
|
|
await reply("success", result)
|
|
elif action == "shell.exec":
|
|
cmd = payload.get("cmd")
|
|
if not isinstance(cmd, str) or not cmd.strip():
|
|
await reply("error", error_payload(ErrorCode.BAD_REQUEST, "缺少 cmd"))
|
|
return
|
|
result = await dispatcher.send_command(device_id, "shell.exec", {"cmd": cmd, "timeout": timeout}, timeout)
|
|
await reply("success", result)
|
|
elif action == "device.info":
|
|
result = await dispatcher.send_command(device_id, "device.info", {})
|
|
await reply("success", result)
|
|
elif action == "screen.capture":
|
|
result = await dispatcher.send_command(device_id, "screen.capture", {}, timeout or 30)
|
|
await reply("success", result)
|
|
elif action == "app.list":
|
|
result = await dispatcher.send_command(device_id, "app.list", {}, timeout or 30)
|
|
await reply("success", result)
|
|
elif action == "app.launch":
|
|
pkg = payload.get("package")
|
|
if not isinstance(pkg, str) or not pkg.strip():
|
|
await reply("error", error_payload(ErrorCode.BAD_REQUEST, "缺少 package"))
|
|
return
|
|
result = await dispatcher.send_command(device_id, "app.launch", {"package": pkg}, timeout or 15)
|
|
await reply("success", result)
|
|
else:
|
|
await reply("error", error_payload(ErrorCode.BAD_REQUEST, f"未知 action: {action}"))
|
|
except DeviceOfflineError as e:
|
|
await reply("error", error_payload(ErrorCode.AGENT_NOT_RUNNING, str(e)))
|
|
except CommandTimeoutError as e:
|
|
await reply("error", error_payload(ErrorCode.COMMAND_TIMEOUT, str(e)))
|
|
except RuntimeError as e:
|
|
await reply("error", error_payload(ErrorCode.BAD_REQUEST, str(e)))
|
|
|
|
|
|
# ---------------- 静态调试页 ----------------
|
|
|
|
@app.get("/")
|
|
async def index() -> FileResponse:
|
|
return FileResponse(WEB_DIR / "index.html")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
uvicorn.run(
|
|
"main:app",
|
|
host=os.environ.get("HOST", "0.0.0.0"),
|
|
port=int(os.environ.get("PORT", "60030")),
|
|
reload=bool(os.environ.get("RELOAD")),
|
|
)
|