"""iOSGuard LLVM opt 工具链管理:并发互斥、按需校验/自愈及每日午夜巡检。""" import asyncio import json import logging import os import sys from datetime import datetime, timedelta from pathlib import Path from typing import Optional from ..config import ( IG_LLVM_GIT_MIRROR, IG_TOOLCHAIN_CACHE_DIR, IG_TOOLCHAIN_DAILY_CHECK_ENABLED, IG_TOOLCHAIN_DAILY_HOUR, IG_TOOLCHAIN_DAILY_MINUTE, IG_TOOLCHAIN_KEEP_VERSIONS, IG_TOOLCHAIN_REBUILD_TIMEOUT_SECONDS, IG_TOOLCHAIN_SOURCE_DIR, ) from ..projects import LEGACY_PROJECT_ID, get_project_source from .log_streamer import log_streamer from .notification import send_toolchain_dingtalk_alert logger = logging.getLogger(__name__) _toolchain_lock = asyncio.Lock() _update_in_progress = False _RESOLVER_REL = Path("iOSGuardIntegration") / "toolchain" / "tools" / "llvm_obf" / "ig_toolchain_resolver.py" def seconds_until_next_run(now: Optional[datetime] = None, hour: int = 0, minute: int = 0) -> float: """计算当前本地时间距离下一次指定时刻(默认 00:00)的秒数,最小返回 1.0。""" current = now or datetime.now() target = current.replace(hour=int(hour) % 24, minute=int(minute) % 60, second=0, microsecond=0) if target <= current: target += timedelta(days=1) return max(1.0, (target - current).total_seconds()) def _augmented_subprocess_env() -> dict: env = os.environ.copy() path_parts = [p for p in env.get("PATH", "").split(":") if p] for extra in ("/opt/homebrew/bin", "/usr/local/bin"): if extra not in path_parts: path_parts.append(extra) env["PATH"] = ":".join(path_parts) env["IG_TOOLCHAIN_CACHE_DIR"] = str(IG_TOOLCHAIN_CACHE_DIR) env["IG_LLVM_GIT_MIRROR"] = IG_LLVM_GIT_MIRROR env["PYTHONUNBUFFERED"] = "1" return env def _load_dingtalk_config() -> dict: try: from ..routers.config import load_upload_config return (load_upload_config() or {}).get("dingtalk", {}) or {} except Exception: return {} async def _send_alert_best_effort(title: str, lines: list[str]) -> None: cfg = _load_dingtalk_config() if not cfg.get("enabled"): return try: await asyncio.to_thread(send_toolchain_dingtalk_alert, cfg, title, lines) except Exception as exc: logger.warning("发送工具链钉钉告警失败: %s", exc) def discover_toolchain_resolver(build_dir: Optional[Path] = None) -> Optional[Path]: """按优先级定位 ig_toolchain_resolver.py:构建快照 > IG_TOOLCHAIN_SOURCE_DIR > Readoor 源码目录。""" if build_dir is not None: cand = Path(build_dir) / _RESOLVER_REL if cand.is_file(): return cand if IG_TOOLCHAIN_SOURCE_DIR: base = Path(IG_TOOLCHAIN_SOURCE_DIR).expanduser() for cand in ( base, base / _RESOLVER_REL, base / "tools" / "llvm_obf" / "ig_toolchain_resolver.py", ): if cand.is_file(): return cand try: from ..routers.config import load_config project = load_config(LEGACY_PROJECT_ID) source = get_project_source(LEGACY_PROJECT_ID, project) candidates = [] if source.shared_dir: candidates.append(source.shared_dir / _RESOLVER_REL) if source.manual_base and source.manual_base.is_dir(): for branch in project.get("branches") or ("main",): candidates.append(source.manual_base / branch / _RESOLVER_REL) for child in sorted(source.manual_base.iterdir()): if child.is_dir(): candidates.append(child / _RESOLVER_REL) for cand in candidates: if cand.is_file(): return cand except Exception as exc: logger.debug("从 Readoor 项目源码定位工具链解析器失败: %s", exc) return None async def ensure_toolchain( resolver_path: Path, *, task_id: Optional[str] = None, force_rebuild: bool = False, notify_on_event: bool = False, ) -> dict: """在全局异步锁下执行 `ig_toolchain_resolver.py --ensure`,必要时自动复用或源码重编 `opt`。""" global _update_in_progress if _toolchain_lock.locked() and task_id: await log_streamer.emit(task_id, "正在等待其他任务完成 LLVM 加固工具链检查/更新...") async with _toolchain_lock: _update_in_progress = True try: cmd = [ sys.executable or "python3", str(resolver_path), "--ensure", "--require-obf", "--json", "--cache-dir", str(IG_TOOLCHAIN_CACHE_DIR), "--git-remote", IG_LLVM_GIT_MIRROR, "--keep-versions", str(IG_TOOLCHAIN_KEEP_VERSIONS), ] if force_rebuild: cmd.append("--force-rebuild") proc = await asyncio.create_subprocess_exec( *cmd, cwd=str(Path(resolver_path).parent), env=_augmented_subprocess_env(), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stderr_tail: list[str] = [] async def _read_stderr(): assert proc.stderr is not None while True: raw = await proc.stderr.readline() if not raw: break line = raw.decode("utf-8", errors="replace").rstrip("\r\n") if not line: continue stderr_tail.append(line) if len(stderr_tail) > 40: stderr_tail.pop(0) logger.info("[IGToolchain] %s", line) if task_id: await log_streamer.emit(task_id, f"[toolchain] {line}") async def _wait_streams(): assert proc.stdout is not None stdout_bytes, _ = await asyncio.gather(proc.stdout.read(), _read_stderr()) await proc.wait() return stdout_bytes try: stdout_bytes = await asyncio.wait_for( _wait_streams(), timeout=IG_TOOLCHAIN_REBUILD_TIMEOUT_SECONDS, ) except asyncio.TimeoutError as exc: proc.kill() await proc.wait() msg = f"LLVM 工具链自动更新超时(>{IG_TOOLCHAIN_REBUILD_TIMEOUT_SECONDS}s)" if notify_on_event: await _send_alert_best_effort( "【iOS打包服务】Xcode 工具链 (opt) 更新失败", [f"**原因:** {msg}", f"**日志尾部:** `{' | '.join(stderr_tail[-5:])}`"], ) raise RuntimeError(msg) from exc stdout_text = (stdout_bytes or b"").decode("utf-8", errors="replace").strip() payload = {} if stdout_text: try: payload = json.loads(stdout_text) except json.JSONDecodeError: payload = {"raw_stdout": stdout_text[-1000:]} if proc.returncode != 0: detail = payload.get("error") or payload.get("warning") or "\n".join(stderr_tail[-10:]) or stdout_text[-800:] if notify_on_event: await _send_alert_best_effort( "【iOS打包服务】Xcode 工具链 (opt) 更新失败", [f"**失败原因:** {detail}"], ) raise RuntimeError(f"LLVM IR 混淆工具链校验/更新失败: {detail}") source_mode = payload.get("source_mode") if notify_on_event and source_mode in ("reused", "built"): xc = payload.get("xcode") or {} sw = payload.get("swift") or {} lines = [ f"**Xcode:** {xc.get('xcode_version', '')} ({xc.get('xcode_build', '')})", f"**Swift:** {sw.get('swift_version', '')} (swiftlang-{sw.get('swiftlang_version', '')})", f"**更新方式:** {'自动冒烟复用' if source_mode == 'reused' else '自动源码重编'}", ] if payload.get("llvm_branch"): lines.append(f"**LLVM 分支:** {payload['llvm_branch']}") lines.append(f"**opt SHA256:** `{(payload.get('opt_sha256') or '')[:12]}`") await _send_alert_best_effort("【iOS打包服务】Xcode 工具链 (opt) 已自动更新", lines) return payload finally: _update_in_progress = False async def get_toolchain_status(resolver_path: Optional[Path] = None) -> dict: """只读检查当前机器 Xcode 与 `opt` 缓存状态。""" resolved = resolver_path or discover_toolchain_resolver() next_run = datetime.now() + timedelta( seconds=seconds_until_next_run(hour=IG_TOOLCHAIN_DAILY_HOUR, minute=IG_TOOLCHAIN_DAILY_MINUTE) ) base_status = { "update_in_progress": _update_in_progress, "daily_check_enabled": IG_TOOLCHAIN_DAILY_CHECK_ENABLED, "next_scheduled_check": next_run.isoformat(timespec="seconds"), "cache_dir": str(IG_TOOLCHAIN_CACHE_DIR), "git_mirror": IG_LLVM_GIT_MIRROR, "resolver_path": str(resolved) if resolved else None, } if resolved is None: return { **base_status, "resolver_found": False, "ready": False, } proc = await asyncio.create_subprocess_exec( sys.executable or "python3", str(resolved), "--check-only", "--json", "--cache-dir", str(IG_TOOLCHAIN_CACHE_DIR), cwd=str(resolved.parent), env=_augmented_subprocess_env(), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) try: stdout_bytes, stderr_bytes = await asyncio.wait_for(proc.communicate(), timeout=15) except asyncio.TimeoutError: proc.kill() await proc.wait() return {**base_status, "resolver_found": True, "ready": False, "error": "检查工具链状态超时"} stdout_text = (stdout_bytes or b"").decode("utf-8", errors="replace").strip() try: info = json.loads(stdout_text) if stdout_text else {} except json.JSONDecodeError: err = (stderr_bytes or b"").decode("utf-8", errors="replace").strip() return {**base_status, "resolver_found": True, "ready": False, "error": err or stdout_text} return {**info, **base_status, "resolver_found": True} async def run_scheduled_toolchain_check() -> Optional[dict]: """供每日午夜定时巡检调用;未配置 Readoor 源码目录时安静跳过。""" resolver = await asyncio.to_thread(discover_toolchain_resolver) if resolver is None: logger.info("每日工具链巡检跳过:尚未发现 iOSGuard 工具链解析器") return None return await ensure_toolchain(resolver, force_rebuild=False, notify_on_event=True) async def midnight_toolchain_scheduler() -> None: """后台无限循环:每天本地时间 00:00(可配)跑一次 Xcode/opt 工具链巡检与自愈。""" while True: wait_seconds = seconds_until_next_run( datetime.now(), IG_TOOLCHAIN_DAILY_HOUR, IG_TOOLCHAIN_DAILY_MINUTE ) logger.info( "工具链每日巡检已调度:将在 %.0f 秒后(%02d:%02d)执行下一次检查", wait_seconds, IG_TOOLCHAIN_DAILY_HOUR % 24, IG_TOOLCHAIN_DAILY_MINUTE % 60, ) await asyncio.sleep(wait_seconds) try: res = await run_scheduled_toolchain_check() if res is not None: logger.info( "每日工具链巡检完成: mode=%s key=%s", res.get("source_mode"), res.get("key"), ) except asyncio.CancelledError: raise except Exception as exc: logger.exception("每日工具链巡检执行异常: %s", exc)