2026-08-25 10:56:55 +08:00
param (
2026-08-28 15:16:28 +08:00
[ string ] $RepoRoot = ( Join-Path $PSScriptRoot "..\.." ),
2026-08-25 10:56:55 +08:00
[ string ] $ServerInfoPath = "" ,
[ switch ] $DryRun ,
[ switch ] $Deploy ,
[ switch ] $UsePuttyPassword ,
[ switch ] $SkipBuild ,
[ switch ] $SkipTests ,
[ switch ] $AllowDirtyWorkingTree ,
[ switch ] $SkipDatabaseInit ,
2026-08-27 12:39:20 +08:00
[ switch ] $PackageOnly ,
2026-09-01 16:34:02 +08:00
[ switch ] $AllowSitTarget ,
2026-08-27 12:39:20 +08:00
[ switch ] $RequireSystemd ,
[ string ] $PackageDirectory = "" ,
[ string ] $ServerInfoJsonPath = "" ,
[ string ] $SshKeyPath = "" ,
[ string ] $KnownHostsPath = "" ,
2026-09-03 09:46:54 +08:00
[ string ] $SshPassword = "" ,
2026-08-25 10:56:55 +08:00
[ string ] $DatabaseTargetName = "mysql02" ,
[ int ] $DatabasePort = 3306 ,
[ string ] $DatabaseName = "jayucloud_salon" ,
[ string ] $DatabaseUser = "" ,
[ string ] $DatabasePassword = "" ,
[ string ] $InitSqlPath = "" ,
2026-08-25 16:21:05 +08:00
[ string ] $CorePattern = "^JC-Salon-Core" ,
[ string ] $GatewayPattern = "^JC-Salon-Gateway" ,
2026-08-25 10:56:55 +08:00
[ string ] $WebTargetName = "" ,
[ string ] $WebTargetHost = "8.137.35.61" ,
2026-08-25 16:21:05 +08:00
[ 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" ,
2026-08-25 10:56:55 +08:00
[ 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"
2026-08-26 19:09:56 +08:00
$defaultInitSqlPath = Join-Path $resolvedRepoRoot "docs\scripts\sql\init\jayucloud-salon.sql"
2026-08-25 10:56:55 +08:00
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 ""
}
2026-10-22 18:29:57 +08:00
function Assert-FlywayMigrationPackaged {
param ([ string ] $Path )
if ( -not ( Test-Path -LiteralPath $Path )) {
throw "Salon Core 发布包不存在: $Path "
}
Add-Type -AssemblyName System . IO . Compression . FileSystem
$zip = [ System.IO.Compression.ZipFile ]:: OpenRead ( $Path )
try {
$migrationEntries = @ ( $zip . Entries | Where-Object { $_ . FullName -match '^BOOT-INF/classes/db/migration/V[0-9]+__[^/]+\.sql$' })
$baselineEntry = $zip . GetEntry ( "BOOT-INF/classes/db/migration/V1__Salon空库初始化.sql" )
$flywayLibrary = @ ( $zip . Entries | Where-Object { $_ . FullName -match '^BOOT-INF/lib/flyway-core-[^/]+\.jar$' })
$mysqlLibrary = @ ( $zip . Entries | Where-Object { $_ . FullName -match '^BOOT-INF/lib/flyway-mysql-[^/]+\.jar$' })
if ( -not $baselineEntry -or $migrationEntries . Count -eq 0 -or $flywayLibrary . Count -eq 0 -or $mysqlLibrary . Count -eq 0 ) {
throw "Salon Core JAR 未包含 Flyway Core、MySQL 适配器和 V1 数据库基线: $Path "
}
}
finally {
$zip . Dispose ()
}
}
2026-08-25 10:56:55 +08:00
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
}
}
}
2026-08-27 12:39:20 +08:00
function Get-ServersFromJson {
param ([ string ] $Path )
if ( -not ( Test-Path -LiteralPath $Path )) {
throw "服务器 JSON 清单不存在: $Path "
}
$items = @ ( Get-Content -LiteralPath $Path -Raw -Encoding UTF8 | ConvertFrom-Json )
foreach ( $item in $items ) {
if ( -not $item . Name -or -not $item . Host ) {
throw "服务器 JSON 清单缺少 Name 或 Host: $Path "
}
[ pscustomobject ] @ {
Name = [ string ] $item . Name
Host = [ string ] $item . Host
Port = if ( $item . Port ) { [ int ] $item . Port } else { 22 }
User = if ( $item . User ) { [ string ] $item . User } else { "root" }
2026-09-03 09:46:54 +08:00
Password = $SshPassword
2026-08-27 12:39:20 +08:00
Purpose = if ( $item . Purpose ) { [ string ] $item . Purpose } else { "" }
Note = if ( $item . Note ) { [ string ] $item . Note } else { "" }
Environment = if ( $item . Environment ) { [ string ] $item . Environment } else { "prod" }
}
}
}
2026-08-25 10:56:55 +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
}
function Assert-ProductionTarget {
2026-09-01 16:34:02 +08:00
param (
[ object[] ] $Servers ,
[ switch ] $AllowSit
)
2026-08-25 10:56:55 +08:00
$blocked = @ ( $Servers | Where-Object { $_ . Name -match "^(?i:MessageHub|mysql|nacos|redis|rabbitmq)" })
if ( $blocked . Count -gt 0 ) {
throw "拒绝把应用发布到基础设施节点: $( $blocked . Name -join ', ' ) "
}
2026-09-01 16:34:02 +08:00
$blockedEnvironments = if ( $AllowSit ) { "(?i)\b(dev|test|local|staging)\b" } else { "(?i)\b(dev|test|local|staging|sit)\b" }
$knownNonProduction = @ ( $Servers | Where-Object { $_ . Environment -match $blockedEnvironments })
2026-08-25 10:56:55 +08:00
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
)
2026-09-03 09:46:54 +08:00
if ( $SshPassword ) {
$sshpass = Get-Command sshpass -ErrorAction SilentlyContinue
if (( -not $DryRun ) -and ( -not $sshpass )) {
throw "找不到 sshpass,无法使用 SSH 密码登录。"
}
$sshpassPath = if ( $sshpass ) { $sshpass . Source } else { "sshpass" }
$env:SSHPASS = $SshPassword
try {
Invoke-Native $sshpassPath @ ( "-e" , "ssh" , "-o" , "StrictHostKeyChecking=accept-new" , "-p" , [ string ] $Server . Port , ( Get-SshTarget $Server ), $Command ) -Sensitive: $Sensitive -RemoteMutation
}
finally {
Remove-Item Env : SSHPASS -ErrorAction SilentlyContinue
}
}
elseif ( $SshKeyPath ) {
2026-08-27 12:39:20 +08:00
$sshArgs = @ ( "-o" , "BatchMode=yes" , "-o" , "StrictHostKeyChecking=yes" , "-i" , $SshKeyPath )
if ( $KnownHostsPath ) {
$sshArgs += @ ( "-o" , "UserKnownHostsFile= $KnownHostsPath " )
}
$sshArgs += @ ( "-p" , [ string ] $Server . Port , ( Get-SshTarget $Server ), $Command )
Invoke-Native "ssh" $sshArgs -Sensitive: $Sensitive -RemoteMutation
}
elseif ( $UsePuttyPassword ) {
2026-08-25 10:56:55 +08:00
$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 "
}
2026-09-03 09:46:54 +08:00
if ( $SshPassword ) {
$sshpass = Get-Command sshpass -ErrorAction SilentlyContinue
if (( -not $DryRun ) -and ( -not $sshpass )) {
throw "找不到 sshpass,无法使用 SSH 密码登录。"
}
$sshpassPath = if ( $sshpass ) { $sshpass . Source } else { "sshpass" }
$env:SSHPASS = $SshPassword
try {
Invoke-Native $sshpassPath @ ( "-e" , "scp" , "-o" , "StrictHostKeyChecking=accept-new" , "-P" , [ string ] $Server . Port , $LocalPath , " $( Get-SshTarget $Server ) : $RemotePath " ) -Sensitive: $Sensitive -RemoteMutation
}
finally {
Remove-Item Env : SSHPASS -ErrorAction SilentlyContinue
}
}
elseif ( $SshKeyPath ) {
2026-08-27 12:39:20 +08:00
$scpArgs = @ ( "-o" , "BatchMode=yes" , "-o" , "StrictHostKeyChecking=yes" , "-i" , $SshKeyPath )
if ( $KnownHostsPath ) {
$scpArgs += @ ( "-o" , "UserKnownHostsFile= $KnownHostsPath " )
}
$scpArgs += @ ( "-P" , [ string ] $Server . Port , $LocalPath , " $( Get-SshTarget $Server ) : $RemotePath " )
Invoke-Native "scp" $scpArgs -Sensitive: $Sensitive -RemoteMutation
}
elseif ( $UsePuttyPassword ) {
2026-08-25 10:56:55 +08:00
$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 {
2026-08-28 13:07:49 +08:00
$commitOutput = & git rev-parse HEAD
if ( $LASTEXITCODE -ne 0 -or $null -eq $commitOutput ) {
throw "无法读取当前 Git 提交号。"
}
$commit = ([ string ] $commitOutput ). Trim ()
$branchOutput = & git branch - -show-current
$branch = if ( $null -ne $branchOutput ) { ([ string ] $branchOutput ). Trim () } else { "" }
if ( -not $branch ) {
$branch = if ( $env:GITHUB_REF_NAME ) { ([ string ] $env:GITHUB_REF_NAME ). Trim () } else { "DETACHED_HEAD" }
}
2026-08-25 10:56:55 +08:00
$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 ) {
2026-08-28 15:41:25 +08:00
$mavenArgs = @ ( "-B" , "package" )
2026-08-25 10:56:55 +08:00
if ( $SkipTests ) {
2026-09-14 16:35:44 +08:00
$mavenArgs += "-Dmaven.test.skip=true"
2026-08-25 10:56:55 +08:00
}
2026-08-25 16:21:05 +08:00
Write-Step "构建 JC-Salon-Core"
Invoke-Native $maven $mavenArgs ( Join-Path $resolvedRepoRoot "JC-Salon-Core" )
2026-08-25 10:56:55 +08:00
2026-08-25 16:21:05 +08:00
Write-Step "构建 JC-Salon-Gateway"
Invoke-Native $maven $mavenArgs ( Join-Path $resolvedRepoRoot "JC-Salon-Gateway" )
2026-08-25 10:56:55 +08:00
2026-08-25 16:21:05 +08:00
Write-Step "构建 JC-Salon-Frontend"
$frontendRoot = Join-Path $resolvedRepoRoot "JC-Salon-Frontend"
2026-08-25 10:56:55 +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-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"
2026-08-25 10:56:55 +08:00
foreach ( $requiredPath in @ ( $coreJar , $gatewayJar , $frontendDist , $InitSqlPath )) {
if ( -not ( Test-Path -LiteralPath $requiredPath )) {
throw "缺少发布产物: $requiredPath "
}
}
2026-10-22 18:29:57 +08:00
Assert-FlywayMigrationPackaged $coreJar
2026-08-25 10:56:55 +08:00
2026-08-25 16:21:05 +08:00
$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"
2026-08-26 19:09:56 +08:00
$sqlArtifact = Join-Path $sqlDir "jayucloud-salon.sql"
2026-08-25 10:56:55 +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 ) {
throw "缺少 tar,无法打包前端 dist。"
}
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-Salon-Frontend" ), "dist" )
2026-08-25 10:56:55 +08:00
$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 "
2026-08-27 12:39:20 +08:00
if [ "` $RequireSystemd " = "True" ] && ! systemctl list-unit-files | grep -q "^` $SERVICE .service"; then
echo "Required systemd unit missing: ` $SERVICE "
exit 44
fi
2026-08-25 10:56:55 +08:00
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 )
2026-08-25 16:21:05 +08:00
$archiveName = "jc-salon-frontend-dist- $releaseTimestamp .tar.gz"
2026-08-25 10:56:55 +08:00
$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
}
}
2026-09-03 23:45:38 +08:00
$manifestDirectory = Split-Path -Parent $manifestPath
if ( -not ( Test-Path -LiteralPath $manifestDirectory )) {
New-Item -ItemType Directory -Path $manifestDirectory -Force | Out-Null
}
2026-08-25 10:56:55 +08:00
$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 ) "
}
}
2026-08-27 12:39:20 +08:00
if ( $PackageOnly ) {
Write-Step "检查工作区"
$gitState = Test-GitState
Write-Step "构建发布包"
$package = Build-ReleasePackage $gitState
$packageManifest = [ pscustomobject ] @ {
releaseTimestamp = $releaseTimestamp
git = $package . Git
artifacts = $package . Hashes
parameters = [ pscustomobject ] @ {
databaseName = $DatabaseName
webRemoteDir = $WebRemoteDir
publicBaseUrl = $PublicBaseUrl
nacosNamespace = "jayucloud-salon"
packageOnly = $true
}
}
2026-09-03 23:45:38 +08:00
$packageManifestDirectory = Split-Path -Parent $manifestPath
if ( -not ( Test-Path -LiteralPath $packageManifestDirectory )) {
New-Item -ItemType Directory -Path $packageManifestDirectory -Force | Out-Null
}
2026-08-27 12:39:20 +08:00
$packageManifest | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $manifestPath -Encoding UTF8
Write-Host "发布包已生成: $( $package . Directory ) "
exit 0
}
function Get-ExistingReleasePackage {
param ([ string ] $Path )
if ( -not ( Test-Path -LiteralPath $Path )) {
throw "已下载发布包目录不存在: $Path "
}
$manifestFile = Get-ChildItem -LiteralPath $Path -Filter "manifest.json" -File -Recurse | Select-Object -First 1
if ( -not $manifestFile ) {
throw "发布包目录中缺少 manifest.json: $Path "
}
$releaseDir = $manifestFile . Directory . FullName
$coreArtifact = Join-Path $releaseDir "backend\JC-Salon-Core.jar"
$gatewayArtifact = Join-Path $releaseDir "backend\JC-Salon-Gateway.jar"
$frontendArtifact = Join-Path $releaseDir "frontend\jc-salon-frontend-dist.tar.gz"
$sqlArtifact = Join-Path $releaseDir "sql\jayucloud-salon.sql"
foreach ( $requiredPath in @ ( $coreArtifact , $gatewayArtifact , $frontendArtifact , $sqlArtifact )) {
if ( -not ( Test-Path -LiteralPath $requiredPath )) {
throw "发布包缺少文件: $requiredPath "
}
}
2026-10-22 18:29:57 +08:00
Assert-FlywayMigrationPackaged $coreArtifact
2026-08-27 12:39:20 +08:00
$hashes = foreach ( $artifact in @ ( $coreArtifact , $gatewayArtifact , $frontendArtifact , $sqlArtifact )) {
$hash = Get-FileHash -LiteralPath $artifact -Algorithm SHA256
[ pscustomobject ] @ { Path = $artifact . Replace ( $releaseDir , "" ). TrimStart ( "\" , "/" ); Sha256 = $hash . Hash }
}
[ pscustomobject ] @ {
Directory = $releaseDir
CoreJar = $coreArtifact
GatewayJar = $gatewayArtifact
FrontendArchive = $frontendArtifact
InitSql = $sqlArtifact
Hashes = @ ( $hashes )
Git = $null
}
}
2026-08-25 10:56:55 +08:00
Write-Step "读取服务器清单"
2026-08-27 12:39:20 +08:00
$resolvedServerInfoPath = if ( $ServerInfoJsonPath ) { ( Resolve-Path -LiteralPath $ServerInfoJsonPath ). Path } else { Resolve-ServerInfoPath $ServerInfoPath }
$servers = if ( $ServerInfoJsonPath ) { @ ( Get-ServersFromJson $resolvedServerInfoPath ) } else { @ ( Get-ServersFromWorkbook $resolvedServerInfoPath ) }
2026-08-25 10:56:55 +08:00
$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 ) 个。"
}
2026-09-01 16:34:02 +08:00
Assert-ProductionTarget ( @ ( $coreServers ) + @ ( $gatewayServers ) + @ ( $webServers )) -AllowSit: $AllowSitTarget
2026-08-25 10:56:55 +08:00
$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
2026-08-27 12:39:20 +08:00
Write-Step "准备发布包"
$package = if ( $PackageDirectory ) { Get-ExistingReleasePackage $PackageDirectory } else { Build-ReleasePackage $gitState }
2026-08-25 10:56:55 +08:00
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 生产发布流程完成。"