842 lines
28 KiB
PowerShell
842 lines
28 KiB
PowerShell
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 = "jayucloud_salon",
|
||
[string]$DatabaseUser = "",
|
||
[string]$DatabasePassword = "",
|
||
[string]$InitSqlPath = "",
|
||
[string]$CorePattern = "^JC-Salon-Core",
|
||
[string]$GatewayPattern = "^JC-Salon-Gateway",
|
||
[string]$WebTargetName = "",
|
||
[string]$WebTargetHost = "8.137.35.61",
|
||
[string]$CoreRemoteAppDir = "/opt/jc-salon-core",
|
||
[string]$GatewayRemoteAppDir = "/opt/jc-salon-gateway",
|
||
[string]$WebRemoteDir = "/opt/jc-salon-frontend",
|
||
[string]$CoreServiceName = "jc-salon-core",
|
||
[string]$GatewayServiceName = "jc-salon-gateway",
|
||
[int]$CoreHealthPort = 81,
|
||
[int]$GatewayHealthPort = 80,
|
||
[string]$HealthPath = "/health/check",
|
||
[int]$HealthTimeoutSeconds = 120,
|
||
[string]$PublicBaseUrl = "https://salon.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 "docs\scripts\sql\migrations\20260825-双端独立数据库\店务独立数据库_20260825.sql"
|
||
if (-not $InitSqlPath) {
|
||
$InitSqlPath = $defaultInitSqlPath
|
||
}
|
||
|
||
function Write-Step {
|
||
param([string]$Message)
|
||
|
||
Write-Host ""
|
||
Write-Host "==> $Message"
|
||
}
|
||
|
||
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
|
||
}
|
||
|
||
$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 "服务器清单没有工作表:$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 "无法解析工作表关系:$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 ($index = 1; $index -le $maxIndex; $index++) {
|
||
if ($valuesByIndex.ContainsKey($index)) { $valuesByIndex[$index] } else { "" }
|
||
}
|
||
if (($values -join "").Trim()) {
|
||
$rows += ,$values
|
||
}
|
||
}
|
||
}
|
||
return $rows
|
||
}
|
||
finally {
|
||
$zip.Dispose()
|
||
}
|
||
}
|
||
|
||
function Get-HeaderIndex {
|
||
param([string[]]$Header, [string[]]$Candidates)
|
||
|
||
foreach ($candidate in $Candidates) {
|
||
$index = [Array]::IndexOf($Header, $candidate.ToLowerInvariant())
|
||
if ($index -ge 0) {
|
||
return $index
|
||
}
|
||
}
|
||
return -1
|
||
}
|
||
|
||
function Get-CellValue {
|
||
param([object[]]$Row, [int]$Index)
|
||
|
||
if ($Index -lt 0 -or $Index -ge $Row.Count) {
|
||
return ""
|
||
}
|
||
return ([string]$Row[$Index]).Trim()
|
||
}
|
||
|
||
function Get-ServerPort {
|
||
param([object[]]$Row, [int]$Index)
|
||
|
||
$value = Get-CellValue $Row $Index
|
||
if (-not $value) {
|
||
return 22
|
||
}
|
||
$value = ($value -split "[/,;,;\s]+")[0]
|
||
$port = 0
|
||
if (-not [int]::TryParse($value, [ref]$port)) {
|
||
throw "服务器清单端口不是数字:$value"
|
||
}
|
||
return $port
|
||
}
|
||
|
||
function Get-ServersFromWorkbook {
|
||
param([string]$Path)
|
||
|
||
if (-not (Test-Path -LiteralPath $Path)) {
|
||
throw "服务器清单不存在:$Path"
|
||
}
|
||
|
||
$rows = @(Get-XlsxFirstSheetRows (Resolve-Path -LiteralPath $Path).Path)
|
||
if ($rows.Count -lt 2) {
|
||
throw "服务器清单没有数据行:$Path"
|
||
}
|
||
|
||
$header = @($rows[0] | ForEach-Object { ([string]$_).Trim().ToLowerInvariant() })
|
||
$nameIndex = Get-HeaderIndex $header @("name", "名称", "服务器名称")
|
||
$hostIndex = Get-HeaderIndex $header @("host", "ip", "ip/域名", "ip地址", "主机", "公网ip", "内网ip")
|
||
$portIndex = Get-HeaderIndex $header @("port", "端口", "ssh端口")
|
||
$userIndex = Get-HeaderIndex $header @("user", "username", "用户名", "账号")
|
||
$passwordIndex = Get-HeaderIndex $header @("password", "密码", "口令")
|
||
$purposeIndex = Get-HeaderIndex $header @("purpose", "功能定位", "业务作用", "用途", "类型")
|
||
$noteIndex = Get-HeaderIndex $header @("note", "备注", "说明")
|
||
$environmentIndex = Get-HeaderIndex $header @("environment", "环境", "所属中心")
|
||
|
||
foreach ($row in $rows[1..($rows.Count - 1)]) {
|
||
if ((-not (Get-CellValue $row $nameIndex)) -or (-not (Get-CellValue $row $hostIndex))) {
|
||
continue
|
||
}
|
||
[pscustomobject]@{
|
||
Name = Get-CellValue $row $nameIndex
|
||
Host = Get-CellValue $row $hostIndex
|
||
Port = Get-ServerPort $row $portIndex
|
||
User = Get-CellValue $row $userIndex
|
||
Password = Get-CellValue $row $passwordIndex
|
||
Purpose = Get-CellValue $row $purposeIndex
|
||
Note = Get-CellValue $row $noteIndex
|
||
Environment = Get-CellValue $row $environmentIndex
|
||
}
|
||
}
|
||
}
|
||
|
||
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 "拒绝把应用发布到基础设施节点:$($blocked.Name -join ', ')"
|
||
}
|
||
|
||
$knownNonProduction = @($Servers | Where-Object { $_.Environment -match "(?i)\b(dev|test|local|staging)\b" })
|
||
if ($knownNonProduction.Count -gt 0) {
|
||
throw "拒绝发布到非生产环境节点:$($knownNonProduction.Name -join ', ')"
|
||
}
|
||
}
|
||
|
||
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,请安装 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
|
||
}
|
||
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 "本地上传文件不存在:$LocalPath"
|
||
}
|
||
|
||
if ($UsePuttyPassword) {
|
||
$pscp = Get-Command pscp -ErrorAction SilentlyContinue
|
||
if ((-not $DryRun) -and (-not $pscp)) {
|
||
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
|
||
}
|
||
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-RemoteShellMany {
|
||
param(
|
||
[object[]]$Servers,
|
||
[string]$Command,
|
||
[string]$GroupName
|
||
)
|
||
|
||
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
|
||
try {
|
||
$commit = (& git rev-parse HEAD).Trim()
|
||
$branch = (& git branch --show-current).Trim()
|
||
$status = @(& git status --porcelain)
|
||
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 "拒绝从脏工作区发布生产,请先提交/暂存,或显式传入 -AllowDirtyWorkingTree。"
|
||
}
|
||
}
|
||
return [pscustomobject]@{
|
||
Branch = $branch
|
||
Commit = $commit
|
||
Dirty = $status.Count -gt 0
|
||
ChangedPathCount = $status.Count
|
||
}
|
||
}
|
||
finally {
|
||
Pop-Location
|
||
}
|
||
}
|
||
|
||
function Assert-InitSqlSafe {
|
||
param([string]$Path)
|
||
|
||
if (-not (Test-Path -LiteralPath $Path)) {
|
||
throw "初始化 SQL 不存在:$Path"
|
||
}
|
||
|
||
$content = Get-Content -LiteralPath $Path -Raw
|
||
if ($content -notmatch "CREATE DATABASE IF NOT EXISTS\s+jayucloud_salon") {
|
||
throw "初始化 SQL 未声明目标库 jayucloud_salon:$Path"
|
||
}
|
||
if ($content -notmatch "(?im)^\s*use\s+jayucloud_salon\s*;") {
|
||
throw "初始化 SQL 未切换到目标库 jayucloud_salon:$Path"
|
||
}
|
||
|
||
$dangerousMatch = [regex]::Match($content, "(?im)^\s*(drop\s+(database|schema|table)|truncate\s+table)\b")
|
||
if ($dangerousMatch.Success) {
|
||
throw "初始化 SQL 包含危险语句:$($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 "构建 JC-Salon-Core"
|
||
Invoke-Native $maven $mavenArgs (Join-Path $resolvedRepoRoot "JC-Salon-Core")
|
||
|
||
Write-Step "构建 JC-Salon-Gateway"
|
||
Invoke-Native $maven $mavenArgs (Join-Path $resolvedRepoRoot "JC-Salon-Gateway")
|
||
|
||
Write-Step "构建 JC-Salon-Frontend"
|
||
$frontendRoot = Join-Path $resolvedRepoRoot "JC-Salon-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 "JC-Salon-Core\target\JC-Salon-Core.jar"
|
||
$gatewayJar = Join-Path $resolvedRepoRoot "JC-Salon-Gateway\target\JC-Salon-Gateway.jar"
|
||
$frontendDist = Join-Path $resolvedRepoRoot "JC-Salon-Frontend\dist"
|
||
foreach ($requiredPath in @($coreJar, $gatewayJar, $frontendDist, $InitSqlPath)) {
|
||
if (-not (Test-Path -LiteralPath $requiredPath)) {
|
||
throw "缺少发布产物:$requiredPath"
|
||
}
|
||
}
|
||
|
||
$coreArtifact = Join-Path $backendDir "JC-Salon-Core.jar"
|
||
$gatewayArtifact = Join-Path $backendDir "JC-Salon-Gateway.jar"
|
||
$frontendArtifact = Join-Path $frontendDir "jc-salon-frontend-dist.tar.gz"
|
||
$sqlArtifact = Join-Path $sqlDir "店务独立数据库_20260825.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,无法打包前端 dist。"
|
||
}
|
||
if (Test-Path -LiteralPath $frontendArtifact) {
|
||
Remove-Item -LiteralPath $frontendArtifact -Force
|
||
}
|
||
Invoke-Native $tar.Source @("-czf", $frontendArtifact, "-C", (Join-Path $resolvedRepoRoot "JC-Salon-Frontend"), "dist")
|
||
|
||
$hashes = foreach ($artifact in @($coreArtifact, $gatewayArtifact, $frontendArtifact, $sqlArtifact)) {
|
||
$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/jayucloud-salon-health.out 2>/tmp/jayucloud-salon-health.err; do
|
||
if [ "`$(date +%s)" -ge "`$deadline" ]; then
|
||
echo "Health check failed for `$SERVICE on port `$HEALTH_PORT"
|
||
cat /tmp/jayucloud-salon-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/jayucloud-salon-health.out
|
||
"@
|
||
}
|
||
|
||
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 "准备 $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 "切换 $GroupName 发布版本"
|
||
$deployCommand = Get-BackendDeployCommand $RemoteAppDir $ServiceName $releaseName $HealthPort
|
||
Invoke-RemoteShellMany $Servers $deployCommand $GroupName
|
||
}
|
||
|
||
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 Publish-Web {
|
||
param([object]$Server, [string]$ArchivePath)
|
||
|
||
$archiveName = "jc-salon-frontend-dist-$releaseTimestamp.tar.gz"
|
||
$quotedWebRemoteDir = ConvertTo-BashSingleQuoted $WebRemoteDir
|
||
Write-Step "准备 Web 目标机器"
|
||
Invoke-RemoteShell $Server "mkdir -p $quotedWebRemoteDir/releases"
|
||
Copy-FileToRemote $ArchivePath $Server "$WebRemoteDir/releases/$archiveName"
|
||
|
||
Write-Step "切换 Web 发布版本"
|
||
Invoke-RemoteShell $Server (Get-WebDeployCommand $archiveName)
|
||
}
|
||
|
||
function Initialize-ProductionDatabase {
|
||
param([object]$DatabaseServer, [string]$SqlArtifact)
|
||
|
||
Assert-InitSqlSafe $SqlArtifact
|
||
|
||
$dbUserValue = if ($DatabaseUser) { $DatabaseUser } else { $DatabaseServer.User }
|
||
$dbPasswordValue = if ($DatabasePassword) { $DatabasePassword } else { $DatabaseServer.Password }
|
||
if (-not $dbUserValue) {
|
||
throw "数据库用户名为空,请传入 -DatabaseUser 或在服务器清单中填写。"
|
||
}
|
||
|
||
$remoteSqlPath = "/tmp/jayucloud-salon-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
|
||
|
||
$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,
|
||
[string]$ResolvedServerInfoPath
|
||
)
|
||
|
||
$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
|
||
managerMiniProgramApi = "$PublicBaseUrl/api/admin"
|
||
nacosNamespace = "jayucloud-salon"
|
||
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/health/check"
|
||
Write-Host "GET $PublicBaseUrl/api/shop/list"
|
||
return
|
||
}
|
||
|
||
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 "读取服务器清单"
|
||
$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 "没有匹配到 Core 服务器,匹配规则:$CorePattern"
|
||
}
|
||
if ($gatewayServers.Count -eq 0) {
|
||
throw "没有匹配到 Gateway 服务器,匹配规则:$GatewayPattern"
|
||
}
|
||
if ($webServers.Count -ne 1) {
|
||
$webSelector = if ($WebTargetName) { "名称 $WebTargetName" } else { "主机 $WebTargetHost" }
|
||
throw "Web 目标必须唯一,当前按 $webSelector 找到 $($webServers.Count) 个。"
|
||
}
|
||
if ((-not $SkipDatabaseInit) -and $databaseServers.Count -ne 1) {
|
||
throw "数据库初始化目标必须唯一,当前按 $DatabaseTargetName 找到 $($databaseServers.Count) 个。"
|
||
}
|
||
|
||
Assert-ProductionTarget (@($coreServers) + @($gatewayServers) + @($webServers))
|
||
$databaseServer = if (-not $SkipDatabaseInit) { $databaseServers[0] } else { $null }
|
||
|
||
Write-Host "服务器清单:$resolvedServerInfoPath"
|
||
@($coreServers + $gatewayServers + $webServers) | Select-Object Name, Host, Port, User, Purpose, Environment | Format-Table -AutoSize
|
||
if ($databaseServer) {
|
||
Write-Host "数据库初始化目标:"
|
||
$databaseServer | Select-Object Name, Host, Port, User, Purpose, Environment | Format-Table -AutoSize
|
||
}
|
||
|
||
Write-Step "检查工作区"
|
||
$gitState = Test-GitState
|
||
|
||
Write-Step "构建发布包"
|
||
$package = Build-ReleasePackage $gitState
|
||
Write-ReleaseManifest $package $coreServers $gatewayServers $webServers[0] $databaseServer $resolvedServerInfoPath
|
||
|
||
if (-not $Deploy) {
|
||
Write-Host "发布包已生成。传入 -Deploy 才会发布到生产;传入 -DryRun 可打印远程动作但不修改远端。"
|
||
exit 0
|
||
}
|
||
|
||
if (-not $SkipDatabaseInit) {
|
||
Initialize-ProductionDatabase $databaseServer $package.InitSql
|
||
}
|
||
else {
|
||
Write-Host "已跳过数据库初始化。"
|
||
}
|
||
|
||
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 "jayucloud_salon 生产发布流程完成。"
|