diff --git a/deploy_tool/installer.py b/deploy_tool/installer.py index 7e9b1d4..ee21622 100644 --- a/deploy_tool/installer.py +++ b/deploy_tool/installer.py @@ -158,6 +158,7 @@ def build_mysql_server_install_command(console_path: Path) -> list[str]: ) return [ str(console_path), + "community", "--install", server, "--silent", @@ -171,6 +172,10 @@ def default_mysql_install_log_path() -> Path: 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 find_mysql_executable() -> Path | None: discovered = shutil.which("mysql") if discovered: @@ -306,6 +311,7 @@ def install_mysql( ) -> 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") console = find_mysql_installer_console() if console is None: install_log.parent.mkdir(parents=True, exist_ok=True) @@ -341,14 +347,24 @@ def install_mysql( server_command = build_mysql_server_install_command(console) on_output("即将再次请求管理员权限,请在出现的窗口中确认安装 MySQL Server。") if elevated_runner is None: - server_exit_code = run_elevated_command( + 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}: - raise RuntimeError(f"MySQL Server 安装失败,退出码: {server_exit_code}。") + 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() configure_mysql_weak_password_policy(executable, on_output) @@ -422,6 +438,58 @@ def run_elevated_command( ctypes.windll.kernel32.CloseHandle(info.hProcess) +def run_elevated_command_with_log( + command: list[str], + log_path: Path, + on_wait: Callable[[], None] | None = None, +) -> 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, + ) + + +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 _run_mysql_sql(mysql_executable: Path, sql: str, password: str) -> subprocess.CompletedProcess[str]: environment = os.environ.copy() environment["MYSQL_PWD"] = password diff --git a/tests/test_installer.py b/tests/test_installer.py index e0c8173..bb5b01e 100644 --- a/tests/test_installer.py +++ b/tests/test_installer.py @@ -22,6 +22,8 @@ from deploy_tool.installer import ( build_mysql_server_install_command, configure_mysql_weak_password_policy, default_mysql_install_log_path, + default_mysql_server_install_log_path, + run_elevated_command_with_log, TOMCAT_VERSION, install_maven, install_mysql, @@ -200,10 +202,10 @@ class InstallerTests(unittest.TestCase): def test_builds_tracked_mysql_server_console_command_with_strong_initial_password(self): command = build_mysql_server_install_command(Path("MySQLInstallerConsole.exe")) - self.assertEqual(command[0:2], ["MySQLInstallerConsole.exe", "--install"]) - self.assertIn("server;8.0.43;x64:*:", command[2]) - self.assertIn(f"root_passwd={MYSQL_INITIAL_ROOT_PASSWORD}", command[2]) - self.assertNotIn(f"root_passwd={MYSQL_ROOT_PASSWORD}", command[2]) + self.assertEqual(command[0:3], ["MySQLInstallerConsole.exe", "community", "--install"]) + self.assertIn("server;8.0.43;x64:*:", command[3]) + self.assertIn(f"root_passwd={MYSQL_INITIAL_ROOT_PASSWORD}", command[3]) + self.assertNotIn(f"root_passwd={MYSQL_ROOT_PASSWORD}", command[3]) self.assertIn("--silent", command) self.assertIn("--auto-handle-prereqs", command) @@ -250,7 +252,7 @@ class InstallerTests(unittest.TestCase): self.assertIn("/passive", commands[0]) self.assertIn(str(install_log), commands[0]) self.assertEqual(commands[1][0], "MySQLInstallerConsole.exe") - self.assertEqual(commands[1][1], "--install") + self.assertEqual(commands[1][1:3], ["community", "--install"]) self.assertTrue(any("校验通过" in message for message in messages)) self.assertTrue(any("进度窗口" in message for message in messages)) self.assertTrue(any(str(install_log) in message for message in messages)) @@ -290,11 +292,37 @@ class InstallerTests(unittest.TestCase): def test_uses_persistent_mysql_install_log_location(self): with patch.dict("os.environ", {"LOCALAPPDATA": r"C:\Users\tester\AppData\Local"}): log_path = default_mysql_install_log_path() + server_log_path = default_mysql_server_install_log_path() self.assertEqual( log_path, Path(r"C:\Users\tester\AppData\Local") / "AutoDeploy" / "logs" / "mysql-install.log", ) + self.assertEqual( + server_log_path, + Path(r"C:\Users\tester\AppData\Local") / "AutoDeploy" / "logs" / "mysql-server-install.log", + ) + + def test_elevated_command_logging_uses_temporary_powershell_wrapper(self): + with tempfile.TemporaryDirectory() as tmp: + log_path = Path(tmp) / "mysql-server-install.log" + + def inspect_wrapper(command, on_wait=None): + self.assertEqual(command[0], "powershell.exe") + script_path = Path(command[-1]) + self.assertTrue(script_path.exists()) + script = script_path.read_text(encoding="utf-8-sig") + self.assertIn("'community' '--install'", script) + self.assertIn(str(log_path), script) + return 2 + + with patch("deploy_tool.installer.run_elevated_command", side_effect=inspect_wrapper): + exit_code = run_elevated_command_with_log( + ["MySQLInstallerConsole.exe", "community", "--install"], + log_path, + ) + + self.assertEqual(exit_code, 2) def test_windows_elevation_dependency_is_imported(self): self.assertIs(installer_module.ctypes, ctypes)