- 迁移57个老素材到新逻辑(本地zip + S3预览图) - 优化文件命名:SPU_作者_店铺_类型.zip - PSD文件单独存储,不打包进all.zip - 修复下载接口,优先使用本地zip文件 - 修复预览图重复问题 - 添加迁移脚本和验证脚本 - 更新文档和迁移计划 迁移统计: - 总素材数:77个 - 成功迁移:57个 - 新逻辑上传:18个 - 空记录:2个
906 lines
32 KiB
Plaintext
906 lines
32 KiB
Plaintext
#Requires -Version 5.1
|
||
|
||
<#
|
||
.SYNOPSIS
|
||
由壹点3D素材 - 远程构建部署脚本(内网环境)
|
||
|
||
.DESCRIPTION
|
||
本地打包代码 -> 上传到构建机 -> 构建镜像 -> 推送到 Registry -> 部署到生产服务器
|
||
优势:保护本地 SSD,智能缓存,构建速度快,可视化管理
|
||
适用:内网环境,构建机和生产服务器在同一内网
|
||
|
||
.PARAMETER Target
|
||
部署目标:shadow(影子系统)或 production(正式系统,默认)
|
||
|
||
.PARAMETER BuildServerIP
|
||
构建机 IP 地址(默认:192.168.42.134)
|
||
|
||
.PARAMETER BuildServerUser
|
||
构建机用户名(默认:root)
|
||
|
||
.PARAMETER BuildServerPassword
|
||
构建机密码
|
||
|
||
.PARAMETER ProdServerIP
|
||
生产服务器 IP 地址(默认:192.168.58.20)
|
||
|
||
.PARAMETER ProdServerUser
|
||
生产服务器用户名(默认:root)
|
||
|
||
.PARAMETER SkipSync
|
||
跳过代码同步
|
||
|
||
.PARAMETER SkipBuild
|
||
跳过镜像构建
|
||
|
||
.PARAMETER NoCache
|
||
构建时不使用缓存
|
||
|
||
.PARAMETER KeepOldImages
|
||
保留旧镜像(不自动清理)
|
||
|
||
.EXAMPLE
|
||
.\deploy-remote-build.ps1
|
||
部署到正式系统
|
||
|
||
.EXAMPLE
|
||
.\deploy-remote-build.ps1 -Target shadow
|
||
部署到影子系统
|
||
|
||
.EXAMPLE
|
||
.\deploy-remote-build.ps1 -NoCache
|
||
强制重新构建(不使用缓存)
|
||
#>
|
||
|
||
param(
|
||
[ValidateSet('shadow', 'production')]
|
||
[string]$Target = 'production',
|
||
|
||
[string]$BuildServerIP = '192.168.42.134',
|
||
[string]$BuildServerUser = 'root',
|
||
[string]$BuildServerPassword = 'Jsjj@8888',
|
||
|
||
[string]$ProdServerIP = '192.168.58.20',
|
||
[string]$ProdServerUser = 'root',
|
||
|
||
[int]$RegistryPort = 5000,
|
||
|
||
[string]$ImageName = 'youyidian-3d-material',
|
||
[string]$ImageTag = 'latest',
|
||
|
||
[switch]$SkipSync,
|
||
[switch]$SkipBuild,
|
||
[switch]$NoCache,
|
||
[switch]$KeepOldImages,
|
||
[switch]$Help
|
||
)
|
||
|
||
# ==================== 配置 ====================
|
||
|
||
$config = @{
|
||
'shadow' = @{
|
||
'port' = 5320
|
||
'containerName' = 'youyidian-3d-shadow'
|
||
'dbName' = 'lobechat_stage'
|
||
'envFile' = '.env.shadow'
|
||
}
|
||
'production' = @{
|
||
'port' = 4320
|
||
'containerName' = 'youyidian-3d-material'
|
||
'dbName' = 'lobechat'
|
||
'envFile' = '.env'
|
||
}
|
||
}
|
||
|
||
$targetConfig = $config[$Target]
|
||
$RemoteBuildDir = "/opt/youyidian-3d-build"
|
||
$RegistryImage = "$BuildServerIP`:$RegistryPort/$ImageName`:$ImageTag"
|
||
|
||
# ==================== 辅助函数 ====================
|
||
|
||
function Write-Success {
|
||
param([string]$Message)
|
||
Write-Host "[OK] $Message" -ForegroundColor Green
|
||
}
|
||
|
||
function Write-Error-Custom {
|
||
param([string]$Message)
|
||
Write-Host "[ERR] $Message" -ForegroundColor Red
|
||
}
|
||
|
||
function Write-Info {
|
||
param([string]$Message)
|
||
Write-Host "[INFO] $Message" -ForegroundColor Cyan
|
||
}
|
||
|
||
function Write-Warning-Custom {
|
||
param([string]$Message)
|
||
Write-Host "[WARN] $Message" -ForegroundColor Yellow
|
||
}
|
||
|
||
function Write-Step {
|
||
param([int]$Step, [string]$Message)
|
||
Write-Host ""
|
||
Write-Host "==================================================" -ForegroundColor Cyan
|
||
Write-Host "[$Step] $Message" -ForegroundColor Magenta
|
||
Write-Host "==================================================" -ForegroundColor Cyan
|
||
}
|
||
|
||
function Write-SubStep {
|
||
param([string]$Message)
|
||
Write-Host " -> $Message" -ForegroundColor Yellow
|
||
}
|
||
|
||
function Write-StreamOutput {
|
||
param([string]$Line, [string]$Prefix = " ")
|
||
$lowerLine = $Line.ToLower()
|
||
|
||
# 关键错误信息 - 高亮显示
|
||
if ($lowerLine -match "error:|failed|fatal|cannot|unable|denied|refused|timeout") {
|
||
Write-Host "$Prefix$Line" -ForegroundColor Red
|
||
}
|
||
# 警告信息
|
||
elseif ($lowerLine -match "warning|warn") {
|
||
Write-Host "$Prefix$Line" -ForegroundColor Yellow
|
||
}
|
||
# 成功信息
|
||
elseif ($lowerLine -match "success|complete|done|built") {
|
||
Write-Host "$Prefix$Line" -ForegroundColor Green
|
||
}
|
||
# Docker 构建步骤
|
||
elseif ($Line -match "Step \d+/\d+|^\s*\d+\.|RUN|COPY|FROM|CACHED|Sending build context") {
|
||
Write-Host "$Prefix$Line" -ForegroundColor Cyan
|
||
}
|
||
# npm/pnpm 相关
|
||
elseif ($Line -match "npm|pnpm|install|build|compile") {
|
||
Write-Host "$Prefix$Line" -ForegroundColor Cyan
|
||
}
|
||
# DATABASE_URL 错误(这是正常的,但需要显示)
|
||
elseif ($Line -match "DATABASE_URL|PrismaClientInitializationError") {
|
||
Write-Host "$Prefix$Line" -ForegroundColor Yellow
|
||
}
|
||
# 其他信息
|
||
else {
|
||
Write-Host "$Prefix$Line" -ForegroundColor Gray
|
||
}
|
||
}
|
||
|
||
# ==================== SSH 连接函数 ====================
|
||
|
||
function Invoke-SSH {
|
||
param(
|
||
[string]$HostIP,
|
||
[string]$User,
|
||
[string]$Password,
|
||
[string]$Command,
|
||
[switch]$Silent,
|
||
[switch]$StreamOutput
|
||
)
|
||
|
||
$plinkPath = "C:\Program Files\PuTTY\plink.exe"
|
||
|
||
if (-not (Test-Path $plinkPath)) {
|
||
Write-Error-Custom "找不到 plink.exe,请安装 PuTTY"
|
||
exit 1
|
||
}
|
||
|
||
if ($StreamOutput) {
|
||
# 流式输出模式
|
||
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
||
$psi.FileName = $plinkPath
|
||
$psi.Arguments = "-batch -pw $Password $User@$HostIP `"$Command`""
|
||
$psi.RedirectStandardOutput = $true
|
||
$psi.RedirectStandardError = $true
|
||
$psi.UseShellExecute = $false
|
||
$psi.CreateNoWindow = $true
|
||
|
||
$process = New-Object System.Diagnostics.Process
|
||
$process.StartInfo = $psi
|
||
[void]$process.Start()
|
||
|
||
$outputBuilder = New-Object System.Text.StringBuilder
|
||
$errorBuilder = New-Object System.Text.StringBuilder
|
||
|
||
$outputHandler = {
|
||
if ($EventArgs.Data) {
|
||
$line = $EventArgs.Data
|
||
[void]$Event.MessageData.AppendLine($line)
|
||
Write-StreamOutput -Line $line
|
||
}
|
||
}
|
||
|
||
$errorHandler = {
|
||
if ($EventArgs.Data) {
|
||
$line = $EventArgs.Data
|
||
[void]$Event.MessageData.AppendLine($line)
|
||
Write-StreamOutput -Line $line
|
||
}
|
||
}
|
||
|
||
$outputEvent = Register-ObjectEvent -InputObject $process -EventName OutputDataReceived -Action $outputHandler -MessageData $outputBuilder
|
||
$errorEvent = Register-ObjectEvent -InputObject $process -EventName ErrorDataReceived -Action $errorHandler -MessageData $errorBuilder
|
||
|
||
$process.BeginOutputReadLine()
|
||
$process.BeginErrorReadLine()
|
||
$process.WaitForExit()
|
||
|
||
Unregister-Event -SourceIdentifier $outputEvent.Name
|
||
Unregister-Event -SourceIdentifier $errorEvent.Name
|
||
|
||
Write-Host ""
|
||
|
||
return @{
|
||
ExitCode = $process.ExitCode
|
||
Output = $outputBuilder.ToString()
|
||
Error = $errorBuilder.ToString()
|
||
}
|
||
}
|
||
else {
|
||
# 普通输出模式
|
||
$result = & $plinkPath -batch -pw $Password "$User@$HostIP" $Command 2>&1
|
||
|
||
if (-not $Silent) {
|
||
$result | ForEach-Object { Write-StreamOutput -Line $_ }
|
||
}
|
||
|
||
return $result
|
||
}
|
||
}
|
||
|
||
function Invoke-BuildServer {
|
||
param(
|
||
[string]$Command,
|
||
[switch]$Silent,
|
||
[switch]$StreamOutput,
|
||
[string]$ServerIP = $BuildServerIP,
|
||
[string]$ServerUser = $BuildServerUser,
|
||
[string]$ServerPassword = $BuildServerPassword
|
||
)
|
||
|
||
$plinkPath = "C:\Program Files\PuTTY\plink.exe"
|
||
if (-not (Test-Path $plinkPath)) {
|
||
Write-Error-Custom "Cannot find plink.exe"
|
||
return $null
|
||
}
|
||
|
||
if ($StreamOutput) {
|
||
# 流式输出模式
|
||
$psiStream = New-Object System.Diagnostics.ProcessStartInfo
|
||
$psiStream.FileName = $plinkPath
|
||
$psiStream.Arguments = "-batch -pw $ServerPassword $ServerUser@$ServerIP `"$Command`""
|
||
$psiStream.RedirectStandardOutput = $true
|
||
$psiStream.RedirectStandardError = $true
|
||
$psiStream.UseShellExecute = $false
|
||
$psiStream.CreateNoWindow = $true
|
||
$psiStream.StandardOutputEncoding = [System.Text.Encoding]::UTF8
|
||
$psiStream.StandardErrorEncoding = [System.Text.Encoding]::UTF8
|
||
|
||
$process = New-Object System.Diagnostics.Process
|
||
$process.StartInfo = $psiStream
|
||
[void]$process.Start()
|
||
|
||
$outputBuilder = New-Object System.Text.StringBuilder
|
||
$errorBuilder = New-Object System.Text.StringBuilder
|
||
|
||
$outputHandler = {
|
||
if ($EventArgs.Data) {
|
||
$line = $EventArgs.Data
|
||
[void]$Event.MessageData.AppendLine($line)
|
||
Write-StreamOutput -Line $line
|
||
}
|
||
}
|
||
|
||
$errorHandler = {
|
||
if ($EventArgs.Data) {
|
||
$line = $EventArgs.Data
|
||
[void]$Event.MessageData.AppendLine($line)
|
||
Write-StreamOutput -Line $line
|
||
}
|
||
}
|
||
|
||
$outputEvent = Register-ObjectEvent -InputObject $process -EventName OutputDataReceived -Action $outputHandler -MessageData $outputBuilder
|
||
$errorEvent = Register-ObjectEvent -InputObject $process -EventName ErrorDataReceived -Action $errorHandler -MessageData $errorBuilder
|
||
|
||
$process.BeginOutputReadLine()
|
||
$process.BeginErrorReadLine()
|
||
$process.WaitForExit()
|
||
|
||
Unregister-Event -SourceIdentifier $outputEvent.Name -ErrorAction SilentlyContinue
|
||
Unregister-Event -SourceIdentifier $errorEvent.Name -ErrorAction SilentlyContinue
|
||
|
||
Write-Host ""
|
||
|
||
return @{
|
||
ExitCode = $process.ExitCode
|
||
Output = $outputBuilder.ToString()
|
||
Error = $errorBuilder.ToString()
|
||
}
|
||
}
|
||
else {
|
||
# 普通输出模式 - 使用直接调用
|
||
& 'C:\Program Files\PuTTY\plink.exe' -batch -pw $ServerPassword "$ServerUser@$ServerIP" $Command 2>&1 | Tee-Object -Variable result
|
||
|
||
if (-not $Silent) {
|
||
$result | ForEach-Object { Write-StreamOutput -Line $_ }
|
||
}
|
||
|
||
return $result
|
||
}
|
||
}
|
||
|
||
function Invoke-ProdServer {
|
||
param(
|
||
[string]$Command,
|
||
[switch]$Silent,
|
||
[switch]$StreamOutput
|
||
)
|
||
$escapedCmd = $Command -replace "'", "'\\''"
|
||
$sshCmd = "ssh -o StrictHostKeyChecking=no $ProdServerUser@$ProdServerIP '$escapedCmd'"
|
||
Invoke-BuildServer -Command $sshCmd -Silent:$Silent -StreamOutput:$StreamOutput -ServerIP $BuildServerIP -ServerUser $BuildServerUser -ServerPassword $BuildServerPassword
|
||
}
|
||
|
||
# ==================== 文件上传函数 ====================
|
||
|
||
function Upload-ToBuildServer {
|
||
param([string]$LocalPath, [string]$RemotePath)
|
||
|
||
Write-SubStep "Start uploading..."
|
||
|
||
$pscpPath = "C:\Program Files\PuTTY\pscp.exe"
|
||
|
||
if (-not (Test-Path $pscpPath)) {
|
||
Write-Error-Custom "找不到 pscp.exe,请安装 PuTTY"
|
||
return $false
|
||
}
|
||
|
||
$fileSize = (Get-Item $LocalPath).Length / 1MB
|
||
Write-Info " File size: $([Math]::Round($fileSize, 2)) MB"
|
||
|
||
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
||
$psi.FileName = $pscpPath
|
||
$psi.Arguments = "-batch -pw $BuildServerPassword $LocalPath `"$BuildServerUser@$BuildServerIP`:$RemotePath`""
|
||
$psi.RedirectStandardOutput = $true
|
||
$psi.RedirectStandardError = $true
|
||
$psi.UseShellExecute = $false
|
||
$psi.CreateNoWindow = $true
|
||
|
||
$process = New-Object System.Diagnostics.Process
|
||
$process.StartInfo = $psi
|
||
[void]$process.Start()
|
||
$process.WaitForExit()
|
||
|
||
return $process.ExitCode -eq 0
|
||
}
|
||
|
||
# ==================== 帮助信息 ====================
|
||
|
||
function Show-Help {
|
||
Write-Host @"
|
||
由壹点3D素材 - 远程构建部署脚本(内网环境)
|
||
|
||
用法:
|
||
.\deploy-remote-build.ps1 # 部署到正式系统
|
||
.\deploy-remote-build.ps1 -Target shadow # 部署到影子系统
|
||
|
||
参数:
|
||
-Target 部署目标: shadow 或 production (默认 production)
|
||
-BuildServerIP 构建机 IP (默认: 192.168.42.134)
|
||
-ProdServerIP 生产服务器 IP (默认: 192.168.58.20)
|
||
-ImageName 镜像名称 (默认: youyidian-3d-material)
|
||
-ImageTag 镜像标签 (默认: latest)
|
||
-SkipSync 跳过代码同步
|
||
-SkipBuild 跳过镜像构建
|
||
-NoCache 构建时不使用缓存 (强制重新构建)
|
||
-KeepOldImages 保留旧镜像 (不自动清理)
|
||
-Help 显示帮助
|
||
|
||
流程:
|
||
1. 打包代码 (排除 node_modules, .next 等)
|
||
2. 上传代码到构建机
|
||
3. 智能检测是否需要重新构建
|
||
4. 在构建机上构建 Docker 镜像 (如需要)
|
||
5. 推送镜像到本地 Registry
|
||
6. 从 Registry 拉取镜像到生产服务器
|
||
7. 在生产服务器上启动容器
|
||
8. 自动清理旧镜像和缓存
|
||
|
||
Registry UI:
|
||
http://$BuildServerIP`:5001
|
||
|
||
示例:
|
||
# 部署到正式系统 (智能缓存)
|
||
.\deploy-remote-build.ps1
|
||
|
||
# 部署到影子系统
|
||
.\deploy-remote-build.ps1 -Target shadow
|
||
|
||
# 强制重新构建 (不使用缓存)
|
||
.\deploy-remote-build.ps1 -NoCache
|
||
|
||
# 跳过代码同步, 直接构建
|
||
.\deploy-remote-build.ps1 -SkipSync
|
||
"@
|
||
}
|
||
|
||
# ==================== 主逻辑 ====================
|
||
|
||
function Main {
|
||
$startTime = Get-Date
|
||
|
||
Write-Host ""
|
||
Write-Host "==================================================" -ForegroundColor Cyan
|
||
Write-Host " 由壹点3D素材 - 远程构建部署 (内网)" -ForegroundColor Cyan
|
||
Write-Host "==================================================" -ForegroundColor Cyan
|
||
Write-Host ""
|
||
|
||
if ($Help) { Show-Help; return }
|
||
|
||
# 显示配置
|
||
Write-Host "Deployment Configuration:" -ForegroundColor Magenta
|
||
Write-Host "--------------------------------------------------" -ForegroundColor Cyan
|
||
Write-Info "Target: $Target"
|
||
Write-Info "Build Server: $BuildServerIP"
|
||
Write-Info "Production Server: $ProdServerIP"
|
||
Write-Info "Container Name: $($targetConfig['containerName'])"
|
||
Write-Info "Port: $($targetConfig['port'])"
|
||
Write-Info "Registry UI: http://$BuildServerIP`:5001"
|
||
Write-Host ""
|
||
|
||
# ==================== 步骤 0: 检查连接 ====================
|
||
Write-Step 0 "Check Environment and Connections"
|
||
|
||
Write-SubStep "Checking build server connection..."
|
||
$dockerCheck = Invoke-BuildServer -Command "docker --version" -Silent
|
||
if ($dockerCheck -notmatch "Docker version") {
|
||
Write-Error-Custom "Cannot connect to build server or Docker not installed"
|
||
Write-Info "Please check:"
|
||
Write-Info " 1. Build server IP: $BuildServerIP"
|
||
Write-Info " 2. SSH password is correct"
|
||
Write-Info " 3. Docker is installed"
|
||
return
|
||
}
|
||
$dockerVersion = $dockerCheck -replace "Docker version ", "" -replace ",.*", ""
|
||
Write-Success "Build server connected (Docker: $dockerVersion)"
|
||
|
||
Write-SubStep "Checking registry status..."
|
||
$registryCheck = Invoke-BuildServer -Command "curl -s http://localhost:5000/v2/_catalog" -Silent
|
||
if ($registryCheck -notmatch "repositories") {
|
||
Write-Warning-Custom "Registry not running, trying to start..."
|
||
Invoke-BuildServer -Command "cd /opt/docker-registry && docker-compose up -d" -Silent | Out-Null
|
||
Start-Sleep -Seconds 5
|
||
$registryCheck = Invoke-BuildServer -Command "curl -s http://localhost:5000/v2/_catalog" -Silent
|
||
if ($registryCheck -match "repositories") {
|
||
Write-Success "Registry started"
|
||
}
|
||
else {
|
||
Write-Error-Custom "Registry failed to start"
|
||
return
|
||
}
|
||
}
|
||
else {
|
||
Write-Success "Registry is running"
|
||
}
|
||
|
||
Write-SubStep "Checking production server connection..."
|
||
$prodCheck = Invoke-ProdServer -Command "echo 'OK'" -Silent
|
||
if ($prodCheck -notmatch "OK") {
|
||
Write-Error-Custom "Cannot connect to production server"
|
||
return
|
||
}
|
||
Write-Success "Production server connected"
|
||
|
||
# ==================== 步骤 1: 同步代码 ====================
|
||
if (-not $SkipSync) {
|
||
Write-Step 1 "Sync Code to Build Server"
|
||
|
||
Write-SubStep "Packaging code..."
|
||
$tempTar = "code-sync-temp.tar.gz"
|
||
$excludes = @(
|
||
"node_modules", ".next", ".git", "*.tar", "*.tar.gz", "uploads/*",
|
||
".build-cache", ".docker-cache", "cache", "flnxi_sucai", "gongxiangp2", "backups",
|
||
"*.log", ".env.local"
|
||
)
|
||
$tarExcludes = $excludes | ForEach-Object { "--exclude=$_" }
|
||
|
||
$tarCmd = "tar -czf $tempTar $($tarExcludes -join ' ') ."
|
||
$bashPath = "C:\Program Files\Git\bin\bash.exe"
|
||
if (Test-Path $bashPath) {
|
||
& $bashPath -c $tarCmd 2>&1 | Out-Null
|
||
}
|
||
else {
|
||
Write-Error-Custom "Cannot find Git bash, code packaging failed"
|
||
return
|
||
}
|
||
|
||
if (-not (Test-Path $tempTar)) {
|
||
Write-Error-Custom "Code packaging failed"
|
||
return
|
||
}
|
||
|
||
$tarSize = [Math]::Round((Get-Item $tempTar).Length / 1MB, 2)
|
||
Write-Success "Code packaged ($tarSize MB)"
|
||
|
||
Write-SubStep "Uploading code..."
|
||
$uploadSuccess = Upload-ToBuildServer -LocalPath $tempTar -RemotePath "/tmp/$tempTar"
|
||
|
||
if (-not $uploadSuccess) {
|
||
Write-Error-Custom "Code upload failed"
|
||
Remove-Item $tempTar -Force -ErrorAction SilentlyContinue
|
||
return
|
||
}
|
||
|
||
Write-SubStep "Updating build directory..."
|
||
Invoke-BuildServer -Command "mkdir -p $RemoteBuildDir && cd $RemoteBuildDir && tar -xzf /tmp/$tempTar && rm /tmp/$tempTar" -Silent | Out-Null
|
||
|
||
Write-Success "Code updated"
|
||
|
||
Remove-Item $tempTar -Force -ErrorAction SilentlyContinue
|
||
|
||
Write-Success "Code sync completed"
|
||
}
|
||
else {
|
||
Write-Step 1 "Skip Code Sync"
|
||
Write-Info "Using existing code on build server"
|
||
}
|
||
|
||
# ==================== 步骤 2: 智能构建镜像 ====================
|
||
if (-not $SkipBuild) {
|
||
Write-Step 2 "Build Docker Image"
|
||
|
||
Write-SubStep "Checking if rebuild is needed..."
|
||
|
||
$needRebuild = $false
|
||
$rebuildReason = ""
|
||
|
||
$imageExists = Invoke-BuildServer -Command "docker images $ImageName`:$ImageTag --format '{{.Repository}}:{{.Tag}}'" -Silent
|
||
if ($imageExists -notmatch "$ImageName`:$ImageTag") {
|
||
$needRebuild = $true
|
||
$rebuildReason = "Image does not exist"
|
||
}
|
||
|
||
if (-not $needRebuild -and -not $SkipSync) {
|
||
$needRebuild = $true
|
||
$rebuildReason = "Code updated"
|
||
}
|
||
|
||
if ($NoCache) {
|
||
$needRebuild = $true
|
||
$rebuildReason = "Force rebuild (-NoCache)"
|
||
}
|
||
|
||
if ($needRebuild) {
|
||
Write-Info "Need to rebuild: $rebuildReason"
|
||
Write-Info "Image name: $ImageName`:$ImageTag"
|
||
Write-Info "Build strategy: Direct build with real-time logs"
|
||
Write-Info "Estimated time: 3-5 min (first), 1-2 min (cached)"
|
||
Write-Host ""
|
||
|
||
$cacheArg = if ($NoCache) { "--no-cache" } else { "" }
|
||
|
||
Write-SubStep "Starting build (real-time output)..."
|
||
Write-Host ""
|
||
Write-Host "==================================================" -ForegroundColor Cyan
|
||
Write-Host "Real-time Build Logs:" -ForegroundColor Magenta
|
||
Write-Host "==================================================" -ForegroundColor Cyan
|
||
Write-Host ""
|
||
|
||
$buildCmd = "cd $RemoteBuildDir && timeout 900 docker build $cacheArg -t $ImageName`:$ImageTag . 2>&1"
|
||
|
||
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
||
$psi.FileName = "C:\Program Files\PuTTY\plink.exe"
|
||
$psi.Arguments = "-batch -pw $BuildServerPassword $BuildServerUser@$BuildServerIP `"$buildCmd`""
|
||
$psi.RedirectStandardOutput = $true
|
||
$psi.RedirectStandardError = $true
|
||
$psi.UseShellExecute = $false
|
||
$psi.CreateNoWindow = $true
|
||
$psi.StandardOutputEncoding = [System.Text.Encoding]::UTF8
|
||
$psi.StandardErrorEncoding = [System.Text.Encoding]::UTF8
|
||
|
||
$process = New-Object System.Diagnostics.Process
|
||
$process.StartInfo = $psi
|
||
[void]$process.Start()
|
||
|
||
$buildSuccess = $false
|
||
|
||
# 使用异步事件处理输出,避免挂起
|
||
$outputBuilder = New-Object System.Text.StringBuilder
|
||
$errorBuilder = New-Object System.Text.StringBuilder
|
||
|
||
$outputHandler = {
|
||
if ($EventArgs.Data) {
|
||
$line = $EventArgs.Data
|
||
[void]$Event.MessageData.AppendLine($line)
|
||
# 清理 ANSI 颜色代码,但保留所有内容
|
||
$cleanLine = $line -replace '\x1b\[[0-9;]*[a-zA-Z]', ''
|
||
# 移除回车符
|
||
$cleanLine = $cleanLine -replace '\r', ''
|
||
# 显示所有非空行
|
||
if ($cleanLine.Trim()) {
|
||
Write-StreamOutput -Line $cleanLine
|
||
}
|
||
# 即使是空行,如果有内容也要输出
|
||
elseif ($line.Trim()) {
|
||
Write-Host " $line" -ForegroundColor Gray
|
||
}
|
||
}
|
||
}
|
||
|
||
$errorHandler = {
|
||
if ($EventArgs.Data) {
|
||
$line = $EventArgs.Data
|
||
[void]$Event.MessageData.AppendLine($line)
|
||
# 清理 ANSI 颜色代码
|
||
$cleanLine = $line -replace '\x1b\[[0-9;]*[a-zA-Z]', ''
|
||
# 移除回车符
|
||
$cleanLine = $cleanLine -replace '\r', ''
|
||
# 显示所有错误输出
|
||
Write-Host " [ERROR] $cleanLine" -ForegroundColor Red
|
||
}
|
||
}
|
||
|
||
$outputEvent = Register-ObjectEvent -InputObject $process -EventName OutputDataReceived -Action $outputHandler -MessageData $outputBuilder
|
||
$errorEvent = Register-ObjectEvent -InputObject $process -EventName ErrorDataReceived -Action $errorHandler -MessageData $errorBuilder
|
||
|
||
$process.BeginOutputReadLine()
|
||
$process.BeginErrorReadLine()
|
||
$process.WaitForExit()
|
||
|
||
Unregister-Event -SourceIdentifier $outputEvent.Name -ErrorAction SilentlyContinue
|
||
Unregister-Event -SourceIdentifier $errorEvent.Name -ErrorAction SilentlyContinue
|
||
|
||
# 检查构建是否成功
|
||
$allOutput = $outputBuilder.ToString()
|
||
$allErrors = $errorBuilder.ToString()
|
||
|
||
if ($allOutput -match "Successfully built|Successfully tagged") {
|
||
$buildSuccess = $true
|
||
}
|
||
|
||
if ($process.ExitCode -eq 0) {
|
||
$imageCheck = Invoke-BuildServer -Command "docker images $ImageName`:$ImageTag --format '{{.Repository}}:{{.Tag}}'" -Silent
|
||
if ($imageCheck -match "$ImageName`:$ImageTag") {
|
||
$buildSuccess = $true
|
||
}
|
||
}
|
||
|
||
# 如果构建失败,显示完整的错误输出
|
||
if (-not $buildSuccess) {
|
||
Write-Host ""
|
||
Write-Error-Custom "Build failed (exit code: $($process.ExitCode))"
|
||
Write-Host ""
|
||
Write-Host "==================================================" -ForegroundColor Red
|
||
Write-Host "Full Error Output:" -ForegroundColor Red
|
||
Write-Host "==================================================" -ForegroundColor Red
|
||
|
||
# 显示标准输出中的错误
|
||
if ($allOutput) {
|
||
$allOutput -split "`n" | ForEach-Object {
|
||
$line = $_ -replace '\x1b\[[0-9;]*[a-zA-Z]', '' -replace '\r', ''
|
||
if ($line.ToLower() -match "error|failed|fatal") {
|
||
Write-Host " $line" -ForegroundColor Red
|
||
}
|
||
}
|
||
}
|
||
|
||
# 显示标准错误输出
|
||
if ($allErrors) {
|
||
Write-Host ""
|
||
Write-Host "Standard Error:" -ForegroundColor Yellow
|
||
Write-Host "--------------------------------------------------" -ForegroundColor Yellow
|
||
$allErrors -split "`n" | ForEach-Object {
|
||
$line = $_ -replace '\x1b\[[0-9;]*[a-zA-Z]', '' -replace '\r', ''
|
||
if ($line.Trim()) {
|
||
Write-Host " $line" -ForegroundColor Red
|
||
}
|
||
}
|
||
}
|
||
|
||
Write-Host "==================================================" -ForegroundColor Red
|
||
return
|
||
}
|
||
|
||
Write-Host ""
|
||
Write-Host "==================================================" -ForegroundColor Cyan
|
||
Write-Host "Build Completed" -ForegroundColor Magenta
|
||
Write-Host "==================================================" -ForegroundColor Cyan
|
||
Write-Host ""
|
||
|
||
$imageSize = Invoke-BuildServer -Command "docker images $ImageName`:$ImageTag --format '{{.Size}}'" -Silent
|
||
Write-Success "Image built successfully (size: $imageSize)"
|
||
}
|
||
else {
|
||
Write-Success "No need to rebuild, using existing image"
|
||
$imageSize = Invoke-BuildServer -Command "docker images $ImageName`:$ImageTag --format '{{.Size}}'" -Silent
|
||
$imageCreated = Invoke-BuildServer -Command "docker images $ImageName`:$ImageTag --format '{{.CreatedAt}}'" -Silent
|
||
Write-Info "Image size: $imageSize"
|
||
Write-Info "Build time: $imageCreated"
|
||
Write-Info "Tip: Use -NoCache to force rebuild"
|
||
}
|
||
}
|
||
else {
|
||
Write-Step 2 "Skip Image Build"
|
||
Write-Info "Using existing image on build server"
|
||
}
|
||
|
||
# ==================== 步骤 3: 推送到 Registry ====================
|
||
Write-Step 3 "Push Image to Registry"
|
||
|
||
Write-SubStep "Tagging image..."
|
||
Invoke-BuildServer -Command "docker tag $ImageName`:$ImageTag $RegistryImage" -Silent | Out-Null
|
||
Write-Success "Image tagged: $RegistryImage"
|
||
|
||
Write-SubStep "Pushing to registry (real-time output)..."
|
||
Write-Host ""
|
||
|
||
$pushCmd = "docker push $RegistryImage 2>&1"
|
||
$pushResult = Invoke-BuildServer -Command $pushCmd -StreamOutput
|
||
|
||
Write-Host ""
|
||
|
||
if ($pushResult.ExitCode -eq 0) {
|
||
Write-Success "Image pushed to registry"
|
||
Write-Info "View image: http://$BuildServerIP`:5001"
|
||
}
|
||
else {
|
||
Write-Error-Custom "Image push failed"
|
||
return
|
||
}
|
||
|
||
# ==================== 步骤 4: 生产服务器拉取镜像 ====================
|
||
Write-Step 4 "Pull Image on Production Server"
|
||
|
||
Write-SubStep "Pulling from registry (real-time output)..."
|
||
Write-Info "Registry: $RegistryImage"
|
||
Write-Host ""
|
||
|
||
$pullCmd = "docker pull $RegistryImage 2>&1 && docker tag $RegistryImage $ImageName`:$ImageTag"
|
||
$pullResult = Invoke-ProdServer -Command $pullCmd -StreamOutput
|
||
|
||
Write-Host ""
|
||
|
||
if ($pullResult.ExitCode -eq 0) {
|
||
Write-Success "Image pulled successfully"
|
||
}
|
||
else {
|
||
Write-Error-Custom "Image pull failed"
|
||
Write-Info "Please check insecure-registry config on production server"
|
||
return
|
||
}
|
||
|
||
# ==================== 步骤 5: 启动容器 ====================
|
||
Write-Step 5 "Start Container on Production Server"
|
||
|
||
$envFile = $targetConfig['envFile']
|
||
$containerName = $targetConfig['containerName']
|
||
$port = $targetConfig['port']
|
||
$deploymentVersion = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
|
||
$downloadTokenSecret = "yydd-product-package-download-token-secret-2026"
|
||
|
||
Write-SubStep "Stopping old container..."
|
||
Invoke-ProdServer -Command "docker stop $containerName 2>/dev/null || true" -Silent | Out-Null
|
||
Invoke-ProdServer -Command "docker rm $containerName 2>/dev/null || true" -Silent | Out-Null
|
||
Write-Success "Old container stopped"
|
||
|
||
Write-SubStep "Starting new container..."
|
||
$startCmd = "docker run -d --name $containerName -p $port`:3000 -v /mnt/PoolOne/apps/youyidian-3d/uploads:/app/uploads --env-file /mnt/PoolOne/apps/youyidian-3d/$envFile -e DISABLE_CACHE=true -e DEPLOYMENT_VERSION=$deploymentVersion -e DOWNLOAD_TOKEN_SECRET=$downloadTokenSecret $ImageName`:$ImageTag"
|
||
|
||
$containerIdResult = Invoke-ProdServer -Command $startCmd -Silent
|
||
|
||
if (-not $containerIdResult -or $containerIdResult -match "Error") {
|
||
Write-Error-Custom "Container start command failed"
|
||
Write-Host " Error: $containerIdResult" -ForegroundColor Red
|
||
return
|
||
}
|
||
|
||
Write-SubStep "Waiting for container to start..."
|
||
Start-Sleep -Seconds 5
|
||
|
||
Write-SubStep "Checking container status (with retry)..."
|
||
$containerStatus = "not_found"
|
||
$maxRetries = 6
|
||
$retryCount = 0
|
||
|
||
while ($retryCount -lt $maxRetries) {
|
||
$containerStatus = Invoke-ProdServer -Command "docker inspect -f '{{.State.Running}}' $containerName 2>/dev/null || echo 'not_found'" -Silent
|
||
if ($containerStatus -match "true") {
|
||
break
|
||
}
|
||
$retryCount++
|
||
if ($retryCount -lt $maxRetries) {
|
||
Write-Info " Retry $retryCount/$maxRetries..."
|
||
Start-Sleep -Seconds 5
|
||
}
|
||
}
|
||
|
||
if ($containerStatus -match "true") {
|
||
Write-Success "Container started successfully"
|
||
Write-Info "Container name: $containerName"
|
||
Write-Info "URL: http://$ProdServerIP`:$port"
|
||
|
||
Write-SubStep "Waiting for application to be ready (checking logs)..."
|
||
Start-Sleep -Seconds 3
|
||
|
||
Write-SubStep "Container logs (last 10 lines):"
|
||
$logs = Invoke-ProdServer -Command "docker logs --tail 10 $containerName 2>&1" -Silent
|
||
if ($logs) {
|
||
$logs -split "`n" | ForEach-Object {
|
||
if ($_ -match "Ready in|ready|started") {
|
||
Write-Host " $_" -ForegroundColor Green
|
||
}
|
||
elseif ($_ -match "error|Error|ERROR|failed|Failed|FAILED") {
|
||
Write-Host " $_" -ForegroundColor Red
|
||
}
|
||
else {
|
||
Write-Host " $_" -ForegroundColor Gray
|
||
}
|
||
}
|
||
}
|
||
}
|
||
else {
|
||
Write-Error-Custom "Container failed to start after $maxRetries retries"
|
||
Write-Host ""
|
||
Write-Host "==================================================" -ForegroundColor Red
|
||
Write-Host "Container Error Logs:" -ForegroundColor Red
|
||
Write-Host "==================================================" -ForegroundColor Red
|
||
$errorLogs = Invoke-ProdServer -Command "docker logs --tail 100 $containerName 2>&1" -Silent
|
||
if ($errorLogs) {
|
||
$errorLogs -split "`n" | ForEach-Object {
|
||
Write-Host " $_" -ForegroundColor Red
|
||
}
|
||
}
|
||
else {
|
||
Write-Host " Cannot get logs (container may not exist)" -ForegroundColor Red
|
||
}
|
||
Write-Host "==================================================" -ForegroundColor Red
|
||
return
|
||
}
|
||
|
||
# ==================== 步骤 6: 清理资源 ====================
|
||
if (-not $KeepOldImages) {
|
||
Write-Step 6 "Clean Up Resources"
|
||
|
||
Write-SubStep "Cleaning build server..."
|
||
$cleanBuildCmd = "docker builder prune -af --filter 'until=6h' 2>&1; docker image prune -f 2>&1"
|
||
Invoke-BuildServer -Command $cleanBuildCmd | Out-Null
|
||
Write-Success "Build server cleaned"
|
||
|
||
Write-SubStep "Cleaning production server..."
|
||
$cleanProdCmd = "docker image prune -af --filter 'until=6h' 2>&1; docker container prune -f --filter 'until=6h' 2>&1"
|
||
Invoke-ProdServer -Command $cleanProdCmd | Out-Null
|
||
Write-Success "Production server cleaned"
|
||
|
||
Write-Success "Resource cleanup completed"
|
||
}
|
||
else {
|
||
Write-Step 6 "Skip Resource Cleanup"
|
||
Write-Info "Keep all old images"
|
||
}
|
||
|
||
# ==================== 完成 ====================
|
||
$endTime = Get-Date
|
||
$duration = [Math]::Round(($endTime - $startTime).TotalSeconds)
|
||
$minutes = [Math]::Floor($duration / 60)
|
||
$seconds = $duration % 60
|
||
|
||
Write-Host ""
|
||
Write-Host "==================================================" -ForegroundColor Green
|
||
Write-Host " Deployment Successful!" -ForegroundColor Green
|
||
Write-Host "==================================================" -ForegroundColor Green
|
||
Write-Host ""
|
||
Write-Host "Deployment Statistics:" -ForegroundColor Magenta
|
||
Write-Host "--------------------------------------------------" -ForegroundColor Cyan
|
||
Write-Info "Target: $Target"
|
||
Write-Info "Container: $containerName"
|
||
Write-Info "URL: http://$ProdServerIP`:$port"
|
||
Write-Info "Registry UI: http://$BuildServerIP`:5001"
|
||
Write-Info "Total time: $minutes min $seconds sec"
|
||
Write-Host ""
|
||
Write-Success "Deployment completed! Ready to use."
|
||
Write-Host ""
|
||
}
|
||
|
||
# 执行主逻辑(只在脚本被直接执行时运行)
|
||
if ($MyInvocation.InvocationName -ne '.') {
|
||
Main
|
||
}
|