start.ps1 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. # ==============================================================================
  2. # lf_mri_platform -- Start services and GUI
  3. # Usage:
  4. # .\start.ps1 -- plug mode: Docker + GUI
  5. # .\start.ps1 -Mode real -- real mode: Docker + spectrometer + GUI
  6. # .\start.ps1 -GuiOnly -- GUI only (services already running)
  7. # .\start.ps1 -ServicesOnly -- Docker + spectrometer, no GUI
  8. # .\start.ps1 -SkipInstall -- skip venv check
  9. # .\start.ps1 -SkipSpectrometer -- skip native spectrometer even in real mode
  10. # ==============================================================================
  11. param(
  12. [ValidateSet("plug", "real")]
  13. [string]$Mode = "plug",
  14. [switch]$GuiOnly,
  15. [switch]$ServicesOnly,
  16. [switch]$SkipInstall,
  17. [switch]$SkipSpectrometer
  18. )
  19. $ErrorActionPreference = "Stop"
  20. $Root = $PSScriptRoot
  21. $GuiDir = Join-Path $Root "apps\gui"
  22. $VenvPython = Join-Path $GuiDir ".venv\Scripts\python.exe"
  23. $AppScript = Join-Path $Root "apps\gui\app.py"
  24. $EnvFile = Join-Path $Root ".env"
  25. $EnvExample = Join-Path $Root ".env.example"
  26. $LogFile = Join-Path $Root "start_log.txt"
  27. # Write all output to log file so errors are readable even if window closes
  28. Start-Transcript -Path $LogFile -Append | Out-Null
  29. Write-Host "=== start.ps1 $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') Mode=$Mode ==="
  30. function Write-Step($msg) { Write-Host "`n==> $msg" -ForegroundColor Cyan }
  31. function Write-OK($msg) { Write-Host " [OK] $msg" -ForegroundColor Green }
  32. function Write-Warn($msg) { Write-Host " [!!] $msg" -ForegroundColor Yellow }
  33. function Write-Fail($msg) {
  34. Write-Host "`n[FAIL] $msg" -ForegroundColor Red
  35. Write-Host " Log: $LogFile" -ForegroundColor DarkGray
  36. try { Stop-Transcript | Out-Null } catch {}
  37. Write-Host "`n Press Enter to close..." -ForegroundColor DarkGray
  38. $null = Read-Host
  39. exit 1
  40. }
  41. # Keep window open on any unhandled error
  42. trap {
  43. Write-Host "`n[ERROR] $_" -ForegroundColor Red
  44. Write-Host " Log: $LogFile" -ForegroundColor DarkGray
  45. try { Stop-Transcript | Out-Null } catch {}
  46. Write-Host "`n Press Enter to close..." -ForegroundColor DarkGray
  47. $null = Read-Host
  48. exit 1
  49. }
  50. function Get-EnvPort($key, $default) {
  51. if (Test-Path $EnvFile) {
  52. $line = Get-Content $EnvFile | Select-String "^$key=(\d+)"
  53. if ($line) { return $line.Matches[0].Groups[1].Value }
  54. }
  55. return $default
  56. }
  57. # -- 1. Check / install GUI venv -----------------------------------------------
  58. if (-not $GuiOnly -and -not $SkipInstall) {
  59. Write-Step "Checking GUI environment"
  60. $needsInstall = $false
  61. if (-not (Test-Path $VenvPython)) {
  62. Write-Warn "Virtual environment not found -- running install"
  63. $needsInstall = $true
  64. } else {
  65. & $VenvPython -c "import PySide6" 2>$null
  66. if ($LASTEXITCODE -ne 0) {
  67. Write-Warn "GUI packages missing -- running install"
  68. $needsInstall = $true
  69. } else {
  70. Write-OK "Virtual environment ready"
  71. }
  72. }
  73. if ($needsInstall) {
  74. $installScript = Join-Path $Root "install.ps1"
  75. if (-not (Test-Path $installScript)) { Write-Fail "install.ps1 not found" }
  76. & powershell.exe -ExecutionPolicy Bypass -File $installScript
  77. if ($LASTEXITCODE -ne 0) { Write-Fail "install.ps1 failed" }
  78. }
  79. }
  80. # -- 2. Docker -----------------------------------------------------------------
  81. if (-not $GuiOnly) {
  82. Write-Step "Checking Docker"
  83. $dockerOk = $false
  84. try { & docker info *>$null; $dockerOk = $true } catch {}
  85. if (-not $dockerOk) {
  86. Write-Warn "Docker not responding -- starting Docker Desktop..."
  87. $dockerExe = "C:\Program Files\Docker\Docker\Docker Desktop.exe"
  88. if (Test-Path $dockerExe) { Start-Process $dockerExe }
  89. else { Write-Fail "Docker Desktop not found -- install from https://docker.com" }
  90. $waited = 0
  91. while ($waited -lt 60) {
  92. Start-Sleep 5
  93. $waited += 5
  94. try { & docker info *>$null; $dockerOk = $true; break } catch {}
  95. Write-Host " ... $waited/60 s" -ForegroundColor DarkGray
  96. }
  97. if (-not $dockerOk) { Write-Fail "Docker did not start in time" }
  98. }
  99. Write-OK "Docker is running"
  100. # -- 3. .env ---------------------------------------------------------------
  101. if (-not (Test-Path $EnvFile)) {
  102. if (Test-Path $EnvExample) {
  103. Copy-Item $EnvExample $EnvFile
  104. Write-Warn ".env created from .env.example"
  105. } else {
  106. Write-Warn ".env missing -- using Compose defaults"
  107. }
  108. }
  109. # -- 4. Start containers ---------------------------------------------------
  110. Write-Step "Starting Docker services (mode: $Mode)"
  111. $env:ORCHESTRATOR_MODE = $Mode
  112. $envArgs = if (Test-Path $EnvFile) { @("--env-file", $EnvFile) } else { @() }
  113. & docker compose @envArgs up -d
  114. if ($LASTEXITCODE -ne 0) { Write-Fail "docker compose up failed" }
  115. Write-OK "Containers started"
  116. # -- 5. Native spectrometer ------------------------------------------------
  117. if (-not $SkipSpectrometer) {
  118. Write-Step "Starting native spectrometer"
  119. $SpecDir = Join-Path $Root "services\spectrometer"
  120. $SpecVenv = Join-Path $SpecDir "mvenv\Scripts\python.exe"
  121. $PicoExe = Join-Path $SpecDir "bin\pico-tcp.exe"
  122. $oldPico = Get-Process -Name "pico-tcp" -ErrorAction SilentlyContinue
  123. if ($oldPico) { $oldPico | Stop-Process -Force; Write-Warn "Killed stale pico-tcp.exe" }
  124. if (-not (Test-Path $SpecVenv)) {
  125. Write-Warn "Spectrometer venv not found -- creating..."
  126. Push-Location $SpecDir
  127. & python -m venv mvenv
  128. if ($LASTEXITCODE -ne 0) { Write-Fail "Failed to create spectrometer venv" }
  129. & $SpecVenv -m pip install -q --upgrade pip
  130. & $SpecVenv -m pip install -q -r requirements.txt
  131. if ($LASTEXITCODE -ne 0) { Write-Fail "Failed to install spectrometer packages" }
  132. Pop-Location
  133. Write-OK "Spectrometer venv created"
  134. } else {
  135. Write-OK "Spectrometer venv found"
  136. }
  137. Push-Location $SpecDir
  138. & $SpecVenv manage.py migrate --noinput 2>&1 | Out-Null
  139. Pop-Location
  140. Write-OK "Migrations applied"
  141. if (Test-Path $PicoExe) {
  142. Start-Process $PicoExe -WindowStyle Normal
  143. Write-OK "pico-tcp.exe started (visible window)"
  144. } else {
  145. Write-Warn "bin\pico-tcp.exe not found -- ADC proxy not started"
  146. }
  147. # Check if runserver is already up by probing port 8000
  148. $specPort = Get-EnvPort "SPECTROMETER_PORT" "8000"
  149. $alreadyUp = $false
  150. try {
  151. $r = Invoke-WebRequest "http://localhost:$specPort/api/" `
  152. -UseBasicParsing -TimeoutSec 2 -ErrorAction Stop
  153. $alreadyUp = ($r.StatusCode -lt 400)
  154. } catch {}
  155. if ($alreadyUp) {
  156. Write-OK "Spectrometer already responding on port $specPort"
  157. } else {
  158. Start-Process $SpecVenv `
  159. -ArgumentList "manage.py runserver 0.0.0.0:$specPort" `
  160. -WorkingDirectory $SpecDir `
  161. -WindowStyle Normal
  162. Write-OK "Spectrometer started in new window (port $specPort)"
  163. }
  164. }
  165. # -- 6. Health check -------------------------------------------------------
  166. Write-Step "Waiting for services to become healthy"
  167. $checkSpec = -not $SkipSpectrometer
  168. $services = @(
  169. @{ Name = "Orchestrator"; Url = "http://localhost:$(Get-EnvPort 'ORCHESTRATOR_PORT' '1717')/health"; Required = $true },
  170. @{ Name = "Seq-Interp"; Url = "http://localhost:$(Get-EnvPort 'SEQ_INTERP_PORT' '7475')/health"; Required = $true },
  171. @{ Name = "Reconstructor"; Url = "http://localhost:$(Get-EnvPort 'RECONSTRUCTOR_PORT' '8081')/health"; Required = $true },
  172. @{ Name = "Spectroscopy"; Url = "http://localhost:$(Get-EnvPort 'SPECTROSCOPY_PORT' '8002')/health"; Required = $true },
  173. @{ Name = "Spectrometer"; Url = "http://localhost:$(Get-EnvPort 'SPECTROMETER_PORT' '8000')/api/"; Required = $checkSpec }
  174. )
  175. $maxWait = 120; $interval = 3; $elapsed = 0
  176. while ($elapsed -lt $maxWait) {
  177. $pending = @()
  178. foreach ($svc in $services) {
  179. if (-not $svc.Required) { continue }
  180. $up = $false
  181. try {
  182. $r = Invoke-WebRequest $svc.Url -UseBasicParsing -TimeoutSec 2 -ErrorAction Stop
  183. $up = ($r.StatusCode -lt 400)
  184. } catch {}
  185. if (-not $up) { $pending += $svc.Name }
  186. }
  187. if ($pending.Count -eq 0) { Write-OK "All required services healthy"; break }
  188. Write-Host (" ... {0}/{1} s waiting: {2}" -f $elapsed, $maxWait, ($pending -join ", ")) -ForegroundColor DarkGray
  189. Start-Sleep $interval
  190. $elapsed += $interval
  191. }
  192. if ($elapsed -ge $maxWait) { Write-Warn "Some services did not respond in time -- continuing anyway" }
  193. Write-Host ""
  194. foreach ($svc in $services) {
  195. $ok = $false
  196. try {
  197. $r = Invoke-WebRequest $svc.Url -UseBasicParsing -TimeoutSec 2 -ErrorAction Stop
  198. $ok = ($r.StatusCode -lt 400)
  199. } catch {}
  200. $icon = if ($ok) { "[OK]" } else { "[--]" }
  201. $color = if ($ok) { "Green" } elseif ($svc.Required) { "Yellow" } else { "DarkGray" }
  202. if (-not $svc.Required -and -not $ok) {
  203. $suffix = " (native -- start manually)"
  204. } else {
  205. $suffix = ""
  206. }
  207. Write-Host (" {0,-6} {1,-16} {2}{3}" -f $icon, $svc.Name, $svc.Url, $suffix) -ForegroundColor $color
  208. }
  209. # -- 7. Write server_config.json -------------------------------------------
  210. Write-Step "Configuring GUI"
  211. $orchPort = Get-EnvPort "ORCHESTRATOR_PORT" "1717"
  212. $seqPort = Get-EnvPort "SEQ_INTERP_PORT" "7475"
  213. $spectPort = Get-EnvPort "SPECTROSCOPY_PORT" "8002"
  214. $cfgPath = Join-Path $Root "apps\gui\cfg\server_config.json"
  215. $cfgObj = @{
  216. srv_name = "srv_interp"
  217. log_dir = "log"
  218. upload_dir = "data/input"
  219. output_dir = "data/output"
  220. server_host = "0.0.0.0"
  221. server_port = [int]$seqPort
  222. orchestrator_url = "http://localhost:$orchPort"
  223. seq_interp_url = "http://localhost:$seqPort"
  224. spectroscopy_url = "http://localhost:$spectPort"
  225. mode = $Mode
  226. }
  227. $cfgObj | ConvertTo-Json -Depth 3 | Set-Content $cfgPath -Encoding utf8
  228. Write-OK "server_config.json updated (mode=$Mode orch=:$orchPort seq=:$seqPort spectro=:$spectPort)"
  229. }
  230. # -- 8. Launch GUI -------------------------------------------------------------
  231. if (-not $ServicesOnly) {
  232. Write-Step "Launching GUI"
  233. if (-not (Test-Path $VenvPython)) {
  234. Write-Warn "Venv not found -- falling back to system Python"
  235. $VenvPython = "python"
  236. }
  237. if (-not (Test-Path $AppScript)) { Write-Fail "GUI entry point not found: $AppScript" }
  238. Start-Process $VenvPython -ArgumentList "`"$AppScript`"" -WorkingDirectory $Root -WindowStyle Normal
  239. Write-OK "GUI launched"
  240. }
  241. # -- Summary -------------------------------------------------------------------
  242. Write-Host ""
  243. Write-Host "============================================================" -ForegroundColor Green
  244. Write-Host (" LF-MRI platform is running [{0} mode]" -f $Mode.ToUpper()) -ForegroundColor Green
  245. Write-Host "============================================================" -ForegroundColor Green
  246. Write-Host ""
  247. if (-not $SkipSpectrometer) {
  248. Write-Host " Stop spectrometer: close the spectrometer terminal window"
  249. Write-Host " Stop pico-tcp: services\spectrometer\autokill.bat"
  250. }
  251. Write-Host " Stop all: .\stop.ps1"
  252. Write-Host " Update code: .\update.bat"
  253. Write-Host ""
  254. Write-Host " Log saved to: $LogFile" -ForegroundColor DarkGray
  255. try { Stop-Transcript | Out-Null } catch {}
  256. Write-Host " Press Enter to close this window..." -ForegroundColor DarkGray
  257. $null = Read-Host