2026-08-25 16:21:05 +08:00
param (
2026-05-24 18:09:11 +08:00
[ string ] $RepoRoot = ( Split-Path -Parent $PSScriptRoot ),
[ string ] $ServerInfoPath = "" ,
[ switch ] $DryRun ,
[ switch ] $Deploy ,
[ switch ] $UsePuttyPassword ,
[ switch ] $SkipBuild ,
[ switch ] $SkipTests ,
[ switch ] $AllowDirtyWorkingTree ,
[ switch ] $SkipDatabaseInit ,
2026-05-29 13:30:56 +08:00
[ string ] $DatabaseTargetName = "mysql02" ,
2026-05-24 18:09:11 +08:00
[ int ] $DatabasePort = 3306 ,
2026-10-14 13:04:10 +08:00
[ string ] $DatabaseName = "jayucloud_artlist" ,
2026-05-24 18:09:11 +08:00
[ string ] $DatabaseUser = "" ,
[ string ] $DatabasePassword = "" ,
[ string ] $InitSqlPath = "" ,
2026-08-25 16:21:05 +08:00
[ string ] $CorePattern = "^JC-ArtList-Core" ,
[ string ] $GatewayPattern = "^JC-ArtList-Gateway" ,
2026-05-24 18:09:11 +08:00
[ string ] $WebTargetName = "" ,
[ string ] $WebTargetHost = "8.137.35.61" ,
2026-08-25 16:21:05 +08:00
[ string ] $CoreRemoteAppDir = "/opt/jc-artlist-core" ,
[ string ] $GatewayRemoteAppDir = "/opt/jc-artlist-gateway" ,
[ string ] $WebRemoteDir = "/opt/jc-artlist-frontend" ,
[ string ] $CoreServiceName = "jc-artlist-core" ,
[ string ] $GatewayServiceName = "jc-artlist-gateway" ,
2026-05-24 18:09:11 +08:00
[ int ] $CoreHealthPort = 81 ,
[ int ] $GatewayHealthPort = 80 ,
[ string ] $HealthPath = "/health/check" ,
[ int ] $HealthTimeoutSeconds = 120 ,
[ string ] $PublicBaseUrl = "https://yunail.art" ,
[ string ] $MavenPath = ""
)
$ErrorActionPreference = "Stop"
2026-06-22 20:39:51 +08:00
$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"
2026-08-26 19:09:56 +08:00
$defaultInitSqlPath = Join-Path $resolvedRepoRoot "docs\scripts\sql\init\jayucloud-artlist.sql"
2026-05-24 18:09:11 +08:00
if ( -not $InitSqlPath ) {
2026-06-22 20:39:51 +08:00
$InitSqlPath = $defaultInitSqlPath
2026-05-24 18:09:11 +08:00
}
function Write-Step {
param ([ string ] $Message )
2026-06-22 20:39:51 +08:00
2026-05-24 18:09:11 +08:00
Write-Host ""
Write-Host "==> $Message "
}
function ConvertTo-BashSingleQuoted {
param ([ AllowNull ()][ string ] $Value )
2026-06-22 20:39:51 +08:00
2026-05-24 18:09:11 +08:00
if ( $null -eq $Value ) {
$Value = ""
}
return "'" + $Value . Replace ( "'" , "'""'""'" ) + "'"
}
2026-06-22 20:39:51 +08:00
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
}
}
2026-05-24 18:09:11 +08:00
function Read-ZipEntryText {
param ( $Zip , [ string ] $Name )
2026-06-22 20:39:51 +08:00
2026-05-24 18:09:11 +08:00
$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 )
2026-06-22 20:39:51 +08:00
2026-05-24 18:09:11 +08:00
foreach ( $attribute in $Element . Attributes ) {
if ( $attribute . LocalName -eq "id" ) {
return $attribute . Value
}
}
return ""
}
function Get-ColumnIndex {
param ([ string ] $CellRef )
2026-06-22 20:39:51 +08:00
2026-05-24 18:09:11 +08:00
$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 ) {
2026-06-22 20:39:51 +08:00
throw "服务器清单没有工作表: $Path "
2026-05-24 18:09:11 +08:00
}
$relationshipId = Get-RelationshipId $firstSheet
$relationship = $null
foreach ( $candidate in $relsXml . GetElementsByTagName ( "Relationship" )) {
if ( $candidate . GetAttribute ( "Id" ) -eq $relationshipId ) {
$relationship = $candidate
break
}
}
if ( -not $relationship ) {
2026-06-22 20:39:51 +08:00
throw "无法解析工作表关系: $relationshipId "
2026-05-24 18:09:11 +08:00
}
$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 ) {
2026-06-22 20:39:51 +08:00
$values = for ( $index = 1 ; $index -le $maxIndex ; $index ++) {
if ( $valuesByIndex . ContainsKey ( $index )) { $valuesByIndex [ $index ] } else { "" }
2026-05-24 18:09:11 +08:00
}
if (( $values -join "" ). Trim ()) {
$rows += , $values
}
}
}
return $rows
}
finally {
$zip . Dispose ()
}
}
2026-06-24 15:04:17 +08:00
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
}
2026-05-24 18:09:11 +08:00
function Get-ServersFromWorkbook {
param ([ string ] $Path )
if ( -not ( Test-Path -LiteralPath $Path )) {
2026-06-22 20:39:51 +08:00
throw "服务器清单不存在: $Path "
2026-05-24 18:09:11 +08:00
}
$rows = @ ( Get-XlsxFirstSheetRows ( Resolve-Path -LiteralPath $Path ). Path )
if ( $rows . Count -lt 2 ) {
2026-06-22 20:39:51 +08:00
throw "服务器清单没有数据行: $Path "
2026-05-24 18:09:11 +08:00
}
2026-06-24 15:04:17 +08:00
$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" , "环境" , "所属中心" )
2026-05-24 18:09:11 +08:00
foreach ( $row in $rows [ 1 ..( $rows . Count - 1 )]) {
2026-06-24 15:04:17 +08:00
if (( -not ( Get-CellValue $row $nameIndex )) -or ( -not ( Get-CellValue $row $hostIndex ))) {
2026-05-24 18:09:11 +08:00
continue
}
[ pscustomobject ] @ {
2026-06-24 15:04:17 +08:00
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
2026-05-24 18:09:11 +08:00
}
}
}
2026-06-22 20:39:51 +08:00
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
}
2026-05-24 18:09:11 +08:00
function Assert-ProductionTarget {
param ([ object[] ] $Servers )
$blocked = @ ( $Servers | Where-Object { $_ . Name -match "^(?i:MessageHub|mysql|nacos|redis|rabbitmq)" })
if ( $blocked . Count -gt 0 ) {
2026-06-22 20:39:51 +08:00
throw "拒绝把应用发布到基础设施节点: $( $blocked . Name -join ', ' ) "
2026-05-24 18:09:11 +08:00
}
$knownNonProduction = @ ( $Servers | Where-Object { $_ . Environment -match "(?i)\b(dev|test|local|staging)\b" })
if ( $knownNonProduction . Count -gt 0 ) {
2026-06-22 20:39:51 +08:00
throw "拒绝发布到非生产环境节点: $( $knownNonProduction . Name -join ', ' ) "
2026-05-24 18:09:11 +08:00
}
}
function Get-SshTarget {
param ([ object ] $Server )
2026-06-22 20:39:51 +08:00
2026-05-24 18:09:11 +08:00
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 )) {
2026-06-22 20:39:51 +08:00
throw "找不到 PuTTY plink,请安装 PuTTY 工具或改用 SSH key。"
2026-05-24 18:09:11 +08:00
}
$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 )) {
2026-06-22 20:39:51 +08:00
throw "本地上传文件不存在: $LocalPath "
2026-05-24 18:09:11 +08:00
}
if ( $UsePuttyPassword ) {
$pscp = Get-Command pscp -ErrorAction SilentlyContinue
if (( -not $DryRun ) -and ( -not $pscp )) {
2026-06-22 20:39:51 +08:00
throw "找不到 PuTTY pscp,请安装 PuTTY 工具或改用 SSH key。"
2026-05-24 18:09:11 +08:00
}
$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
}
}
2026-06-22 20:39:51 +08:00
function Invoke-RemoteShellMany {
2026-05-24 18:09:11 +08:00
param (
[ object[] ] $Servers ,
[ string ] $Command ,
[ string ] $GroupName
)
2026-06-22 20:39:51 +08:00
foreach ( $server in $Servers ) {
Write-Host " $GroupName target: $( $server . Name ) $( $server . User ) @ $( $server . Host ) : $( $server . Port ) "
Invoke-RemoteShell $server $Command
2026-05-24 18:09:11 +08:00
}
}
function Test-GitState {
2026-06-22 20:39:51 +08:00
Push-Location $resolvedRepoRoot
2026-05-24 18:09:11 +08:00
try {
$commit = (& git rev-parse HEAD ). Trim ()
$branch = (& git branch - -show-current ). Trim ()
$status = @ (& git status - -porcelain )
2026-06-22 20:39:51 +08:00
if ( $status . Count -gt 0 ) {
Write-Warning "当前工作区有 $( $status . Count ) 个变更路径。"
2026-05-24 18:09:11 +08:00
$status | Select-Object -First 40 | ForEach-Object { Write-Warning $_ }
if ( $Deploy -and ( -not $DryRun ) -and ( -not $AllowDirtyWorkingTree )) {
2026-06-22 20:39:51 +08:00
throw "拒绝从脏工作区发布生产,请先提交/暂存,或显式传入 -AllowDirtyWorkingTree。"
2026-05-24 18:09:11 +08:00
}
}
return [ pscustomobject ] @ {
Branch = $branch
Commit = $commit
2026-06-22 20:39:51 +08:00
Dirty = $status . Count -gt 0
2026-05-24 18:09:11 +08:00
ChangedPathCount = $status . Count
}
}
finally {
Pop-Location
}
}
2026-06-22 20:39:51 +08:00
function Assert-InitSqlSafe {
2026-05-24 18:09:11 +08:00
param ([ string ] $Path )
if ( -not ( Test-Path -LiteralPath $Path )) {
2026-06-22 20:39:51 +08:00
throw "初始化 SQL 不存在: $Path "
2026-05-24 18:09:11 +08:00
}
$content = Get-Content -LiteralPath $Path -Raw
2026-10-14 13:04:10 +08:00
if ( $content -notmatch "CREATE DATABASE IF NOT EXISTS\s+jayucloud_artlist" ) {
throw "初始化 SQL 未声明目标库 jayucloud_artlist: $Path "
2026-06-22 20:39:51 +08:00
}
2026-10-14 13:04:10 +08:00
if ( $content -notmatch "(?im)^\s*use\s+jayucloud_artlist\s*;" ) {
throw "初始化 SQL 未切换到目标库 jayucloud_artlist: $Path "
2026-06-22 20:39:51 +08:00
}
$dangerousMatch = [ regex ]:: Match ( $content , "(?im)^\s*(drop\s+(database|schema|table)|truncate\s+table)\b" )
2026-05-24 18:09:11 +08:00
if ( $dangerousMatch . Success ) {
2026-06-22 20:39:51 +08:00
throw "初始化 SQL 包含危险语句: $( $dangerousMatch . Value ) "
2026-05-24 18:09:11 +08:00
}
}
function Build-ReleasePackage {
param ([ object ] $GitState )
2026-06-22 20:39:51 +08:00
New-Item -ItemType Directory -Force -Path $backendDir , $frontendDir , $sqlDir | Out-Null
2026-05-24 18:09:11 +08:00
$maven = Resolve-Maven $MavenPath
if ( -not $SkipBuild ) {
$mavenArgs = @ ( "-q" , "package" )
if ( $SkipTests ) {
$mavenArgs += "-DskipTests"
}
2026-08-25 16:21:05 +08:00
Write-Step "构建 JC-ArtList-Core"
Invoke-Native $maven $mavenArgs ( Join-Path $resolvedRepoRoot "JC-ArtList-Core" )
2026-05-24 18:09:11 +08:00
2026-08-25 16:21:05 +08:00
Write-Step "构建 JC-ArtList-Gateway"
Invoke-Native $maven $mavenArgs ( Join-Path $resolvedRepoRoot "JC-ArtList-Gateway" )
2026-05-24 18:09:11 +08:00
2026-08-25 16:21:05 +08:00
Write-Step "构建 JC-ArtList-Frontend"
$frontendRoot = Join-Path $resolvedRepoRoot "JC-ArtList-Frontend"
2026-05-24 18:09:11 +08:00
if ( -not ( Test-Path -LiteralPath ( Join-Path $frontendRoot "node_modules" ))) {
Invoke-Native "npm" @ ( "ci" ) $frontendRoot
}
Invoke-Native "npm" @ ( "run" , "build" ) $frontendRoot
}
2026-08-25 16:21:05 +08:00
$coreJar = Join-Path $resolvedRepoRoot "JC-ArtList-Core\target\JC-ArtList-Core.jar"
$gatewayJar = Join-Path $resolvedRepoRoot "JC-ArtList-Gateway\target\JC-ArtList-Gateway.jar"
$frontendDist = Join-Path $resolvedRepoRoot "JC-ArtList-Frontend\dist"
2026-05-24 18:09:11 +08:00
foreach ( $requiredPath in @ ( $coreJar , $gatewayJar , $frontendDist , $InitSqlPath )) {
if ( -not ( Test-Path -LiteralPath $requiredPath )) {
2026-06-22 20:39:51 +08:00
throw "缺少发布产物: $requiredPath "
2026-05-24 18:09:11 +08:00
}
}
2026-08-25 16:21:05 +08:00
$coreArtifact = Join-Path $backendDir "JC-ArtList-Core.jar"
$gatewayArtifact = Join-Path $backendDir "JC-ArtList-Gateway.jar"
$frontendArtifact = Join-Path $frontendDir "jc-artlist-frontend-dist.tar.gz"
2026-08-26 19:09:56 +08:00
$sqlArtifact = Join-Path $sqlDir "jayucloud-artlist.sql"
2026-05-24 18:09:11 +08:00
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 ) {
2026-06-22 20:39:51 +08:00
throw "缺少 tar,无法打包前端 dist。"
2026-05-24 18:09:11 +08:00
}
if ( Test-Path -LiteralPath $frontendArtifact ) {
Remove-Item -LiteralPath $frontendArtifact -Force
}
2026-08-25 16:21:05 +08:00
Invoke-Native $tar . Source @ ( "-czf" , $frontendArtifact , "-C" , ( Join-Path $resolvedRepoRoot "JC-ArtList-Frontend" ), "dist" )
2026-05-24 18:09:11 +08:00
2026-06-22 20:39:51 +08:00
$hashes = foreach ( $artifact in @ ( $coreArtifact , $gatewayArtifact , $frontendArtifact , $sqlArtifact )) {
2026-05-24 18:09:11 +08:00
$hash = Get-FileHash -LiteralPath $artifact -Algorithm SHA256
[ pscustomobject ] @ {
2026-06-22 20:39:51 +08:00
Path = $artifact . Replace ( $resolvedRepoRoot , "" ). TrimStart ( "\" , "/" )
2026-05-24 18:09:11 +08:00
Sha256 = $hash . Hash
}
}
return [ pscustomobject ] @ {
2026-06-22 20:39:51 +08:00
Directory = $releaseDir
2026-05-24 18:09:11 +08:00
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 "
2026-06-22 20:39:51 +08:00
BACKUP_NAME="app- $releaseTimestamp .jar"
2026-05-24 18:09:11 +08:00
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
2026-06-22 20:39:51 +08:00
nohup java -jar "` $APP_DIR /app.jar" > "` $APP_DIR /logs/app- $releaseTimestamp .log" 2>&1 &
2026-05-24 18:09:11 +08:00
echo `$! > "` $APP_DIR /app.pid"
fi
deadline=` $((`$( date + % s ) + `$ HEALTH_TIMEOUT ))
2026-10-14 13:04:10 +08:00
until curl -fsS "http://127.0.0.1:` $HEALTH_PORT ` $HEALTH_PATH " >/tmp/jayucloud-artlist-health.out 2>/tmp/jayucloud-artlist-health.err; do
2026-05-24 18:09:11 +08:00
if [ "` $( date + % s ) " -ge "` $deadline " ]; then
echo "Health check failed for ` $SERVICE on port ` $HEALTH_PORT "
2026-10-14 13:04:10 +08:00
cat /tmp/jayucloud-artlist-health.err || true
2026-05-24 18:09:11 +08:00
if command -v systemctl >/dev/null 2>&1; then journalctl -u "` $SERVICE " -n 80 --no-pager || true; fi
exit 43
fi
sleep 3
done
2026-10-14 13:04:10 +08:00
cat /tmp/jayucloud-artlist-health.out
2026-05-24 18:09:11 +08:00
"@
}
function Publish-BackendGroup {
param (
[ string ] $GroupName ,
[ object[] ] $Servers ,
[ string ] $ArtifactPath ,
[ string ] $RemoteAppDir ,
[ string ] $ServiceName ,
[ int ] $HealthPort
)
$artifactBaseName = [ System.IO.Path ]:: GetFileNameWithoutExtension ( $ArtifactPath )
2026-06-22 20:39:51 +08:00
$releaseName = " $artifactBaseName - $releaseTimestamp .jar"
2026-05-24 18:09:11 +08:00
$quotedRemoteAppDir = ConvertTo-BashSingleQuoted $RemoteAppDir
2026-06-22 20:39:51 +08:00
Write-Step "准备 $GroupName 目标机器"
2026-05-24 18:09:11 +08:00
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 "
}
2026-06-22 20:39:51 +08:00
Write-Step "切换 $GroupName 发布版本"
2026-05-24 18:09:11 +08:00
$deployCommand = Get-BackendDeployCommand $RemoteAppDir $ServiceName $releaseName $HealthPort
2026-06-22 20:39:51 +08:00
Invoke-RemoteShellMany $Servers $deployCommand $GroupName
2026-05-24 18:09:11 +08:00
}
function Get-WebDeployCommand {
param ([ string ] $ArchiveName )
$webDir = ConvertTo-BashSingleQuoted $WebRemoteDir
$archiveName = ConvertTo-BashSingleQuoted $ArchiveName
return @"
set -e
WEB_DIR= $webDir
ARCHIVE_NAME= $archiveName
2026-06-22 20:39:51 +08:00
RELEASE_BASE="` $WEB_DIR /releases/ $releaseTimestamp "
2026-05-24 18:09:11 +08:00
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 )
2026-08-25 16:21:05 +08:00
$archiveName = "jc-artlist-frontend-dist- $releaseTimestamp .tar.gz"
2026-05-24 18:09:11 +08:00
$quotedWebRemoteDir = ConvertTo-BashSingleQuoted $WebRemoteDir
2026-06-22 20:39:51 +08:00
Write-Step "准备 Web 目标机器"
2026-05-24 18:09:11 +08:00
Invoke-RemoteShell $Server "mkdir -p $quotedWebRemoteDir /releases"
Copy-FileToRemote $ArchivePath $Server " $WebRemoteDir /releases/ $archiveName "
2026-06-22 20:39:51 +08:00
Write-Step "切换 Web 发布版本"
Invoke-RemoteShell $Server ( Get-WebDeployCommand $archiveName )
2026-05-24 18:09:11 +08:00
}
function Initialize-ProductionDatabase {
param ([ object ] $DatabaseServer , [ string ] $SqlArtifact )
2026-06-22 20:39:51 +08:00
Assert-InitSqlSafe $SqlArtifact
2026-05-24 18:09:11 +08:00
$dbUserValue = if ( $DatabaseUser ) { $DatabaseUser } else { $DatabaseServer . User }
$dbPasswordValue = if ( $DatabasePassword ) { $DatabasePassword } else { $DatabaseServer . Password }
if ( -not $dbUserValue ) {
2026-06-22 20:39:51 +08:00
throw "数据库用户名为空,请传入 -DatabaseUser 或在服务器清单中填写。"
2026-05-24 18:09:11 +08:00
}
2026-10-14 13:04:10 +08:00
$remoteSqlPath = "/tmp/jayucloud-artlist-init- $releaseTimestamp .sql"
2026-06-22 20:39:51 +08:00
Write-Step "初始化生产空库"
Write-Host "数据库目标: $( $DatabaseServer . Name ) $( $DatabaseServer . Host ) : $DatabasePort / $DatabaseName "
2026-05-24 18:09:11 +08:00
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 ,
2026-06-22 20:39:51 +08:00
[ object ] $DatabaseServer ,
[ string ] $ResolvedServerInfoPath
2026-05-24 18:09:11 +08:00
)
$manifest = [ pscustomobject ] @ {
2026-06-22 20:39:51 +08:00
releaseTimestamp = $releaseTimestamp
repoRoot = $resolvedRepoRoot
2026-05-24 18:09:11 +08:00
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
2026-06-22 20:39:51 +08:00
serverInfoPath = $ResolvedServerInfoPath
2026-05-24 18:09:11 +08:00
coreRemoteAppDir = $CoreRemoteAppDir
gatewayRemoteAppDir = $GatewayRemoteAppDir
webRemoteDir = $WebRemoteDir
publicBaseUrl = $PublicBaseUrl
2026-06-22 20:39:51 +08:00
managerMiniProgramApi = " $PublicBaseUrl /api/admin"
2026-10-14 13:04:10 +08:00
nacosNamespace = "jayucloud-artlist"
2026-05-24 18:09:11 +08:00
dryRun = [ bool ] $DryRun
deploy = [ bool ] $Deploy
}
}
2026-06-22 20:39:51 +08:00
$manifest | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $manifestPath -Encoding UTF8
Write-Host "Manifest: $manifestPath "
2026-05-24 18:09:11 +08:00
}
function Invoke-PublicSmokeTests {
if ( $DryRun ) {
Write-Host "DryRun public smoke tests:"
2026-06-22 20:39:51 +08:00
Write-Host "GET $PublicBaseUrl /health/check"
2026-05-24 18:09:11 +08:00
Write-Host "GET $PublicBaseUrl /api/shop/list"
return
}
2026-06-22 20:39:51 +08:00
Write-Step "生产公开冒烟"
foreach ( $url in @ ( " $PublicBaseUrl /health/check" , " $PublicBaseUrl /api/shop/list" )) {
2026-05-24 18:09:11 +08:00
Write-Host "GET $url "
$response = Invoke-WebRequest -Uri $url -UseBasicParsing -TimeoutSec 20
Write-Host "Status $( $response . StatusCode ) Length $( $response . RawContentLength ) "
}
}
2026-06-22 20:39:51 +08:00
Write-Step "读取服务器清单"
2026-05-24 18:09:11 +08:00
$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 ) {
2026-06-22 20:39:51 +08:00
throw "没有匹配到 Core 服务器,匹配规则: $CorePattern "
2026-05-24 18:09:11 +08:00
}
if ( $gatewayServers . Count -eq 0 ) {
2026-06-22 20:39:51 +08:00
throw "没有匹配到 Gateway 服务器,匹配规则: $GatewayPattern "
2026-05-24 18:09:11 +08:00
}
if ( $webServers . Count -ne 1 ) {
2026-06-22 20:39:51 +08:00
$webSelector = if ( $WebTargetName ) { "名称 $WebTargetName " } else { "主机 $WebTargetHost " }
throw "Web 目标必须唯一,当前按 $webSelector 找到 $( $webServers . Count ) 个。"
2026-05-24 18:09:11 +08:00
}
if (( -not $SkipDatabaseInit ) -and $databaseServers . Count -ne 1 ) {
2026-06-22 20:39:51 +08:00
throw "数据库初始化目标必须唯一,当前按 $DatabaseTargetName 找到 $( $databaseServers . Count ) 个。"
2026-05-24 18:09:11 +08:00
}
Assert-ProductionTarget ( @ ( $coreServers ) + @ ( $gatewayServers ) + @ ( $webServers ))
$databaseServer = if ( -not $SkipDatabaseInit ) { $databaseServers [ 0 ] } else { $null }
2026-06-22 20:39:51 +08:00
Write-Host "服务器清单: $resolvedServerInfoPath "
2026-05-24 18:09:11 +08:00
@ ( $coreServers + $gatewayServers + $webServers ) | Select-Object Name , Host , Port , User , Purpose , Environment | Format-Table -AutoSize
if ( $databaseServer ) {
2026-06-22 20:39:51 +08:00
Write-Host "数据库初始化目标:"
2026-05-24 18:09:11 +08:00
$databaseServer | Select-Object Name , Host , Port , User , Purpose , Environment | Format-Table -AutoSize
}
2026-06-22 20:39:51 +08:00
Write-Step "检查工作区"
2026-05-24 18:09:11 +08:00
$gitState = Test-GitState
2026-06-22 20:39:51 +08:00
Write-Step "构建发布包"
2026-05-24 18:09:11 +08:00
$package = Build-ReleasePackage $gitState
2026-06-22 20:39:51 +08:00
Write-ReleaseManifest $package $coreServers $gatewayServers $webServers [ 0 ] $databaseServer $resolvedServerInfoPath
2026-05-24 18:09:11 +08:00
if ( -not $Deploy ) {
2026-06-22 20:39:51 +08:00
Write-Host "发布包已生成。传入 -Deploy 才会发布到生产;传入 -DryRun 可打印远程动作但不修改远端。"
2026-05-24 18:09:11 +08:00
exit 0
}
if ( -not $SkipDatabaseInit ) {
Initialize-ProductionDatabase $databaseServer $package . InitSql
}
else {
2026-06-22 20:39:51 +08:00
Write-Host "已跳过数据库初始化。"
2026-05-24 18:09:11 +08:00
}
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 ""
2026-10-14 13:04:10 +08:00
Write-Host "jayucloud-artlist 生产发布流程完成。"