185 lines
6.2 KiB
Python
185 lines
6.2 KiB
Python
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
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 = 8 * 1024 * 1024
|
||
DEFAULT_MAX_SOURCE_BYTES = 2 * 1024 * 1024
|
||
DEFAULT_MAX_FILES = 12
|
||
|
||
|
||
@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 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 = file.relative_to(logs_dir).as_posix()
|
||
data = _tail_bytes(file, max_source_bytes)
|
||
zf.writestr(f"logs/{rel}", data)
|
||
manifest["files"].append(
|
||
{
|
||
"path": rel,
|
||
"original_size": file.stat().st_size,
|
||
"included_size": len(data),
|
||
"mtime": int(file.stat().st_mtime),
|
||
}
|
||
)
|
||
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
|