Start MySQL service before password setup

This commit is contained in:
王鹏
2026-10-09 10:37:12 +08:00
parent e3d67d9975
commit 2f98295cde
2 changed files with 96 additions and 2 deletions

View File

@@ -331,6 +331,7 @@ def install_mysql(
existing_executable = find_mysql_executable() existing_executable = find_mysql_executable()
if existing_executable is not None: if existing_executable is not None:
on_output(f"检测到已安装的 MySQL,跳过 Server 安装: {existing_executable}") on_output(f"检测到已安装的 MySQL,跳过 Server 安装: {existing_executable}")
ensure_mysql_service_running(on_output)
configure_mysql_weak_password_policy(existing_executable, on_output) configure_mysql_weak_password_policy(existing_executable, on_output)
return existing_executable return existing_executable
console = find_mysql_installer_console() console = find_mysql_installer_console()
@@ -388,6 +389,7 @@ def install_mysql(
raise RuntimeError(f"MySQL Server 安装失败,退出码: {server_exit_code}。{suffix}") raise RuntimeError(f"MySQL Server 安装失败,退出码: {server_exit_code}。{suffix}")
on_output("MySQL Server 安装任务已完成,正在检测命令行工具...") on_output("MySQL Server 安装任务已完成,正在检测命令行工具...")
executable = wait_for_mysql_executable() executable = wait_for_mysql_executable()
ensure_mysql_service_running(on_output)
configure_mysql_weak_password_policy(executable, on_output) configure_mysql_weak_password_policy(executable, on_output)
return executable return executable
@@ -396,6 +398,7 @@ def run_elevated_command(
command: list[str], command: list[str],
on_wait: Callable[[], None] | None = None, on_wait: Callable[[], None] | None = None,
wait_notice_interval: float = 30.0, wait_notice_interval: float = 30.0,
show_window: bool = True,
) -> int: ) -> int:
if os.name != "nt": if os.name != "nt":
return subprocess.run(command, shell=False).returncode return subprocess.run(command, shell=False).returncode
@@ -430,7 +433,7 @@ def run_elevated_command(
info.lpVerb = "runas" info.lpVerb = "runas"
info.lpFile = command[0] info.lpFile = command[0]
info.lpParameters = subprocess.list2cmdline(command[1:]) info.lpParameters = subprocess.list2cmdline(command[1:])
info.nShow = 1 # SW_SHOWNORMAL: show the Windows Installer progress window. info.nShow = 1 if show_window else 0
if not shell_execute(ctypes.byref(info)): if not shell_execute(ctypes.byref(info)):
error_code = ctypes.windll.kernel32.GetLastError() error_code = ctypes.windll.kernel32.GetLastError()
if error_code == 1223: if error_code == 1223:
@@ -463,6 +466,7 @@ def run_elevated_command_with_log(
command: list[str], command: list[str],
log_path: Path, log_path: Path,
on_wait: Callable[[], None] | None = None, on_wait: Callable[[], None] | None = None,
show_window: bool = True,
) -> int: ) -> int:
"""Run an elevated native command and preserve its stdout/stderr.""" """Run an elevated native command and preserve its stdout/stderr."""
log_path = Path(log_path) log_path = Path(log_path)
@@ -499,6 +503,7 @@ def run_elevated_command_with_log(
str(script_path), str(script_path),
], ],
on_wait=on_wait, on_wait=on_wait,
show_window=show_window,
) )
@@ -511,6 +516,58 @@ def _read_install_log_tail(log_path: Path, max_lines: int = 20) -> str:
return "\n".join(lines[-max_lines:]) return "\n".join(lines[-max_lines:])
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",
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} 未运行,正在请求管理员权限启动...")
command = ["sc.exe", "start", service_name]
exit_code = (
elevated_runner(command)
if elevated_runner is not None
else run_elevated_command(command, show_window=False)
)
if exit_code not in {0, 1056}:
raise RuntimeError(f"无法启动 Windows 服务 {service_name},退出码: {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
time.sleep(retry_delay)
raise RuntimeError(
f"Windows 服务 {service_name} 启动超时,请检查 MySQL 数据目录和错误日志。"
)
def _run_mysql_sql(mysql_executable: Path, sql: str, password: str) -> subprocess.CompletedProcess[str]: def _run_mysql_sql(mysql_executable: Path, sql: str, password: str) -> subprocess.CompletedProcess[str]:
environment = os.environ.copy() environment = os.environ.copy()
environment["MYSQL_PWD"] = password environment["MYSQL_PWD"] = password

View File

@@ -25,6 +25,8 @@ from deploy_tool.installer import (
configure_mysql_weak_password_policy, configure_mysql_weak_password_policy,
default_mysql_install_log_path, default_mysql_install_log_path,
default_mysql_server_install_log_path, default_mysql_server_install_log_path,
ensure_mysql_service_running,
query_mysql_service_state,
run_elevated_command_with_log, run_elevated_command_with_log,
TOMCAT_VERSION, TOMCAT_VERSION,
install_maven, install_maven,
@@ -243,6 +245,7 @@ class InstallerTests(unittest.TestCase):
return_value=Path("MySQLInstallerConsole.exe"), return_value=Path("MySQLInstallerConsole.exe"),
), ),
patch("deploy_tool.installer.wait_for_mysql_executable", return_value=Path("mysql.exe")), patch("deploy_tool.installer.wait_for_mysql_executable", return_value=Path("mysql.exe")),
patch("deploy_tool.installer.ensure_mysql_service_running"),
patch("deploy_tool.installer.configure_mysql_weak_password_policy") as configure, patch("deploy_tool.installer.configure_mysql_weak_password_policy") as configure,
): ):
messages = [] messages = []
@@ -281,6 +284,7 @@ class InstallerTests(unittest.TestCase):
), ),
patch("deploy_tool.installer.find_mysql_executable", return_value=None), patch("deploy_tool.installer.find_mysql_executable", return_value=None),
patch("deploy_tool.installer.wait_for_mysql_executable", return_value=Path("mysql.exe")), patch("deploy_tool.installer.wait_for_mysql_executable", return_value=Path("mysql.exe")),
patch("deploy_tool.installer.ensure_mysql_service_running"),
patch("deploy_tool.installer.configure_mysql_weak_password_policy") as configure, patch("deploy_tool.installer.configure_mysql_weak_password_policy") as configure,
): ):
messages = [] messages = []
@@ -314,8 +318,9 @@ class InstallerTests(unittest.TestCase):
with tempfile.TemporaryDirectory() as tmp: with tempfile.TemporaryDirectory() as tmp:
log_path = Path(tmp) / "mysql-server-install.log" log_path = Path(tmp) / "mysql-server-install.log"
def inspect_wrapper(command, on_wait=None): def inspect_wrapper(command, on_wait=None, show_window=True):
self.assertEqual(command[0], "powershell.exe") self.assertEqual(command[0], "powershell.exe")
self.assertTrue(show_window)
script_path = Path(command[-1]) script_path = Path(command[-1])
self.assertTrue(script_path.exists()) self.assertTrue(script_path.exists())
script = script_path.read_text(encoding="utf-8-sig") script = script_path.read_text(encoding="utf-8-sig")
@@ -409,6 +414,7 @@ class InstallerTests(unittest.TestCase):
mysql = Path(r"C:\Program Files\MySQL\MySQL Server 8.0\bin\mysql.exe") mysql = Path(r"C:\Program Files\MySQL\MySQL Server 8.0\bin\mysql.exe")
with ( with (
patch("deploy_tool.installer.find_mysql_executable", return_value=mysql), patch("deploy_tool.installer.find_mysql_executable", return_value=mysql),
patch("deploy_tool.installer.ensure_mysql_service_running") as ensure_service,
patch("deploy_tool.installer.configure_mysql_weak_password_policy") as configure, patch("deploy_tool.installer.configure_mysql_weak_password_policy") as configure,
patch("deploy_tool.installer.find_mysql_installer_console") as find_console, patch("deploy_tool.installer.find_mysql_installer_console") as find_console,
): ):
@@ -416,10 +422,41 @@ class InstallerTests(unittest.TestCase):
executable = install_mysql(messages.append) executable = install_mysql(messages.append)
self.assertEqual(executable, mysql) self.assertEqual(executable, mysql)
ensure_service.assert_called_once_with(messages.append)
configure.assert_called_once_with(mysql, messages.append) configure.assert_called_once_with(mysql, messages.append)
find_console.assert_not_called() find_console.assert_not_called()
self.assertTrue(any("跳过 Server 安装" in message for message in messages)) self.assertTrue(any("跳过 Server 安装" in message for message in messages))
def test_reads_mysql_windows_service_state_without_console_window(self):
running = CompletedProcess([], 0, stdout=b"STATE : 4 RUNNING\r\n", stderr=b"")
with patch("deploy_tool.installer.subprocess.run", return_value=running) as run:
state = query_mysql_service_state()
self.assertEqual(state, 4)
self.assertEqual(run.call_args.args[0], ["sc.exe", "query", "MySQL80"])
self.assertEqual(
run.call_args.kwargs["creationflags"],
getattr(subprocess, "CREATE_NO_WINDOW", 0),
)
def test_starts_stopped_mysql_windows_service(self):
commands = []
def elevated_runner(command):
commands.append(command)
return 0
with (
patch("deploy_tool.installer.query_mysql_service_state", side_effect=[1, 2, 4]),
patch("deploy_tool.installer.time.sleep"),
):
messages = []
ensure_mysql_service_running(messages.append, elevated_runner=elevated_runner)
self.assertEqual(commands, [["sc.exe", "start", "MySQL80"]])
self.assertTrue(any("已启动" in message for message in messages))
def test_mysql_without_validation_component_still_sets_and_verifies_password(self): def test_mysql_without_validation_component_still_sets_and_verifies_password(self):
no_component = CompletedProcess([], 0, stdout="", stderr="") no_component = CompletedProcess([], 0, stdout="", stderr="")
success = CompletedProcess([], 0, stdout="1\n", stderr="") success = CompletedProcess([], 0, stdout="1\n", stderr="")