aisop/tools/Switch-Djev.ps1

146 lines
7.1 KiB
PowerShell

[CmdletBinding()]
param(
[Parameter(Position=0)][ValidateSet('lite','nano','status','config')][string]$Model = 'status',
[Parameter(Position=1)][ValidateSet('lite','nano')][string]$Tier,
[ValidateRange(1,65535)][int]$Port = 8766,
[string]$LiteRoot = 'E:\D3Lite',
[string]$NanoRoot = 'E:\D3Nano'
)
$ErrorActionPreference = 'Stop'
$repo = Split-Path -Parent $PSScriptRoot
$roots = @{ 'd3-lite' = [IO.Path]::GetFullPath($LiteRoot); 'd3-nano' = [IO.Path]::GetFullPath($NanoRoot) }
$endpoint = "http://127.0.0.1:$Port"
$logs = Join-Path (Split-Path -Parent $repo) 'scratch\logs'
$script = Join-Path $PSScriptRoot 'start_d3_lite_local.py'
$python = Join-Path $LiteRoot '.venv\Scripts\python.exe'
$configPath = Join-Path $LiteRoot 'djev.json'
function Get-ConfiguredTier {
if (!(Test-Path -LiteralPath $configPath)) { return 'lite' }
$config = Get-Content -LiteralPath $configPath -Raw -Encoding UTF8 | ConvertFrom-Json
if ($config.tier -notin @('lite','nano')) { throw 'Invalid djev tier in configuration.' }
return $config.tier
}
function Save-Selection([string]$SelectedTier) {
$temp = "$configPath.tmp"
$config = @{ tier = $SelectedTier; nano_root = $roots['d3-nano'] } | ConvertTo-Json
[IO.File]::WriteAllText($temp, $config, (New-Object Text.UTF8Encoding($false)))
if (Test-Path -LiteralPath $configPath) { [IO.File]::Replace($temp, $configPath, "$configPath.bak") }
else { [IO.File]::Move($temp, $configPath) }
}
function Get-Health {
try { return Invoke-RestMethod "$endpoint/health" -TimeoutSec 2 } catch { return $null }
}
function Show-Health($Health) {
$configured = Get-ConfiguredTier
if ($null -eq $Health) { Write-Host "djev | Not running Configured: $configured Endpoint: $endpoint"; return }
$tier = switch ($Health.model) { 'd3-lite' { 'lite' }; 'd3-nano' { 'nano' }; default { 'unknown' } }
Write-Host "djev | Tier: $tier Configured: $configured Status: $($Health.status) Endpoint: $endpoint/v1/systemone"
}
# Identify only known local D3 launchers, including the venv Python child on Windows.
function Get-ManagedProcesses {
@(Get-CimInstance Win32_Process -Filter "name='python.exe'" | Where-Object {
$line = $_.CommandLine
$knownRoot = $false
foreach ($root in $roots.Values) {
if ($line -match ('--root\s+"?' + [regex]::Escape($root) + '"?(?=\s|$)')) { $knownRoot = $true }
}
$knownRoot -and $line -match '(?i)[\\/]start_d3_lite_local\.py"?\s' -and
$line -match ('--port\s+' + $Port + '(?=\s|$)')
})
}
function Stop-Managed {
$managed = @(Get-ManagedProcesses)
$listeners = @(Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue)
foreach ($listener in $listeners) {
if ($listener.OwningProcess -notin $managed.ProcessId) { throw "Port $Port belongs to an unmanaged process; nothing was stopped." }
}
# Recheck creation time before stopping, to guard against PID reuse.
foreach ($item in $managed) {
$live = Get-CimInstance Win32_Process -Filter "ProcessId=$($item.ProcessId)"
if ($live -and $live.CreationDate -eq $item.CreationDate -and $live.CommandLine -eq $item.CommandLine) {
Stop-Process -Id $item.ProcessId -Force -ErrorAction SilentlyContinue
}
}
$deadline = [DateTime]::UtcNow.AddSeconds(15)
while (@(Get-ManagedProcesses).Count -gt 0) {
if ([DateTime]::UtcNow -gt $deadline) { throw 'Previous djev process did not stop.' }
Start-Sleep -Milliseconds 250
}
}
function Start-Model([string]$Name) {
$root = $roots[$Name]
$tierName = $Name.Substring(3)
$outLog = Join-Path $logs "djev-$tierName-switch.stdout.log"
$errLog = Join-Path $logs "djev-$tierName-switch.stderr.log"
$arguments = @('-u', ('"' + $script + '"'), '--root', ('"' + $root + '"'), '--port', $Port, '--warmup-image', '--ignore-selection')
$child = Start-Process -FilePath $python -ArgumentList $arguments -WorkingDirectory $repo -WindowStyle Hidden -PassThru -RedirectStandardOutput $outLog -RedirectStandardError $errLog
$marker = @{ Pid = $child.Id; StartedUtc = $child.StartTime.ToUniversalTime().ToString('o') } | ConvertTo-Json -Compress
# Desktop startup checks LiteRoot's marker, even when Nano serves the shared endpoint.
[IO.File]::WriteAllText((Join-Path $LiteRoot "sophelper-d3-$Port.json"), $marker)
[IO.File]::WriteAllText((Join-Path $root "sophelper-d3-$Port.json"), $marker)
Set-Content -LiteralPath (Join-Path $root 'server.pid') -Value $child.Id -Encoding ascii
Write-Host "Loading djev ($($Name.Substring(3))) ..."
$deadline = [DateTime]::UtcNow.AddSeconds(180)
do {
$health = Get-Health
if ($health -and $health.status -eq 'ready' -and $health.model -eq $Name -and 'image' -in $health.modalities) {
return
}
if ($child.HasExited) { throw "djev exited. Log: $errLog" }
if ([DateTime]::UtcNow -gt $deadline) { throw "djev startup timed out. Log: $errLog" }
Start-Sleep -Milliseconds 500
} while ($true)
}
$lock = $null
try {
if ($Model -eq 'status') { Show-Health (Get-Health); exit 0 }
if ($Model -eq 'config' -and !$Tier) { Write-Host "djev | Configured: $(Get-ConfiguredTier) Config: $configPath"; exit 0 }
if ($Model -ne 'config' -and $Tier) { throw 'The second argument is only used with config.' }
if ($Model -eq 'config') { $Model = $Tier; $configOnly = $true } else { $configOnly = $false }
$target = "d3-$Model"
foreach ($path in @($python, $script, (Join-Path $roots[$target] 'model\MODEL_MANIFEST.json'), (Join-Path $roots[$target] 'local-model-manifest.json'))) {
if (!(Test-Path -LiteralPath $path -PathType Leaf)) { throw "Required file missing: $path" }
}
$package = Get-Content -LiteralPath (Join-Path $roots[$target] 'model\MODEL_MANIFEST.json') -Raw -Encoding UTF8 | ConvertFrom-Json
if ($package.model_name -ne $target) { throw 'djev package does not match the requested tier.' }
New-Item -ItemType Directory -Force -Path $logs | Out-Null
# Use the desktop startup lock too; never run two loads on the same endpoint.
$lock = [IO.File]::Open((Join-Path $LiteRoot "sophelper-d3-$Port.lock"), 'OpenOrCreate', 'ReadWrite', 'None')
if ($configOnly) {
Save-Selection $Model
Write-Host "djev | Configured: $Model Config: $configPath"
exit 0
}
$previous = Get-Health
if ($previous -and $previous.model -eq $target -and $previous.status -eq 'ready' -and 'image' -in $previous.modalities) {
Save-Selection $Model
Show-Health $previous
exit 0
}
if ($previous -and $previous.model -notin $roots.Keys) { throw 'Endpoint is not a known djev service.' }
Stop-Managed
try { Start-Model $target; Save-Selection $Model; Show-Health (Get-Health) }
catch {
$failure = $_
Stop-Managed
if ($previous -and $previous.model -in $roots.Keys) {
Write-Warning 'Switch failed; restoring previous djev service.'
Start-Model $previous.model
}
throw $failure
}
} catch {
Write-Error $_ -ErrorAction Continue
exit 1
} finally {
if ($null -ne $lock) { $lock.Dispose() }
}