feat: 接入 iOSGuard LLVM 混淆工具链与 IPA 加固门禁,按分支策略兼容旧版本打包
- 新增 toolchain_manager:构建前自愈校验 LLVM opt 工具链,按 Xcode 版本与渠道隔离 obj_cache - readoor31/readoor31OtherPay Archive 透传 IG_DIST_CHANNEL/IG_OBF_MODE/IG_ALL_GUARD_OFF/IG_RELEASE_SEED - Archive 前核对分发渠道编译条件:上架包缺失 IG_APPSTORE_DISTRIBUTION 即阻断,非上架包带该条件仅告警,未接入 anti_tamper 的分支跳过 - 导出后执行 IPA 加固门禁审计,失败阻断上传;持久化 dSYM、混淆映射、诊断事件码与审计报告 - 混淆是否执行改由分支 AutoPacking/build_policy.json 声明:force_obfuscation=true 强制,否则按任务勾选,兼容旧分支/旧 Tag;恢复打包页混淆勾选框 - 分支未自带混淆脚本时回退服务端脚本并告警;同步更新服务端 L1 混淆脚本 - .gitignore 忽略 iosguard_cache 与 artifacts 运行时目录;README 补充分支打包策略说明
This commit is contained in:
@@ -6,15 +6,21 @@ import plistlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
from typing import List, Optional
|
||||
|
||||
from ..config import (
|
||||
ARTIFACTS_DIR,
|
||||
BUILD_BASE_DIR,
|
||||
DEFAULT_BUILD_DIR_RETENTION_HOURS,
|
||||
DEFAULT_IG_OBF_MODE,
|
||||
BUILD_TIMEOUT_HOURS,
|
||||
IG_CACHE_DIR,
|
||||
IG_TOOLCHAIN_CACHE_DIR,
|
||||
SKINS_DIR,
|
||||
AUTOMATION_DIR,
|
||||
get_git_remote_url,
|
||||
@@ -25,6 +31,7 @@ from .log_streamer import log_streamer
|
||||
from .distribution import DistributionError, publish_dsym, publish_ipa
|
||||
from .notification import NotificationError, merge_project_at_mobiles, send_dingtalk_notification
|
||||
from .project_patcher import ProjectPatchError, apply_project_config
|
||||
from .toolchain_manager import ensure_toolchain
|
||||
|
||||
|
||||
class BuildError(Exception):
|
||||
@@ -280,6 +287,9 @@ def _cleanup_superseded_tasks(db):
|
||||
log_path.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
task_artifacts_dir = ARTIFACTS_DIR / task.id
|
||||
if task_artifacts_dir.exists():
|
||||
shutil.rmtree(task_artifacts_dir, ignore_errors=True)
|
||||
db.delete(task)
|
||||
if tasks:
|
||||
db.commit()
|
||||
@@ -478,7 +488,7 @@ async def run_build_task(task_id: str):
|
||||
try:
|
||||
timeout_seconds = BUILD_TIMEOUT_HOURS * 3600
|
||||
|
||||
async def _do_build():
|
||||
async def _prepare_until_obfuscation():
|
||||
nonlocal build_dir
|
||||
# 1. 串行准备源码快照;后续步骤在任务独立目录中并行执行。
|
||||
await asyncio.to_thread(_db_update, db, task, current_step="source_prepare")
|
||||
@@ -486,6 +496,13 @@ async def run_build_task(task_id: str):
|
||||
build_dir, source_commit = await prepare_source_snapshot(task_id, task)
|
||||
await asyncio.to_thread(_db_update, db, task, build_dir=str(build_dir))
|
||||
|
||||
# 1.5 按分支自身声明决定是否混淆:分支 build_policy.json 声明强制时必混淆,
|
||||
# 否则沿用任务勾选(兼容旧分支/旧 Tag)。先于生成配置写回,保证 ENABLE_OBFUSCATION 与实际一致。
|
||||
run_obf, obf_reason = _resolve_obfuscation_decision(build_dir, definition, task)
|
||||
await log_streamer.emit(task_id, f"代码混淆: {'启用' if run_obf else '不启用'}({obf_reason})")
|
||||
if bool(task.obfuscation) != run_obf:
|
||||
await asyncio.to_thread(_db_update, db, task, obfuscation=run_obf)
|
||||
|
||||
# 2. 生成配置
|
||||
await asyncio.to_thread(_db_update, db, task, current_step="config")
|
||||
config_data = await generate_config(task_id, task, build_dir)
|
||||
@@ -503,26 +520,43 @@ async def run_build_task(task_id: str):
|
||||
await asyncio.to_thread(_db_update, db, task, current_step="pod_install")
|
||||
await run_pod_install(task_id, build_dir, definition["xcode"])
|
||||
|
||||
# 4. 代码混淆(可选)
|
||||
if task.obfuscation:
|
||||
# 4. 代码混淆(是否执行已在 1.5 按分支策略/任务勾选确定)
|
||||
if run_obf:
|
||||
await asyncio.to_thread(_db_update, db, task, current_step="obfuscation")
|
||||
await run_obfuscation(task_id, task, config_data, build_dir)
|
||||
|
||||
return definition, config_data
|
||||
|
||||
definition, config_data = await asyncio.wait_for(_prepare_until_obfuscation(), timeout=timeout_seconds)
|
||||
|
||||
# 4.5 校验并按需自愈 LLVM opt 工具链(独立于构建超时预算)
|
||||
await asyncio.to_thread(_db_update, db, task, current_step="toolchain_prepare")
|
||||
prepared_env = await _prepare_iosguard_build_env(task_id, config_data, build_dir)
|
||||
|
||||
async def _build_and_upload():
|
||||
# 5. 构建项目
|
||||
await asyncio.to_thread(_db_update, db, task, current_step="build")
|
||||
ipa_path = await build_project(task_id, task, config_data, build_dir, definition["xcode"])
|
||||
ipa_path = await build_project(
|
||||
task_id, task, config_data, build_dir, definition["xcode"], prepared_env=prepared_env
|
||||
)
|
||||
|
||||
# 查找 dSYM
|
||||
# 查找并持久化 dSYM、混淆映射、事件码与混淆审计到 DATA_DIR/artifacts/<task_id>,防止 _cleanup_build_dir 删除
|
||||
dsym_path = await find_dsym(task_id, build_dir, config_data.get("SCHEME", ""))
|
||||
|
||||
# 查找混淆映射表
|
||||
obf_maps_path = build_dir / "obfuscation_maps"
|
||||
persisted_dsym_path, persisted_maps_path = await asyncio.to_thread(
|
||||
persist_task_artifacts,
|
||||
task_id,
|
||||
build_dir,
|
||||
config_data.get("SCHEME", ""),
|
||||
dsym_path,
|
||||
)
|
||||
if persisted_dsym_path is not None:
|
||||
dsym_path = persisted_dsym_path
|
||||
|
||||
update_fields = {"ipa_path": str(ipa_path)}
|
||||
if dsym_path:
|
||||
update_fields["dsym_path"] = str(dsym_path)
|
||||
if obf_maps_path.exists():
|
||||
update_fields["obfuscation_maps_path"] = str(obf_maps_path)
|
||||
if persisted_maps_path:
|
||||
update_fields["obfuscation_maps_path"] = str(persisted_maps_path)
|
||||
await asyncio.to_thread(_db_update, db, task, **update_fields)
|
||||
|
||||
# 6. 上传产物:Ad Hoc 发布安装页,App Store 上传 IPA 供下载提交。
|
||||
@@ -577,8 +611,8 @@ async def run_build_task(task_id: str):
|
||||
except NotificationError as exc:
|
||||
await log_streamer.emit(task_id, f"钉钉通知未发送: {exc}", level="warn")
|
||||
|
||||
# 带超时执行打包
|
||||
await asyncio.wait_for(_do_build(), timeout=timeout_seconds)
|
||||
# 带超时执行编译构建与上传
|
||||
await asyncio.wait_for(_build_and_upload(), timeout=timeout_seconds)
|
||||
|
||||
# 保存打包日志
|
||||
if build_dir and build_dir.exists():
|
||||
@@ -921,15 +955,73 @@ async def run_pod_install(task_id: str, build_dir: Path, xcode: dict = None):
|
||||
await log_streamer.emit(task_id, "依赖安装完成")
|
||||
|
||||
|
||||
BRANCH_BUILD_POLICY = Path("AutoPacking") / "build_policy.json"
|
||||
|
||||
|
||||
def _load_branch_build_policy(build_dir: Path) -> dict:
|
||||
"""读取源码快照自带的打包策略 AutoPacking/build_policy.json。
|
||||
|
||||
策略随分支代码提交,由分支声明自身的打包契约;文件缺失、解析失败或非对象时返回空字典,
|
||||
即按旧分支处理(行为与引入该文件前一致)。
|
||||
"""
|
||||
policy_file = build_dir / BRANCH_BUILD_POLICY
|
||||
if not policy_file.is_file():
|
||||
return {}
|
||||
try:
|
||||
data = json.loads(policy_file.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def _resolve_obfuscation_decision(build_dir: Path, definition: dict, task) -> tuple:
|
||||
"""决定本次是否执行 L1 混淆,返回 (是否混淆, 原因)。
|
||||
|
||||
- 项目不支持混淆:始终不混淆;
|
||||
- 分支 build_policy.json 显式声明 "force_obfuscation": true:强制混淆,忽略任务勾选;
|
||||
- 其余(含所有旧分支/旧 Tag):沿用任务勾选。
|
||||
不按混淆脚本是否存在推断:2.195.0 起的旧 Tag 已带脚本,但当时混淆为可选。
|
||||
"""
|
||||
if not definition.get("obfuscation"):
|
||||
return False, "项目不支持代码混淆"
|
||||
policy = _load_branch_build_policy(build_dir)
|
||||
if policy.get("force_obfuscation") is True:
|
||||
return True, f"分支 {BRANCH_BUILD_POLICY} 声明强制混淆"
|
||||
if (build_dir / BRANCH_BUILD_POLICY).is_file() and not policy:
|
||||
return bool(task.obfuscation), f"分支 {BRANCH_BUILD_POLICY} 无法解析,按任务勾选"
|
||||
return bool(task.obfuscation), "分支未声明强制混淆,按任务勾选"
|
||||
|
||||
|
||||
def _resolve_obfuscation_dir(build_dir: Path) -> Path:
|
||||
"""优先使用源码分支自带的 AutoPacking/obfuscation(如 feat/llvm-obf-m0),旧分支回退服务端内置脚本。"""
|
||||
branch_dir = build_dir / "AutoPacking" / "obfuscation"
|
||||
if (
|
||||
(branch_dir / "obfuscate_symbols.py").is_file()
|
||||
and (branch_dir / "scripts" / "obfuscation_self_check.sh").is_file()
|
||||
):
|
||||
return branch_dir
|
||||
return AUTOMATION_DIR / "obfuscation"
|
||||
|
||||
|
||||
async def run_obfuscation(task_id: str, task, config_data: dict, build_dir: Path):
|
||||
"""执行代码混淆"""
|
||||
await log_streamer.emit_step(task_id, "代码混淆")
|
||||
|
||||
obf_root = _resolve_obfuscation_dir(build_dir)
|
||||
await log_streamer.emit(task_id, f"L1 混淆脚本目录: {obf_root}")
|
||||
if obf_root == AUTOMATION_DIR / "obfuscation":
|
||||
await log_streamer.emit_warning(
|
||||
task_id,
|
||||
"分支未自带混淆脚本,改用服务端内置脚本混淆;该脚本面向新版代码,旧版本若混淆失败可取消勾选混淆后重打",
|
||||
)
|
||||
|
||||
env = os.environ.copy()
|
||||
env["TARGET_NAME"] = config_data.get("SCHEME", "")
|
||||
env["SKIP_OBF_PHASE"] = "1"
|
||||
seed = os.environ.get("IG_RELEASE_SEED") or config_data.get("IG_RELEASE_SEED") or f"{task_id}_{config_data.get('BUILD_VERSION', '0')}"
|
||||
env["OBF_SALT"] = seed
|
||||
# 自检
|
||||
self_check_script = AUTOMATION_DIR / "obfuscation" / "scripts" / "obfuscation_self_check.sh"
|
||||
self_check_script = obf_root / "scripts" / "obfuscation_self_check.sh"
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
"bash", str(self_check_script), str(build_dir),
|
||||
cwd=str(build_dir),
|
||||
@@ -951,9 +1043,9 @@ async def run_obfuscation(task_id: str, task, config_data: dict, build_dir: Path
|
||||
await log_streamer.emit(task_id, "混淆自检通过")
|
||||
|
||||
# 执行混淆
|
||||
obfuscate_script = AUTOMATION_DIR / "obfuscation" / "obfuscate_symbols.py"
|
||||
obfuscate_script = obf_root / "obfuscate_symbols.py"
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
"python3", str(obfuscate_script), "--archive-mode",
|
||||
"python3", str(obfuscate_script), "--archive-mode", "--salt", seed,
|
||||
cwd=str(build_dir),
|
||||
env=env,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
@@ -973,7 +1065,307 @@ async def run_obfuscation(task_id: str, task, config_data: dict, build_dir: Path
|
||||
await log_streamer.emit(task_id, "代码混淆完成")
|
||||
|
||||
|
||||
async def build_project(task_id: str, task, config_data: dict, build_dir: Path, xcode: dict = None) -> Path:
|
||||
def _prune_old_obj_caches(obj_cache_root: Path, current_ver_dir: str, keep: int = 3) -> None:
|
||||
if not obj_cache_root.is_dir():
|
||||
return
|
||||
keep_n = max(1, int(keep))
|
||||
others = [
|
||||
d for d in obj_cache_root.iterdir()
|
||||
if d.is_dir() and d.name != current_ver_dir
|
||||
]
|
||||
others.sort(key=lambda d: d.stat().st_mtime_ns, reverse=True)
|
||||
for stale in others[max(0, keep_n - 1):]:
|
||||
shutil.rmtree(stale, ignore_errors=True)
|
||||
|
||||
|
||||
async def _prepare_iosguard_build_env(task_id: str, config_data: dict, build_dir: Path) -> dict:
|
||||
"""注入 iOSGuard LLVM IR/Route 2 模式、分渠道与版本隔离的缓存,并在构建前自愈校验 `opt` 工具链。"""
|
||||
env = os.environ.copy()
|
||||
env["SKIP_OBF_PHASE"] = "1"
|
||||
|
||||
dist_channel = "appstore" if config_data.get("BUILD_TYPE") == "App_Store" else "dev"
|
||||
all_off = "1" if os.environ.get("IG_ALL_GUARD_OFF") == "1" else "0"
|
||||
raw_mode = (os.environ.get("IG_OBF_MODE") or config_data.get("IG_OBF_MODE") or DEFAULT_IG_OBF_MODE).strip() or "full"
|
||||
effective_mode = "off" if all_off == "1" else raw_mode
|
||||
seed = os.environ.get("IG_RELEASE_SEED") or config_data.get("IG_RELEASE_SEED") or f"{task_id}_{config_data.get('BUILD_VERSION', '0')}"
|
||||
|
||||
obj_cache_override = os.environ.get("IG_OBF_OBJ_CACHE_DIR", "").strip()
|
||||
sdk_cache_dir = Path(os.environ.get("IG_SDK_CACHE_DIR") or (IG_CACHE_DIR / "sdk_cache"))
|
||||
sdk_cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
env["IG_DIST_CHANNEL"] = dist_channel
|
||||
env["IG_OBF_MODE"] = effective_mode
|
||||
env["IG_ALL_GUARD_OFF"] = all_off
|
||||
env["IG_RELEASE_SEED"] = seed
|
||||
env["IG_TOOLCHAIN_CACHE_DIR"] = str(IG_TOOLCHAIN_CACHE_DIR)
|
||||
env["IG_SDK_CACHE_DIR"] = str(sdk_cache_dir)
|
||||
|
||||
resolver_path = build_dir / "iOSGuardIntegration" / "toolchain" / "tools" / "llvm_obf" / "ig_toolchain_resolver.py"
|
||||
if not resolver_path.is_file():
|
||||
default_obj_dir = Path(obj_cache_override) if obj_cache_override else (IG_CACHE_DIR / "obj_cache" / f"default-{dist_channel}")
|
||||
default_obj_dir.mkdir(parents=True, exist_ok=True)
|
||||
env["IG_OBF_OBJ_CACHE_DIR"] = str(default_obj_dir)
|
||||
return env
|
||||
|
||||
if all_off == "1" or effective_mode == "off":
|
||||
default_obj_dir = Path(obj_cache_override) if obj_cache_override else (IG_CACHE_DIR / "obj_cache")
|
||||
default_obj_dir.mkdir(parents=True, exist_ok=True)
|
||||
env["IG_OBF_OBJ_CACHE_DIR"] = str(default_obj_dir)
|
||||
await log_streamer.emit(
|
||||
task_id,
|
||||
f"iOSGuard IR 混淆已显式关闭,跳过 opt 校验(IG_OBF_MODE={effective_mode}, IG_ALL_GUARD_OFF={all_off})",
|
||||
)
|
||||
return env
|
||||
|
||||
await log_streamer.emit_step(task_id, "检查工具链")
|
||||
env["IG_REQUIRE_LLVM_OBF"] = "1"
|
||||
try:
|
||||
tc_info = await ensure_toolchain(resolver_path, task_id=task_id, notify_on_event=True)
|
||||
except Exception as exc:
|
||||
raise BuildError(f"LLVM IR 混淆工具链校验失败(IG_REQUIRE_LLVM_OBF=1): {exc}", category="config") from exc
|
||||
|
||||
if obj_cache_override:
|
||||
obj_cache_dir = Path(obj_cache_override)
|
||||
else:
|
||||
xc_build = ((tc_info or {}).get("xcode") or {}).get("xcode_build") or "unknown"
|
||||
passes_h8 = ((tc_info or {}).get("passes_hash") or "legacy")[:8]
|
||||
obj_cache_dir = IG_CACHE_DIR / "obj_cache" / f"{xc_build}-{passes_h8}" / dist_channel
|
||||
await asyncio.to_thread(_prune_old_obj_caches, IG_CACHE_DIR / "obj_cache", obj_cache_dir.parent.name, 3)
|
||||
obj_cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
env["IG_OBF_OBJ_CACHE_DIR"] = str(obj_cache_dir)
|
||||
|
||||
await log_streamer.emit(
|
||||
task_id,
|
||||
f"iOSGuard 发布模式: IG_OBF_MODE={effective_mode}, IG_DIST_CHANNEL={dist_channel}, "
|
||||
f"opt={tc_info.get('source_mode', 'ready')}, seed={seed}, obj_cache={obj_cache_dir}",
|
||||
)
|
||||
return env
|
||||
|
||||
|
||||
def persist_task_artifacts(
|
||||
task_id: str,
|
||||
build_dir: Path,
|
||||
scheme: str = "",
|
||||
dsym_path: Path = None,
|
||||
) -> tuple:
|
||||
"""将 dSYM、符号/方法映射、诊断事件码与混淆审计持久化到 ARTIFACTS_DIR/<task_id>,脱离 build_dir 生命周期。"""
|
||||
artifact_root = ARTIFACTS_DIR / task_id
|
||||
persisted_dsym = None
|
||||
persisted_maps = None
|
||||
|
||||
archive_dsyms_dir = build_dir / "build" / f"{scheme}.xcarchive" / "dSYMs" if scheme else None
|
||||
dsym_bundles = sorted(archive_dsyms_dir.glob("*.dSYM")) if archive_dsyms_dir and archive_dsyms_dir.is_dir() else []
|
||||
|
||||
if dsym_bundles:
|
||||
dsym_dest_dir = artifact_root / f"{scheme or 'app'}_dSYMs"
|
||||
dsym_dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
for bundle in dsym_bundles:
|
||||
dst = dsym_dest_dir / bundle.name
|
||||
if dst.exists():
|
||||
shutil.rmtree(dst, ignore_errors=True)
|
||||
shutil.copytree(bundle, dst, symlinks=True)
|
||||
persisted_dsym = dsym_dest_dir
|
||||
elif dsym_path and Path(dsym_path).exists():
|
||||
src = Path(dsym_path)
|
||||
artifact_root.mkdir(parents=True, exist_ok=True)
|
||||
dst = artifact_root / src.name
|
||||
if src.is_dir():
|
||||
if dst.exists():
|
||||
shutil.rmtree(dst, ignore_errors=True)
|
||||
shutil.copytree(src, dst, symlinks=True)
|
||||
else:
|
||||
shutil.copy2(src, dst)
|
||||
persisted_dsym = dst
|
||||
|
||||
maps_dest_dir = artifact_root / "obfuscation_maps"
|
||||
copied_any = False
|
||||
|
||||
src_maps_dir = build_dir / "obfuscation_maps"
|
||||
if src_maps_dir.is_dir():
|
||||
for item in sorted(src_maps_dir.glob("*.json")):
|
||||
if item.is_file():
|
||||
maps_dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(item, maps_dest_dir / item.name)
|
||||
copied_any = True
|
||||
|
||||
unmapped_file = build_dir / "unmapped_mappings.json"
|
||||
if unmapped_file.is_file():
|
||||
maps_dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(unmapped_file, maps_dest_dir / unmapped_file.name)
|
||||
copied_any = True
|
||||
|
||||
diag_events = build_dir / "iOSGuardIntegration" / "toolchain" / "config" / "ig_diag_events.json"
|
||||
if diag_events.is_file():
|
||||
maps_dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(diag_events, maps_dest_dir / "ig_diag_events.json")
|
||||
copied_any = True
|
||||
|
||||
derived_data = build_dir / "build" / "derived_data"
|
||||
if derived_data.is_dir():
|
||||
audits = sorted(derived_data.rglob("ig_obfuscation_audit.json"))
|
||||
if audits:
|
||||
chosen = next((a for a in audits if scheme and f"{scheme}.build" in str(a)), audits[0])
|
||||
maps_dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(chosen, maps_dest_dir / "ig_obfuscation_audit.json")
|
||||
copied_any = True
|
||||
|
||||
ipa_audit_report = build_dir / "build" / "ipa_audit_report.json"
|
||||
if ipa_audit_report.is_file():
|
||||
maps_dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(ipa_audit_report, maps_dest_dir / "ipa_audit_report.json")
|
||||
copied_any = True
|
||||
|
||||
if copied_any:
|
||||
persisted_maps = maps_dest_dir
|
||||
|
||||
return persisted_dsym, persisted_maps
|
||||
|
||||
|
||||
async def _run_exported_ipa_audit(
|
||||
task_id: str,
|
||||
audit_script: Path,
|
||||
ipa_path: Path,
|
||||
archive_path: Path,
|
||||
export_path: Path,
|
||||
config_data: dict,
|
||||
build_dir: Path,
|
||||
build_env: dict,
|
||||
) -> None:
|
||||
"""导出后执行完整 IPA 加固门禁审计(Route 2 + StaticHygieneGate + Mach-O 门禁),不通过直接阻断上传。"""
|
||||
scheme = config_data.get("SCHEME", "")
|
||||
cmd = [
|
||||
sys.executable or "python3",
|
||||
str(audit_script),
|
||||
str(ipa_path),
|
||||
"--archive",
|
||||
str(archive_path),
|
||||
"--report-out",
|
||||
str(export_path / "ipa_audit_report.json"),
|
||||
]
|
||||
if config_data.get("BUNDLE_ID"):
|
||||
cmd.extend(["--bundle-id", config_data["BUNDLE_ID"]])
|
||||
|
||||
derived_data = export_path / "derived_data"
|
||||
if derived_data.is_dir():
|
||||
audits = sorted(derived_data.rglob("ig_obfuscation_audit.json"))
|
||||
if audits:
|
||||
chosen = next((a for a in audits if scheme and f"{scheme}.build" in str(a)), audits[0])
|
||||
cmd.extend(["--audit-json", str(chosen)])
|
||||
|
||||
maps_dir = build_dir / "obfuscation_maps"
|
||||
if maps_dir.is_dir():
|
||||
sym_maps = sorted(maps_dir.glob("symbol_map_*.json"))
|
||||
if sym_maps:
|
||||
exact = [m for m in sym_maps if scheme and f"_{scheme}_" in m.name]
|
||||
chosen_sym = (exact or sym_maps)[-1]
|
||||
cmd.extend(["--symbol-map", str(chosen_sym)])
|
||||
|
||||
await log_streamer.emit(task_id, "开始 IPA 加固门禁审计...")
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
*cmd,
|
||||
cwd=str(build_dir),
|
||||
env=build_env,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.STDOUT,
|
||||
)
|
||||
audit_output = []
|
||||
async for line in process.stdout:
|
||||
decoded = line.decode("utf-8", errors="replace").strip()
|
||||
if decoded:
|
||||
audit_output.append(decoded)
|
||||
await log_streamer.emit(task_id, decoded)
|
||||
await process.wait()
|
||||
if process.returncode != 0:
|
||||
raise BuildError(
|
||||
"IPA 加固门禁审计失败,已阻止上传",
|
||||
category="build",
|
||||
detail="\n".join(audit_output[-25:]),
|
||||
)
|
||||
|
||||
|
||||
IG_APPSTORE_FLAG = "IG_APPSTORE_DISTRIBUTION"
|
||||
IG_ANTI_TAMPER_SOURCE = "IGAntiTamper.c"
|
||||
|
||||
|
||||
async def _verify_dist_channel_flag(
|
||||
task_id: str,
|
||||
container_args: tuple,
|
||||
scheme: str,
|
||||
build_dir: Path,
|
||||
build_env: dict,
|
||||
) -> None:
|
||||
"""Archive 前核对分发渠道编译条件,确保 500/501 防砸壳/重签名校验与渠道一致。
|
||||
|
||||
App 工程不再在 Release 写死 IG_APPSTORE_DISTRIBUTION,唯一来源是本服务透传的
|
||||
IG_DIST_CHANNEL=appstore。上架包缺失该条件 → 防砸壳/重签名检测整体失效,必须阻断;
|
||||
非上架包带上该条件(旧分支仍写死)→ Ad-hoc 包会被误判 500/501 而锁定敏感入口,仅告警不阻断。
|
||||
未接入 anti_tamper 的历史分支直接跳过。
|
||||
"""
|
||||
project_file = build_dir / "readoor.xcodeproj" / "project.pbxproj"
|
||||
if not project_file.is_file():
|
||||
return
|
||||
if IG_ANTI_TAMPER_SOURCE not in project_file.read_text(encoding="utf-8", errors="replace"):
|
||||
return
|
||||
|
||||
channel = build_env.get("IG_DIST_CHANNEL", "dev")
|
||||
cmd = [
|
||||
"xcodebuild", "-showBuildSettings",
|
||||
*container_args,
|
||||
"-scheme", scheme,
|
||||
"-configuration", "Release",
|
||||
"-sdk", "iphoneos",
|
||||
f"IG_DIST_CHANNEL={channel}",
|
||||
f"IG_ALL_GUARD_OFF={build_env.get('IG_ALL_GUARD_OFF', '0')}",
|
||||
]
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
*cmd,
|
||||
cwd=str(build_dir),
|
||||
env=build_env,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.STDOUT,
|
||||
)
|
||||
flag_lines = []
|
||||
tail = []
|
||||
async for line in process.stdout:
|
||||
decoded = line.decode("utf-8", errors="replace").strip()
|
||||
if not decoded:
|
||||
continue
|
||||
tail = (tail + [decoded])[-20:]
|
||||
if decoded.startswith(("OTHER_SWIFT_FLAGS =", "SWIFT_ACTIVE_COMPILATION_CONDITIONS =")) \
|
||||
and any(tok in (IG_APPSTORE_FLAG, f"-D{IG_APPSTORE_FLAG}") for tok in decoded.split()):
|
||||
flag_lines.append(decoded)
|
||||
await process.wait()
|
||||
|
||||
if channel == "appstore":
|
||||
if process.returncode != 0:
|
||||
raise BuildError(
|
||||
f"上架包分发渠道编译条件核对失败(xcodebuild -showBuildSettings 退出码 {process.returncode})",
|
||||
category="config",
|
||||
detail="\n".join(tail),
|
||||
)
|
||||
if not flag_lines:
|
||||
raise BuildError(
|
||||
f"上架包未注入 {IG_APPSTORE_FLAG}(IG_DIST_CHANNEL=appstore 未生效),"
|
||||
"防砸壳/重签名检测将失效,已阻止 Archive",
|
||||
category="config",
|
||||
)
|
||||
await log_streamer.emit(task_id, f"分发渠道核对通过:上架包已注入 {IG_APPSTORE_FLAG}")
|
||||
elif flag_lines:
|
||||
await log_streamer.emit_warning(
|
||||
task_id,
|
||||
f"非上架包仍带 {IG_APPSTORE_FLAG}(分支工程可能仍在 Release 写死该条件),"
|
||||
"安装后可能因 500/501 被锁定登录/支付并延迟退出,请升级分支工程配置",
|
||||
)
|
||||
|
||||
|
||||
async def build_project(
|
||||
task_id: str,
|
||||
task,
|
||||
config_data: dict,
|
||||
build_dir: Path,
|
||||
xcode: dict = None,
|
||||
prepared_env: Optional[dict] = None,
|
||||
) -> Path:
|
||||
"""构建项目;xcode 为项目定义中的 {workspace, project},优先使用 workspace"""
|
||||
await log_streamer.emit_step(task_id, "构建项目")
|
||||
|
||||
@@ -998,8 +1390,12 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path,
|
||||
if str(relative) in project_text and not (build_dir / relative).is_file():
|
||||
raise BuildError(f"源码快照缺少工程引用的脚本:{relative}", category="config")
|
||||
|
||||
build_env = prepared_env if prepared_env is not None else await _prepare_iosguard_build_env(task_id, config_data, build_dir)
|
||||
export_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if scheme in ("readoor31", "readoor31OtherPay"):
|
||||
await _verify_dist_channel_flag(task_id, container_args, scheme, build_dir, build_env)
|
||||
|
||||
# 清理
|
||||
await log_streamer.emit(task_id, "清理项目...")
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
@@ -1009,6 +1405,7 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path,
|
||||
"-configuration", "Release",
|
||||
"-derivedDataPath", str(export_path / "derived_data"),
|
||||
cwd=str(build_dir),
|
||||
env=build_env,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.STDOUT,
|
||||
)
|
||||
@@ -1020,8 +1417,9 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path,
|
||||
|
||||
# Archive
|
||||
await log_streamer.emit(task_id, "开始 Archive...")
|
||||
archive_started_at = time.monotonic()
|
||||
archive_output = []
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
archive_cmd = [
|
||||
"xcodebuild", "archive",
|
||||
*container_args,
|
||||
"-scheme", scheme,
|
||||
@@ -1029,7 +1427,18 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path,
|
||||
"-archivePath", str(archive_path),
|
||||
"-derivedDataPath", str(export_path / "derived_data"),
|
||||
"-destination", "generic/platform=ios",
|
||||
]
|
||||
if scheme in ("readoor31", "readoor31OtherPay"):
|
||||
archive_cmd.extend([
|
||||
f"IG_DIST_CHANNEL={build_env['IG_DIST_CHANNEL']}",
|
||||
f"IG_OBF_MODE={build_env['IG_OBF_MODE']}",
|
||||
f"IG_ALL_GUARD_OFF={build_env['IG_ALL_GUARD_OFF']}",
|
||||
f"IG_RELEASE_SEED={build_env['IG_RELEASE_SEED']}",
|
||||
])
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
*archive_cmd,
|
||||
cwd=str(build_dir),
|
||||
env=build_env,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.STDOUT,
|
||||
)
|
||||
@@ -1039,10 +1448,12 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path,
|
||||
archive_output.append(decoded)
|
||||
await log_streamer.emit(task_id, decoded)
|
||||
await process.wait()
|
||||
archive_elapsed = time.monotonic() - archive_started_at
|
||||
|
||||
if process.returncode != 0:
|
||||
category, hint = _classify_build_error(archive_output, "archive")
|
||||
raise BuildError(hint, category=category, detail="\n".join(archive_output[-20:]))
|
||||
await log_streamer.emit(task_id, f"Archive 构建完成,耗时: {archive_elapsed:.1f}s")
|
||||
|
||||
# 导出 IPA
|
||||
await log_streamer.emit(task_id, "导出 IPA...")
|
||||
@@ -1054,6 +1465,7 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path,
|
||||
"-exportPath", str(export_path),
|
||||
"-exportOptionsPlist", str(export_plist),
|
||||
cwd=str(build_dir),
|
||||
env=build_env,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.STDOUT,
|
||||
)
|
||||
@@ -1075,11 +1487,47 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path,
|
||||
|
||||
ipa_path = ipa_files[0]
|
||||
await log_streamer.emit(task_id, f"IPA 已导出: {ipa_path.name}")
|
||||
|
||||
if (
|
||||
scheme in ("readoor31", "readoor31OtherPay")
|
||||
and build_env.get("IG_ALL_GUARD_OFF") != "1"
|
||||
and build_env.get("IG_OBF_MODE") != "off"
|
||||
):
|
||||
audit_script = (
|
||||
build_dir
|
||||
/ "iOSGuardIntegration"
|
||||
/ "toolchain"
|
||||
/ "tools"
|
||||
/ "xcode_archive"
|
||||
/ "audit_exported_ipa.py"
|
||||
)
|
||||
if audit_script.is_file():
|
||||
await _run_exported_ipa_audit(
|
||||
task_id,
|
||||
audit_script,
|
||||
ipa_path,
|
||||
archive_path,
|
||||
export_path,
|
||||
config_data,
|
||||
build_dir,
|
||||
build_env,
|
||||
)
|
||||
|
||||
return ipa_path
|
||||
|
||||
|
||||
async def find_dsym(task_id: str, build_dir: Path, scheme: str = "") -> Path:
|
||||
"""查找当前 target(主 App)对应的 dSYM 文件,忽略 Extension/Framework 各自的 dSYM"""
|
||||
"""优先从 .xcarchive/dSYMs 查找全部 dSYM(含主 App 与 IGArchiveGuard.framework),否则回退 derived_data。"""
|
||||
if scheme:
|
||||
archive_dsyms = build_dir / "build" / f"{scheme}.xcarchive" / "dSYMs"
|
||||
if archive_dsyms.is_dir():
|
||||
main_dsym = archive_dsyms / f"{scheme}.app.dSYM"
|
||||
if main_dsym.exists():
|
||||
return main_dsym
|
||||
bundles = sorted(archive_dsyms.glob("*.dSYM"))
|
||||
if bundles:
|
||||
return bundles[0]
|
||||
|
||||
derived_data = build_dir / "build" / "derived_data"
|
||||
if not derived_data.exists():
|
||||
return None
|
||||
|
||||
@@ -124,3 +124,44 @@ def send_dingtalk_notification(
|
||||
if result.get("errcode", 0) != 0:
|
||||
raise NotificationError(f"钉钉通知发送失败: {result.get('errmsg', '未知错误')}")
|
||||
return True
|
||||
|
||||
|
||||
def send_toolchain_dingtalk_alert(
|
||||
dingtalk_config: dict,
|
||||
title: str,
|
||||
lines: list[str],
|
||||
) -> bool:
|
||||
"""发送 Xcode/opt 工具链状态通知(标题和正文必须保留「打包」关键词)。"""
|
||||
if not (dingtalk_config or {}).get("enabled"):
|
||||
return False
|
||||
|
||||
webhook_url = (dingtalk_config.get("webhook_url") or "").strip()
|
||||
if not webhook_url:
|
||||
raise NotificationError("钉钉通知已启用,但未配置 Webhook URL")
|
||||
|
||||
safe_title = title if "打包" in title else f"【iOS打包服务】{title}"
|
||||
mobiles = normalize_mobiles(dingtalk_config.get("at_mobiles", []))
|
||||
body_lines = [f"## {safe_title}", "", *lines]
|
||||
if mobiles:
|
||||
body_lines.extend(["", " ".join(f"@{m}" for m in mobiles)])
|
||||
|
||||
payload = {
|
||||
"msgtype": "markdown",
|
||||
"markdown": {"title": safe_title, "text": "\n\n".join(body_lines)},
|
||||
"at": {"atMobiles": mobiles, "isAtAll": False},
|
||||
}
|
||||
response = httpx.post(
|
||||
_signed_webhook_url(webhook_url, dingtalk_config.get("secret", "")),
|
||||
json=payload,
|
||||
timeout=15,
|
||||
)
|
||||
if response.status_code // 100 != 2:
|
||||
raise NotificationError(f"钉钉通知发送失败 ({response.status_code})")
|
||||
|
||||
try:
|
||||
result = response.json()
|
||||
except ValueError as exc:
|
||||
raise NotificationError("钉钉通知返回内容无效") from exc
|
||||
if result.get("errcode", 0) != 0:
|
||||
raise NotificationError(f"钉钉通知发送失败: {result.get('errmsg', '未知错误')}")
|
||||
return True
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
"""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)
|
||||
Reference in New Issue
Block a user