param( [string]$RepoRoot = (Split-Path -Parent $PSScriptRoot), [string]$ServerInfoPath = "", [switch]$DryRun, [switch]$Deploy, [switch]$UsePuttyPassword, [switch]$SkipBuild, [switch]$SkipTests, [switch]$AllowDirtyWorkingTree, [switch]$SkipDatabaseInit, [string]$DatabaseTargetName = "mysql02", [int]$DatabasePort = 3306, [string]$DatabaseName = "nailart", [string]$DatabaseUser = "", [string]$DatabasePassword = "", [string]$InitSqlPath = "", [string]$CorePattern = "^YumiNail-Core", [string]$GatewayPattern = "^YumiNail-Gateway", [string]$WebTargetName = "", [string]$WebTargetHost = "8.137.35.61", [string]$CoreRemoteAppDir = "/opt/yuminail-core", [string]$GatewayRemoteAppDir = "/opt/yuminail-gateway", [string]$WebRemoteDir = "/opt/yuminail-frontend", [string]$CoreServiceName = "yuminail-core", [string]$GatewayServiceName = "yuminail-gateway", [int]$CoreHealthPort = 81, [int]$GatewayHealthPort = 80, [string]$HealthPath = "/health/check", [int]$HealthTimeoutSeconds = 120, [string]$PublicBaseUrl = "https://yunail.art", [string]$MavenPath = "" ) $ErrorActionPreference = "Stop" $ReleaseTimestamp = Get-Date -Format "yyyyMMdd-HHmmss" $ResolvedRepoRoot = (Resolve-Path -LiteralPath $RepoRoot).Path $ReleaseRoot = Join-Path $ResolvedRepoRoot "artifacts\release" $ReleaseDir = Join-Path $ReleaseRoot $ReleaseTimestamp $BackendDir = Join-Path $ReleaseDir "backend" $FrontendDir = Join-Path $ReleaseDir "frontend" $SqlDir = Join-Path $ReleaseDir "sql" $ManifestPath = Join-Path $ReleaseDir "manifest.json" $DefaultInitSqlPath = Join-Path $ResolvedRepoRoot "YumiNail-Core\src\main\resources\files\YumiNail.sql" if (-not $InitSqlPath) { $InitSqlPath = $DefaultInitSqlPath } function Write-Step { param([string]$Message) Write-Host "" Write-Host "==> $Message" } function Resolve-ServerInfoPath { param([string]$ExplicitPath) if ($ExplicitPath) { if (-not (Test-Path -LiteralPath $ExplicitPath)) { throw "Server workbook not found: $ExplicitPath" } return (Resolve-Path -LiteralPath $ExplicitPath).Path } $codeRoot = "Y:\code" if (-not (Test-Path -LiteralPath $codeRoot)) { throw "Server workbook path was not provided and $codeRoot does not exist." } $workbooks = @(Get-ChildItem -LiteralPath $codeRoot -Filter "*.xlsx" -File | Sort-Object LastWriteTime -Descending) if ($workbooks.Count -eq 0) { throw "No .xlsx server workbook found under $codeRoot. Pass -ServerInfoPath explicitly." } return $workbooks[0].FullName } function ConvertTo-BashSingleQuoted { param([AllowNull()][string]$Value) if ($null -eq $Value) { $Value = "" } return "'" + $Value.Replace("'", "'""'""'") + "'" } function Read-ZipEntryText { param($Zip, [string]$Name) $entry = $Zip.GetEntry($Name) if (-not $entry) { return $null } $stream = $entry.Open() try { $reader = [System.IO.StreamReader]::new($stream, [System.Text.Encoding]::UTF8) try { return $reader.ReadToEnd() } finally { $reader.Dispose() } } finally { $stream.Dispose() } } function Get-RelationshipId { param($Element) foreach ($attribute in $Element.Attributes) { if ($attribute.LocalName -eq "id") { return $attribute.Value } } return "" } function Get-ColumnIndex { param([string]$CellRef) $letters = ([regex]::Match($CellRef, "^[A-Z]+")).Value $index = 0 foreach ($character in $letters.ToCharArray()) { $index = ($index * 26) + ([int][char]$character - [int][char]"A" + 1) } return $index } function Get-XlsxFirstSheetRows { param([string]$Path) Add-Type -AssemblyName System.IO.Compression.FileSystem $zip = [System.IO.Compression.ZipFile]::OpenRead($Path) try { $sharedStrings = @() $sharedText = Read-ZipEntryText $zip "xl/sharedStrings.xml" if ($sharedText) { [xml]$sharedXml = $sharedText foreach ($sharedItem in $sharedXml.GetElementsByTagName("si")) { $sharedStrings += $sharedItem.InnerText } } [xml]$workbookXml = Read-ZipEntryText $zip "xl/workbook.xml" [xml]$relsXml = Read-ZipEntryText $zip "xl/_rels/workbook.xml.rels" $firstSheet = $workbookXml.GetElementsByTagName("sheet").Item(0) if (-not $firstSheet) { throw "Workbook has no sheets: $Path" } $relationshipId = Get-RelationshipId $firstSheet $relationship = $null foreach ($candidate in $relsXml.GetElementsByTagName("Relationship")) { if ($candidate.GetAttribute("Id") -eq $relationshipId) { $relationship = $candidate break } } if (-not $relationship) { throw "Cannot resolve workbook relationship $relationshipId" } $target = $relationship.Target $sheetPath = if ($target.StartsWith("/")) { $target.TrimStart("/") } elseif ($target.StartsWith("xl/")) { $target } else { "xl/$target" } [xml]$sheetXml = Read-ZipEntryText $zip $sheetPath $rows = @() foreach ($row in $sheetXml.GetElementsByTagName("row")) { $valuesByIndex = @{} $maxIndex = 0 foreach ($cell in $row.GetElementsByTagName("c")) { $index = Get-ColumnIndex $cell.r $maxIndex = [Math]::Max($maxIndex, $index) $valueNodes = $cell.GetElementsByTagName("v") $valueNode = if ($valueNodes.Count -gt 0) { $valueNodes.Item(0) } else { $null } $value = "" if ($cell.GetAttribute("t") -eq "s" -and $valueNode -and $valueNode.InnerText -ne "") { $sharedIndex = [int]$valueNode.InnerText if ($sharedIndex -lt $sharedStrings.Count) { $value = $sharedStrings[$sharedIndex] } } elseif ($cell.GetAttribute("t") -eq "inlineStr") { $value = $cell.InnerText } elseif ($valueNode) { $value = $valueNode.InnerText } $valuesByIndex[$index] = $value } if ($maxIndex -gt 0) { $values = for ($i = 1; $i -le $maxIndex; $i++) { if ($valuesByIndex.ContainsKey($i)) { $valuesByIndex[$i] } else { "" } } if (($values -join "").Trim()) { $rows += ,$values } } } return $rows } finally { $zip.Dispose() } } function Get-ServersFromWorkbook { param([string]$Path) if (-not (Test-Path -LiteralPath $Path)) { throw "Server workbook not found: $Path" } $rows = @(Get-XlsxFirstSheetRows (Resolve-Path -LiteralPath $Path).Path) if ($rows.Count -lt 2) { throw "Server workbook has no data rows: $Path" } foreach ($row in $rows[1..($rows.Count - 1)]) { if ($row.Count -lt 5) { continue } [pscustomobject]@{ Name = [string]$row[0] Host = [string]$row[1] Port = if ($row[2]) { [int]$row[2] } else { 22 } User = [string]$row[3] Password = [string]$row[4] Purpose = if ($row.Count -gt 5) { [string]$row[5] } else { "" } Note = if ($row.Count -gt 6) { [string]$row[6] } else { "" } Environment = if ($row.Count -gt 7) { [string]$row[7] } else { "" } } } } function Assert-ProductionTarget { param([object[]]$Servers) $blocked = @($Servers | Where-Object { $_.Name -match "^(?i:MessageHub|mysql|nacos|redis|rabbitmq)" }) if ($blocked.Count -gt 0) { throw "Refusing to deploy to infrastructure or non-YumiNail rows: $($blocked.Name -join ', ')" } $knownNonProduction = @($Servers | Where-Object { $_.Environment -match "(?i)\b(dev|test|local|staging)\b" }) if ($knownNonProduction.Count -gt 0) { throw "Refusing to deploy to rows marked as non-production: $($knownNonProduction.Name -join ', ')" } } function Resolve-Maven { param([string]$PreferredPath) if ($PreferredPath -and (Test-Path -LiteralPath $PreferredPath)) { return (Resolve-Path -LiteralPath $PreferredPath).Path } $fromPath = Get-Command mvn.cmd -ErrorAction SilentlyContinue if ($fromPath) { return $fromPath.Source } $fromPath = Get-Command mvn -ErrorAction SilentlyContinue if ($fromPath) { return $fromPath.Source } $fallback = "D:\开发\apache-maven-3.9.9\bin\mvn.cmd" if (Test-Path -LiteralPath $fallback) { return $fallback } throw "Cannot find Maven. Pass -MavenPath with an absolute Maven executable path." } function Invoke-Native { param( [string]$FilePath, [string[]]$Arguments, [string]$WorkingDirectory = "", [switch]$RemoteMutation, [switch]$Sensitive ) if ($Sensitive) { Write-Host ">> $FilePath " } else { $displayArguments = @() for ($index = 0; $index -lt $Arguments.Count; $index++) { $argument = $Arguments[$index] if ($argument -eq "-pw") { $displayArguments += $argument if (($index + 1) -lt $Arguments.Count) { $displayArguments += "***" $index++ } } else { $displayArguments += $argument } } Write-Host ">> $FilePath $($displayArguments -join ' ')" } if ($DryRun -and $RemoteMutation) { return } $previousLocation = Get-Location try { if ($WorkingDirectory) { Set-Location -LiteralPath $WorkingDirectory } & $FilePath @Arguments if ($LASTEXITCODE -ne 0) { throw "Command failed with exit code ${LASTEXITCODE}: $FilePath" } } finally { Set-Location $previousLocation } } function Get-SshTarget { param([object]$Server) return "$($Server.User)@$($Server.Host)" } function Invoke-RemoteShell { param( [object]$Server, [string]$Command, [switch]$Sensitive ) if ($UsePuttyPassword) { $plink = Get-Command plink -ErrorAction SilentlyContinue if ((-not $DryRun) -and (-not $plink)) { throw "PuTTY plink not found. Install PuTTY tools or configure SSH keys and omit -UsePuttyPassword." } $plinkPath = if ($plink) { $plink.Source } else { "plink" } Invoke-Native $plinkPath @("-batch", "-ssh", "-P", [string]$Server.Port, "-l", $Server.User, "-pw", $Server.Password, $Server.Host, $Command) -Sensitive:$Sensitive -RemoteMutation } else { Invoke-Native "ssh" @("-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=accept-new", "-p", [string]$Server.Port, (Get-SshTarget $Server), $Command) -Sensitive:$Sensitive -RemoteMutation } } function Copy-FileToRemote { param( [string]$LocalPath, [object]$Server, [string]$RemotePath, [switch]$Sensitive ) if (-not (Test-Path -LiteralPath $LocalPath)) { throw "Local upload file not found: $LocalPath" } if ($UsePuttyPassword) { $pscp = Get-Command pscp -ErrorAction SilentlyContinue if ((-not $DryRun) -and (-not $pscp)) { throw "PuTTY pscp not found. Install PuTTY tools or configure SSH keys and omit -UsePuttyPassword." } $pscpPath = if ($pscp) { $pscp.Source } else { "pscp" } Invoke-Native $pscpPath @("-batch", "-P", [string]$Server.Port, "-pw", $Server.Password, $LocalPath, "$(Get-SshTarget $Server):$RemotePath") -Sensitive:$Sensitive -RemoteMutation } else { Invoke-Native "scp" @("-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=accept-new", "-P", [string]$Server.Port, $LocalPath, "$(Get-SshTarget $Server):$RemotePath") -Sensitive:$Sensitive -RemoteMutation } } function Invoke-RemoteShellParallel { param( [object[]]$Servers, [string]$Command, [string]$GroupName ) if ($DryRun) { foreach ($server in $Servers) { Write-Host "DryRun parallel $GroupName on $($server.Name):" Invoke-RemoteShell $server $Command } return } if ($UsePuttyPassword) { foreach ($server in $Servers) { Invoke-RemoteShell $server $Command -Sensitive } return } $jobs = foreach ($server in $Servers) { Start-Job -Name "$GroupName-$($server.Name)" -ScriptBlock { param([int]$Port, [string]$User, [string]$HostName, [string]$RemoteCommand) & ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new -p $Port "$User@$HostName" $RemoteCommand exit $LASTEXITCODE } -ArgumentList $server.Port, $server.User, $server.Host, $Command } $failed = @() foreach ($job in $jobs) { Wait-Job $job | Out-Null $output = Receive-Job $job if ($output) { $output | ForEach-Object { Write-Host "[$($job.Name)] $_" } } if ($job.State -ne "Completed") { $failed += $job.Name } elseif ($job.ChildJobs[0].JobStateInfo.Reason -and $job.ChildJobs[0].JobStateInfo.Reason.Message) { $failed += $job.Name } Remove-Job $job -Force } if ($failed.Count -gt 0) { throw "Parallel remote command failed for ${GroupName}: $($failed -join ', ')" } } function Test-GitState { Push-Location $ResolvedRepoRoot try { $commit = (& git rev-parse HEAD).Trim() $branch = (& git branch --show-current).Trim() $status = @(& git status --porcelain) $dirty = $status.Count -gt 0 if ($dirty) { Write-Warning "Git working tree has $($status.Count) changed paths." $status | Select-Object -First 40 | ForEach-Object { Write-Warning $_ } if ($Deploy -and (-not $DryRun) -and (-not $AllowDirtyWorkingTree)) { throw "Refusing production deployment from a dirty working tree. Commit/stash first or rerun with -AllowDirtyWorkingTree." } } return [pscustomobject]@{ Branch = $branch Commit = $commit Dirty = $dirty ChangedPathCount = $status.Count ChangedPaths = @($status) } } finally { Pop-Location } } function Test-SqlSafety { param([string]$Path) if (-not (Test-Path -LiteralPath $Path)) { throw "Init SQL not found: $Path" } $content = Get-Content -LiteralPath $Path -Raw $dangerousMatch = [regex]::Match($content, "(?im)^\s*(drop\s+(database|schema|table)|truncate\s+table|delete\s+from)\b") if ($dangerousMatch.Success) { throw "Refusing init SQL with destructive statement near: $($dangerousMatch.Value)" } } function Build-ReleasePackage { param([object]$GitState) New-Item -ItemType Directory -Force -Path $BackendDir, $FrontendDir, $SqlDir | Out-Null $maven = Resolve-Maven $MavenPath if (-not $SkipBuild) { $mavenArgs = @("-q", "package") if ($SkipTests) { $mavenArgs += "-DskipTests" } Write-Step "Build YumiNail-Core" Invoke-Native $maven $mavenArgs (Join-Path $ResolvedRepoRoot "YumiNail-Core") Write-Step "Build YumiNail-Gateway" Invoke-Native $maven $mavenArgs (Join-Path $ResolvedRepoRoot "YumiNail-Gateway") Write-Step "Build YumiNail-Frontend" $frontendRoot = Join-Path $ResolvedRepoRoot "YumiNail-Frontend" if (-not (Test-Path -LiteralPath (Join-Path $frontendRoot "node_modules"))) { Invoke-Native "npm" @("ci") $frontendRoot } Invoke-Native "npm" @("run", "build") $frontendRoot } $coreJar = Join-Path $ResolvedRepoRoot "YumiNail-Core\target\YumiNail-Core.jar" $gatewayJar = Join-Path $ResolvedRepoRoot "YumiNail-Gateway\target\YumiNail-Gateway.jar" $frontendDist = Join-Path $ResolvedRepoRoot "YumiNail-Frontend\dist" foreach ($requiredPath in @($coreJar, $gatewayJar, $frontendDist, $InitSqlPath)) { if (-not (Test-Path -LiteralPath $requiredPath)) { throw "Required release artifact is missing: $requiredPath" } } $coreArtifact = Join-Path $BackendDir "YumiNail-Core.jar" $gatewayArtifact = Join-Path $BackendDir "YumiNail-Gateway.jar" $frontendArtifact = Join-Path $FrontendDir "yuminail-frontend-dist.tar.gz" $sqlArtifact = Join-Path $SqlDir "YumiNail.sql" Copy-Item -LiteralPath $coreJar -Destination $coreArtifact -Force Copy-Item -LiteralPath $gatewayJar -Destination $gatewayArtifact -Force Copy-Item -LiteralPath $InitSqlPath -Destination $sqlArtifact -Force $tar = Get-Command tar -ErrorAction SilentlyContinue if (-not $tar) { throw "tar is required to package the frontend dist archive." } if (Test-Path -LiteralPath $frontendArtifact) { Remove-Item -LiteralPath $frontendArtifact -Force } Invoke-Native $tar.Source @("-czf", $frontendArtifact, "-C", (Join-Path $ResolvedRepoRoot "YumiNail-Frontend"), "dist") $artifacts = @($coreArtifact, $gatewayArtifact, $frontendArtifact, $sqlArtifact) $hashes = foreach ($artifact in $artifacts) { $hash = Get-FileHash -LiteralPath $artifact -Algorithm SHA256 [pscustomobject]@{ Path = $artifact.Replace($ResolvedRepoRoot, "").TrimStart("\", "/") Sha256 = $hash.Hash } } return [pscustomobject]@{ Directory = $ReleaseDir CoreJar = $coreArtifact GatewayJar = $gatewayArtifact FrontendArchive = $frontendArtifact InitSql = $sqlArtifact Hashes = @($hashes) Git = $GitState } } function Get-BackendDeployCommand { param( [string]$RemoteAppDir, [string]$ServiceName, [string]$ReleaseName, [int]$HealthPort ) $appDir = ConvertTo-BashSingleQuoted $RemoteAppDir $service = ConvertTo-BashSingleQuoted $ServiceName $releaseName = ConvertTo-BashSingleQuoted $ReleaseName $healthPath = ConvertTo-BashSingleQuoted $HealthPath $timeout = [string]$HealthTimeoutSeconds $healthPortText = [string]$HealthPort return @" set -e APP_DIR=$appDir SERVICE=$service RELEASE_NAME=$releaseName HEALTH_PATH=$healthPath HEALTH_PORT=$healthPortText HEALTH_TIMEOUT=$timeout RELEASE="`$APP_DIR/releases/`$RELEASE_NAME" BACKUP_NAME="app-$ReleaseTimestamp.jar" mkdir -p "`$APP_DIR/releases" "`$APP_DIR/backups" "`$APP_DIR/logs" test -f "`$RELEASE" if command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files | grep -q "^`$SERVICE.service"; then systemctl stop "`$SERVICE" || true fi if [ -f "`$APP_DIR/app.jar" ]; then cp "`$APP_DIR/app.jar" "`$APP_DIR/backups/`$BACKUP_NAME" fi cp "`$RELEASE" "`$APP_DIR/app.jar" if command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files | grep -q "^`$SERVICE.service"; then systemctl start "`$SERVICE" else if [ -f "`$APP_DIR/app.pid" ]; then kill "`$(cat "`$APP_DIR/app.pid")" >/dev/null 2>&1 || true; fi pkill -f "java .*`$APP_DIR/app.jar" >/dev/null 2>&1 || true nohup java -jar "`$APP_DIR/app.jar" > "`$APP_DIR/logs/app-$ReleaseTimestamp.log" 2>&1 & echo `$! > "`$APP_DIR/app.pid" fi deadline=`$((`$(date +%s) + `$HEALTH_TIMEOUT)) until curl -fsS "http://127.0.0.1:`$HEALTH_PORT`$HEALTH_PATH" >/tmp/yuminail-health.out 2>/tmp/yuminail-health.err; do if [ "`$(date +%s)" -ge "`$deadline" ]; then echo "Health check failed for `$SERVICE on port `$HEALTH_PORT" cat /tmp/yuminail-health.err || true if command -v systemctl >/dev/null 2>&1; then journalctl -u "`$SERVICE" -n 80 --no-pager || true; fi exit 43 fi sleep 3 done cat /tmp/yuminail-health.out if command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files | grep -q "^`$SERVICE.service"; then systemctl --no-pager --full status "`$SERVICE" | sed -n '1,30p' else ps -fp "`$(cat "`$APP_DIR/app.pid")" fi "@ } function Get-BackendRollbackCommand { param( [string]$RemoteAppDir, [string]$ServiceName, [int]$HealthPort ) $appDir = ConvertTo-BashSingleQuoted $RemoteAppDir $service = ConvertTo-BashSingleQuoted $ServiceName $healthPath = ConvertTo-BashSingleQuoted $HealthPath $timeout = [string]$HealthTimeoutSeconds $healthPortText = [string]$HealthPort return @" set -e APP_DIR=$appDir SERVICE=$service HEALTH_PATH=$healthPath HEALTH_PORT=$healthPortText HEALTH_TIMEOUT=$timeout BACKUP=`$(ls -1t "`$APP_DIR/backups"/app-*.jar 2>/dev/null | head -n 1 || true) if [ -z "`$BACKUP" ]; then echo "No backup jar found for rollback: `$APP_DIR" exit 44 fi if command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files | grep -q "^`$SERVICE.service"; then systemctl stop "`$SERVICE" || true fi cp "`$BACKUP" "`$APP_DIR/app.jar" if command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files | grep -q "^`$SERVICE.service"; then systemctl start "`$SERVICE" else if [ -f "`$APP_DIR/app.pid" ]; then kill "`$(cat "`$APP_DIR/app.pid")" >/dev/null 2>&1 || true; fi pkill -f "java .*`$APP_DIR/app.jar" >/dev/null 2>&1 || true nohup java -jar "`$APP_DIR/app.jar" > "`$APP_DIR/logs/app-rollback-$ReleaseTimestamp.log" 2>&1 & echo `$! > "`$APP_DIR/app.pid" fi deadline=`$((`$(date +%s) + `$HEALTH_TIMEOUT)) until curl -fsS "http://127.0.0.1:`$HEALTH_PORT`$HEALTH_PATH" >/tmp/yuminail-health.out 2>/tmp/yuminail-health.err; do if [ "`$(date +%s)" -ge "`$deadline" ]; then echo "Rollback health check failed for `$SERVICE" cat /tmp/yuminail-health.err || true exit 45 fi sleep 3 done echo "Rolled back `$SERVICE to `$BACKUP" "@ } function Publish-BackendGroup { param( [string]$GroupName, [object[]]$Servers, [string]$ArtifactPath, [string]$RemoteAppDir, [string]$ServiceName, [int]$HealthPort ) $artifactBaseName = [System.IO.Path]::GetFileNameWithoutExtension($ArtifactPath) $releaseName = "$artifactBaseName-$ReleaseTimestamp.jar" $quotedRemoteAppDir = ConvertTo-BashSingleQuoted $RemoteAppDir Write-Step "Prepare $GroupName on $($Servers.Count) hosts" foreach ($server in $Servers) { Write-Host "$GroupName target: $($server.Name) $($server.User)@$($server.Host):$($server.Port)" Invoke-RemoteShell $server "mkdir -p $quotedRemoteAppDir/releases $quotedRemoteAppDir/backups $quotedRemoteAppDir/logs" Copy-FileToRemote $ArtifactPath $server "$RemoteAppDir/releases/$releaseName" } Write-Step "Switch $GroupName release" $deployCommand = Get-BackendDeployCommand $RemoteAppDir $ServiceName $releaseName $HealthPort $rollbackCommand = Get-BackendRollbackCommand $RemoteAppDir $ServiceName $HealthPort try { Invoke-RemoteShellParallel $Servers $deployCommand $GroupName } catch { Write-Warning "$GroupName deployment failed. Running rollback on this group." Invoke-RemoteShellParallel $Servers $rollbackCommand "$GroupName-rollback" throw } } function Get-WebDeployCommand { param([string]$ArchiveName) $webDir = ConvertTo-BashSingleQuoted $WebRemoteDir $archiveName = ConvertTo-BashSingleQuoted $ArchiveName return @" set -e WEB_DIR=$webDir ARCHIVE_NAME=$archiveName RELEASE_BASE="`$WEB_DIR/releases/$ReleaseTimestamp" ARCHIVE="`$WEB_DIR/releases/`$ARCHIVE_NAME" mkdir -p "`$RELEASE_BASE" if [ -L "`$WEB_DIR/current" ]; then readlink "`$WEB_DIR/current" > "`$WEB_DIR/previous-release.txt"; fi tar -xzf "`$ARCHIVE" -C "`$RELEASE_BASE" if [ -d "`$RELEASE_BASE/dist" ]; then TARGET="`$RELEASE_BASE/dist" else TARGET="`$RELEASE_BASE" fi ln -sfn "`$TARGET" "`$WEB_DIR/current" nginx -t if command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files | grep -q "^nginx.service"; then systemctl reload nginx else nginx -s reload fi echo "Web current -> `$TARGET" "@ } function Get-WebRollbackCommand { $webDir = ConvertTo-BashSingleQuoted $WebRemoteDir return @" set -e WEB_DIR=$webDir if [ ! -f "`$WEB_DIR/previous-release.txt" ]; then echo "No previous web release recorded." exit 46 fi PREVIOUS=`$(cat "`$WEB_DIR/previous-release.txt") if [ -z "`$PREVIOUS" ] || [ ! -d "`$PREVIOUS" ]; then echo "Previous web release is invalid: `$PREVIOUS" exit 47 fi ln -sfn "`$PREVIOUS" "`$WEB_DIR/current" nginx -t if command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files | grep -q "^nginx.service"; then systemctl reload nginx else nginx -s reload fi echo "Rolled back web current -> `$PREVIOUS" "@ } function Publish-Web { param([object]$Server, [string]$ArchivePath) $archiveName = "yuminail-frontend-dist-$ReleaseTimestamp.tar.gz" $quotedWebRemoteDir = ConvertTo-BashSingleQuoted $WebRemoteDir Write-Step "Prepare Web on $($Server.Name)" Invoke-RemoteShell $Server "mkdir -p $quotedWebRemoteDir/releases" Copy-FileToRemote $ArchivePath $Server "$WebRemoteDir/releases/$archiveName" Write-Step "Switch Web release" $deployCommand = Get-WebDeployCommand $archiveName $rollbackCommand = Get-WebRollbackCommand try { Invoke-RemoteShell $Server $deployCommand } catch { Write-Warning "Web deployment failed. Running web rollback." Invoke-RemoteShell $Server $rollbackCommand throw } } function Initialize-ProductionDatabase { param([object]$DatabaseServer, [string]$SqlArtifact) Test-SqlSafety $SqlArtifact $dbUserValue = if ($DatabaseUser) { $DatabaseUser } else { $DatabaseServer.User } $dbPasswordValue = if ($DatabasePassword) { $DatabasePassword } else { $DatabaseServer.Password } if (-not $dbUserValue) { throw "Database user is empty. Pass -DatabaseUser or provide it in the workbook row." } $remoteSqlPath = "/tmp/yuminail-init-$ReleaseTimestamp.sql" Write-Step "Initialize empty production database" Write-Host "Database target: $($DatabaseServer.Name) $($DatabaseServer.Host):$DatabasePort/$DatabaseName" Invoke-RemoteShell $DatabaseServer "rm -f '$remoteSqlPath'" Copy-FileToRemote $SqlArtifact $DatabaseServer $remoteSqlPath -Sensitive $dbName = ConvertTo-BashSingleQuoted $DatabaseName $dbUser = ConvertTo-BashSingleQuoted $dbUserValue $dbPassword = ConvertTo-BashSingleQuoted $dbPasswordValue $dbPort = [string]$DatabasePort $sqlFile = ConvertTo-BashSingleQuoted $remoteSqlPath $command = @' set -e DB_NAME=__DB_NAME__ DB_PORT=__DB_PORT__ DB_USER=__DB_USER__ SQL_FILE=__SQL_FILE__ export MYSQL_PWD=__DB_PASSWORD__ if ! command -v mysql >/dev/null 2>&1; then echo "mysql client not found on database host" exit 48 fi mysql -h 127.0.0.1 -P "$DB_PORT" -u"$DB_USER" --default-character-set=utf8mb4 --batch --skip-column-names -e "CREATE DATABASE IF NOT EXISTS \`$DB_NAME\` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" TABLE_COUNT=$(mysql -h 127.0.0.1 -P "$DB_PORT" -u"$DB_USER" --default-character-set=utf8mb4 --batch --skip-column-names -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='${DB_NAME}';") if [ "$TABLE_COUNT" != "0" ]; then echo "Database ${DB_NAME} is not empty: ${TABLE_COUNT} tables. Refusing initialization." rm -f "$SQL_FILE" unset MYSQL_PWD exit 49 fi mysql -h 127.0.0.1 -P "$DB_PORT" -u"$DB_USER" --default-character-set=utf8mb4 < "$SQL_FILE" ADMIN_COUNT=$(mysql -h 127.0.0.1 -P "$DB_PORT" -u"$DB_USER" --default-character-set=utf8mb4 --batch --skip-column-names "$DB_NAME" -e "SELECT COUNT(*) FROM t_user WHERE account='xiaowang';") rm -f "$SQL_FILE" unset MYSQL_PWD echo "Database initialized. Admin account rows: ${ADMIN_COUNT}" '@ $command = $command.Replace("__DB_NAME__", $dbName) $command = $command.Replace("__DB_PORT__", $dbPort) $command = $command.Replace("__DB_USER__", $dbUser) $command = $command.Replace("__DB_PASSWORD__", $dbPassword) $command = $command.Replace("__SQL_FILE__", $sqlFile) Invoke-RemoteShell $DatabaseServer $command -Sensitive } function Write-ReleaseManifest { param( [object]$Package, [object[]]$CoreServers, [object[]]$GatewayServers, [object]$WebServer, [object]$DatabaseServer ) $manifest = [pscustomobject]@{ releaseTimestamp = $ReleaseTimestamp repoRoot = $ResolvedRepoRoot git = $Package.Git artifacts = $Package.Hashes targets = [pscustomobject]@{ core = @($CoreServers | Select-Object Name, Host, Port, User, Purpose, Environment) gateway = @($GatewayServers | Select-Object Name, Host, Port, User, Purpose, Environment) web = $WebServer | Select-Object Name, Host, Port, User, Purpose, Environment database = if ($DatabaseServer) { $DatabaseServer | Select-Object Name, Host, Port, User, Purpose, Environment } else { $null } } parameters = [pscustomobject]@{ initializeDatabase = -not [bool]$SkipDatabaseInit databaseName = $DatabaseName serverInfoPath = $resolvedServerInfoPath coreRemoteAppDir = $CoreRemoteAppDir gatewayRemoteAppDir = $GatewayRemoteAppDir webRemoteDir = $WebRemoteDir publicBaseUrl = $PublicBaseUrl dryRun = [bool]$DryRun deploy = [bool]$Deploy } } $manifest | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $ManifestPath -Encoding UTF8 Write-Host "Manifest: $ManifestPath" } function Invoke-PublicSmokeTests { if ($DryRun) { Write-Host "DryRun public smoke tests:" Write-Host "GET $PublicBaseUrl" Write-Host "GET $PublicBaseUrl/api/shop/list" return } Write-Step "Public smoke tests" foreach ($url in @($PublicBaseUrl, "$PublicBaseUrl/api/shop/list")) { Write-Host "GET $url" $response = Invoke-WebRequest -Uri $url -UseBasicParsing -TimeoutSec 20 Write-Host "Status $($response.StatusCode) Length $($response.RawContentLength)" } } Write-Step "Read server workbook" $resolvedServerInfoPath = Resolve-ServerInfoPath $ServerInfoPath $servers = @(Get-ServersFromWorkbook $resolvedServerInfoPath) $coreServers = @($servers | Where-Object { $_.Name -match $CorePattern }) $gatewayServers = @($servers | Where-Object { $_.Name -match $GatewayPattern }) $webServers = @(if ($WebTargetName) { $servers | Where-Object { $_.Name -eq $WebTargetName } } else { $servers | Where-Object { $_.Host -eq $WebTargetHost } }) $databaseServers = @($servers | Where-Object { $_.Name -eq $DatabaseTargetName }) if ($coreServers.Count -eq 0) { throw "No Core servers matched pattern: $CorePattern" } if ($gatewayServers.Count -eq 0) { throw "No Gateway servers matched pattern: $GatewayPattern" } if ($webServers.Count -ne 1) { $webSelector = if ($WebTargetName) { "name '$WebTargetName'" } else { "host '$WebTargetHost'" } throw "Expected exactly one Web target by $webSelector, found $($webServers.Count)." } if ((-not $SkipDatabaseInit) -and $databaseServers.Count -ne 1) { throw "Expected exactly one database target named '$DatabaseTargetName', found $($databaseServers.Count)." } Assert-ProductionTarget (@($coreServers) + @($gatewayServers) + @($webServers)) $databaseServer = if (-not $SkipDatabaseInit) { $databaseServers[0] } else { $null } Write-Host "Server workbook: $resolvedServerInfoPath" Write-Host "Selected YumiNail targets:" @($coreServers + $gatewayServers + $webServers) | Select-Object Name, Host, Port, User, Purpose, Environment | Format-Table -AutoSize if ($databaseServer) { Write-Host "Database init target:" $databaseServer | Select-Object Name, Host, Port, User, Purpose, Environment | Format-Table -AutoSize } Write-Step "Check git state" $gitState = Test-GitState Write-Step "Build release package" $package = Build-ReleasePackage $gitState Write-ReleaseManifest $package $coreServers $gatewayServers $webServers[0] $databaseServer if (-not $Deploy) { Write-Host "Package prepared. Add -Deploy to publish. Add -DryRun to print remote actions without changing production." exit 0 } if (-not $SkipDatabaseInit) { Initialize-ProductionDatabase $databaseServer $package.InitSql } else { Write-Host "Database initialization skipped." } Publish-BackendGroup "Core" $coreServers $package.CoreJar $CoreRemoteAppDir $CoreServiceName $CoreHealthPort Publish-BackendGroup "Gateway" $gatewayServers $package.GatewayJar $GatewayRemoteAppDir $GatewayServiceName $GatewayHealthPort Publish-Web $webServers[0] $package.FrontendArchive Invoke-PublicSmokeTests Write-Host "" Write-Host "YumiNail production deployment workflow finished."