修复指尖管理师上线配置

This commit is contained in:
2026-06-22 20:39:51 +08:00
parent 9400e53fe9
commit a53b27ef20
7 changed files with 425 additions and 459 deletions
+198 -340
View File
@@ -10,19 +10,19 @@ param(
[switch]$SkipDatabaseInit,
[string]$DatabaseTargetName = "mysql02",
[int]$DatabasePort = 3306,
[string]$DatabaseName = "nailart",
[string]$DatabaseName = "FingertipDesigner",
[string]$DatabaseUser = "",
[string]$DatabasePassword = "",
[string]$InitSqlPath = "",
[string]$CorePattern = "^YumiNail-Core",
[string]$GatewayPattern = "^YumiNail-Gateway",
[string]$CorePattern = "^FD-Core",
[string]$GatewayPattern = "^FD-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",
[string]$CoreRemoteAppDir = "/opt/fingertip-designer-core",
[string]$GatewayRemoteAppDir = "/opt/fingertip-designer-gateway",
[string]$WebRemoteDir = "/opt/fingertip-designer-frontend",
[string]$CoreServiceName = "fingertip-designer-core",
[string]$GatewayServiceName = "fingertip-designer-gateway",
[int]$CoreHealthPort = 81,
[int]$GatewayHealthPort = 80,
[string]$HealthPath = "/health/check",
@@ -33,58 +33,93 @@ param(
$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"
$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 "scripts\sql\init\YumiNail.sql"
if (-not $InitSqlPath) {
$InitSqlPath = $DefaultInitSqlPath
$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 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
}
throw "找不到 Maven,请通过 -MavenPath 传入 Maven 可执行文件绝对路径。"
}
function Invoke-Native {
param(
[string]$FilePath,
[string[]]$Arguments,
[string]$WorkingDirectory = "",
[switch]$RemoteMutation,
[switch]$Sensitive
)
if ($Sensitive) {
Write-Host ">> $FilePath <敏感参数已隐藏>"
}
else {
Write-Host ">> $FilePath $($Arguments -join ' ')"
}
if ($DryRun -and $RemoteMutation) {
return
}
$previousLocation = Get-Location
try {
if ($WorkingDirectory) {
Set-Location -LiteralPath $WorkingDirectory
}
& $FilePath @Arguments
if ($LASTEXITCODE -ne 0) {
throw "命令执行失败,退出码 ${LASTEXITCODE}:$FilePath"
}
}
finally {
Set-Location $previousLocation
}
}
function Read-ZipEntryText {
param($Zip, [string]$Name)
$entry = $Zip.GetEntry($Name)
if (-not $entry) {
return $null
@@ -107,6 +142,7 @@ function Read-ZipEntryText {
function Get-RelationshipId {
param($Element)
foreach ($attribute in $Element.Attributes) {
if ($attribute.LocalName -eq "id") {
return $attribute.Value
@@ -117,6 +153,7 @@ function Get-RelationshipId {
function Get-ColumnIndex {
param([string]$CellRef)
$letters = ([regex]::Match($CellRef, "^[A-Z]+")).Value
$index = 0
foreach ($character in $letters.ToCharArray()) {
@@ -144,7 +181,7 @@ function Get-XlsxFirstSheetRows {
[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"
throw "服务器清单没有工作表:$Path"
}
$relationshipId = Get-RelationshipId $firstSheet
@@ -156,7 +193,7 @@ function Get-XlsxFirstSheetRows {
}
}
if (-not $relationship) {
throw "Cannot resolve workbook relationship $relationshipId"
throw "无法解析工作表关系:$relationshipId"
}
$target = $relationship.Target
@@ -197,8 +234,8 @@ function Get-XlsxFirstSheetRows {
}
if ($maxIndex -gt 0) {
$values = for ($i = 1; $i -le $maxIndex; $i++) {
if ($valuesByIndex.ContainsKey($i)) { $valuesByIndex[$i] } else { "" }
$values = for ($index = 1; $index -le $maxIndex; $index++) {
if ($valuesByIndex.ContainsKey($index)) { $valuesByIndex[$index] } else { "" }
}
if (($values -join "").Trim()) {
$rows += ,$values
@@ -216,12 +253,12 @@ function Get-ServersFromWorkbook {
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path)) {
throw "Server workbook not found: $Path"
throw "服务器清单不存在:$Path"
}
$rows = @(Get-XlsxFirstSheetRows (Resolve-Path -LiteralPath $Path).Path)
if ($rows.Count -lt 2) {
throw "Server workbook has no data rows: $Path"
throw "服务器清单没有数据行:$Path"
}
foreach ($row in $rows[1..($rows.Count - 1)]) {
@@ -241,96 +278,46 @@ function Get-ServersFromWorkbook {
}
}
function Resolve-ServerInfoPath {
param([string]$ExplicitPath)
if ($ExplicitPath) {
if (-not (Test-Path -LiteralPath $ExplicitPath)) {
throw "服务器清单不存在:$ExplicitPath"
}
return (Resolve-Path -LiteralPath $ExplicitPath).Path
}
$codeRoot = "Y:\code"
if (-not (Test-Path -LiteralPath $codeRoot)) {
throw "未传入 -ServerInfoPath,且默认目录不存在:$codeRoot"
}
$workbooks = @(Get-ChildItem -LiteralPath $codeRoot -Filter "*.xlsx" -File | Sort-Object LastWriteTime -Descending)
if ($workbooks.Count -eq 0) {
throw "默认目录下没有服务器清单 xlsx,请显式传入 -ServerInfoPath。"
}
return $workbooks[0].FullName
}
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 ', ')"
throw "拒绝把应用发布到基础设施节点:$($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 <sensitive arguments omitted>"
}
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
throw "拒绝发布到非生产环境节点:$($knownNonProduction.Name -join ', ')"
}
}
function Get-SshTarget {
param([object]$Server)
return "$($Server.User)@$($Server.Host)"
}
@@ -344,7 +331,7 @@ function Invoke-RemoteShell {
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."
throw "找不到 PuTTY plink,请安装 PuTTY 工具或改用 SSH key。"
}
$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
@@ -363,13 +350,13 @@ function Copy-FileToRemote {
)
if (-not (Test-Path -LiteralPath $LocalPath)) {
throw "Local upload file not found: $LocalPath"
throw "本地上传文件不存在:$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."
throw "找不到 PuTTY pscp,请安装 PuTTY 工具或改用 SSH key。"
}
$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
@@ -379,77 +366,37 @@ function Copy-FileToRemote {
}
}
function Invoke-RemoteShellParallel {
function Invoke-RemoteShellMany {
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 ', ')"
foreach ($server in $Servers) {
Write-Host "$GroupName target: $($server.Name) $($server.User)@$($server.Host):$($server.Port)"
Invoke-RemoteShell $server $Command
}
}
function Test-GitState {
Push-Location $ResolvedRepoRoot
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."
if ($status.Count -gt 0) {
Write-Warning "当前工作区有 $($status.Count) 个变更路径。"
$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."
throw "拒绝从脏工作区发布生产,请先提交/暂存,或显式传入 -AllowDirtyWorkingTree。"
}
}
return [pscustomobject]@{
Branch = $branch
Commit = $commit
Dirty = $dirty
Dirty = $status.Count -gt 0
ChangedPathCount = $status.Count
ChangedPaths = @($status)
}
}
finally {
@@ -457,24 +404,31 @@ function Test-GitState {
}
}
function Test-SqlSafety {
function Assert-InitSqlSafe {
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path)) {
throw "Init SQL not found: $Path"
throw "初始化 SQL 不存在:$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 ($content -notmatch "CREATE DATABASE IF NOT EXISTS\s+FingertipDesigner") {
throw "初始化 SQL 未声明目标库 FingertipDesigner:$Path"
}
if ($content -notmatch "(?im)^\s*use\s+FingertipDesigner\s*;") {
throw "初始化 SQL 未切换到目标库 FingertipDesigner:$Path"
}
$dangerousMatch = [regex]::Match($content, "(?im)^\s*(drop\s+(database|schema|table)|truncate\s+table)\b")
if ($dangerousMatch.Success) {
throw "Refusing init SQL with destructive statement near: $($dangerousMatch.Value)"
throw "初始化 SQL 包含危险语句:$($dangerousMatch.Value)"
}
}
function Build-ReleasePackage {
param([object]$GitState)
New-Item -ItemType Directory -Force -Path $BackendDir, $FrontendDir, $SqlDir | Out-Null
New-Item -ItemType Directory -Force -Path $backendDir, $frontendDir, $sqlDir | Out-Null
$maven = Resolve-Maven $MavenPath
if (-not $SkipBuild) {
@@ -483,57 +437,56 @@ function Build-ReleasePackage {
$mavenArgs += "-DskipTests"
}
Write-Step "Build YumiNail-Core"
Invoke-Native $maven $mavenArgs (Join-Path $ResolvedRepoRoot "YumiNail-Core")
Write-Step "构建 FD-Core"
Invoke-Native $maven $mavenArgs (Join-Path $resolvedRepoRoot "FD-Core")
Write-Step "Build YumiNail-Gateway"
Invoke-Native $maven $mavenArgs (Join-Path $ResolvedRepoRoot "YumiNail-Gateway")
Write-Step "构建 FD-Gateway"
Invoke-Native $maven $mavenArgs (Join-Path $resolvedRepoRoot "FD-Gateway")
Write-Step "Build YumiNail-Frontend"
$frontendRoot = Join-Path $ResolvedRepoRoot "YumiNail-Frontend"
Write-Step "构建 FD-Frontend"
$frontendRoot = Join-Path $resolvedRepoRoot "FD-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"
$coreJar = Join-Path $resolvedRepoRoot "FD-Core\target\FingertipDesigner-Core.jar"
$gatewayJar = Join-Path $resolvedRepoRoot "FD-Gateway\target\FingertipDesigner-Gateway.jar"
$frontendDist = Join-Path $resolvedRepoRoot "FD-Frontend\dist"
foreach ($requiredPath in @($coreJar, $gatewayJar, $frontendDist, $InitSqlPath)) {
if (-not (Test-Path -LiteralPath $requiredPath)) {
throw "Required release artifact is missing: $requiredPath"
throw "缺少发布产物:$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"
$coreArtifact = Join-Path $backendDir "FingertipDesigner-Core.jar"
$gatewayArtifact = Join-Path $backendDir "FingertipDesigner-Gateway.jar"
$frontendArtifact = Join-Path $frontendDir "fingertip-designer-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."
throw "缺少 tar,无法打包前端 dist。"
}
if (Test-Path -LiteralPath $frontendArtifact) {
Remove-Item -LiteralPath $frontendArtifact -Force
}
Invoke-Native $tar.Source @("-czf", $frontendArtifact, "-C", (Join-Path $ResolvedRepoRoot "YumiNail-Frontend"), "dist")
Invoke-Native $tar.Source @("-czf", $frontendArtifact, "-C", (Join-Path $resolvedRepoRoot "FD-Frontend"), "dist")
$artifacts = @($coreArtifact, $gatewayArtifact, $frontendArtifact, $sqlArtifact)
$hashes = foreach ($artifact in $artifacts) {
$hashes = foreach ($artifact in @($coreArtifact, $gatewayArtifact, $frontendArtifact, $sqlArtifact)) {
$hash = Get-FileHash -LiteralPath $artifact -Algorithm SHA256
[pscustomobject]@{
Path = $artifact.Replace($ResolvedRepoRoot, "").TrimStart("\", "/")
Path = $artifact.Replace($resolvedRepoRoot, "").TrimStart("\", "/")
Sha256 = $hash.Hash
}
}
return [pscustomobject]@{
Directory = $ReleaseDir
Directory = $releaseDir
CoreJar = $coreArtifact
GatewayJar = $gatewayArtifact
FrontendArchive = $frontendArtifact
@@ -567,7 +520,7 @@ HEALTH_PATH=$healthPath
HEALTH_PORT=$healthPortText
HEALTH_TIMEOUT=$timeout
RELEASE="`$APP_DIR/releases/`$RELEASE_NAME"
BACKUP_NAME="app-$ReleaseTimestamp.jar"
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
@@ -582,75 +535,20 @@ if command -v systemctl >/dev/null 2>&1 && systemctl list-unit-files | grep -q "
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 &
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
until curl -fsS "http://127.0.0.1:`$HEALTH_PORT`$HEALTH_PATH" >/tmp/fingertip-designer-health.out 2>/tmp/fingertip-designer-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
cat /tmp/fingertip-designer-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"
cat /tmp/fingertip-designer-health.out
"@
}
@@ -665,26 +563,18 @@ function Publish-BackendGroup {
)
$artifactBaseName = [System.IO.Path]::GetFileNameWithoutExtension($ArtifactPath)
$releaseName = "$artifactBaseName-$ReleaseTimestamp.jar"
$releaseName = "$artifactBaseName-$releaseTimestamp.jar"
$quotedRemoteAppDir = ConvertTo-BashSingleQuoted $RemoteAppDir
Write-Step "Prepare $GroupName on $($Servers.Count) hosts"
Write-Step "准备 $GroupName 目标机器"
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"
Write-Step "切换 $GroupName 发布版本"
$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
}
Invoke-RemoteShellMany $Servers $deployCommand $GroupName
}
function Get-WebDeployCommand {
@@ -696,7 +586,7 @@ function Get-WebDeployCommand {
set -e
WEB_DIR=$webDir
ARCHIVE_NAME=$archiveName
RELEASE_BASE="`$WEB_DIR/releases/$ReleaseTimestamp"
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
@@ -717,67 +607,33 @@ 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"
$archiveName = "fingertip-designer-frontend-dist-$releaseTimestamp.tar.gz"
$quotedWebRemoteDir = ConvertTo-BashSingleQuoted $WebRemoteDir
Write-Step "Prepare Web on $($Server.Name)"
Write-Step "准备 Web 目标机器"
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
}
Write-Step "切换 Web 发布版本"
Invoke-RemoteShell $Server (Get-WebDeployCommand $archiveName)
}
function Initialize-ProductionDatabase {
param([object]$DatabaseServer, [string]$SqlArtifact)
Test-SqlSafety $SqlArtifact
Assert-InitSqlSafe $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."
throw "数据库用户名为空,请传入 -DatabaseUser 或在服务器清单中填写。"
}
$remoteSqlPath = "/tmp/yuminail-init-$ReleaseTimestamp.sql"
Write-Step "Initialize empty production database"
Write-Host "Database target: $($DatabaseServer.Name) $($DatabaseServer.Host):$DatabasePort/$DatabaseName"
$remoteSqlPath = "/tmp/fingertip-designer-init-$releaseTimestamp.sql"
Write-Step "初始化生产空库"
Write-Host "数据库目标:$($DatabaseServer.Name) $($DatabaseServer.Host):$DatabasePort/$DatabaseName"
Invoke-RemoteShell $DatabaseServer "rm -f '$remoteSqlPath'"
Copy-FileToRemote $SqlArtifact $DatabaseServer $remoteSqlPath -Sensitive
@@ -825,12 +681,13 @@ function Write-ReleaseManifest {
[object[]]$CoreServers,
[object[]]$GatewayServers,
[object]$WebServer,
[object]$DatabaseServer
[object]$DatabaseServer,
[string]$ResolvedServerInfoPath
)
$manifest = [pscustomobject]@{
releaseTimestamp = $ReleaseTimestamp
repoRoot = $ResolvedRepoRoot
releaseTimestamp = $releaseTimestamp
repoRoot = $resolvedRepoRoot
git = $Package.Git
artifacts = $Package.Hashes
targets = [pscustomobject]@{
@@ -842,36 +699,38 @@ function Write-ReleaseManifest {
parameters = [pscustomobject]@{
initializeDatabase = -not [bool]$SkipDatabaseInit
databaseName = $DatabaseName
serverInfoPath = $resolvedServerInfoPath
serverInfoPath = $ResolvedServerInfoPath
coreRemoteAppDir = $CoreRemoteAppDir
gatewayRemoteAppDir = $GatewayRemoteAppDir
webRemoteDir = $WebRemoteDir
publicBaseUrl = $PublicBaseUrl
managerMiniProgramApi = "$PublicBaseUrl/api/admin"
nacosNamespace = "FingertipDesigner"
dryRun = [bool]$DryRun
deploy = [bool]$Deploy
}
}
$manifest | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $ManifestPath -Encoding UTF8
Write-Host "Manifest: $ManifestPath"
$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/health/check"
Write-Host "GET $PublicBaseUrl/api/shop/list"
return
}
Write-Step "Public smoke tests"
foreach ($url in @($PublicBaseUrl, "$PublicBaseUrl/api/shop/list")) {
Write-Step "生产公开冒烟"
foreach ($url in @("$PublicBaseUrl/health/check", "$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"
Write-Step "读取服务器清单"
$resolvedServerInfoPath = Resolve-ServerInfoPath $ServerInfoPath
$servers = @(Get-ServersFromWorkbook $resolvedServerInfoPath)
$coreServers = @($servers | Where-Object { $_.Name -match $CorePattern })
@@ -885,39 +744,38 @@ else {
$databaseServers = @($servers | Where-Object { $_.Name -eq $DatabaseTargetName })
if ($coreServers.Count -eq 0) {
throw "No Core servers matched pattern: $CorePattern"
throw "没有匹配到 Core 服务器,匹配规则:$CorePattern"
}
if ($gatewayServers.Count -eq 0) {
throw "No Gateway servers matched pattern: $GatewayPattern"
throw "没有匹配到 Gateway 服务器,匹配规则:$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)."
$webSelector = if ($WebTargetName) { "名称 $WebTargetName" } else { "主机 $WebTargetHost" }
throw "Web 目标必须唯一,当前按 $webSelector 找到 $($webServers.Count) 个。"
}
if ((-not $SkipDatabaseInit) -and $databaseServers.Count -ne 1) {
throw "Expected exactly one database target named '$DatabaseTargetName', found $($databaseServers.Count)."
throw "数据库初始化目标必须唯一,当前按 $DatabaseTargetName 找到 $($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:"
Write-Host "服务器清单:$resolvedServerInfoPath"
@($coreServers + $gatewayServers + $webServers) | Select-Object Name, Host, Port, User, Purpose, Environment | Format-Table -AutoSize
if ($databaseServer) {
Write-Host "Database init target:"
Write-Host "数据库初始化目标:"
$databaseServer | Select-Object Name, Host, Port, User, Purpose, Environment | Format-Table -AutoSize
}
Write-Step "Check git state"
Write-Step "检查工作区"
$gitState = Test-GitState
Write-Step "Build release package"
Write-Step "构建发布包"
$package = Build-ReleasePackage $gitState
Write-ReleaseManifest $package $coreServers $gatewayServers $webServers[0] $databaseServer
Write-ReleaseManifest $package $coreServers $gatewayServers $webServers[0] $databaseServer $resolvedServerInfoPath
if (-not $Deploy) {
Write-Host "Package prepared. Add -Deploy to publish. Add -DryRun to print remote actions without changing production."
Write-Host "发布包已生成。传入 -Deploy 才会发布到生产;传入 -DryRun 可打印远程动作但不修改远端。"
exit 0
}
@@ -925,7 +783,7 @@ if (-not $SkipDatabaseInit) {
Initialize-ProductionDatabase $databaseServer $package.InitSql
}
else {
Write-Host "Database initialization skipped."
Write-Host "已跳过数据库初始化。"
}
Publish-BackendGroup "Core" $coreServers $package.CoreJar $CoreRemoteAppDir $CoreServiceName $CoreHealthPort
@@ -934,4 +792,4 @@ Publish-Web $webServers[0] $package.FrontendArchive
Invoke-PublicSmokeTests
Write-Host ""
Write-Host "YumiNail production deployment workflow finished."
Write-Host "FingertipDesigner 生产发布流程完成。"