runtime.py 15.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
"""启动期 / 运行期工具:崩溃诊断、日志初始化、temp 清理、系统信息。

从 image_generator.py 顶部抽出,让 main_qml.py(QML 主入口)和旧 main()
(QWidget 入口,task #19 删)共用同一套启动序列。
"""
import faulthandler
import json
import logging
import os
import platform
import sys
import tempfile
import threading
import time
import traceback
from datetime import datetime
from logging.handlers import RotatingFileHandler
from pathlib import Path


def flush_logs() -> None:
    """强制刷盘所有日志 handlers(包括 fsync 到磁盘)。

    macOS 对 UI 线程卡顿超过阈值会 SIGKILL,缓冲区未刷盘的日志会丢失,
    下次崩溃定位不到。在可疑阶段边界调用此函数保证日志落盘。
    """
    try:
        for h in logging.getLogger().handlers:
            try:
                h.flush()
                # 在普通 RotatingFileHandler 上也强制 fsync —
                # flush() 只把 Python buffer 推到 OS,fsync 才进磁盘
                stream = getattr(h, "stream", None)
                if stream and hasattr(stream, "fileno"):
                    try:
                        os.fsync(stream.fileno())
                    except (OSError, ValueError):
                        pass
            except Exception:
                pass
    except Exception:
        pass


class TieredFsyncHandler(RotatingFileHandler):
    """分级落盘的 RotatingFileHandler。

    Why: 每条 emit 都 fsync 是大锤打蚊子(性能浪费);完全不 fsync 则 macOS
    SIGKILL / 系统崩溃时丢日志。诊断价值越高的日志,落盘保障越严:

    - WARNING 及以上:emit 即 fsync(一条不丢,logger.exception 必然到磁盘)
    - INFO 及以下:走默认 buffered 写入(零开销,性能优先)

    搭配后台 _periodic_fsync_loop daemon 线程,普通日志最坏丢 1s。
    """
    def emit(self, record):
        super().emit(record)
        if record.levelno >= logging.WARNING:
            try:
                if self.stream:
                    self.stream.flush()
                    os.fsync(self.stream.fileno())
            except Exception:
                pass


_fsync_thread_started = False


def start_periodic_fsync(interval_seconds: float = 1.0) -> None:
    """启动后台周期 fsync daemon 线程,确保 INFO 级别日志最坏丢 1s。

    幂等:重复调用只启动一次。daemon=True 进程退出自动结束。
    """
    global _fsync_thread_started
    if _fsync_thread_started:
        return
    _fsync_thread_started = True

    def _loop():
        while True:
            time.sleep(interval_seconds)
            try:
                for h in logging.getLogger().handlers:
                    stream = getattr(h, "stream", None)
                    if stream and hasattr(stream, "fileno"):
                        try:
                            h.flush()
                            os.fsync(stream.fileno())
                        except Exception:
                            pass
            except Exception:
                pass

    threading.Thread(target=_loop, daemon=True, name="log-fsync-loop").start()


def cleanup_clipboard_tempfiles(max_age_hours: int = 24) -> int:
    """清理遗留的剪贴板临时文件,防止长时间运行累积到磁盘/句柄上限。

    仅删除 {tempdir}/nano_banana_app/clipboard_*.png / _clipboard_tmp.png 中
    超过 max_age_hours 小时的文件。返回删除数量。
    """
    try:
        import time
        temp_dir = Path(tempfile.gettempdir()) / "nano_banana_app"
        if not temp_dir.exists():
            return 0
        cutoff = time.time() - max_age_hours * 3600
        removed = 0
        for p in temp_dir.iterdir():
            try:
                if not p.is_file():
                    continue
                name = p.name
                if not (name.startswith("clipboard_") or name == "_clipboard_tmp.png"):
                    continue
                if p.stat().st_mtime < cutoff:
                    p.unlink()
                    removed += 1
            except Exception:
                pass
        return removed
    except Exception:
        return 0


def get_crash_log_path() -> Path:
    """获取崩溃日志文件路径(尽早可用,不依赖任何初始化)"""
    system = platform.system()
    if system == "Darwin":
        p = Path.home() / "Library/Application Support/ZB100ImageGenerator"
    elif system == "Windows":
        p = Path(os.environ.get("APPDATA", str(Path.home()))) / "ZB100ImageGenerator"
    else:
        p = Path.home() / ".config/zb100imagegenerator"
    try:
        p.mkdir(parents=True, exist_ok=True)
    except Exception:
        p = Path(tempfile.gettempdir()) / "ZB100ImageGenerator"
        p.mkdir(parents=True, exist_ok=True)
    return p / "crash_log.txt"


def enable_crash_diagnostics() -> None:
    """在最早期启用崩溃诊断工具:faulthandler / 全局 excepthook / Qt msg handler。"""
    crash_log = get_crash_log_path()

    # 1. faulthandler: segfault 时自动输出 Python 调用栈到文件
    try:
        crash_fh = open(crash_log, "a", encoding="utf-8")
        crash_fh.write(f"\n{'=' * 60}\n")
        crash_fh.write(f"[STARTUP] {datetime.now().isoformat()} - faulthandler 已启用\n")
        # macOS native crash 提示:faulthandler 只能给 Python 栈;C++ 崩溃栈在系统 crash report
        if sys.platform == "darwin":
            crash_fh.write(
                "[HINT] 若启动后立刻闪退、本文件无 Python 栈,说明是 native C++ 崩溃。\n"
                "       系统 crash report 路径:\n"
                "         ~/Library/Logs/DiagnosticReports/ZB100ImageGenerator-*.ips\n"
                "         ~/Library/Logs/DiagnosticReports/ZB100ImageGenerator-*.crash\n"
                "       也可在「控制台」app → 左侧「崩溃报告」中查看。\n"
                "       上报问题请同时附 logs/app.log 和系统 crash report。\n"
            )
        crash_fh.flush()
        try:
            os.fsync(crash_fh.fileno())  # 启动期立即 fsync — 防 native 崩溃前丢这段元信息
        except Exception:
            pass
        faulthandler.enable(file=crash_fh, all_threads=True)
        # 同时输出到 stderr (仅在 stderr 真实存在时;windowed build 下跳过)
        if sys.stderr is not None:
            try:
                faulthandler.enable(file=sys.stderr, all_threads=True)
            except (RuntimeError, ValueError):
                pass
        try:
            print(f"崩溃诊断日志路径: {crash_log}")
        except Exception:
            pass
    except Exception as e:
        try:
            print(f"faulthandler 启用失败: {e}")
        except Exception:
            pass
        if sys.stderr is not None:
            try:
                faulthandler.enable()
            except (RuntimeError, ValueError):
                pass

    # 2. 全局 Python 异常钩子
    def _global_excepthook(exc_type, exc_value, exc_tb):
        msg = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
        logging.critical(f"未捕获异常:\n{msg}")
        try:
            with open(crash_log, "a", encoding="utf-8") as f:
                f.write(f"\n[UNCAUGHT EXCEPTION] {datetime.now().isoformat()}\n{msg}\n")
        except Exception:
            pass
        sys.__excepthook__(exc_type, exc_value, exc_tb)

    sys.excepthook = _global_excepthook

    # 3. 子线程未捕获异常钩子 (Python 3.8+)
    # sys.excepthook 只在主线程生效, QThread / threading.Thread 里逃出 try/except
    # 的异常默认无声丢失 (Thread._bootstrap_inner 内部吞掉, 不调用 sys.excepthook).
    # ImageGenerationWorker / audit UploadWorker / history 后台任务都需要这层兜底,
    # 否则 worker 线程崩溃时 crash_log / app.log 都看不到 Python 栈.
    def _thread_excepthook(args):
        # SystemExit 走标准库语义: 正常退出, 不当 bug
        if args.exc_type is SystemExit:
            return
        msg = "".join(traceback.format_exception(
            args.exc_type, args.exc_value, args.exc_traceback
        ))
        thread_name = args.thread.name if args.thread else "<unknown>"
        logging.critical(f"线程 [{thread_name}] 未捕获异常:\n{msg}")
        try:
            with open(crash_log, "a", encoding="utf-8") as f:
                f.write(
                    f"\n[THREAD UNCAUGHT] {datetime.now().isoformat()} "
                    f"thread={thread_name}\n{msg}\n"
                )
        except Exception:
            pass

    threading.excepthook = _thread_excepthook

    # 4. Qt 消息拦截器
    try:
        from PySide6.QtCore import qInstallMessageHandler, QtMsgType

        def _qt_message_handler(mode, context, message):
            level_map = {
                QtMsgType.QtDebugMsg: "QT_DEBUG",
                QtMsgType.QtInfoMsg: "QT_INFO",
                QtMsgType.QtWarningMsg: "QT_WARNING",
                QtMsgType.QtCriticalMsg: "QT_CRITICAL",
                QtMsgType.QtFatalMsg: "QT_FATAL",
            }
            level = level_map.get(mode, "QT_UNKNOWN")
            location = f"{context.file}:{context.line}" if context.file else "unknown"
            full_msg = f"[{level}] {location} - {message}"

            if mode in (QtMsgType.QtWarningMsg, QtMsgType.QtCriticalMsg, QtMsgType.QtFatalMsg):
                logging.warning(full_msg)
                try:
                    with open(crash_log, "a", encoding="utf-8") as f:
                        f.write(f"[{datetime.now().isoformat()}] {full_msg}\n")
                except Exception:
                    pass
            else:
                logging.debug(full_msg)

        qInstallMessageHandler(_qt_message_handler)
    except Exception as e:
        print(f"Qt 消息拦截器安装失败: {e}")


def log_system_info() -> None:
    """记录系统环境信息,用于排查兼容性问题"""
    logger = logging.getLogger(__name__)
    info_lines = [
        f"操作系统: {platform.system()} {platform.release()} ({platform.version()})",
        f"架构: {platform.machine()}",
        f"Python: {sys.version}",
        f"打包模式: {'PyInstaller' if getattr(sys, 'frozen', False) else '开发环境'}",
    ]

    try:
        import PySide6
        info_lines.append(f"PySide6: {PySide6.__version__}")
    except Exception:
        info_lines.append("PySide6: 版本获取失败")

    try:
        from PySide6.QtCore import qVersion
        info_lines.append(f"Qt: {qVersion()}")
    except Exception:
        info_lines.append("Qt: 版本获取失败")

    try:
        import PIL
        info_lines.append(f"Pillow: {PIL.__version__}")
    except Exception:
        info_lines.append("Pillow: 版本获取失败")

    try:
        from google import genai as _genai
        info_lines.append(
            f"google-genai: {_genai.__version__}" if hasattr(_genai, '__version__')
            else "google-genai: 已加载"
        )
    except Exception:
        info_lines.append("google-genai: 未安装或加载失败")

    if getattr(sys, 'frozen', False):
        info_lines.append(f"可执行路径: {sys.executable}")
        if hasattr(sys, '_MEIPASS'):
            info_lines.append(f"_MEIPASS: {sys._MEIPASS}")

    full_info = "\n  ".join(info_lines)
    logger.info(f"系统环境信息:\n  {full_info}")

    # 同时写入崩溃日志
    try:
        crash_log = get_crash_log_path()
        with open(crash_log, "a", encoding="utf-8") as f:
            f.write(f"[SYSTEM INFO] {datetime.now().isoformat()}\n  {full_info}\n")
    except Exception:
        pass


def init_logging(log_level=logging.INFO) -> bool:
    """初始化日志:智能选 logs 目录 + RotatingFileHandler + 可选 console。

    从 config.json 的 logging_config 读配置(enabled / level / log_to_console /
    max_bytes / backup_count),失败时用 INFO 级别 + 默认 5MB 滚动 + 控制台。
    成功返回 True,失败返回 False。
    """
    try:
        # 智能选择 logs 目录
        def _candidates():
            system = platform.system()
            cands = []

            if getattr(sys, 'frozen', False) and system == "Darwin":
                cands.append(Path.home() / "Library/Application Support/ZB100ImageGenerator/logs")
            elif getattr(sys, 'frozen', False):
                cands.append(Path(sys.executable).parent / "logs")
            else:
                # 开发环境:项目根目录(core/ 的上一级)
                cands.append(Path(__file__).resolve().parent.parent / "logs")

            if system == "Darwin":
                cands.append(Path.home() / "Library/Application Support/ZB100ImageGenerator/logs")
                cands.append(Path.home() / "Documents/ZB100ImageGenerator/logs")
            elif system == "Windows":
                cands.append(Path(os.environ.get("APPDATA", "")) / "ZB100ImageGenerator/logs")
                cands.append(Path.home() / "Documents/ZB100ImageGenerator/logs")
            else:
                cands.append(Path.home() / ".config/zb100imagegenerator/logs")
                cands.append(Path.home() / "Documents/ZB100ImageGenerator/logs")

            return cands

        def _writable(path: Path) -> bool:
            try:
                path.mkdir(parents=True, exist_ok=True)
                test = path / ".write_test"
                test.write_text("test")
                test.unlink()
                return True
            except Exception:
                return False

        logs_dir = None
        for c in _candidates():
            if _writable(c):
                logs_dir = c
                print(f"使用logs目录: {logs_dir}")
                break
        if logs_dir is None:
            logs_dir = Path(tempfile.gettempdir()) / "ZB100ImageGenerator_logs"
            logs_dir.mkdir(exist_ok=True)
            print(f"警告: 所有logs路径都不可用,使用临时目录: {logs_dir}")

        # 读取 config.json 的 logging_config
        script_dir = (
            Path(__file__).resolve().parent.parent
            if not getattr(sys, 'frozen', False)
            else Path(sys.executable).parent
        )
        config_path = script_dir / "config.json"
        logging_config = {"enabled": True, "level": "INFO", "log_to_console": True}
        if config_path.exists():
            try:
                with open(config_path, 'r', encoding='utf-8') as f:
                    cfg = json.load(f)
                    logging_config = cfg.get("logging_config", logging_config)
            except Exception as e:
                print(f"加载日志配置失败: {e}")

        if not logging_config.get("enabled", True):
            print("日志系统已禁用")
            return True

        level_str = logging_config.get("level", "INFO").upper()
        log_level = getattr(logging, level_str, logging.INFO)

        logs_dir.mkdir(parents=True, exist_ok=True)
        log_file = logs_dir / "app.log"
        log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

        max_bytes = int(logging_config.get("max_bytes", 5 * 1024 * 1024))
        backup_count = int(logging_config.get("backup_count", 5))
        # TieredFsyncHandler:WARNING+ 同步 fsync,INFO 走 buffered + 后台周期 fsync
        handlers = [TieredFsyncHandler(log_file, maxBytes=max_bytes,
                                       backupCount=backup_count, encoding='utf-8')]
        if logging_config.get("log_to_console", True):
            handlers.append(logging.StreamHandler())

        logging.basicConfig(level=log_level, format=log_format, handlers=handlers, force=True)

        # 启动后台周期 fsync 线程(兜底 INFO 级别日志最坏丢 1s)
        start_periodic_fsync(interval_seconds=1.0)

        logging.info(f"日志系统初始化完成 - 级别: {level_str}, 文件: {log_file}(分级 fsync + 1s 周期兜底)")
        return True

    except Exception as e:
        print(f"日志系统初始化失败: {e}")
        return False