#requires -Version 7.2 [CmdletBinding()] param( [Parameter(Mandatory)][ValidateSet('Init','Middleware','Bootstrap','Restore','Build','Start','Stop','Status','Firewall','InstallAutostart')][string]$Action, [string]$DataRoot = 'D:/am-freescan-data', [string]$PublicBaseUrl = 'http://127.0.0.1:5180', [switch]$ConfirmStopped, [string]$MigrationPath, [string]$MaintenanceToken ) $ErrorActionPreference = 'Stop' $repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..')) $private = Join-Path $repo '.local/standalone' $runtimeFile = Join-Path $private 'runtime.json' $compose = Join-Path $PSScriptRoot 'compose.yaml' $envFile = Join-Path $private 'compose.env' $pidFile = Join-Path $private 'backend-process.json' $jar = Join-Path $private 'backend/yudao-server.jar' $bootstrap = Join-Path $repo 'scripts/bootstrap_standalone.py' function Invoke-Checked([string]$Program, [string[]]$Arguments) { & $Program @Arguments if ($LASTEXITCODE -ne 0) { throw "$Program failed ($LASTEXITCODE); do not continue to the next deployment step" } } function Compose([string[]]$Arguments) { $project = if ($cfg.composeProject) { $cfg.composeProject } else { 'am-freescan-standalone' } if ($project -notmatch '^[a-z0-9][a-z0-9_-]*$') { throw 'Invalid Compose project name' } Invoke-Checked 'docker' (@('compose','-p',$project,'--env-file',$envFile,'-f',$compose) + $Arguments) } function Read-Runtime { if (-not (Test-Path -LiteralPath $runtimeFile)) { throw 'Run Init first' } $value = Get-Content -LiteralPath $runtimeFile -Raw | ConvertFrom-Json if ($value.mysql.host -ne '127.0.0.1' -or $value.mysql.database -ne 'am-freescan' -or $value.mysql.port -ne 3306 -or $value.redis.host -ne '127.0.0.1' -or $value.redis.port -ne 6379) { throw 'Standalone middleware must remain local' } return $value } function Secret([int]$Length) { $bytes = [byte[]]::new($Length) [Security.Cryptography.RandomNumberGenerator]::Fill($bytes) return -join ($bytes | ForEach-Object { 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789'[$_ % 55] }) } function Write-ComposeEnv($cfg) { $web = (Join-Path $cfg.dataRoot 'web').Replace('\','/') $backup = (Join-Path $cfg.dataRoot 'backups').Replace('\','/') @("MYSQL_ROOT_PASSWORD=$($cfg.mysqlRootPassword)","MYSQL_APP_PASSWORD=$($cfg.mysql.password)","REDIS_PASSWORD=$($cfg.redis.password)","WEB_ROOT='$web'","BACKUP_ROOT='$backup'") | Set-Content -LiteralPath $envFile -Encoding utf8NoBOM } function Ensure-Idle($cfg) { if (-not $ConfirmStopped) { throw 'Onsite confirmation required: use -ConfirmStopped only after acquisition and all physical motion have stopped' } Invoke-Checked 'python' @($bootstrap,'--config',$runtimeFile,'--check-idle') } function Owned-Backend { if (-not (Test-Path -LiteralPath $pidFile)) { return $null } $saved = Get-Content -LiteralPath $pidFile -Raw | ConvertFrom-Json $process = Get-Process -Id $saved.pid -ErrorAction SilentlyContinue if (-not $process) { return $null } $details = Get-CimInstance Win32_Process -Filter "ProcessId=$($saved.pid)" if ($process.StartTime.ToUniversalTime().ToString('o') -ne $saved.startedUtc -or -not $details.CommandLine -or $details.CommandLine.IndexOf($jar,[StringComparison]::OrdinalIgnoreCase) -lt 0) { throw 'PID was reused or points to another service; refusing to stop it' } return $process } function Healthy { # This application does not bundle Actuator. Use its existing, public, read-only # tenant lookup, and require an initialized primary tenant rather than HTTP 200 alone. try { $reply = Invoke-RestMethod 'http://127.0.0.1:48090/admin-api/system/tenant/simple-list' -TimeoutSec 3 return $reply.code -eq 0 -and @($reply.data | Where-Object { $_.id -eq 1 }).Count -eq 1 } catch { return $false } } if ($Action -eq 'Init') { if (Test-Path -LiteralPath $runtimeFile) { Write-Output 'Private instance config already exists; preserved without changes'; exit 0 } foreach ($port in @(3306,6379,48090,5180)) { if (Get-NetTCPConnection -State Listen -LocalPort $port -ErrorAction SilentlyContinue) { throw "Port $port is occupied; identify its owner before creating an independent instance" } } if (-not [IO.Path]::IsPathFullyQualified($DataRoot)) { throw 'DataRoot must be an absolute Windows path' } $origin = [uri]$PublicBaseUrl if ($origin.Scheme -notin @('http','https') -or -not $origin.Host -or $origin.UserInfo -or $origin.Query -or $origin.Fragment -or $origin.AbsolutePath -ne '/') { throw 'PublicBaseUrl must be a plain browser-accessible HTTP(S) origin' } $DataRoot = [IO.Path]::GetFullPath($DataRoot).TrimEnd('\','/').Replace('\','/') if (Test-Path -LiteralPath $DataRoot) { if (Get-ChildItem -LiteralPath $DataRoot -Force) { throw 'Choose a new empty DataRoot; do not adopt another deployment storage directory' } } New-Item -ItemType Directory -Path $private -Force | Out-Null $principal = [Security.Principal.WindowsIdentity]::GetCurrent().Name Invoke-Checked 'icacls.exe' @($private,'/inheritance:r','/grant:r',"${principal}:(OI)(CI)F",'*S-1-5-18:(OI)(CI)F','*S-1-5-32-544:(OI)(CI)F') foreach ($dir in @('artifacts','uploads','web','backups','logs','certs','tmp')) { New-Item -ItemType Directory -Path (Join-Path $DataRoot $dir) -Force | Out-Null } New-Item -ItemType Directory -Path (Join-Path $private 'backend') -Force | Out-Null $cfg = [ordered]@{ instanceId = [guid]::NewGuid().ToString('N'); dataRoot = $DataRoot; uploadRoot = "$DataRoot/uploads" publicBaseUrl = $PublicBaseUrl.TrimEnd('/'); adminPassword = (Secret 14); mysqlRootPassword = (Secret 32) mysql = @{host='127.0.0.1';port=3306;database='am-freescan';user='freescan';password=(Secret 32)} redis = @{host='127.0.0.1';port=6379;database=15;password=(Secret 32)} } $cfg | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $runtimeFile -Encoding utf8NoBOM Write-ComposeEnv $cfg @('username=admin',"password=$($cfg.adminPassword)") | Set-Content -LiteralPath (Join-Path $private 'initial-admin.txt') -Encoding utf8NoBOM Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'application-private.example.yaml') -Destination (Join-Path $private 'application-private.yaml') Write-Output 'Independent config created in .local/standalone; passwords are stored privately and are not printed' exit 0 } $cfg = Read-Runtime Write-ComposeEnv $cfg switch ($Action) { 'Middleware' { Compose @('up','-d','--wait','mysql','redis') } 'Bootstrap' { Invoke-Checked 'python' @($bootstrap) Invoke-Checked 'python' @($bootstrap,'--config',$runtimeFile,'--apply') Invoke-Checked 'python' @($bootstrap,'--config',$runtimeFile,'--verify') } 'Build' { if (Owned-Backend) { throw 'Stop this backend safely before replacing its runtime package' } $java = if ($env:JAVA_HOME) { Join-Path $env:JAVA_HOME 'bin/java.exe' } else { (Get-Command java).Source } $version = (& $java -version 2>&1 | Out-String) if ($version -notmatch 'version "17\.') { throw 'Build and runtime require JDK 17' } $maven = (& mvn -version 2>&1 | Out-String) if ($maven -notmatch 'Apache Maven 3\.9\.') { throw 'Use Maven 3.9.x and place it first on PATH' } Push-Location (Join-Path $repo 'am-backend') try { Invoke-Checked 'mvn' @('-pl','yudao-server','-am','package','-DskipTests','-DskipITs') } finally { Pop-Location } Copy-Item -LiteralPath (Join-Path $repo 'am-backend/yudao-server/target/yudao-server.jar') -Destination $jar -Force Push-Location (Join-Path $repo 'am-web') try { Invoke-Checked 'pnpm' @('install','--frozen-lockfile') Invoke-Checked 'pnpm' @('build:standalone') Copy-Item -Path 'dist-standalone/*' -Destination (Join-Path $cfg.dataRoot 'web') -Recurse -Force } finally { Pop-Location } git -C $repo rev-parse HEAD | Set-Content -LiteralPath (Join-Path $private 'deployed-commit.txt') -Encoding utf8NoBOM (Get-FileHash -LiteralPath $jar).Hash | Set-Content -LiteralPath (Join-Path $private 'backend-sha256.txt') -Encoding utf8NoBOM } 'Restore' { if (-not $ConfirmStopped -or -not $MigrationPath) { throw 'Restore requires -MigrationPath and -ConfirmStopped; source must remain stopped' } Invoke-Checked 'python' @((Join-Path $repo 'scripts/migrate_standalone.py'),'import','--config',$runtimeFile,'--package',$MigrationPath,'--confirm-source-stopped') Invoke-Checked 'python' @($bootstrap,'--config',$runtimeFile,'--upgrade') Invoke-Checked 'python' @($bootstrap,'--config',$runtimeFile,'--verify') } 'Start' { $maintenanceFile = Join-Path $private 'maintenance.json' if (Test-Path -LiteralPath $maintenanceFile) { $maintenance = Get-Content -LiteralPath $maintenanceFile -Raw | ConvertFrom-Json if (-not $MaintenanceToken -or $maintenance.token -ne $MaintenanceToken) { throw 'Deployment maintenance is active; normal/autostart startup is blocked until the deployment finishes' } } $until = [datetime]::UtcNow.AddSeconds(120) do { & docker info *> $null; if ($LASTEXITCODE -eq 0) { break }; Start-Sleep 3 } while ([datetime]::UtcNow -lt $until) if ($LASTEXITCODE -ne 0) { throw 'Docker Desktop is not ready; start it in this Windows user session' } Compose @('up','-d','--wait','mysql','redis') Invoke-Checked 'python' @($bootstrap,'--config',$runtimeFile,'--verify') if (-not (Test-Path -LiteralPath $jar) -or -not (Test-Path -LiteralPath (Join-Path $cfg.dataRoot 'web/index.html'))) { throw 'Run Build first' } $owned = Owned-Backend if (-not $owned) { if (Get-NetTCPConnection -State Listen -LocalPort 48090 -ErrorAction SilentlyContinue) { throw '48090 belongs to another process; do not kill it' } if (Get-NetUDPEndpoint -LocalPort 4433 -ErrorAction SilentlyContinue) { throw 'UDP 4433 belongs to another process; identify it before starting' } $java = if ($env:JAVA_HOME) { Join-Path $env:JAVA_HOME 'bin/java.exe' } else { (Get-Command java).Source } if ((& $java -version 2>&1 | Out-String) -notmatch 'version "17\.') { throw 'Runtime requires JDK 17' } $env:AM_FREESCAN_HOME = $cfg.dataRoot $env:AM_FREESCAN_DB_USER = 'freescan'; $env:AM_FREESCAN_DB_PASSWORD = $cfg.mysql.password $env:AM_FREESCAN_REDIS_PASSWORD = $cfg.redis.password; $env:AM_FREESCAN_PUBLIC_BASE_URL = $cfg.publicBaseUrl $privateYaml = (Join-Path $private 'application-private.yaml').Replace('\','/') $arguments = @('-Xms512m','-Xmx2g','-Dfile.encoding=UTF-8',('"-Djava.io.tmpdir='+$cfg.dataRoot+'/tmp"'),'-jar',('"'+$jar+'"'),'--spring.profiles.active=standalone',('"--spring.config.additional-location=optional:file:'+$privateYaml+'"')) $process = Start-Process -FilePath $java -ArgumentList $arguments -WorkingDirectory $repo -WindowStyle Hidden -PassThru -RedirectStandardOutput (Join-Path $cfg.dataRoot 'logs/launch.stdout.log') -RedirectStandardError (Join-Path $cfg.dataRoot 'logs/launch.stderr.log') @{pid=$process.Id;startedUtc=$process.StartTime.ToUniversalTime().ToString('o')} | ConvertTo-Json | Set-Content -LiteralPath $pidFile -Encoding utf8NoBOM } $until = [datetime]::UtcNow.AddSeconds(120) while (-not (Healthy) -and [datetime]::UtcNow -lt $until) { Start-Sleep 2 } if (-not (Healthy)) { throw 'Backend is not healthy; inspect dataRoot/logs without printing passwords' } Compose @('up','-d','--force-recreate','web') Compose @('exec','-T','web','nginx','-t') Write-Output "Backend healthy; browser entry: $($cfg.publicBaseUrl)" } 'Stop' { Ensure-Idle $cfg $process = Owned-Backend if ($process) { Stop-Process -Id $process.Id -ErrorAction Stop; $process.WaitForExit(30000) | Out-Null } Write-Output 'Owned backend stopped; middleware, frontend and persistent data retained' } 'Status' { Compose @('ps') Write-Output "Backend healthy: $(Healthy)" Get-NetTCPConnection -State Listen -LocalPort 48090,5180 -ErrorAction SilentlyContinue | Select-Object LocalPort,OwningProcess Get-NetUDPEndpoint -LocalPort 4433 -ErrorAction SilentlyContinue | Select-Object LocalPort,OwningProcess } 'Firewall' { foreach ($rule in @(@{name='AM-FreeScan-Web';port=5180;protocol='TCP'},@{name='AM-FreeScan-QUIC';port=4433;protocol='UDP'},@{name='AM-FreeScan-API';port=48090;protocol='TCP'})) { if (-not (Get-NetFirewallRule -Name $rule.name -ErrorAction SilentlyContinue)) { New-NetFirewallRule -Name $rule.name -DisplayName $rule.name -Direction Inbound -Action Allow -Protocol $rule.protocol -LocalPort $rule.port -Profile Private -RemoteAddress LocalSubnet | Out-Null } } Write-Output 'Added only application rules for Private/LocalSubnet; database and Redis ports remain loopback-only' } 'InstallAutostart' { $executable = (Get-Command pwsh).Source $taskAction = New-ScheduledTaskAction -Execute $executable -Argument ('-NoProfile -ExecutionPolicy Bypass -File "'+$PSCommandPath+'" -Action Start') -WorkingDirectory $repo $trigger = New-ScheduledTaskTrigger -AtLogOn -User ([Security.Principal.WindowsIdentity]::GetCurrent().Name) $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -MultipleInstances IgnoreNew Register-ScheduledTask -TaskName 'AM-FreeScan-Standalone' -Action $taskAction -Trigger $trigger -Settings $settings -Description 'Start the independent instance after this user logs in and Docker Desktop is ready' -Force | Out-Null Write-Output 'Login startup registered; also enable Docker Desktop startup at login. No unattended pre-login startup is claimed.' } }