from __future__ import annotations import ctypes import json import re import hashlib import os import shutil import ssl import subprocess import tempfile import time import urllib.error import urllib.request import zipfile from dataclasses import dataclass from pathlib import Path from typing import BinaryIO, Callable from .scanner import ScanResult from .mysql_recovery import MYSQL_RECOVERY_HELPERS JDK_PACKAGES = { "8": "EclipseAdoptium.Temurin.8.JDK", "11": "EclipseAdoptium.Temurin.11.JDK", "17": "EclipseAdoptium.Temurin.17.JDK", "21": "EclipseAdoptium.Temurin.21.JDK", } WINGET_PACKAGES = { "Gradle": "Gradle.Gradle", "Node.js": "OpenJS.NodeJS.LTS", "Git": "Git.Git", } MAVEN_VERSION = "3.10.0" MAVEN_ARCHIVE_NAME = f"apache-maven-{MAVEN_VERSION}-bin.zip" MAVEN_DOWNLOAD_BASE = f"https://dlcdn.apache.org/maven/maven-3/{MAVEN_VERSION}/binaries" TOMCAT_VERSION = "9.0.122" TOMCAT_ARCHIVE_NAME = f"apache-tomcat-{TOMCAT_VERSION}-windows-x64.zip" TOMCAT_DOWNLOAD_BASE = f"https://dlcdn.apache.org/tomcat/tomcat-9/v{TOMCAT_VERSION}/bin" MYSQL_VERSION = "8.0.43" MYSQL_ROOT_PASSWORD = "123456" MYSQL_INITIAL_ROOT_PASSWORD = "AutoDeploy#2026" MYSQL_INSTALLER_ARCHIVE_NAME = f"mysql-installer-community-{MYSQL_VERSION}.0.msi" MYSQL_INSTALLER_URL = ( "https://downloads.mysql.com/archives/get/p/25/file/" f"{MYSQL_INSTALLER_ARCHIVE_NAME}" ) MYSQL_INSTALLER_SHA256 = "F60502EB1EE10A9C1D0A26706A627D224DFAE466D82EF3EB9D76A8A718DB9D80" NODE_DIST_BASE = "https://nodejs.org/dist" ANSI_PATTERN = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]") PERCENT_PATTERN = re.compile(r"(\d{1,3})\s*%") PROGRESS_CHARS = "█▓▒░▏▎▍▌▋▊▉■□▪▫▬─━═|/-\\" @dataclass(frozen=True) class JdkRecommendation: version: str reason: str @dataclass(frozen=True) class NodeRecommendation: requirements: tuple[str, ...] reason: str @property def display_requirement(self) -> str: return " 且 ".join(self.requirements) @dataclass(frozen=True) class NodeRelease: version: str lts: str | bool def recommend_jdk_version(scan: ScanResult | None) -> JdkRecommendation: if not scan or not scan.backend: return JdkRecommendation("8", "\u672a\u626b\u63cf\u5230\u540e\u7aef\u7248\u672c\u4fe1\u606f\uff0c\u9ed8\u8ba4\u63a8\u8350 JDK 8\u3002") metadata = scan.backend.metadata java_version = metadata.get("java_version") if java_version: mapped = _map_java_version(java_version) source = metadata.get("java_version_source", "\u9879\u76ee\u914d\u7f6e") return JdkRecommendation(mapped, f"\u6839\u636e {source}={java_version} \u63a8\u8350 JDK {mapped}\u3002") boot_version = metadata.get("spring_boot_version", "") if boot_version.startswith("3."): return JdkRecommendation("17", f"Spring Boot 3.x \u9700\u8981 Java 17+\uff0c\u68c0\u6d4b\u5230 Spring Boot {boot_version}\uff0c\u63a8\u8350 JDK 17\u3002") if boot_version.startswith("2."): return JdkRecommendation("8", f"\u68c0\u6d4b\u5230 Spring Boot {boot_version}\uff0c\u9ed8\u8ba4\u63a8\u8350\u517c\u5bb9\u6027\u66f4\u597d\u7684 JDK 8\u3002") return JdkRecommendation("8", "\u672a\u53d1\u73b0\u660e\u786e Java \u7248\u672c\uff0c\u9ed8\u8ba4\u63a8\u8350 JDK 8\u3002") def recommend_node_version(scan: ScanResult | None) -> NodeRecommendation: if not scan or not scan.detected_frontends: return NodeRecommendation(("lts",), "未扫描到前端版本信息,使用 Node.js 最新 LTS。") requirements: list[str] = [] reasons: list[str] = [] for frontend in scan.detected_frontends: requirement = frontend.metadata.get("node_requirement", "").strip() source = frontend.metadata.get("node_requirement_source", "").strip() if requirement and requirement not in requirements: requirements.append(requirement) if requirement: name = frontend.metadata.get("display_name", frontend.path.name) reasons.append(f"{name}: {source or '项目配置'} → {requirement}") if not requirements: return NodeRecommendation(("lts",), "项目未声明 Node.js 版本,使用最新 LTS。") return NodeRecommendation(tuple(requirements), ";".join(reasons)) def build_install_command(tool_name: str, version: str | None = None) -> list[str]: if tool_name == "JDK": package_id = JDK_PACKAGES.get(version or "8") if not package_id: raise ValueError(f"\u4e0d\u652f\u6301\u7684 JDK \u7248\u672c: {version}") else: package_id = WINGET_PACKAGES.get(tool_name) if not package_id: raise ValueError(f"\u4e0d\u652f\u6301\u81ea\u52a8\u5b89\u88c5: {tool_name}") command = [ "winget", "install", "--exact", "--id", package_id, ] command.extend([ "--accept-source-agreements", "--accept-package-agreements", "--disable-interactivity", ]) return command def build_mysql_installer_command(installer_path: Path, log_path: Path) -> list[str]: return [ "msiexec.exe", "/i", str(installer_path), "/passive", "/norestart", "/L*V", str(log_path), ] def build_mysql_server_install_command(console_path: Path) -> list[str]: server = ( f"server;{MYSQL_VERSION};x64:*:" "type=main;open_win_firewall=false;tcp_ip=true;port=3306;" f"rootpasswd={MYSQL_INITIAL_ROOT_PASSWORD}" ) return [ str(console_path), "community", "--install", server, "--silent", "--auto-handle-prereqs", ] def default_mysql_install_log_path() -> Path: local_app_data = os.environ.get("LOCALAPPDATA", "").strip() base = Path(local_app_data) if local_app_data else Path.home() / ".autodeploy" return base / "AutoDeploy" / "logs" / "mysql-install.log" def default_mysql_server_install_log_path() -> Path: return default_mysql_install_log_path().with_name("mysql-server-install.log") def default_mysql_service_log_path() -> Path: return default_mysql_install_log_path().with_name("mysql-service-start.log") def find_mysql_executable() -> Path | None: discovered = shutil.which("mysql") if discovered: return Path(discovered) roots = [ Path(os.environ.get("ProgramFiles", r"C:\Program Files")), Path(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")), ] for root in roots: for relative in ( Path("MySQL") / "MySQL Server 8.0" / "bin" / "mysql.exe", Path("MySQL") / "MySQL Server 8.4" / "bin" / "mysql.exe", ): candidate = root / relative if candidate.exists(): return candidate return None def find_mysql_installer_console() -> Path | None: discovered = shutil.which("MySQLInstallerConsole") if discovered: return Path(discovered) roots = [ Path(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")), Path(os.environ.get("ProgramFiles", r"C:\Program Files")), ] for root in roots: candidate = root / "MySQL" / "MySQL Installer for Windows" / "MySQLInstallerConsole.exe" if candidate.exists(): return candidate return None def wait_for_mysql_installer_console(timeout: float = 30.0, poll_interval: float = 1.0) -> Path: deadline = time.monotonic() + timeout while True: executable = find_mysql_installer_console() if executable is not None: return executable if time.monotonic() >= deadline: raise RuntimeError("MySQL Installer 已结束,但未找到 MySQLInstallerConsole.exe。") time.sleep(poll_interval) def wait_for_mysql_executable(timeout: float = 90.0, poll_interval: float = 1.0) -> Path: deadline = time.monotonic() + timeout while True: executable = find_mysql_executable() if executable is not None: return executable if time.monotonic() >= deadline: raise RuntimeError("MySQL 安装命令已结束,但未找到 mysql.exe。") time.sleep(poll_interval) def configure_mysql_weak_password_policy( mysql_executable: Path, on_output: Callable[[str], None], initial_password: str = MYSQL_INITIAL_ROOT_PASSWORD, final_password: str = MYSQL_ROOT_PASSWORD, attempts: int = 30, retry_delay: float = 2.0, ) -> None: on_output("正在连接 MySQL,并永久启用 6 位弱密码策略...") variables_result: subprocess.CompletedProcess[str] | None = None active_password = initial_password total_attempts = max(attempts, 1) for attempt in range(total_attempts): variables_result = _run_mysql_sql( mysql_executable, "SHOW VARIABLES LIKE 'validate_password%';", initial_password, ) if variables_result.returncode == 0: break error_text = f"{variables_result.stderr}\n{variables_result.stdout}".lower() if "access denied" in error_text or "error 1045" in error_text: for candidate_password, message in ( (final_password, "检测到 root 已使用默认密码,继续校验弱密码策略..."), ("", "检测到新初始化的无密码 root 账号,立即设置默认密码..."), ): configured_result = _run_mysql_sql( mysql_executable, "SHOW VARIABLES LIKE 'validate_password%';", candidate_password, ) if configured_result.returncode == 0: variables_result = configured_result active_password = candidate_password on_output(message) break break if attempt + 1 < total_attempts: if attempt == 0 or (attempt + 1) % 5 == 0: on_output(f"MySQL 服务尚未就绪,正在后台重试({attempt + 1}/{total_attempts})...") time.sleep(retry_delay) assert variables_result is not None if variables_result.returncode != 0: detail = _process_error(variables_result) raise RuntimeError(f"无法使用 root 账号连接 MySQL,不能写入弱密码策略。{detail}") variable_names = variables_result.stdout.lower() statements: list[str] = [] if "validate_password.policy" in variable_names: statements.extend( [ "SET PERSIST validate_password.policy = 'LOW'", "SET PERSIST validate_password.length = 6", "SET PERSIST validate_password.mixed_case_count = 0", "SET PERSIST validate_password.number_count = 0", "SET PERSIST validate_password.special_char_count = 0", ] ) elif "validate_password_policy" in variable_names: statements.extend( [ "SET PERSIST validate_password_policy = 'LOW'", "SET PERSIST validate_password_length = 6", "SET PERSIST validate_password_mixed_case_count = 0", "SET PERSIST validate_password_number_count = 0", "SET PERSIST validate_password_special_char_count = 0", ] ) else: on_output("MySQL 未启用 validate_password 组件,当前已允许 6 位弱密码。") escaped_password = final_password.replace("'", "''") statements.append(f"ALTER USER 'root'@'localhost' IDENTIFIED BY '{escaped_password}'") configure_result = _run_mysql_sql( mysql_executable, ";\n".join(statements) + ";\n", active_password, ) if configure_result.returncode != 0: detail = _process_error(configure_result) raise RuntimeError(f"MySQL 弱密码策略配置失败。{detail}") verify_result = _run_mysql_sql(mysql_executable, "SELECT 1;", final_password) if verify_result.returncode != 0: detail = _process_error(verify_result) raise RuntimeError(f"MySQL 已配置,但 root 登录验证失败。{detail}") on_output("MySQL 已永久允许 6 位弱密码,root 默认密码配置完成。") def install_mysql( on_output: Callable[[str], None], opener: Callable[..., BinaryIO] | None = None, elevated_runner: Callable[[list[str]], int] | None = None, log_path: Path | None = None, ) -> Path: open_url = opener or urllib.request.urlopen install_log = Path(log_path) if log_path is not None else default_mysql_install_log_path() server_install_log = install_log.with_name("mysql-server-install.log") existing_executable = find_mysql_executable() if existing_executable is not None: on_output(f"检测到已安装的 MySQL,跳过 Server 安装: {existing_executable}") ensure_mysql_service_running(on_output, mysql_executable=existing_executable) configure_mysql_weak_password_policy(existing_executable, on_output) return existing_executable console = find_mysql_installer_console() if console is None: install_log.parent.mkdir(parents=True, exist_ok=True) if install_log.exists(): install_log.unlink() with tempfile.TemporaryDirectory(prefix="autodeploy-mysql-") as temporary: installer_path = Path(temporary) / MYSQL_INSTALLER_ARCHIVE_NAME on_output(f"正在从 MySQL 官方归档地址下载 MySQL Installer {MYSQL_VERSION}...") _download_to_file(MYSQL_INSTALLER_URL, installer_path, open_url, on_output) actual_checksum = _sha256(installer_path) if actual_checksum.lower() != MYSQL_INSTALLER_SHA256.lower(): raise RuntimeError("MySQL 安装包 SHA-256 校验失败,已停止安装。") on_output("MySQL 安装包校验通过,正在请求管理员权限安装...") on_output("确认管理员授权后会显示 Windows Installer 进度窗口,请勿关闭 AutoDeploy。") on_output(f"MySQL 详细安装日志: {install_log}") command = build_mysql_installer_command(installer_path, install_log) if elevated_runner is None: exit_code = run_elevated_command( command, on_wait=lambda: on_output("MySQL Installer 正在安装,请继续等待进度窗口完成..."), ) else: exit_code = elevated_runner(command) if exit_code not in {0, 1641, 3010}: raise RuntimeError(f"MySQL Installer 安装失败,退出码: {exit_code}。详细日志: {install_log}") if exit_code in {1641, 3010}: on_output("MySQL Installer 安装完成,Windows 提示稍后需要重新启动。") console = wait_for_mysql_installer_console() on_output("MySQL Installer 已完成,正在启动 MySQL Server 安装任务...") else: on_output(f"检测到已有 MySQL Installer,将直接安装 MySQL Server: {console}") server_command = build_mysql_server_install_command(console) on_output("即将再次请求管理员权限,请在出现的窗口中确认安装 MySQL Server。") if elevated_runner is None: on_output(f"MySQL Server 安装日志: {server_install_log}") server_exit_code = run_elevated_command_with_log( server_command, server_install_log, on_wait=lambda: on_output("MySQL Server 仍在安装和配置,请继续等待..."), ) else: server_exit_code = elevated_runner(server_command) if server_exit_code not in {0, 1641, 3010}: detail = _read_install_log_tail(server_install_log) if detail: on_output("MySQL Installer Console 报错详情:") for line in detail.splitlines(): on_output(line) suffix = f" 详细日志: {server_install_log}" if detail: suffix += f"\n{detail}" raise RuntimeError(f"MySQL Server 安装失败,退出码: {server_exit_code}。{suffix}") on_output("MySQL Server 安装任务已完成,正在检测命令行工具...") executable = wait_for_mysql_executable() ensure_mysql_service_running(on_output, mysql_executable=executable) configure_mysql_weak_password_policy(executable, on_output) return executable def run_elevated_command( command: list[str], on_wait: Callable[[], None] | None = None, wait_notice_interval: float = 30.0, show_window: bool = True, ) -> int: if os.name != "nt": return subprocess.run(command, shell=False).returncode from ctypes import wintypes class ShellExecuteInfo(ctypes.Structure): _fields_ = [ ("cbSize", wintypes.DWORD), ("fMask", wintypes.ULONG), ("hwnd", wintypes.HWND), ("lpVerb", wintypes.LPCWSTR), ("lpFile", wintypes.LPCWSTR), ("lpParameters", wintypes.LPCWSTR), ("lpDirectory", wintypes.LPCWSTR), ("nShow", ctypes.c_int), ("hInstApp", wintypes.HINSTANCE), ("lpIDList", wintypes.LPVOID), ("lpClass", wintypes.LPCWSTR), ("hkeyClass", wintypes.HKEY), ("dwHotKey", wintypes.DWORD), ("hIcon", wintypes.HANDLE), ("hProcess", wintypes.HANDLE), ] shell_execute = ctypes.windll.shell32.ShellExecuteExW shell_execute.argtypes = [ctypes.POINTER(ShellExecuteInfo)] shell_execute.restype = wintypes.BOOL info = ShellExecuteInfo() info.cbSize = ctypes.sizeof(info) info.fMask = 0x00000040 # SEE_MASK_NOCLOSEPROCESS info.lpVerb = "runas" info.lpFile = command[0] info.lpParameters = subprocess.list2cmdline(command[1:]) info.nShow = 1 if show_window else 0 if not shell_execute(ctypes.byref(info)): error_code = ctypes.windll.kernel32.GetLastError() if error_code == 1223: raise RuntimeError("用户取消了 MySQL 安装所需的管理员授权。") raise OSError(error_code, "无法以管理员权限启动 MySQL 安装程序") try: wait_timeout_ms = 1000 wait_timeout = 0x00000102 wait_object_0 = 0x00000000 last_notice = time.monotonic() while True: wait_result = ctypes.windll.kernel32.WaitForSingleObject(info.hProcess, wait_timeout_ms) if wait_result == wait_object_0: break if wait_result != wait_timeout: raise OSError(ctypes.windll.kernel32.GetLastError(), "等待 MySQL 安装程序时发生错误") now = time.monotonic() if on_wait is not None and now - last_notice >= wait_notice_interval: on_wait() last_notice = now exit_code = wintypes.DWORD() if not ctypes.windll.kernel32.GetExitCodeProcess(info.hProcess, ctypes.byref(exit_code)): raise OSError(ctypes.windll.kernel32.GetLastError(), "无法读取 MySQL 安装程序退出码") return int(exit_code.value) finally: ctypes.windll.kernel32.CloseHandle(info.hProcess) def run_elevated_command_with_log( command: list[str], log_path: Path, on_wait: Callable[[], None] | None = None, show_window: bool = True, ) -> int: """Run an elevated native command and preserve its stdout/stderr.""" log_path = Path(log_path) log_path.parent.mkdir(parents=True, exist_ok=True) if log_path.exists(): log_path.unlink() def ps_literal(value: str) -> str: return "'" + value.replace("'", "''") + "'" arguments = " ".join(ps_literal(argument) for argument in command[1:]) invocation = f"& {ps_literal(command[0])}" if arguments: invocation += f" {arguments}" script = ( "$ErrorActionPreference = 'Continue'\n" f"$output = {invocation} 2>&1\n" "$exitCode = $LASTEXITCODE\n" f"$output | Out-File -LiteralPath {ps_literal(str(log_path))} -Encoding utf8\n" "if ($null -eq $exitCode) { $exitCode = 1 }\n" "exit $exitCode\n" ) with tempfile.TemporaryDirectory(prefix="autodeploy-elevated-") as temporary: script_path = Path(temporary) / "run-command.ps1" script_path.write_text(script, encoding="utf-8-sig") return run_elevated_command( [ "powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", str(script_path), ], on_wait=on_wait, show_window=show_window, ) def _read_install_log_tail(log_path: Path, max_lines: int = 20) -> str: try: raw = Path(log_path).read_bytes() except OSError: return "" lines = format_install_output(raw) return "\n".join(lines[-max_lines:]) def _read_mysql_recovery_summary(log_path: Path) -> str: lines = _read_install_log_tail(log_path, max_lines=300).splitlines() causes = [line for line in lines if any(marker in line.lower() for marker in ( "[error]", "not found", "recovery failed:", "not empty", "existing entries:", "configuration backup:", "data directory:", "my.ini:", ))] return "\n".join(causes[:14] or lines[-20:]) def query_mysql_service_state(service_name: str = "MySQL80") -> int | None: if os.name != "nt": return 4 creation_flags = getattr(subprocess, "CREATE_NO_WINDOW", 0) completed = subprocess.run( ["sc.exe", "query", service_name], capture_output=True, shell=False, creationflags=creation_flags, ) if completed.returncode != 0: return None output = completed.stdout + completed.stderr match = re.search(rb"STATE\s*:\s*(\d+)", output, re.IGNORECASE) return int(match.group(1)) if match else None def ensure_mysql_service_running( on_output: Callable[[str], None], service_name: str = "MySQL80", mysql_executable: Path | None = None, elevated_runner: Callable[[list[str]], int] | None = None, attempts: int = 60, retry_delay: float = 1.0, ) -> None: state = query_mysql_service_state(service_name) if state == 4: on_output(f"Windows 服务 {service_name} 已运行。") return if state is None: raise RuntimeError(f"已找到 MySQL 文件,但未找到 Windows 服务 {service_name}。") on_output(f"Windows 服务 {service_name} 未运行,正在请求管理员权限启动...") if elevated_runner is not None: exit_code = elevated_runner(["sc.exe", "start", service_name]) else: service_log = default_mysql_service_log_path() on_output(f"MySQL 服务启动日志: {service_log}") server_executable = ( Path(mysql_executable).with_name("mysqld.exe") if mysql_executable is not None else None ) exit_code = run_mysql_service_start_diagnostic( service_name, service_log, mysql_server_executable=server_executable, ) if exit_code == 2: raise RuntimeError( f"MySQL 初始化或配置失败。详细日志: {service_log}\n" f"{_read_mysql_recovery_summary(service_log)}" ) if exit_code not in {0, 1056}: on_output( f"Windows 服务启动命令返回 {exit_code},服务可能仍在后台恢复,继续等待运行状态..." ) for attempt in range(max(attempts, 1)): state = query_mysql_service_state(service_name) if state == 4: on_output(f"Windows 服务 {service_name} 已启动。") return if attempt == 4 or (attempt + 1) % 15 == 0: on_output( f"Windows 服务 {service_name} 正在启动或恢复,继续等待({attempt + 1}/{max(attempts, 1)})..." ) time.sleep(retry_delay) detail = mysql_service_failure_detail(mysql_executable, state) diagnostic = _read_mysql_recovery_summary(default_mysql_service_log_path()) diagnostic_text = f"\n启动诊断:\n{diagnostic}" if diagnostic else "" raise RuntimeError( f"Windows 服务 {service_name} 启动超时,启动命令退出码: {exit_code}。" f"{detail}{diagnostic_text}" ) def build_mysql_service_start_script( service_name: str = "MySQL80", mysql_server_executable: Path | None = None, ) -> str: escaped_service_name = service_name.replace("'", "''") escaped_mysql_executable = str(mysql_server_executable or "").replace("'", "''") return ( MYSQL_RECOVERY_HELPERS + f"\n$name='{escaped_service_name}';\n" + f"$mysqlExe='{escaped_mysql_executable}';\n" + r''' $ErrorActionPreference = 'Continue' $data = '' $recoveryFailed = $false try { $service = Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") -ErrorAction Stop if (-not $service) { throw ('Windows service not found: ' + $name) } $service | Select-Object Name,State,StartName,PathName,ExitCode,ProcessId | Format-List | Out-String | Write-Output if ($service.State -eq 'Running') { exit 0 } $layout = Get-MySqlServiceLayout $service $mysqlExe = $layout.Server $ini = $layout.Ini $data = $layout.Data Write-Output ('mysqld.exe: ' + $mysqlExe) Write-Output ('my.ini: ' + $ini) Write-Output ('Data directory: ' + $data) if ($service.State -eq 'Stopped' -and $service.ProcessId -eq 0) { $initialized = Initialize-EmptyMySqlData $service $layout # Use the account actually registered for this service. $account = $service.StartName if ($account -eq 'NT AUTHORITY\NetworkService') { $sid = 'S-1-5-20' } elseif ($account -eq 'LocalSystem') { $sid = 'S-1-5-18' } else { $identity = New-Object Security.Principal.NTAccount($account) $sid = $identity.Translate([Security.Principal.SecurityIdentifier]).Value } $grantCode = Invoke-MySqlRecoveryCommand 'icacls.exe' @( $data, '/grant', ('*' + $sid + ':(OI)(CI)M'), '/T', '/C' ) if ($grantCode -ne 0) { throw ('Data directory permission repair failed: ' + $grantCode) } Write-Output 'mysqld configuration validation:' $validation = Invoke-MySqlRecoveryCommand $mysqlExe @( ('--defaults-file=' + $ini), '--validate-config', '--console' ) if ($validation -ne 0) { throw ('MySQL configuration validation failed: ' + $validation) } try { Start-Service -Name $name -ErrorAction Stop } catch { Write-Output ('Start-Service: ' + $_.Exception.Message) } } for ($attempt = 0; $attempt -lt 12; $attempt++) { $service = Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") if ($service.State -eq 'Running') { Write-Output 'MySQL service is running.' exit 0 } if ($service.State -eq 'Stopped') { break } Start-Sleep -Seconds 1 } Write-Output ('Service state after recovery: ' + $service.State) } catch { $recoveryFailed = $true Write-Output ('MySQL recovery failed: ' + $_.Exception.Message) } if ($data -and (Test-Path -LiteralPath $data)) { $err = Get-ChildItem -LiteralPath $data -Filter '*.err' -File -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -First 1 if ($err) { Write-Output ('Error log: ' + $err.FullName) Get-Content -LiteralPath $err.FullName -Tail 30 } else { Write-Output 'No .err log found with administrator privileges.' } } $since = (Get-Date).AddMinutes(-10) if ($recoveryFailed) { exit 2 } Write-Output 'Recent Windows service events:' Get-WinEvent -FilterHashtable @{LogName='System';StartTime=$since} -ErrorAction SilentlyContinue | Where-Object {$_.ProviderName -eq 'Service Control Manager' -and $_.Message -match $name} | Select-Object -First 3 TimeCreated,Id,Message | Format-List | Out-String | Write-Output exit 1 ''' ) def run_mysql_service_start_diagnostic( service_name: str, log_path: Path, mysql_server_executable: Path | None = None, ) -> int: with tempfile.TemporaryDirectory(prefix="autodeploy-mysql-service-") as temporary: script_path = Path(temporary) / "start-mysql-service.ps1" script_path.write_text( build_mysql_service_start_script(service_name, mysql_server_executable), encoding="utf-8-sig", ) return run_elevated_command_with_log( [ "powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", str(script_path), ], log_path, show_window=False, ) def find_mysql_error_log(mysql_executable: Path | None = None) -> Path | None: data_roots: list[Path] = [] program_data = os.environ.get("PROGRAMDATA", "").strip() if program_data: data_roots.append(Path(program_data) / "MySQL" / "MySQL Server 8.0" / "Data") if mysql_executable is not None: data_roots.append(Path(mysql_executable).parent.parent / "data") logs: list[Path] = [] for data_root in data_roots: try: logs.extend(path for path in data_root.glob("*.err") if path.is_file()) except OSError: continue if not logs: return None try: return max(logs, key=lambda path: path.stat().st_mtime) except OSError: return logs[0] def mysql_service_failure_detail( mysql_executable: Path | None, state: int | None, ) -> str: state_names = { 1: "STOPPED", 2: "START_PENDING", 3: "STOP_PENDING", 4: "RUNNING", 5: "CONTINUE_PENDING", 6: "PAUSE_PENDING", 7: "PAUSED", } state_text = state_names.get(state, "UNKNOWN") error_log = find_mysql_error_log(mysql_executable) if error_log is None: return f" 当前服务状态: {state_text}。未找到 MySQL .err 错误日志。" detail = _read_install_log_tail(error_log, max_lines=16) if not detail: return f" 当前服务状态: {state_text}。错误日志: {error_log}" return f" 当前服务状态: {state_text}。错误日志: {error_log}\n{detail}" def _run_mysql_sql(mysql_executable: Path, sql: str, password: str) -> subprocess.CompletedProcess[str]: environment = os.environ.copy() environment["MYSQL_PWD"] = password creation_flags = getattr(subprocess, "CREATE_NO_WINDOW", 0) if os.name == "nt" else 0 return subprocess.run( [ str(mysql_executable), "--protocol=TCP", "--host=127.0.0.1", "--user=root", "--batch", "--skip-column-names", ], input=sql, capture_output=True, text=True, timeout=15, shell=False, env=environment, creationflags=creation_flags, ) def _process_error(completed: subprocess.CompletedProcess[str]) -> str: detail = (completed.stderr or completed.stdout or "").strip() return f" 错误: {detail}" if detail else "" def default_maven_install_root() -> Path: local_app_data = os.environ.get("LOCALAPPDATA", "").strip() base = Path(local_app_data) if local_app_data else Path.home() / ".autodeploy" return base / "AutoDeploy" / "tools" def resolve_node_release(index_data: bytes | str, requirements: tuple[str, ...]) -> NodeRelease: try: releases = json.loads(index_data) except (json.JSONDecodeError, UnicodeDecodeError, TypeError) as exc: raise RuntimeError("Node.js 官方版本索引格式无效。") from exc if not isinstance(releases, list): raise RuntimeError("Node.js 官方版本索引格式无效。") candidates: list[NodeRelease] = [] for item in releases: if not isinstance(item, dict) or not isinstance(item.get("version"), str): continue version = item["version"].lstrip("v") if not re.fullmatch(r"\d+\.\d+\.\d+", version): continue files = item.get("files") if isinstance(files, list) and "win-x64-zip" not in files: continue lts = item.get("lts", False) if all(_node_version_matches(version, requirement, lts) for requirement in requirements): candidates.append(NodeRelease(version, lts if isinstance(lts, str) else bool(lts))) if not candidates: joined = " 且 ".join(requirements) raise RuntimeError(f"Node.js 官方版本中找不到满足项目要求的 Windows x64 版本: {joined}") return max(candidates, key=lambda item: _version_tuple(item.version)) def install_node( requirements: tuple[str, ...], on_output: Callable[[str], None], install_root: Path | None = None, opener: Callable[..., BinaryIO] | None = None, ) -> tuple[Path, Path, str]: root = Path(install_root) if install_root is not None else default_maven_install_root() open_url = opener or urllib.request.urlopen allow_windows_fallback = opener is None and os.name == "nt" on_output(f"正在读取 Node.js 官方版本索引,项目要求: {' 且 '.join(requirements)}") index_data = _read_url_bytes( f"{NODE_DIST_BASE}/index.json", open_url, 30, on_output, allow_windows_fallback=allow_windows_fallback, ) release = resolve_node_release(index_data, requirements) version = release.version directory_name = f"node-v{version}-win-x64" archive_name = f"{directory_name}.zip" product_home = root / directory_name node_executable = product_home / "node.exe" npm_executable = product_home / "npm.cmd" if node_executable.exists() and npm_executable.exists(): on_output(f"Node.js {version} 已安装: {node_executable}") return node_executable, npm_executable, version archive_url = f"{NODE_DIST_BASE}/v{version}/{archive_name}" checksum_url = f"{NODE_DIST_BASE}/v{version}/SHASUMS256.txt" root.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(prefix="autodeploy-node-") as temporary: temp_dir = Path(temporary) archive_path = temp_dir / archive_name on_output(f"已自动选择 Node.js {version},正在从官方地址下载...") _download_to_file_with_windows_fallback( archive_url, archive_path, open_url, on_output, allow_windows_fallback=allow_windows_fallback, ) checksum_data = _read_url_bytes( checksum_url, open_url, 30, on_output, allow_windows_fallback=allow_windows_fallback, ) expected_checksum = _parse_node_checksum(checksum_data, archive_name) actual_checksum = _sha256(archive_path) if actual_checksum.lower() != expected_checksum.lower(): raise RuntimeError("Node.js 安装包 SHA-256 校验失败,已停止安装。") on_output("Node.js 安装包校验通过,正在解压...") extract_root = temp_dir / "extracted" _safe_extract_zip(archive_path, extract_root) extracted_home = extract_root / directory_name if not (extracted_home / "node.exe").exists() or not (extracted_home / "npm.cmd").exists(): raise RuntimeError("Node.js 安装包结构异常,未找到 node.exe 或 npm.cmd。") shutil.copytree(extracted_home, product_home, dirs_exist_ok=True) on_output(f"Node.js {version} 安装完成: {node_executable}") return node_executable, npm_executable, version def _parse_node_checksum(data: bytes, archive_name: str) -> str: text = data.decode("ascii", errors="strict") for line in text.splitlines(): parts = line.split() if len(parts) >= 2 and parts[-1].lstrip("*") == archive_name: checksum = parts[0] if re.fullmatch(r"[0-9a-fA-F]{64}", checksum): return checksum raise RuntimeError(f"Node.js 校验清单中未找到 {archive_name}。") def _read_url_bytes( url: str, opener: Callable[..., BinaryIO], timeout: int, on_output: Callable[[str], None], *, allow_windows_fallback: bool, ) -> bytes: try: with opener(url, timeout=timeout) as response: return response.read() except Exception as exc: if not allow_windows_fallback or not _is_certificate_verification_failure(exc): raise on_output("Python 未信任当前网络证书,正在改用 Windows 系统证书存储重试下载...") with tempfile.TemporaryDirectory(prefix="autodeploy-windows-download-") as temporary: destination = Path(temporary) / "download.bin" try: _download_with_windows_certificates(url, destination, timeout) except Exception: on_output( "Windows 系统证书存储仍无法下载,正在按用户设置跳过 HTTPS 证书校验重试..." ) with _open_url_without_certificate_validation(url, timeout=timeout) as response: return response.read() return destination.read_bytes() def _download_to_file_with_windows_fallback( url: str, destination: Path, opener: Callable[..., BinaryIO], on_output: Callable[[str], None], *, allow_windows_fallback: bool, ) -> None: try: _download_to_file(url, destination, opener, on_output) except Exception as exc: if not allow_windows_fallback or not _is_certificate_verification_failure(exc): raise destination.unlink(missing_ok=True) on_output("Python 未信任当前网络证书,正在改用 Windows 系统证书存储重试下载...") try: _download_with_windows_certificates(url, destination, 60) except Exception: destination.unlink(missing_ok=True) on_output( "Windows 系统证书存储仍无法下载,正在按用户设置跳过 HTTPS 证书校验重试..." ) _download_to_file( url, destination, _open_url_without_certificate_validation, on_output, ) def _open_url_without_certificate_validation(url: str, timeout: int): context = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE return urllib.request.urlopen(url, timeout=timeout, context=context) def _is_certificate_verification_failure(exc: BaseException) -> bool: if isinstance(exc, ssl.SSLCertVerificationError): return True reason = getattr(exc, "reason", None) if isinstance(reason, ssl.SSLCertVerificationError): return True message = str(exc).upper() return "CERTIFICATE_VERIFY_FAILED" in message or "SELF-SIGNED CERTIFICATE" in message def _download_with_windows_certificates(url: str, destination: Path, timeout: int) -> None: powershell = shutil.which("powershell.exe") or str( Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" / "WindowsPowerShell" / "v1.0" / "powershell.exe" ) script = ( "& { param([string]$Url,[string]$Destination,[int]$TimeoutSeconds) " "$ErrorActionPreference='Stop'; $ProgressPreference='SilentlyContinue'; " "Invoke-WebRequest -UseBasicParsing -Uri $Url -OutFile $Destination -TimeoutSec $TimeoutSeconds }" ) completed = subprocess.run( [ powershell, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script, url, str(destination), str(timeout), ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace", shell=False, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0) if os.name == "nt" else 0, ) if completed.returncode != 0 or not destination.is_file() or destination.stat().st_size == 0: detail = completed.stdout.strip() or f"退出码 {completed.returncode}" raise RuntimeError( "Windows 系统证书存储也无法完成 HTTPS 下载。" "请将网络代理的根证书安装到 Windows 受信任的根证书颁发机构。" f"\n{detail}" ) def _node_version_matches(version: str, requirement: str, lts: object) -> bool: text = requirement.strip().lower() if text in {"", "*", "node", "latest"}: return True if text.startswith("lts"): requested_name = text.partition("/")[2] if requested_name in {"", "*", "-*"}: return bool(lts) return isinstance(lts, str) and lts.lower() == requested_name return any(_node_clause_matches(version, clause) for clause in text.split("||")) def _node_clause_matches(version: str, clause: str) -> bool: current = _version_tuple(version) normalized = clause.replace(",", " ").replace("(", " ").replace(")", " ") hyphen = re.fullmatch(r"\s*v?(\d+(?:\.\d+){0,2})\s+-\s+v?(\d+(?:\.\d+){0,2})\s*", normalized) if hyphen: return _compare_versions(current, ">=", _partial_version_tuple(hyphen.group(1))) and _compare_versions( current, "<=", _partial_version_tuple(hyphen.group(2), upper=True) ) tokens = re.findall(r"(?:>=|<=|>|<|=|\^|~)?\s*v?\d+(?:\.\d+){0,2}(?:\.(?:x|\*))?|(?:\d+\.)?(?:x|\*)", normalized) if not tokens: return False return all(_node_token_matches(current, token.replace(" ", "")) for token in tokens) def _node_token_matches(current: tuple[int, int, int], token: str) -> bool: match = re.fullmatch(r"(>=|<=|>|<|=|\^|~)?v?(.+)", token) if not match: return False operator = match.group(1) or "" value = match.group(2) if value in {"x", "*"}: return True parts = value.split(".") numeric = [int(part) for part in parts if part not in {"x", "*"}] if not numeric: return True target = tuple((numeric + [0, 0, 0])[:3]) if operator == "^": upper = (target[0] + 1, 0, 0) if target[0] else (0, target[1] + 1, 0) return current >= target and current < upper if operator == "~": upper = (target[0], target[1] + 1, 0) if len(numeric) > 1 else (target[0] + 1, 0, 0) return current >= target and current < upper if operator: return _compare_versions(current, operator, target) if len(numeric) == 1: return current[0] == target[0] if len(numeric) == 2: return current[:2] == target[:2] return current == target def _version_tuple(value: str) -> tuple[int, int, int]: parts = [int(part) for part in value.lstrip("v").split(".")[:3]] return tuple((parts + [0, 0, 0])[:3]) def _partial_version_tuple(value: str, upper: bool = False) -> tuple[int, int, int]: parts = [int(part) for part in value.split(".")] padded = (parts + ([999999] * 3 if upper else [0] * 3))[:3] return tuple(padded) def _compare_versions( current: tuple[int, int, int], operator: str, target: tuple[int, int, int], ) -> bool: return { ">=": current >= target, "<=": current <= target, ">": current > target, "<": current < target, "=": current == target, }.get(operator, False) def install_maven( on_output: Callable[[str], None], install_root: Path | None = None, opener: Callable[..., BinaryIO] | None = None, ) -> Path: root = Path(install_root) if install_root is not None else default_maven_install_root() archive_url = f"{MAVEN_DOWNLOAD_BASE}/{MAVEN_ARCHIVE_NAME}" return _install_verified_apache_archive( product_name="Maven", version=MAVEN_VERSION, archive_name=MAVEN_ARCHIVE_NAME, archive_url=archive_url, extracted_dir_name=f"apache-maven-{MAVEN_VERSION}", executable_relative=Path("bin") / "mvn.cmd", on_output=on_output, install_root=root, opener=opener, ) def install_tomcat( on_output: Callable[[str], None], install_root: Path | None = None, opener: Callable[..., BinaryIO] | None = None, ) -> Path: root = Path(install_root) if install_root is not None else default_maven_install_root() archive_url = f"{TOMCAT_DOWNLOAD_BASE}/{TOMCAT_ARCHIVE_NAME}" return _install_verified_apache_archive( product_name="Tomcat", version=TOMCAT_VERSION, archive_name=TOMCAT_ARCHIVE_NAME, archive_url=archive_url, extracted_dir_name=f"apache-tomcat-{TOMCAT_VERSION}", executable_relative=Path("bin") / "catalina.bat", on_output=on_output, install_root=root, opener=opener, ) def _install_verified_apache_archive( *, product_name: str, version: str, archive_name: str, archive_url: str, extracted_dir_name: str, executable_relative: Path, on_output: Callable[[str], None], install_root: Path, opener: Callable[..., BinaryIO] | None, ) -> Path: product_home = install_root / extracted_dir_name executable = product_home / executable_relative if executable.exists(): on_output(f"{product_name} {version} 已安装: {executable}") return executable open_url = opener or urllib.request.urlopen checksum_url = f"{archive_url}.sha512" install_root.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(prefix=f"autodeploy-{product_name.lower()}-") as temporary: temp_dir = Path(temporary) archive_path = temp_dir / archive_name on_output(f"正在从 Apache 官方地址下载 {product_name} {version}...") _download_to_file(archive_url, archive_path, open_url, on_output) expected_checksum = _download_checksum(checksum_url, open_url) actual_checksum = _sha512(archive_path) if actual_checksum.lower() != expected_checksum.lower(): raise RuntimeError(f"{product_name} 安装包 SHA-512 校验失败,已停止安装。") on_output(f"{product_name} 安装包校验通过,正在解压...") extract_root = temp_dir / "extracted" _safe_extract_zip(archive_path, extract_root) extracted_home = extract_root / extracted_dir_name extracted_executable = extracted_home / executable_relative if not extracted_executable.exists(): raise RuntimeError(f"{product_name} 安装包结构异常,未找到 {executable_relative}。") shutil.copytree(extracted_home, product_home, dirs_exist_ok=True) if not executable.exists(): raise RuntimeError(f"{product_name} 解压完成,但未找到 {executable_relative}。") on_output(f"{product_name} {version} 安装完成: {executable}") return executable def _download_to_file( url: str, destination: Path, opener: Callable[..., BinaryIO], on_output: Callable[[str], None], ) -> None: with opener(url, timeout=60) as response, destination.open("wb") as output: headers = getattr(response, "headers", {}) total_text = headers.get("Content-Length", "") if hasattr(headers, "get") else "" total = int(total_text) if str(total_text).isdigit() else 0 downloaded = 0 last_percent = -10 while True: chunk = response.read(1024 * 256) if not chunk: break output.write(chunk) downloaded += len(chunk) if total: percent = min(downloaded * 100 // total, 100) if percent >= last_percent + 10 or percent == 100: on_output(f"下载进度: {percent}%") last_percent = percent def _download_checksum(url: str, opener: Callable[..., BinaryIO]) -> str: with opener(url, timeout=30) as response: text = response.read().decode("ascii", errors="strict").strip() checksum = text.split()[0] if text else "" if not re.fullmatch(r"[0-9a-fA-F]{128}", checksum): raise RuntimeError("Apache Maven 校验文件格式无效。") return checksum def _sha512(path: Path) -> str: digest = hashlib.sha512() with path.open("rb") as source: for chunk in iter(lambda: source.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def _sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as source: for chunk in iter(lambda: source.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def _safe_extract_zip(archive_path: Path, destination: Path) -> None: destination.mkdir(parents=True, exist_ok=True) destination_resolved = destination.resolve() with zipfile.ZipFile(archive_path) as archive: for member in archive.infolist(): target = (destination / member.filename).resolve() if target != destination_resolved and destination_resolved not in target.parents: raise RuntimeError("ZIP 安装包包含不安全的文件路径。") archive.extractall(destination) def run_install_command(command: list[str], on_output) -> int: output_lines: list[str] = [] process = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False, bufsize=0, ) assert process.stdout is not None last_line = "" for raw_line in process.stdout: for line in format_install_output(raw_line): if line and line != last_line: on_output(line) output_lines.append(line) last_line = line exit_code = process.wait() failure_hint = explain_install_failure(_tool_name_from_command(command), exit_code, output_lines) if failure_hint: on_output(failure_hint) return exit_code def explain_install_failure(tool_name: str | None, exit_code: int, output_lines: list[str]) -> str: if exit_code == 0: return "" output_text = "\n".join(output_lines) if tool_name == "Maven" and ("找不到与输入条件匹配的程序包" in output_text or "No package found" in output_text): return ( "winget 当前源找不到 Maven 包。请手动下载 Apache Maven,解压后在工具里选择 " "apache-maven 的 bin\\mvn.cmd,或把该 bin 目录加入 PATH。" ) return "" def format_install_output(raw: bytes) -> list[str]: text = _decode_process_bytes(raw) text = ANSI_PATTERN.sub("", text).replace("\b", "") lines: list[str] = [] for part in re.split(r"[\r\n]+", text): cleaned = _clean_install_line(part) if cleaned: lines.append(cleaned) return lines def _decode_process_bytes(raw: bytes) -> str: for encoding in ("utf-8", "utf-16", "gb18030", "mbcs"): try: return raw.decode(encoding) except (LookupError, UnicodeDecodeError): continue return raw.decode("utf-8", errors="replace") def _clean_install_line(line: str) -> str: text = line.strip() if not text: return "" percent = PERCENT_PATTERN.search(text) progress_only = _looks_like_progress_line(text) if percent and progress_only: value = min(int(percent.group(1)), 100) return f"\u5b89\u88c5\u8fdb\u5ea6: {value}%" if progress_only: return "" return text def _looks_like_progress_line(text: str) -> bool: if not text: return False progress_count = sum(1 for char in text if char in PROGRESS_CHARS) percent = bool(PERCENT_PATTERN.search(text)) if percent and progress_count: return True visible = [char for char in text if not char.isspace()] if not visible: return False return progress_count / len(visible) > 0.45 def _tool_name_from_command(command: list[str]) -> str | None: package_ids = {package_id: name for name, package_id in WINGET_PACKAGES.items()} package_ids.update({package_id: "JDK" for package_id in JDK_PACKAGES.values()}) for part in command: name = package_ids.get(part) if name: return name return None def _map_java_version(version: str) -> str: try: major = int(version.split(".", 1)[0]) except ValueError: return "8" if major <= 8: return "8" if major <= 11: return "11" if major <= 17: return "17" return "21"