Repair incomplete MySQL server setup

This commit is contained in:
王鹏
2026-10-09 11:00:40 +08:00
parent 7966b061c0
commit a2cf38f1a4
2 changed files with 66 additions and 17 deletions

View File

@@ -260,15 +260,20 @@ def configure_mysql_weak_password_policy(
break break
error_text = f"{variables_result.stderr}\n{variables_result.stdout}".lower() error_text = f"{variables_result.stderr}\n{variables_result.stdout}".lower()
if "access denied" in error_text or "error 1045" in error_text: if "access denied" in error_text or "error 1045" in error_text:
for candidate_password, message in (
(final_password, "检测到 root 已使用默认密码,继续校验弱密码策略..."),
("", "检测到新初始化的无密码 root 账号,立即设置默认密码..."),
):
configured_result = _run_mysql_sql( configured_result = _run_mysql_sql(
mysql_executable, mysql_executable,
"SHOW VARIABLES LIKE 'validate_password%';", "SHOW VARIABLES LIKE 'validate_password%';",
final_password, candidate_password,
) )
if configured_result.returncode == 0: if configured_result.returncode == 0:
variables_result = configured_result variables_result = configured_result
active_password = final_password active_password = candidate_password
on_output("检测到 root 已使用默认密码,继续校验弱密码策略...") on_output(message)
break
break break
if attempt + 1 < total_attempts: if attempt + 1 < total_attempts:
if attempt == 0 or (attempt + 1) % 5 == 0: if attempt == 0 or (attempt + 1) % 5 == 0:
@@ -558,10 +563,15 @@ def ensure_mysql_service_running(
else: else:
service_log = default_mysql_service_log_path() service_log = default_mysql_service_log_path()
on_output(f"MySQL 服务启动日志: {service_log}") on_output(f"MySQL 服务启动日志: {service_log}")
server_executable = (
Path(mysql_executable).with_name("mysqld.exe")
if mysql_executable is not None
else None
)
exit_code = run_mysql_service_start_diagnostic( exit_code = run_mysql_service_start_diagnostic(
service_name, service_name,
service_log, service_log,
mysql_executable=mysql_executable, mysql_server_executable=server_executable,
) )
if exit_code not in {0, 1056}: if exit_code not in {0, 1056}:
on_output( on_output(
@@ -589,10 +599,10 @@ def ensure_mysql_service_running(
def build_mysql_service_start_script( def build_mysql_service_start_script(
service_name: str = "MySQL80", service_name: str = "MySQL80",
mysql_executable: Path | None = None, mysql_server_executable: Path | None = None,
) -> str: ) -> str:
escaped_service_name = service_name.replace("'", "''") escaped_service_name = service_name.replace("'", "''")
escaped_mysql_executable = str(mysql_executable or "").replace("'", "''") escaped_mysql_executable = str(mysql_server_executable or "").replace("'", "''")
return ( return (
"$ErrorActionPreference='Continue';" "$ErrorActionPreference='Continue';"
f"$name='{escaped_service_name}';" f"$name='{escaped_service_name}';"
@@ -608,6 +618,14 @@ def build_mysql_service_start_script(
"Write-Output ('my.ini: '+$ini+' exists='+[bool](Test-Path -LiteralPath $ini));" "Write-Output ('my.ini: '+$ini+' exists='+[bool](Test-Path -LiteralPath $ini));"
"$data=Join-Path $env:ProgramData 'MySQL\\MySQL Server 8.0\\Data';" "$data=Join-Path $env:ProgramData 'MySQL\\MySQL Server 8.0\\Data';"
"Write-Output ('Data directory: '+$data+' exists='+[bool](Test-Path -LiteralPath $data));" "Write-Output ('Data directory: '+$data+' exists='+[bool](Test-Path -LiteralPath $data));"
"if(Test-Path -LiteralPath $data){"
"Write-Output 'Granting MySQL service account access to the data directory...';"
"& icacls.exe $data /grant '*S-1-5-20:(OI)(CI)M' /T /C 2>&1 | Out-String | Write-Output;"
"try { Start-Service -Name $name -ErrorAction Stop } catch { Write-Output ($_ | Out-String) };"
"Start-Sleep -Seconds 8;"
"$service=Get-CimInstance Win32_Service -Filter (\"Name='\"+$name+\"'\");"
"Write-Output ('Service state after permission repair: '+$service.State)"
"};"
"$err=Get-ChildItem -LiteralPath $data -Filter '*.err' -File -ErrorAction SilentlyContinue | " "$err=Get-ChildItem -LiteralPath $data -Filter '*.err' -File -ErrorAction SilentlyContinue | "
"Sort-Object LastWriteTime -Descending | Select-Object -First 1;" "Sort-Object LastWriteTime -Descending | Select-Object -First 1;"
"if($err){Write-Output ('Error log: '+$err.FullName); Get-Content -LiteralPath $err.FullName -Tail 30}" "if($err){Write-Output ('Error log: '+$err.FullName); Get-Content -LiteralPath $err.FullName -Tail 30}"
@@ -619,6 +637,18 @@ def build_mysql_service_start_script(
"& $mysqlExe (\"--defaults-file=\"+$ini) --validate-config --console 2>&1 | Out-String | Write-Output;" "& $mysqlExe (\"--defaults-file=\"+$ini) --validate-config --console 2>&1 | Out-String | Write-Output;"
"Write-Output ('validate-config exit code: '+$LASTEXITCODE)" "Write-Output ('validate-config exit code: '+$LASTEXITCODE)"
"};" "};"
"$systemDatabase=Join-Path $data 'mysql';"
"if($service.State -ne 'Running' -and $mysqlExe -and "
"(Test-Path -LiteralPath $mysqlExe) -and -not (Test-Path -LiteralPath $systemDatabase)){"
"Write-Output 'MySQL system database is missing; attempting safe initialization without deleting data...';"
"& $mysqlExe (\"--defaults-file=\"+$ini) --initialize-insecure --console 2>&1 | Out-String | Write-Output;"
"Write-Output ('initialize-insecure exit code: '+$LASTEXITCODE);"
"& icacls.exe $data /grant '*S-1-5-20:(OI)(CI)M' /T /C 2>&1 | Out-String | Write-Output;"
"try { Start-Service -Name $name -ErrorAction Stop } catch { Write-Output ($_ | Out-String) };"
"Start-Sleep -Seconds 12;"
"$service=Get-CimInstance Win32_Service -Filter (\"Name='\"+$name+\"'\");"
"Write-Output ('Service state after initialization: '+$service.State)"
"};"
"$since=(Get-Date).AddMinutes(-10);" "$since=(Get-Date).AddMinutes(-10);"
"Write-Output 'Recent Windows service events:';" "Write-Output 'Recent Windows service events:';"
"Get-WinEvent -FilterHashtable @{LogName='System';StartTime=$since} -ErrorAction SilentlyContinue | " "Get-WinEvent -FilterHashtable @{LogName='System';StartTime=$since} -ErrorAction SilentlyContinue | "
@@ -636,12 +666,12 @@ def build_mysql_service_start_script(
def run_mysql_service_start_diagnostic( def run_mysql_service_start_diagnostic(
service_name: str, service_name: str,
log_path: Path, log_path: Path,
mysql_executable: Path | None = None, mysql_server_executable: Path | None = None,
) -> int: ) -> int:
with tempfile.TemporaryDirectory(prefix="autodeploy-mysql-service-") as temporary: with tempfile.TemporaryDirectory(prefix="autodeploy-mysql-service-") as temporary:
script_path = Path(temporary) / "start-mysql-service.ps1" script_path = Path(temporary) / "start-mysql-service.ps1"
script_path.write_text( script_path.write_text(
build_mysql_service_start_script(service_name, mysql_executable), build_mysql_service_start_script(service_name, mysql_server_executable),
encoding="utf-8-sig", encoding="utf-8-sig",
) )
return run_elevated_command_with_log( return run_elevated_command_with_log(

View File

@@ -386,7 +386,9 @@ class InstallerTests(unittest.TestCase):
retry_delay=0, retry_delay=0,
) )
self.assertEqual(run.call_count, 2) self.assertEqual(run.call_count, 3)
self.assertEqual(run.call_args_list[1].kwargs["env"]["MYSQL_PWD"], MYSQL_ROOT_PASSWORD)
self.assertEqual(run.call_args_list[2].kwargs["env"]["MYSQL_PWD"], "")
def test_mysql_password_configuration_accepts_already_configured_password(self): def test_mysql_password_configuration_accepts_already_configured_password(self):
denied = CompletedProcess( denied = CompletedProcess(
@@ -476,9 +478,23 @@ class InstallerTests(unittest.TestCase):
self.assertTrue(any("继续等待运行状态" in message for message in messages)) self.assertTrue(any("继续等待运行状态" in message for message in messages))
self.assertTrue(any("已启动" in message for message in messages)) self.assertTrue(any("已启动" in message for message in messages))
def test_mysql_service_diagnostic_uses_server_executable(self):
mysql_client = Path(r"C:\Program Files\MySQL\MySQL Server 8.0\bin\mysql.exe")
with (
patch("deploy_tool.installer.query_mysql_service_state", side_effect=[1, 4]),
patch("deploy_tool.installer.run_mysql_service_start_diagnostic", return_value=0) as diagnostic,
):
ensure_mysql_service_running(lambda _message: None, mysql_executable=mysql_client)
diagnostic.assert_called_once()
self.assertEqual(
diagnostic.call_args.kwargs["mysql_server_executable"],
mysql_client.with_name("mysqld.exe"),
)
def test_builds_privileged_mysql_service_start_diagnostic(self): def test_builds_privileged_mysql_service_start_diagnostic(self):
script = build_mysql_service_start_script( script = build_mysql_service_start_script(
mysql_executable=Path(r"C:\Program Files\MySQL\MySQL Server 8.0\bin\mysqld.exe") mysql_server_executable=Path(r"C:\Program Files\MySQL\MySQL Server 8.0\bin\mysqld.exe")
) )
self.assertIn("Start-Service -Name $name", script) self.assertIn("Start-Service -Name $name", script)
self.assertIn("Get-CimInstance Win32_Service", script) self.assertIn("Get-CimInstance Win32_Service", script)
@@ -487,6 +503,9 @@ class InstallerTests(unittest.TestCase):
self.assertIn("*.err", script) self.assertIn("*.err", script)
self.assertIn("Get-Content", script) self.assertIn("Get-Content", script)
self.assertIn("--validate-config", script) self.assertIn("--validate-config", script)
self.assertIn("initialize-insecure", script)
self.assertIn("S-1-5-20", script)
self.assertIn("Service state after permission repair", script)
self.assertIn("Get-WinEvent", script) self.assertIn("Get-WinEvent", script)
self.assertIn("mysqld.exe", script) self.assertIn("mysqld.exe", script)
@@ -518,7 +537,7 @@ class InstallerTests(unittest.TestCase):
exit_code = run_mysql_service_start_diagnostic( exit_code = run_mysql_service_start_diagnostic(
"MySQL80", "MySQL80",
log_path, log_path,
mysql_executable=Path("mysqld.exe"), mysql_server_executable=Path("mysqld.exe"),
) )
self.assertEqual(exit_code, 1) self.assertEqual(exit_code, 1)