347 lines
12 KiB
Python
347 lines
12 KiB
Python
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import platform
|
||
import subprocess
|
||
import time
|
||
import zipfile
|
||
from dataclasses import dataclass
|
||
from pathlib import Path
|
||
from typing import Any
|
||
from urllib import request
|
||
|
||
from douyin.core import path_config
|
||
from douyin.license.license_manager import get_default_license_path, get_default_verify_url
|
||
|
||
DEFAULT_MAX_ARCHIVE_BYTES = 32 * 1024 * 1024
|
||
DEFAULT_MAX_SOURCE_BYTES = 4 * 1024 * 1024
|
||
DEFAULT_MAX_FILES = 32
|
||
DEFAULT_MAX_IMAGE_BYTES = 5 * 1024 * 1024
|
||
SENSITIVE_KEY_PARTS = ("key", "token", "secret", "password", "license", "card")
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class LogUploadResult:
|
||
ok: bool
|
||
message: str
|
||
reason: str = ""
|
||
archive_path: str = ""
|
||
size: int = 0
|
||
|
||
|
||
def get_default_log_upload_url() -> str:
|
||
raw = str(os.environ.get("DOUYIN_LOG_UPLOAD_URL") or "").strip()
|
||
if raw:
|
||
return raw
|
||
verify_url = get_default_verify_url()
|
||
if verify_url.endswith("/verify_license"):
|
||
return verify_url[: -len("/verify_license")] + "/logs/upload"
|
||
return verify_url.rstrip("/") + "/logs/upload"
|
||
|
||
|
||
def _candidate_log_files(logs_dir: Path) -> list[Path]:
|
||
suffixes = {".log", ".jsonl", ".txt"}
|
||
if not logs_dir.exists():
|
||
return []
|
||
files = [
|
||
p
|
||
for p in logs_dir.rglob("*")
|
||
if p.is_file() and p.suffix.lower() in suffixes and p.name != ".keep"
|
||
]
|
||
return sorted(files, key=lambda p: p.stat().st_mtime, reverse=True)
|
||
|
||
|
||
def _tail_bytes(path: Path, limit: int) -> bytes:
|
||
size = path.stat().st_size
|
||
with path.open("rb") as f:
|
||
if size > limit:
|
||
f.seek(size - limit)
|
||
return f.read(limit)
|
||
|
||
|
||
def _safe_rel(path: Path, base: Path) -> str:
|
||
try:
|
||
return path.relative_to(base).as_posix()
|
||
except Exception:
|
||
return path.name
|
||
|
||
|
||
def _redact_value(key: str, value: Any) -> Any:
|
||
key_l = str(key or "").lower()
|
||
if isinstance(value, dict):
|
||
return {str(k): _redact_value(str(k), v) for k, v in value.items()}
|
||
if isinstance(value, list):
|
||
return [_redact_value(key, item) for item in value]
|
||
if any(part in key_l for part in SENSITIVE_KEY_PARTS):
|
||
return "<redacted>"
|
||
return value
|
||
|
||
|
||
def _read_redacted_config() -> dict[str, Any] | None:
|
||
try:
|
||
path = Path(path_config.get_config_path())
|
||
obj = json.loads(path.read_text(encoding="utf-8-sig"))
|
||
if not isinstance(obj, dict):
|
||
return None
|
||
return {str(k): _redact_value(str(k), v) for k, v in obj.items()}
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
def _candidate_state_files(state_dir: Path) -> list[Path]:
|
||
if not state_dir.exists():
|
||
return []
|
||
names = {
|
||
"reservations.json",
|
||
"room_pos_map.json",
|
||
"high_value_rooms.json",
|
||
"runtime_stats.json",
|
||
"dashboard_stats.json",
|
||
}
|
||
files = [p for p in state_dir.rglob("*.json") if p.is_file() and p.name in names]
|
||
return sorted(files, key=lambda p: p.stat().st_mtime, reverse=True)
|
||
|
||
|
||
def _candidate_pic_files(pic_dir: Path) -> list[Path]:
|
||
if not pic_dir.exists():
|
||
return []
|
||
preferred = []
|
||
for name in (
|
||
"screenshot.png",
|
||
"screenshot.png.tmp",
|
||
"screenshot.jpg",
|
||
"latest.png",
|
||
"last_match.png",
|
||
):
|
||
p = pic_dir / name
|
||
if p.is_file():
|
||
preferred.append(p)
|
||
|
||
def _is_diagnostic_pic(path: Path) -> bool:
|
||
suffix = path.suffix.lower()
|
||
if suffix in {".png", ".jpg", ".jpeg"}:
|
||
return True
|
||
return path.name.lower().endswith(".png.tmp")
|
||
|
||
recent = sorted(
|
||
[p for p in pic_dir.rglob("*") if p.is_file() and _is_diagnostic_pic(p)],
|
||
key=lambda p: p.stat().st_mtime,
|
||
reverse=True,
|
||
)
|
||
result: list[Path] = []
|
||
for item in [*preferred, *recent]:
|
||
if item not in result:
|
||
result.append(item)
|
||
if len(result) >= 12:
|
||
break
|
||
return result
|
||
|
||
|
||
def _run_command(cmd: list[str], timeout: int = 5) -> dict[str, Any]:
|
||
try:
|
||
proc = subprocess.run(cmd, text=True, capture_output=True, timeout=timeout)
|
||
return {
|
||
"cmd": cmd,
|
||
"returncode": proc.returncode,
|
||
"stdout": (proc.stdout or "")[-4000:],
|
||
"stderr": (proc.stderr or "")[-2000:],
|
||
}
|
||
except Exception as exc:
|
||
return {"cmd": cmd, "error": f"{type(exc).__name__}: {exc}"}
|
||
|
||
|
||
def _diagnostic_environment() -> dict[str, Any]:
|
||
payload: dict[str, Any] = {
|
||
"created_at": int(time.time()),
|
||
"platform": platform.platform(),
|
||
"python": platform.python_version(),
|
||
"cwd": os.getcwd(),
|
||
"project_root": path_config.get_project_root(),
|
||
"logs_dir": path_config.get_logs_dir(),
|
||
"pic_dir": path_config.get_pic_dir(),
|
||
"state_dir": path_config.get_state_dir(),
|
||
}
|
||
adb = ""
|
||
try:
|
||
from gui.gui_core import find_adb_executable
|
||
|
||
adb = str(find_adb_executable() or "")
|
||
except Exception:
|
||
adb = str(os.environ.get("ADB") or "adb")
|
||
payload["adb"] = adb
|
||
payload["adb_version"] = _run_command([adb, "version"]) if adb else {"error": "adb not found"}
|
||
payload["adb_devices"] = _run_command([adb, "devices", "-l"]) if adb else {"error": "adb not found"}
|
||
return payload
|
||
|
||
|
||
def build_diagnostic_log_archive(
|
||
*,
|
||
output_dir: str | os.PathLike[str] | None = None,
|
||
max_archive_bytes: int = DEFAULT_MAX_ARCHIVE_BYTES,
|
||
max_source_bytes: int = DEFAULT_MAX_SOURCE_BYTES,
|
||
max_files: int = DEFAULT_MAX_FILES,
|
||
) -> Path:
|
||
logs_dir = Path(path_config.get_logs_dir())
|
||
out_dir = Path(output_dir) if output_dir is not None else logs_dir
|
||
out_dir.mkdir(parents=True, exist_ok=True)
|
||
archive = out_dir / f"diagnostic_logs_{int(time.time())}.zip"
|
||
files = _candidate_log_files(logs_dir)[: max(1, int(max_files))]
|
||
if not files:
|
||
raise FileNotFoundError("没有找到可上传的日志文件")
|
||
|
||
with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as zf:
|
||
manifest: dict[str, Any] = {
|
||
"created_at": int(time.time()),
|
||
"source": "douyin_guaji",
|
||
"truncated_each_file_bytes": int(max_source_bytes),
|
||
"files": [],
|
||
}
|
||
for file in files:
|
||
rel = _safe_rel(file, logs_dir)
|
||
data = _tail_bytes(file, max_source_bytes)
|
||
zf.writestr(f"logs/{rel}", data)
|
||
manifest["files"].append(
|
||
{
|
||
"path": f"logs/{rel}",
|
||
"original_size": file.stat().st_size,
|
||
"included_size": len(data),
|
||
"mtime": int(file.stat().st_mtime),
|
||
}
|
||
)
|
||
try:
|
||
pic_dir = Path(path_config.get_pic_dir())
|
||
for file in _candidate_pic_files(pic_dir):
|
||
if file.stat().st_size > DEFAULT_MAX_IMAGE_BYTES:
|
||
continue
|
||
rel = _safe_rel(file, pic_dir)
|
||
zf.write(file, f"pic/{rel}")
|
||
manifest["files"].append(
|
||
{
|
||
"path": f"pic/{rel}",
|
||
"original_size": file.stat().st_size,
|
||
"included_size": file.stat().st_size,
|
||
"mtime": int(file.stat().st_mtime),
|
||
}
|
||
)
|
||
except Exception as exc:
|
||
manifest["pic_error"] = str(exc)
|
||
try:
|
||
state_dir = Path(path_config.get_state_dir())
|
||
for file in _candidate_state_files(state_dir):
|
||
rel = _safe_rel(file, state_dir)
|
||
data = _tail_bytes(file, max_source_bytes)
|
||
zf.writestr(f"state/{rel}", data)
|
||
manifest["files"].append(
|
||
{
|
||
"path": f"state/{rel}",
|
||
"original_size": file.stat().st_size,
|
||
"included_size": len(data),
|
||
"mtime": int(file.stat().st_mtime),
|
||
}
|
||
)
|
||
except Exception as exc:
|
||
manifest["state_error"] = str(exc)
|
||
redacted_cfg = _read_redacted_config()
|
||
if redacted_cfg is not None:
|
||
zf.writestr(
|
||
"config/config.redacted.json",
|
||
json.dumps(redacted_cfg, ensure_ascii=False, indent=2),
|
||
)
|
||
zf.writestr(
|
||
"diagnostics/environment.json",
|
||
json.dumps(_diagnostic_environment(), ensure_ascii=False, indent=2),
|
||
)
|
||
zf.writestr("manifest.json", json.dumps(manifest, ensure_ascii=False, indent=2))
|
||
|
||
if archive.stat().st_size > max_archive_bytes:
|
||
try:
|
||
archive.unlink()
|
||
finally:
|
||
raise ValueError(f"诊断日志包超过大小限制(最大 {max_archive_bytes // (1024 * 1024)} MB)")
|
||
return archive
|
||
|
||
|
||
def upload_diagnostic_logs(
|
||
*,
|
||
upload_url: str = "",
|
||
timeout_seconds: int = 20,
|
||
http_post_file=None,
|
||
) -> LogUploadResult:
|
||
license_path = get_default_license_path()
|
||
if not license_path.exists():
|
||
return LogUploadResult(False, "缺少授权文件,无法上传日志", "missing_license")
|
||
try:
|
||
license_doc = json.loads(license_path.read_text(encoding="utf-8"))
|
||
except Exception as exc:
|
||
return LogUploadResult(False, f"授权文件读取失败: {exc}", "invalid_license")
|
||
|
||
try:
|
||
archive = build_diagnostic_log_archive()
|
||
except Exception as exc:
|
||
return LogUploadResult(False, str(exc), "archive_failed")
|
||
|
||
url = str(upload_url or "").strip() or get_default_log_upload_url()
|
||
try:
|
||
post = http_post_file or _default_http_post_file
|
||
data = post(
|
||
url,
|
||
license_doc=license_doc,
|
||
file_path=archive,
|
||
timeout_seconds=timeout_seconds,
|
||
)
|
||
except Exception as exc:
|
||
return LogUploadResult(False, f"上传失败: {exc}", "upload_failed", str(archive), archive.stat().st_size)
|
||
if not bool(data.get("ok")):
|
||
return LogUploadResult(
|
||
False,
|
||
str(data.get("message") or data.get("error") or "上传失败"),
|
||
str(data.get("reason") or "rejected"),
|
||
str(archive),
|
||
archive.stat().st_size,
|
||
)
|
||
return LogUploadResult(True, "日志上传成功", "ok", str(archive), archive.stat().st_size)
|
||
|
||
|
||
def _default_http_post_file(
|
||
url: str,
|
||
*,
|
||
license_doc: dict[str, Any],
|
||
file_path: Path,
|
||
timeout_seconds: int = 20,
|
||
) -> dict[str, Any]:
|
||
boundary = f"----DYGJ{int(time.time() * 1000)}"
|
||
payload = json.dumps(license_doc, ensure_ascii=False).encode("utf-8")
|
||
file_data = file_path.read_bytes()
|
||
body = bytearray()
|
||
|
||
def add_field(name: str, value: bytes, content_type: str = "text/plain") -> None:
|
||
body.extend(f"--{boundary}\r\n".encode("ascii"))
|
||
body.extend(f'Content-Disposition: form-data; name="{name}"\r\n'.encode("ascii"))
|
||
body.extend(f"Content-Type: {content_type}\r\n\r\n".encode("ascii"))
|
||
body.extend(value)
|
||
body.extend(b"\r\n")
|
||
|
||
add_field("license", payload, "application/json")
|
||
body.extend(f"--{boundary}\r\n".encode("ascii"))
|
||
body.extend(
|
||
f'Content-Disposition: form-data; name="log_file"; filename="{file_path.name}"\r\n'.encode("ascii")
|
||
)
|
||
body.extend(b"Content-Type: application/zip\r\n\r\n")
|
||
body.extend(file_data)
|
||
body.extend(b"\r\n")
|
||
body.extend(f"--{boundary}--\r\n".encode("ascii"))
|
||
|
||
req = request.Request(
|
||
url,
|
||
data=bytes(body),
|
||
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
|
||
method="POST",
|
||
)
|
||
with request.urlopen(req, timeout=max(1, int(timeout_seconds))) as resp:
|
||
raw = resp.read().decode("utf-8")
|
||
obj = json.loads(raw)
|
||
if not isinstance(obj, dict):
|
||
raise ValueError("server response is not an object")
|
||
return obj
|