Capture privileged MySQL service diagnostics

This commit is contained in:
王鹏
2026-10-09 10:44:33 +08:00
parent 37d266ad2a
commit d1321d8059
2 changed files with 72 additions and 7 deletions

View File

@@ -176,6 +176,10 @@ def default_mysql_server_install_log_path() -> Path:
return default_mysql_install_log_path().with_name("mysql-server-install.log") 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: def find_mysql_executable() -> Path | None:
discovered = shutil.which("mysql") discovered = shutil.which("mysql")
if discovered: if discovered:
@@ -549,14 +553,23 @@ def ensure_mysql_service_running(
raise RuntimeError(f"已找到 MySQL 文件,但未找到 Windows 服务 {service_name}。") raise RuntimeError(f"已找到 MySQL 文件,但未找到 Windows 服务 {service_name}。")
on_output(f"Windows 服务 {service_name} 未运行,正在请求管理员权限启动...") on_output(f"Windows 服务 {service_name} 未运行,正在请求管理员权限启动...")
command = ["sc.exe", "start", service_name] if elevated_runner is not None:
exit_code = ( exit_code = elevated_runner(["sc.exe", "start", service_name])
elevated_runner(command) else:
if elevated_runner is not None service_log = default_mysql_service_log_path()
else run_elevated_command(command, show_window=False) on_output(f"MySQL 服务启动日志: {service_log}")
) exit_code = run_elevated_command_with_log(
build_mysql_service_start_command(service_name),
service_log,
show_window=False,
)
if exit_code not in {0, 1056}: if exit_code not in {0, 1056}:
raise RuntimeError(f"无法启动 Windows 服务 {service_name},退出码: {exit_code}。") detail = _read_install_log_tail(default_mysql_service_log_path(), max_lines=24)
suffix = f"\n{detail}" if detail else ""
raise RuntimeError(
f"无法启动 Windows 服务 {service_name},退出码: {exit_code}。"
f" 详细日志: {default_mysql_service_log_path()}{suffix}"
)
for attempt in range(max(attempts, 1)): for attempt in range(max(attempts, 1)):
state = query_mysql_service_state(service_name) state = query_mysql_service_state(service_name)
@@ -573,6 +586,38 @@ def ensure_mysql_service_running(
) )
def build_mysql_service_start_command(service_name: str = "MySQL80") -> list[str]:
escaped_service_name = service_name.replace("'", "''")
script = (
"$ErrorActionPreference='Continue';"
f"$name='{escaped_service_name}';"
"$startError='';"
"try { Start-Service -Name $name -ErrorAction Stop } "
"catch { $startError=($_ | Out-String); Write-Output $startError };"
"Start-Sleep -Seconds 3;"
"$service=Get-CimInstance Win32_Service -Filter (\"Name='\"+$name+\"'\");"
"$service | Select-Object Name,State,StartName,PathName | Format-List | Out-String | Write-Output;"
"$ini=Join-Path $env:ProgramData 'MySQL\\MySQL Server 8.0\\my.ini';"
"Write-Output ('my.ini: '+$ini+' exists='+[bool](Test-Path -LiteralPath $ini));"
"$data=Join-Path $env:ProgramData 'MySQL\\MySQL Server 8.0\\Data';"
"Write-Output ('Data directory: '+$data+' exists='+[bool](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.'};"
"if($service.State -eq 'Running'){exit 0}else{exit 1}"
)
return [
"powershell.exe",
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-Command",
script,
]
def find_mysql_error_log(mysql_executable: Path | None = None) -> Path | None: def find_mysql_error_log(mysql_executable: Path | None = None) -> Path | None:
data_roots: list[Path] = [] data_roots: list[Path] = []
program_data = os.environ.get("PROGRAMDATA", "").strip() program_data = os.environ.get("PROGRAMDATA", "").strip()

View File

@@ -22,9 +22,11 @@ from deploy_tool.installer import (
NODE_DIST_BASE, NODE_DIST_BASE,
build_mysql_installer_command, build_mysql_installer_command,
build_mysql_server_install_command, build_mysql_server_install_command,
build_mysql_service_start_command,
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,
default_mysql_service_log_path,
ensure_mysql_service_running, ensure_mysql_service_running,
find_mysql_error_log, find_mysql_error_log,
mysql_service_failure_detail, mysql_service_failure_detail,
@@ -459,6 +461,24 @@ class InstallerTests(unittest.TestCase):
self.assertEqual(commands, [["sc.exe", "start", "MySQL80"]]) self.assertEqual(commands, [["sc.exe", "start", "MySQL80"]])
self.assertTrue(any("已启动" in message for message in messages)) self.assertTrue(any("已启动" in message for message in messages))
def test_builds_privileged_mysql_service_start_diagnostic(self):
command = build_mysql_service_start_command()
self.assertEqual(command[0], "powershell.exe")
script = command[-1]
self.assertIn("Start-Service -Name $name", script)
self.assertIn("Get-CimInstance Win32_Service", script)
self.assertIn("my.ini", script)
self.assertIn("*.err", script)
self.assertIn("Get-Content", script)
with patch.dict("os.environ", {"LOCALAPPDATA": r"C:\Users\tester\AppData\Local"}):
log_path = default_mysql_service_log_path()
self.assertEqual(
log_path,
Path(r"C:\Users\tester\AppData\Local") / "AutoDeploy" / "logs" / "mysql-service-start.log",
)
def test_reports_mysql_error_log_when_service_stops_after_start(self): def test_reports_mysql_error_log_when_service_stops_after_start(self):
with tempfile.TemporaryDirectory() as tmp: with tempfile.TemporaryDirectory() as tmp:
program_data = Path(tmp) program_data = Path(tmp)