diff --git a/README.md b/README.md index 478804f..0e6da37 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ AutoDeploy 是一个面向 Windows 的 Spring Boot / SSM + Vue 本地自动化 - 从 Maven、Gradle 和 Spring Boot 配置中推断 Java 版本,推荐 JDK 8、11、17 或 21。 - 检测 JDK、Maven、Tomcat、Gradle、Node.js、npm、Vue CLI、MySQL 和 Git。 - 支持手动指定工具路径,并可将工具目录写入当前用户的 `PATH`;JDK、Maven、Tomcat 和 Gradle 会同步设置对应的环境变量。 -- Maven 和 Tomcat 从 Apache 官方地址下载并校验后安装到当前用户目录;MySQL 从 Oracle 官方归档下载安装包并校验 SHA-256,固定安装 8.0.43,默认将 root 密码设置为 `123456` 并永久允许 6 位弱密码。MySQL 安装时会显示 Windows Installer 进度窗口,详细日志保存在 `%LOCALAPPDATA%\AutoDeploy\logs\mysql-install.log`。JDK、Node.js 等环境通过 `winget` 接受软件源和包协议后无人值守安装,执行安装前会要求用户确认。 +- Maven 和 Tomcat 从 Apache 官方地址下载并校验后安装到当前用户目录;MySQL 从 Oracle 官方归档下载安装包并校验 SHA-256,固定安装 8.0.43,默认将 root 密码设置为 `123456` 并永久允许 6 位弱密码。MySQL 分两阶段安装并等待 Server 安装任务的真实结果;已有 MySQL Installer 时直接复用。首次安装会显示 Windows Installer 进度窗口,详细日志保存在 `%LOCALAPPDATA%\AutoDeploy\logs\mysql-install.log`。JDK、Node.js 等环境通过 `winget` 接受软件源和包协议后无人值守安装,执行安装前会要求用户确认。 - 使用 Maven 或 Gradle 构建后端;已有可运行 JAR/WAR 时自动跳过重复构建。 - 将传统 SSM 项目的 WAR 发布到 Tomcat 9,并等待 8080 端口就绪。 - 前端缺少 `node_modules` 时自动执行 `npm install`,随后运行 `serve`、`dev` 或 `start` 脚本。 diff --git a/deploy_tool/gui.py b/deploy_tool/gui.py index 6ad1e46..d49882f 100644 --- a/deploy_tool/gui.py +++ b/deploy_tool/gui.py @@ -396,10 +396,11 @@ class DeployWorkbench(tk.Tk): def install_mysql_async(self) -> None: if not messagebox.askyesno( "确认安装 MySQL", - f"将从 MySQL 官方归档下载 MySQL Community Server {MYSQL_VERSION} 完整安装包(约 354 MB)," - f"校验 SHA-256 后安装。\n\nroot 默认密码为 {MYSQL_ROOT_PASSWORD},并永久允许 6 位弱密码;" + f"本机没有 MySQL Installer 时,将从官方归档下载 {MYSQL_VERSION} 完整安装包(约 354 MB)," + f"校验 SHA-256 后安装;已有 Installer 时直接安装 Server。\n\n" + f"root 默认密码为 {MYSQL_ROOT_PASSWORD},并永久允许 6 位弱密码;" "仅开放本机连接,不自动开放 Windows 防火墙端口。\n\n" - "安装时会请求管理员权限,确认后将显示 Windows Installer 进度窗口。是否继续?", + "安装时会请求管理员权限;首次安装可能出现两次授权提示。是否继续?", ): return self._append_log(f"开始安装 MySQL {MYSQL_VERSION}...") diff --git a/deploy_tool/installer.py b/deploy_tool/installer.py index 7015d15..328ef35 100644 --- a/deploy_tool/installer.py +++ b/deploy_tool/installer.py @@ -38,6 +38,7 @@ 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/" @@ -101,11 +102,6 @@ def build_install_command(tool_name: str, version: str | None = None) -> list[st def build_mysql_installer_command(installer_path: Path, log_path: Path) -> list[str]: - console_args = ( - f"CONSOLEARGS=install server;{MYSQL_VERSION};x64:*:" - "type=config;open_win_firewall=false;tcp_ip=true;port=3306;" - f"root_passwd={MYSQL_ROOT_PASSWORD} --silent --auto-handle-prereqs" - ) return [ "msiexec.exe", "/i", @@ -114,21 +110,22 @@ def build_mysql_installer_command(installer_path: Path, log_path: Path) -> list[ "/norestart", "/L*V", str(log_path), - console_args, ] -def build_windows_command_parameters(command: list[str]) -> str: - parameters: list[str] = [] - for argument in command[1:]: - if argument.startswith("CONSOLEARGS="): - value = argument.removeprefix("CONSOLEARGS=") - if '"' in value: - raise ValueError("MySQL CONSOLEARGS 包含不支持的双引号。") - parameters.append(f'CONSOLEARGS="{value}"') - else: - parameters.append(subprocess.list2cmdline([argument])) - return " ".join(parameters) +def build_mysql_server_install_command(console_path: Path) -> list[str]: + server = ( + f"server;{MYSQL_VERSION};x64:*:" + "type=config;open_win_firewall=false;tcp_ip=true;port=3306;" + f"root_passwd={MYSQL_INITIAL_ROOT_PASSWORD}" + ) + return [ + str(console_path), + "--install", + server, + "--silent", + "--auto-handle-prereqs", + ] def default_mysql_install_log_path() -> Path: @@ -157,6 +154,33 @@ def find_mysql_executable() -> Path | None: 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: @@ -171,7 +195,8 @@ def wait_for_mysql_executable(timeout: float = 90.0, poll_interval: float = 1.0) def configure_mysql_weak_password_policy( mysql_executable: Path, on_output: Callable[[str], None], - password: str = MYSQL_ROOT_PASSWORD, + initial_password: str = MYSQL_INITIAL_ROOT_PASSWORD, + final_password: str = MYSQL_ROOT_PASSWORD, attempts: int = 30, retry_delay: float = 2.0, ) -> None: @@ -181,7 +206,7 @@ def configure_mysql_weak_password_policy( variables_result = _run_mysql_sql( mysql_executable, "SHOW VARIABLES LIKE 'validate_password%';", - password, + initial_password, ) if variables_result.returncode == 0: break @@ -218,14 +243,18 @@ def configure_mysql_weak_password_policy( else: on_output("MySQL 未启用 validate_password 组件,当前已允许 6 位弱密码。") - escaped_password = password.replace("'", "''") + 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", password) + configure_result = _run_mysql_sql( + mysql_executable, + ";\n".join(statements) + ";\n", + initial_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;", password) + 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}") @@ -240,32 +269,50 @@ 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() - 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 安装仍在进行,请继续等待进度窗口完成..."), - ) - else: - exit_code = elevated_runner(command) - if exit_code not in {0, 1641, 3010}: - raise RuntimeError(f"MySQL 安装命令失败,退出码: {exit_code}。详细日志: {install_log}") - on_output("Windows Installer 已完成,正在检测 MySQL 服务和命令行工具...") - if exit_code in {1641, 3010}: - on_output("MySQL 安装完成,Windows 提示稍后需要重新启动。") + 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: + server_exit_code = run_elevated_command( + server_command, + 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}。") + on_output("MySQL Server 安装任务已完成,正在检测命令行工具...") executable = wait_for_mysql_executable() configure_mysql_weak_password_policy(executable, on_output) return executable @@ -308,7 +355,7 @@ def run_elevated_command( info.fMask = 0x00000040 # SEE_MASK_NOCLOSEPROCESS info.lpVerb = "runas" info.lpFile = command[0] - info.lpParameters = build_windows_command_parameters(command) + info.lpParameters = subprocess.list2cmdline(command[1:]) info.nShow = 1 # SW_SHOWNORMAL: show the Windows Installer progress window. if not shell_execute(ctypes.byref(info)): error_code = ctypes.windll.kernel32.GetLastError() diff --git a/tests/test_installer.py b/tests/test_installer.py index 962322d..73326fc 100644 --- a/tests/test_installer.py +++ b/tests/test_installer.py @@ -11,12 +11,13 @@ from unittest.mock import patch import deploy_tool.installer as installer_module from deploy_tool.installer import ( MAVEN_ARCHIVE_NAME, + MYSQL_INITIAL_ROOT_PASSWORD, MYSQL_VERSION, MYSQL_ROOT_PASSWORD, MYSQL_INSTALLER_SHA256, MYSQL_INSTALLER_URL, build_mysql_installer_command, - build_windows_command_parameters, + build_mysql_server_install_command, configure_mysql_weak_password_policy, default_mysql_install_log_path, TOMCAT_VERSION, @@ -121,24 +122,19 @@ class InstallerTests(unittest.TestCase): self.assertIn("/L*V", command) self.assertIn("mysql-install.log", command) self.assertEqual(MYSQL_VERSION, "8.0.43") - self.assertIn("root_passwd=123456", command[-1]) - self.assertIn("open_win_firewall=false", command[-1]) + self.assertFalse(any("CONSOLEARGS" in argument for argument in command)) self.assertEqual(MYSQL_INSTALLER_SHA256, "F60502EB1EE10A9C1D0A26706A627D224DFAE466D82EF3EB9D76A8A718DB9D80") self.assertIn("downloads.mysql.com/archives/", MYSQL_INSTALLER_URL) - def test_formats_mysql_consoleargs_as_an_msi_property_value(self): - command = build_mysql_installer_command( - Path(r"C:\Temp Folder\mysql-installer.msi"), - Path(r"C:\Log Folder\mysql-install.log"), - ) + def test_builds_tracked_mysql_server_console_command_with_strong_initial_password(self): + command = build_mysql_server_install_command(Path("MySQLInstallerConsole.exe")) - parameters = build_windows_command_parameters(command) - - self.assertIn('/i "C:\\Temp Folder\\mysql-installer.msi"', parameters) - self.assertIn('/L*V "C:\\Log Folder\\mysql-install.log"', parameters) - self.assertIn('CONSOLEARGS="install server;8.0.43;x64:*:', parameters) - self.assertIn('root_passwd=123456 --silent --auto-handle-prereqs"', parameters) - self.assertNotIn('"CONSOLEARGS=', parameters) + 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.assertIn("--silent", command) + self.assertIn("--auto-handle-prereqs", command) def test_mysql_is_not_installed_from_stale_winget_manifest(self): with self.assertRaises(ValueError): @@ -154,13 +150,19 @@ class InstallerTests(unittest.TestCase): def elevated_runner(command): commands.append(command) - self.assertTrue(Path(command[2]).exists()) + if command[0] == "msiexec.exe": + self.assertTrue(Path(command[2]).exists()) return 0 with tempfile.TemporaryDirectory() as tmp: install_log = Path(tmp) / "logs" / "mysql-install.log" with ( patch("deploy_tool.installer.MYSQL_INSTALLER_SHA256", checksum), + patch("deploy_tool.installer.find_mysql_installer_console", return_value=None), + patch( + "deploy_tool.installer.wait_for_mysql_installer_console", + return_value=Path("MySQLInstallerConsole.exe"), + ), patch("deploy_tool.installer.wait_for_mysql_executable", return_value=Path("mysql.exe")), patch("deploy_tool.installer.configure_mysql_weak_password_policy") as configure, ): @@ -176,11 +178,44 @@ class InstallerTests(unittest.TestCase): self.assertEqual(commands[0][0], "msiexec.exe") 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.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)) configure.assert_called_once() + def test_reuses_existing_mysql_installer_without_downloading_bundle(self): + commands = [] + + def elevated_runner(command): + commands.append(command) + return 0 + + def unexpected_download(_url, _timeout): + self.fail("MySQL bundle should not be downloaded when Installer already exists") + + with ( + patch( + "deploy_tool.installer.find_mysql_installer_console", + return_value=Path("MySQLInstallerConsole.exe"), + ), + patch("deploy_tool.installer.wait_for_mysql_executable", return_value=Path("mysql.exe")), + patch("deploy_tool.installer.configure_mysql_weak_password_policy") as configure, + ): + messages = [] + executable = install_mysql( + messages.append, + opener=unexpected_download, + elevated_runner=elevated_runner, + ) + + self.assertEqual(executable, Path("mysql.exe")) + self.assertEqual(len(commands), 1) + self.assertEqual(commands[0][0], "MySQLInstallerConsole.exe") + self.assertTrue(any("检测到已有 MySQL Installer" in message for message in messages)) + configure.assert_called_once() + 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() @@ -211,7 +246,8 @@ class InstallerTests(unittest.TestCase): self.assertIn("SET PERSIST validate_password.policy = 'LOW'", sql) self.assertIn("SET PERSIST validate_password.length = 6", sql) self.assertIn("ALTER USER 'root'@'localhost' IDENTIFIED BY '123456'", sql) - self.assertEqual(configure_call.kwargs["env"]["MYSQL_PWD"], MYSQL_ROOT_PASSWORD) + self.assertEqual(configure_call.kwargs["env"]["MYSQL_PWD"], MYSQL_INITIAL_ROOT_PASSWORD) + self.assertEqual(run.call_args_list[2].kwargs["env"]["MYSQL_PWD"], MYSQL_ROOT_PASSWORD) self.assertNotIn(MYSQL_ROOT_PASSWORD, configure_call.args[0]) self.assertTrue(any("永久允许 6 位弱密码" in message for message in messages))