Files
Crypto_Scam/server_control.ps1
T
listik 85425483c0
Offline regression tests / windows (3.11) (push) Canceled after 0s
Offline regression tests / windows (3.12) (push) Canceled after 0s
Offline regression tests / windows (3.13) (push) Canceled after 0s
1
2026-10-23 20:49:12 +03:00

93 lines
5.4 KiB
PowerShell

# Запуск и остановка сервера симулятора (вызывается из ЗАПУСТИТЬ_СЕРВЕР.bat и ОСТАНОВИТЬ_СЕРВЕР.bat).
# start — сервер в фоне без окон (страница + движок с автоперезапуском), затем открывается страница
# stop — останавливает страницу, движок и его цикл перезапуска
# Если в Планировщике есть задача «RealtimePaperSimulator watchdog» (поднимает сервер раз в 5 минут),
# stop её выключает, а start включает обратно — иначе она запустила бы сервер снова.
param([Parameter(Position = 0)] [string] $Action = "start")
$ErrorActionPreference = "Continue"
$Dir = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $Dir
$Url = "http://127.0.0.1:8765"
$Task = "RealtimePaperSimulator watchdog"
$Parts = 'web_sim_service\.bat|web_sim\.py|web_proxy\.py'
function Server-Processes {
Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -and $_.CommandLine -match $Parts -and
$_.ProcessId -ne $PID -and $_.Name -notmatch 'powershell' }
}
function Answers {
try { Invoke-RestMethod "$Url/api/state" -TimeoutSec 3 | Out-Null; return $true } catch { return $false }
}
function Set-Watchdog([bool] $On) {
$t = Get-ScheduledTask -TaskName $Task -ErrorAction SilentlyContinue
if (-not $t) { return }
if ($On) { Enable-ScheduledTask -TaskName $Task | Out-Null; Write-Host "Сторож в Планировщике включён (поднимает сервер, если тот упадёт)." }
else { Disable-ScheduledTask -TaskName $Task | Out-Null; Write-Host "Сторож в Планировщике выключен, чтобы не запустил сервер снова." }
}
if ($Action -eq "stop") {
if (-not (Server-Processes)) { Write-Host "Сервер не запущен." -ForegroundColor Yellow; Set-Watchdog $false; exit 0 }
# реальная торговля: закрытие, которое идёт прямо сейчас, лучше не прерывать
try {
$real = Invoke-RestMethod "$Url/api/basis?ex=cross_real" -TimeoutSec 5
$closing = @($real.positions | Where-Object { $_.real -and $_.closing })
$open = @($real.positions | Where-Object { $_.real })
if ($closing.Count) {
Write-Host ("Сейчас закрывается реальная сделка: " + (($closing | ForEach-Object { $_.base }) -join ", ")) -ForegroundColor Red
$ans = Read-Host "Всё равно остановить? (y — да, иначе — нет)"
if ($ans -ne "y") { Write-Host "Остановка отменена."; exit 1 }
} elseif ($open.Count) {
Write-Host ("Открытые реальные сделки: " + (($open | ForEach-Object { $_.base }) -join ", ") +
" — пока сервер остановлен, за ними никто не следит; после запуска программа продолжит их вести.") -ForegroundColor Yellow
}
} catch {}
Set-Watchdog $false
# сначала цикл перезапуска (иначе он поднимет движок), потом движок и страница
foreach ($round in 1..3) {
$procs = @(Server-Processes)
if (-not $procs.Count) { break }
$procs | Sort-Object { if ($_.CommandLine -match 'web_sim_service') { 0 } else { 1 } } |
ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
Start-Sleep -Seconds 2
}
if (Server-Processes) { Write-Host "Не все части сервера остановились — запустите файл ещё раз." -ForegroundColor Red; exit 1 }
Write-Host "Сервер остановлен." -ForegroundColor Green
exit 0
}
# --- start ---------------------------------------------------------------------------------------------------
if ((Server-Processes) -and (Answers)) {
Write-Host "Сервер уже работает: $Url" -ForegroundColor Green
Set-Watchdog $true
Start-Process $Url
exit 0
}
$VenvPython = Join-Path $Dir ".venv\Scripts\python.exe"
$haveVenv = $false
if (Test-Path -LiteralPath $VenvPython) {
try {
& $VenvPython -B -c "import sys, websocket, numpy; sys.exit(0 if sys.version_info >= (3, 11) else 1)" 2>$null
$haveVenv = $LASTEXITCODE -eq 0
} catch { $haveVenv = $false }
}
if (-not $haveVenv) {
Write-Host "Окружение отсутствует или повреждено — запускаю восстановление..."
& powershell -NoProfile -ExecutionPolicy Bypass -File (Join-Path $Dir "setup.ps1") /install-only
if ($LASTEXITCODE -ne 0) { exit 1 }
}
Write-Host "Запускаю сервер в фоне (без окон)..."
Start-Process -FilePath "wscript.exe" -ArgumentList "`"$(Join-Path $Dir 'web_sim_autostart.vbs')`"" -WorkingDirectory $Dir -WindowStyle Hidden
Set-Watchdog $true
foreach ($i in 1..45) {
if (Answers) {
Write-Host "Сервер работает: $Url" -ForegroundColor Green
Start-Process $Url
exit 0
}
Start-Sleep -Seconds 1
}
Write-Host "Сервер не ответил за 45 секунд. Журнал движка: web_sim_data\backend.log" -ForegroundColor Red
exit 1