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()
if existing_executable is not None:
on_output(f"检测到已安装的 MySQL,跳过 Server 安装: {existing_executable}")
ensure_mysql_service_running(on_output)
configure_mysql_weak_password_policy(existing_executable, on_output)
return existing_executable
console = find_mysql_installer_console()
@@ -388,6 +389,7 @@ def install_mysql(
raise RuntimeError(f"MySQL Server 安装失败,退出码: {server_exit_code}。{suffix}")
on_output("MySQL Server 安装任务已完成,正在检测命令行工具...")
executable = wait_for_mysql_executable()
ensure_mysql_service_running(on_output)
configure_mysql_weak_password_policy(executable, on_output)
return executable
@@ -396,6 +398,7 @@ 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
@@ -430,7 +433,7 @@ def run_elevated_command(
info.lpVerb = "runas"
info.lpFile = command[0]
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)):
error_code = ctypes.windll.kernel32.GetLastError()
if error_code == 1223:
@@ -463,6 +466,7 @@ 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)
@@ -499,6 +503,7 @@ def run_elevated_command_with_log(
str(script_path),
],
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:])
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]:
environment = os.environ.copy()
environment["MYSQL_PWD"] = password