Recover empty MySQL data directories with stable log names
This commit is contained in:
@@ -16,6 +16,7 @@ from pathlib import Path
|
||||
from typing import BinaryIO, Callable
|
||||
|
||||
from .scanner import ScanResult
|
||||
from .mysql_recovery import MYSQL_RECOVERY_HELPERS
|
||||
|
||||
|
||||
JDK_PACKAGES = {
|
||||
@@ -525,6 +526,15 @@ def _read_install_log_tail(log_path: Path, max_lines: int = 20) -> str:
|
||||
return "\n".join(lines[-max_lines:])
|
||||
|
||||
|
||||
def _read_mysql_recovery_summary(log_path: Path) -> str:
|
||||
lines = _read_install_log_tail(log_path, max_lines=300).splitlines()
|
||||
causes = [line for line in lines if any(marker in line.lower() for marker in (
|
||||
"[error]", "not found", "recovery failed:", "not empty", "existing entries:",
|
||||
"configuration backup:", "data directory:", "my.ini:",
|
||||
))]
|
||||
return "\n".join(causes[:14] or lines[-20:])
|
||||
|
||||
|
||||
def query_mysql_service_state(service_name: str = "MySQL80") -> int | None:
|
||||
if os.name != "nt":
|
||||
return 4
|
||||
@@ -573,6 +583,11 @@ def ensure_mysql_service_running(
|
||||
service_log,
|
||||
mysql_server_executable=server_executable,
|
||||
)
|
||||
if exit_code == 2:
|
||||
raise RuntimeError(
|
||||
f"MySQL 初始化或配置失败。详细日志: {service_log}\n"
|
||||
f"{_read_mysql_recovery_summary(service_log)}"
|
||||
)
|
||||
if exit_code not in {0, 1056}:
|
||||
on_output(
|
||||
f"Windows 服务启动命令返回 {exit_code},服务可能仍在后台恢复,继续等待运行状态..."
|
||||
@@ -589,7 +604,7 @@ def ensure_mysql_service_running(
|
||||
)
|
||||
time.sleep(retry_delay)
|
||||
detail = mysql_service_failure_detail(mysql_executable, state)
|
||||
diagnostic = _read_install_log_tail(default_mysql_service_log_path(), max_lines=24)
|
||||
diagnostic = _read_mysql_recovery_summary(default_mysql_service_log_path())
|
||||
diagnostic_text = f"\n启动诊断:\n{diagnostic}" if diagnostic else ""
|
||||
raise RuntimeError(
|
||||
f"Windows 服务 {service_name} 启动超时,启动命令退出码: {exit_code}。"
|
||||
@@ -604,62 +619,78 @@ def build_mysql_service_start_script(
|
||||
escaped_service_name = service_name.replace("'", "''")
|
||||
escaped_mysql_executable = str(mysql_server_executable or "").replace("'", "''")
|
||||
return (
|
||||
"$ErrorActionPreference='Continue';"
|
||||
f"$name='{escaped_service_name}';"
|
||||
f"$mysqlExe='{escaped_mysql_executable}';"
|
||||
"$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,ExitCode,ProcessId | "
|
||||
"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));"
|
||||
"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 | "
|
||||
"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($mysqlExe -and (Test-Path -LiteralPath $mysqlExe)){"
|
||||
"Write-Output ('mysqld.exe: '+$mysqlExe);"
|
||||
"Write-Output 'mysqld version:'; & $mysqlExe --version 2>&1 | Out-String | Write-Output;"
|
||||
"Write-Output 'mysqld configuration validation:';"
|
||||
"& $mysqlExe (\"--defaults-file=\"+$ini) --validate-config --console 2>&1 | Out-String | Write-Output;"
|
||||
"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);"
|
||||
"Write-Output 'Recent Windows service events:';"
|
||||
"Get-WinEvent -FilterHashtable @{LogName='System';StartTime=$since} -ErrorAction SilentlyContinue | "
|
||||
"Where-Object {$_.ProviderName -eq 'Service Control Manager' -and $_.Message -match $name} | "
|
||||
"Select-Object -First 8 TimeCreated,Id,LevelDisplayName,Message | Format-List | Out-String | Write-Output;"
|
||||
"Write-Output 'Recent MySQL/Application events:';"
|
||||
"Get-WinEvent -FilterHashtable @{LogName='Application';StartTime=$since} -ErrorAction SilentlyContinue | "
|
||||
"Where-Object {$_.ProviderName -match 'MySQL|Application Error' -or $_.Message -match 'mysqld|MySQL80'} | "
|
||||
"Select-Object -First 8 TimeCreated,ProviderName,Id,LevelDisplayName,Message | "
|
||||
"Format-List | Out-String | Write-Output;"
|
||||
"if($service.State -eq 'Running'){exit 0}else{exit 1}"
|
||||
MYSQL_RECOVERY_HELPERS
|
||||
+ f"\n$name='{escaped_service_name}';\n"
|
||||
+ f"$mysqlExe='{escaped_mysql_executable}';\n"
|
||||
+ r'''
|
||||
$ErrorActionPreference = 'Continue'
|
||||
$data = ''
|
||||
$recoveryFailed = $false
|
||||
try {
|
||||
$service = Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") -ErrorAction Stop
|
||||
if (-not $service) { throw ('Windows service not found: ' + $name) }
|
||||
$service | Select-Object Name,State,StartName,PathName,ExitCode,ProcessId |
|
||||
Format-List | Out-String | Write-Output
|
||||
if ($service.State -eq 'Running') { exit 0 }
|
||||
$layout = Get-MySqlServiceLayout $service
|
||||
$mysqlExe = $layout.Server
|
||||
$ini = $layout.Ini
|
||||
$data = $layout.Data
|
||||
Write-Output ('mysqld.exe: ' + $mysqlExe)
|
||||
Write-Output ('my.ini: ' + $ini)
|
||||
Write-Output ('Data directory: ' + $data)
|
||||
if ($service.State -eq 'Stopped' -and $service.ProcessId -eq 0) {
|
||||
$initialized = Initialize-EmptyMySqlData $service $layout
|
||||
# Use the account actually registered for this service.
|
||||
$account = $service.StartName
|
||||
if ($account -eq 'NT AUTHORITY\NetworkService') { $sid = 'S-1-5-20' }
|
||||
elseif ($account -eq 'LocalSystem') { $sid = 'S-1-5-18' }
|
||||
else {
|
||||
$identity = New-Object Security.Principal.NTAccount($account)
|
||||
$sid = $identity.Translate([Security.Principal.SecurityIdentifier]).Value
|
||||
}
|
||||
$grantCode = Invoke-MySqlRecoveryCommand 'icacls.exe' @(
|
||||
$data, '/grant', ('*' + $sid + ':(OI)(CI)M'), '/T', '/C'
|
||||
)
|
||||
if ($grantCode -ne 0) { throw ('Data directory permission repair failed: ' + $grantCode) }
|
||||
Write-Output 'mysqld configuration validation:'
|
||||
$validation = Invoke-MySqlRecoveryCommand $mysqlExe @(
|
||||
('--defaults-file=' + $ini), '--validate-config', '--console'
|
||||
)
|
||||
if ($validation -ne 0) { throw ('MySQL configuration validation failed: ' + $validation) }
|
||||
try { Start-Service -Name $name -ErrorAction Stop }
|
||||
catch { Write-Output ('Start-Service: ' + $_.Exception.Message) }
|
||||
}
|
||||
for ($attempt = 0; $attempt -lt 12; $attempt++) {
|
||||
$service = Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'")
|
||||
if ($service.State -eq 'Running') {
|
||||
Write-Output 'MySQL service is running.'
|
||||
exit 0
|
||||
}
|
||||
if ($service.State -eq 'Stopped') { break }
|
||||
Start-Sleep -Seconds 1
|
||||
}
|
||||
Write-Output ('Service state after recovery: ' + $service.State)
|
||||
} catch {
|
||||
$recoveryFailed = $true
|
||||
Write-Output ('MySQL recovery failed: ' + $_.Exception.Message)
|
||||
}
|
||||
if ($data -and (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.' }
|
||||
}
|
||||
$since = (Get-Date).AddMinutes(-10)
|
||||
if ($recoveryFailed) { exit 2 }
|
||||
Write-Output 'Recent Windows service events:'
|
||||
Get-WinEvent -FilterHashtable @{LogName='System';StartTime=$since} -ErrorAction SilentlyContinue |
|
||||
Where-Object {$_.ProviderName -eq 'Service Control Manager' -and $_.Message -match $name} |
|
||||
Select-Object -First 3 TimeCreated,Id,Message | Format-List | Out-String | Write-Output
|
||||
exit 1
|
||||
'''
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user