feat: portable Windows data layout and launcher package

Separate persistent user data from application code (data/work_tracker.db,
data/uploads, data/storage) with idempotent legacy migration and SQLite
integrity checks. Add offline packaging scripts for a Windows x11 x64
portable ZIP (embeddable Python, Start/Stop/Backup.bat). Fix launcher:
no multiline python -c in BAT and no os.dup2 — uvicorn runs detached with
wvt.log; health wait and busy-port diagnostics included.
This commit is contained in:
Арсентьев Александр
2026-10-20 15:55:04 +03:00
parent a6449a7d70
commit b97d79e13a
28 changed files with 2432 additions and 11 deletions
+39
View File
@@ -0,0 +1,39 @@
@echo off
setlocal EnableExtensions
chcp 65001 >nul
set "APP_HOME=%~dp0"
set "DATA=%APP_HOME%data"
set "BK=%APP_HOME%backups"
set "PY=%APP_HOME%python\python.exe"
set "SCRIPTS=%APP_HOME%scripts"
set "LOGDIR=%APP_HOME%data\logs"
set "BKLOG=%LOGDIR%\startup.log"
if not exist "%PY%" (
echo [ERROR] Local Python not found: %PY%
pause
exit /b 1
)
if not exist "%DATA%" mkdir "%DATA%"
if not exist "%BK%" mkdir "%BK%"
if not exist "%LOGDIR%" mkdir "%LOGDIR%"
echo Creating backup...
echo ==== BACKUP %DATE% %TIME% ====>> "%BKLOG%"
"%PY%" "%SCRIPTS%\backup_data.py" "%DATA%" "%BK%" > "%TEMP%\wvt_backup_out.txt" 2> "%TEMP%\wvt_backup_err.txt"
set "BKERR=%ERRORLEVEL%"
type "%TEMP%\wvt_backup_out.txt" >> "%BKLOG%"
type "%TEMP%\wvt_backup_err.txt" >> "%BKLOG%"
if %BKERR% NEQ 0 (
echo [ERROR] Backup failed. See %BKLOG%
if exist "%TEMP%\wvt_backup_err.txt" type "%TEMP%\wvt_backup_err.txt"
pause
exit /b 2
)
set /p OUTZIP=<"%TEMP%\wvt_backup_out.txt"
echo Backup created: %OUTZIP%
echo BACKUP_OK %OUTZIP%>> "%BKLOG%"
exit /b 0
+45
View File
@@ -0,0 +1,45 @@
# Work Volume Tracker — Portable (Windows 11 x64)
## Быстрый старт
1. Распакуйте архив в любую папку, например `C:\WorkVolumeTracker\`.
2. Запустите `Start.bat`.
3. Браузер откроется автоматически: `http://127.0.0.1:8000`
4. Создайте проект и вносите данные.
5. Для остановки — `Stop.bat`.
## Структура
```
WorkVolumeTracker/
app/ код приложения (можно обновлять)
python/ локальный Python + зависимости
data/ ВАШИ ДАННЫЕ (не удалять, не входит в обновление)
work_tracker.db
uploads/
storage/
backups/ резервные копии
Start.bat запуск + открытие браузера
Stop.bat остановка
Backup.bat ZIP-копия data/
README.md
```
## Обновление
Заменяйте только `app/` и `python/`. Каталоги `data/` и `backups/`
**не удаляйте** и не перезаписывайте.
## Резервная копия
`Backup.bat` создаёт `backups\backup-YYYYMMDD-HHMMSS.zip`
(согласованная копия SQLite, включая WAL/SHM, и файлы storage/uploads).
## Удаление
Удалите папку с программой. Ваши данные — внутри `data/` и `backups/`
(перенесите их заранее, если нужно).
## Офлайн
Интерфейс работает без интернета (Bootstrap локально, CDN не используется).
+67
View File
@@ -0,0 +1,67 @@
@echo off
setlocal EnableExtensions
chcp 65001 >nul
set "APP_HOME=%~dp0"
set "PORT=8000"
set "PY=%APP_HOME%python\python.exe"
set "SCRIPTS=%APP_HOME%scripts"
set "LOGDIR=%APP_HOME%data\logs"
set "STARTLOG=%LOGDIR%\startup.log"
set "APPLOG=%LOGDIR%\wvt.log"
set "CRASHLOG=%LOGDIR%\wvt-crash.log"
set "PIDFILE=%APP_HOME%data\wvt.pid"
if not exist "%LOGDIR%" mkdir "%LOGDIR%"
echo ==== START %DATE% %TIME% ====>> "%STARTLOG%"
echo APP_HOME=%APP_HOME%>> "%STARTLOG%"
echo STEP=begin>> "%STARTLOG%"
if not exist "%PY%" (
echo [ERROR] Local Python not found: %PY%
echo [ERROR] Local Python not found>> "%STARTLOG%"
echo The package is incomplete. Re-extract the ZIP and run Start.bat from the WorkVolumeTracker folder.
if not defined WVT_NO_PAUSE pause
exit /b 1
)
if not exist "%APP_HOME%data" mkdir "%APP_HOME%data"
if not exist "%APP_HOME%backups" mkdir "%APP_HOME%backups"
echo STEP=check_port>> "%STARTLOG%"
"%PY%" "%SCRIPTS%\check_port.py" %PORT% >> "%STARTLOG%" 2>&1
if %ERRORLEVEL% EQU 0 (
echo [ERROR] Port %PORT% is already in use.
echo [ERROR] Port %PORT% busy>> "%STARTLOG%"
echo Stop the other program or run Stop.bat first, then try again.
if not defined WVT_NO_PAUSE pause
exit /b 2
)
echo Starting Work Volume Tracker on http://127.0.0.1:%PORT% ...
echo STEP=start_server>> "%STARTLOG%"
"%PY%" "%SCRIPTS%\start_server.py" %PORT% "%APPLOG%" "%PIDFILE%" >> "%STARTLOG%" 2>&1
echo spawn_exit=%ERRORLEVEL%>> "%STARTLOG%"
echo STEP=wait_health>> "%STARTLOG%"
"%PY%" "%SCRIPTS%\wait_health.py" %PORT% 30 >> "%STARTLOG%" 2>&1
if %ERRORLEVEL% NEQ 0 (
echo [ERROR] The application did not become ready in 30 seconds.
echo [ERROR] health timeout>> "%STARTLOG%"
echo.
echo --- diagnostics ---
"%PY%" "%SCRIPTS%\diagnose_start.py" %PORT% "%APPLOG%" "%PIDFILE%"
"%PY%" "%SCRIPTS%\diagnose_start.py" %PORT% "%APPLOG%" "%PIDFILE%" >> "%STARTLOG%" 2>&1
echo See logs: %APPLOG% and %STARTLOG%
if not defined WVT_NO_PAUSE pause
exit /b 4
)
echo STEP=save_pid>> "%STARTLOG%"
"%PY%" "%SCRIPTS%\save_pid.py" %PORT% "%PIDFILE%" >> "%STARTLOG%" 2>&1
echo STEP=open_browser>> "%STARTLOG%"
if not defined WVT_NO_BROWSER start "" /b "http://127.0.0.1:%PORT%/projects/"
echo Ready. Browser opened http://127.0.0.1:%PORT%/projects/
echo To stop: use Stop.bat
echo READY>> "%STARTLOG%"
exit /b 0
+33
View File
@@ -0,0 +1,33 @@
@echo off
setlocal EnableExtensions
chcp 65001 >nul
set "APP_HOME=%~dp0"
set "PORT=8000"
set "PY=%APP_HOME%python\python.exe"
set "SCRIPTS=%APP_HOME%scripts"
set "PIDFILE=%APP_HOME%data\wvt.pid"
set "LOGDIR=%APP_HOME%data\logs"
set "STOPLOG=%LOGDIR%\startup.log"
echo Stopping Work Volume Tracker...
echo ==== STOP %DATE% %TIME% ====>> "%STOPLOG%"
if exist "%PIDFILE%" (
set /p PID=<"%PIDFILE%"
if defined PID (
if not "%PID%"=="" (
taskkill /PID %PID% /F >nul 2>&1
)
)
)
if exist "%PY%" (
"%PY%" "%SCRIPTS%\stop_port.py" %PORT% >> "%STOPLOG%" 2>&1
) else (
powershell -NoProfile -Command "Get-NetTCPConnection -LocalPort %PORT% -State Listen -ErrorAction SilentlyContinue | ForEach-Object { Stop-Process -Id $_.OwningProcess -Force }" >nul 2>&1
)
if exist "%PIDFILE%" del "%PIDFILE%" >nul 2>&1
echo Stopped.
echo STOPPED>> "%STOPLOG%"
exit /b 0
+199
View File
@@ -0,0 +1,199 @@
"""Build Work Volume Tracker portable ZIP for Windows 11 x64 (clean install)."""
from __future__ import annotations
import os
import re
import shutil
import subprocess
import sys
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
PACK = ROOT / "packaging"
OUT_DIR = ROOT / "_portable_build"
STAGE = OUT_DIR / "stage" / "WorkVolumeTracker"
ZIP_PATH = OUT_DIR / "WorkVolumeTracker-portable-win11-x64.zip"
CDN_PATTERNS = [
(re.compile(r'https://cdn\.jsdelivr\.net/npm/bootstrap@5\.3\.0/dist/css/bootstrap\.min\.css'),
'/static/vendor/bootstrap.min.css'),
(re.compile(r'https://cdn\.jsdelivr\.net/npm/bootstrap@5\.3\.0/dist/js/bootstrap\.bundle\.min\.js'),
'/static/vendor/bootstrap.bundle.min.js'),
]
# Only document templates actually loaded by application code.
ACTIVE_TEMPLATES = {
"ks2/ks2_ru_v2.xlsx",
"ks2/ks2_ru_markers.docx",
"ks2/manifest.json",
"ks3/ks3_ru_markers.docx",
"ks3/manifest.json",
"ks3/ks3_ru_v1.docx",
}
EXCLUDE_DIR_NAMES = {
"__pycache__", ".pytest_cache", ".pytest-tmp", ".git", ".mimocode", ".qwen",
"data", "backups", "storage", "uploads", "node_modules",
}
def rewrite_cdn(text: str) -> tuple[str, int]:
n = 0
for pat, repl in CDN_PATTERNS:
text, k = pat.subn(repl, text)
n += k
return text, n
def copy_app(src: Path, dst: Path) -> int:
rewritten = 0
for path in src.rglob("*"):
rel = path.relative_to(src)
if any(part in EXCLUDE_DIR_NAMES for part in rel.parts):
continue
if path.is_dir():
continue
# never ship user/test junk inside app/
name = path.name
if name.endswith((".db", ".db-wal", ".db-shm")):
continue
if name.startswith("_tmp_"):
continue
target = dst / rel
target.parent.mkdir(parents=True, exist_ok=True)
if path.suffix.lower() in {".html", ".htm", ".css", ".js"}:
text = path.read_text(encoding="utf-8")
new_text, k = rewrite_cdn(text)
target.write_text(new_text, encoding="utf-8", newline="")
rewritten += k
else:
shutil.copy2(path, target)
return rewritten
def copy_templates_docs(src: Path, dst: Path) -> list[str]:
copied = []
for rel in sorted(ACTIVE_TEMPLATES):
s = src / rel
if not s.is_file():
raise SystemExit(f"missing active template: {s}")
t = dst / rel
t.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(s, t)
copied.append(rel)
return copied
def setup_python(stage: Path) -> list[str]:
embed_zip = PACK / "python-embed.zip"
if not embed_zip.is_file():
raise SystemExit("packaging/python-embed.zip missing")
py_dir = stage / "python"
with zipfile.ZipFile(embed_zip) as zf:
zf.extractall(py_dir)
# allow site-packages and the package root (app/ lives next to python/)
pth_files = list(py_dir.glob("python*._pth"))
for pth in pth_files:
content = pth.read_text(encoding="utf-8")
lines = [ln for ln in content.splitlines() if ln.strip()]
wanted = ["python312.zip", ".", "..", "Lib/site-packages"]
# keep comment block harmless; write a known-good path list
pth.write_text("\n".join(wanted) + "\n", encoding="utf-8")
site = py_dir / "Lib" / "site-packages"
site.mkdir(parents=True, exist_ok=True)
wheels = sorted((PACK / "wheels").glob("*.whl"))
if not wheels:
raise SystemExit("packaging/wheels is empty")
installed = []
for whl in wheels:
with zipfile.ZipFile(whl) as zf:
zf.extractall(site)
installed.append(whl.name)
return installed
def write_cwd_runner(stage: Path) -> None:
# tiny launcher helper used by bats: ensure CWD is app home
(stage / "app_home.txt").write_text(
"Portable root. Run Start.bat from this folder.\n", encoding="utf-8"
)
def main() -> int:
if STAGE.exists():
shutil.rmtree(STAGE)
OUT_DIR.mkdir(parents=True, exist_ok=True)
STAGE.mkdir(parents=True)
# 1. application code (templates rewritten offline)
rewritten = copy_app(ROOT / "app", STAGE / "app")
# 2. offline bootstrap vendor
vendor_dst = STAGE / "app" / "static" / "vendor"
vendor_dst.mkdir(parents=True, exist_ok=True)
shutil.copy2(PACK / "vendor" / "bootstrap.min.css", vendor_dst / "bootstrap.min.css")
shutil.copy2(PACK / "vendor" / "bootstrap.bundle.min.js", vendor_dst / "bootstrap.bundle.min.js")
# 3. active document templates only
templates_copied = copy_templates_docs(ROOT / "app" / "templates_docs",
STAGE / "app" / "templates_docs")
# 4. runtime
wheels = setup_python(STAGE)
# 5. scripts + launcher helpers
for name in ("Start.bat", "Stop.bat", "Backup.bat", "README.md"):
src = PACK / name
dst = STAGE / name
# cmd.exe requires CRLF; keep UTF-8 (no BOM is fine for ASCII; BOM for safety)
raw = src.read_bytes()
if raw.startswith(b"\xef\xbb\xbf"):
raw = raw[3:]
text = raw.decode("utf-8")
text = text.replace("\r\n", "\n").replace("\n", "\r\n")
# UTF-8 BOM helps cmd.exe render Cyrillic after chcp 65001
dst.write_bytes(b"\xef\xbb\xbf" + text.encode("utf-8"))
scripts_dst = STAGE / "scripts"
scripts_dst.mkdir(parents=True, exist_ok=True)
for py in sorted((PACK / "scripts").glob("*.py")):
shutil.copy2(py, scripts_dst / py.name)
# 6. empty data + backups placeholders (created empty — no user data)
(STAGE / "data").mkdir(exist_ok=True)
(STAGE / "data" / "uploads").mkdir(exist_ok=True)
(STAGE / "data" / "storage").mkdir(exist_ok=True)
(STAGE / "backups").mkdir(exist_ok=True)
(STAGE / "data" / ".keep").write_text("", encoding="utf-8")
(STAGE / "backups" / ".keep").write_text("", encoding="utf-8")
write_cwd_runner(STAGE)
# sanity: no user data inside stage
leaked = []
for p in STAGE.rglob("*"):
rel = p.relative_to(STAGE).as_posix()
if p.is_file() and (
rel.endswith("work_tracker.db") or "verify_upload" in rel
or rel.startswith("app/uploads/") or "/daily_reports/" in rel
and rel.startswith("data/")
):
leaked.append(rel)
if leaked:
raise SystemExit(f"user data leaked into package: {leaked[:5]}")
# 7. zip
if ZIP_PATH.exists():
ZIP_PATH.unlink()
with zipfile.ZipFile(ZIP_PATH, "w", compression=zipfile.ZIP_DEFLATED) as zf:
for path in sorted(STAGE.rglob("*")):
if path.is_file():
zf.write(path, path.relative_to(STAGE.parent).as_posix())
size = ZIP_PATH.stat().st_size
count = sum(1 for p in STAGE.rglob("*") if p.is_file())
print("ZIP:", ZIP_PATH)
print("SIZE:", size)
print("FILES_IN_STAGE:", count)
print("CDN_REWRITES:", rewritten)
print("WHEELS:", len(wheels))
print("TEMPLATES:", templates_copied)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+58
View File
@@ -0,0 +1,58 @@
"""Create a consistent backup ZIP of the data directory (SQLite + uploads + storage).
Usage: backup_data.py <data_dir> <backups_dir>
Prints the created zip path on stdout.
Exit codes: 0 ok, 1 error, 2 bad args.
"""
import shutil
import sqlite3
import sys
import tempfile
import time
import zipfile
from pathlib import Path
def main() -> int:
if len(sys.argv) != 3:
print("usage: backup_data.py <data_dir> <backups_dir>", file=sys.stderr)
return 2
data = Path(sys.argv[1])
backups = Path(sys.argv[2])
backups.mkdir(parents=True, exist_ok=True)
stamp = time.strftime("%Y%m%d-%H%M%S")
out_zip = backups / f"backup-{stamp}.zip"
stage = Path(tempfile.mkdtemp(prefix="wvt-bk-", dir=str(backups)))
try:
db = data / "work_tracker.db"
if db.is_file():
src = sqlite3.connect(db)
dst = sqlite3.connect(stage / "work_tracker.db")
try:
with dst:
src.backup(dst)
finally:
dst.close()
src.close()
for sub in ("uploads", "storage"):
s = data / sub
if s.is_dir():
shutil.copytree(s, stage / sub, dirs_exist_ok=True)
with zipfile.ZipFile(out_zip, "w", compression=zipfile.ZIP_DEFLATED) as zf:
for path in sorted(stage.rglob("*")):
if path.is_file():
zf.write(path, path.relative_to(stage).as_posix())
print(out_zip)
return 0
except Exception as exc:
print(f"ERROR {type(exc).__name__}: {exc}", file=sys.stderr)
return 1
finally:
shutil.rmtree(stage, ignore_errors=True)
if __name__ == "__main__":
raise SystemExit(main())
+32
View File
@@ -0,0 +1,32 @@
"""Check whether TCP port is already in use on 127.0.0.1.
Exit codes:
0 - port is busy
1 - port is free
2 - bad arguments
"""
import socket
import sys
def main() -> int:
if len(sys.argv) != 2:
print("usage: check_port.py <port>", file=sys.stderr)
return 2
try:
port = int(sys.argv[1])
except ValueError:
print(f"bad port: {sys.argv[1]}", file=sys.stderr)
return 2
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1.0)
try:
result = sock.connect_ex(("127.0.0.1", port))
finally:
sock.close()
# connect_ex == 0 means something accepted the connection -> busy
return 0 if result == 0 else 1
if __name__ == "__main__":
raise SystemExit(main())
+52
View File
@@ -0,0 +1,52 @@
"""Print launch diagnostics when /health did not answer.
Usage: diagnose_start.py <port> <wvt.log> <pidfile>
"""
from __future__ import annotations
import sys
from pathlib import Path
def tail(path: Path, n: int = 30) -> str:
try:
text = path.read_text(encoding="utf-8", errors="replace")
except Exception as exc:
return f"(cannot read {path}: {exc})"
lines = text.splitlines()
return "\n".join(lines[-n:])
def main() -> int:
port = sys.argv[1] if len(sys.argv) > 1 else "?"
log = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("wvt.log")
pidfile = Path(sys.argv[3]) if len(sys.argv) > 3 else Path("wvt.pid")
crash = log.parent / "wvt-crash.log"
print(f"port={port}")
if pidfile.is_file():
pid = pidfile.read_text(encoding="utf-8", errors="replace").strip()
print(f"pidfile={pidfile} pid={pid or '(empty)'}")
if pid.isdigit():
import subprocess
out = subprocess.run(
["tasklist", "/FI", f"PID eq {pid}"],
capture_output=True,
)
print(out.stdout.decode("utf-8", errors="replace").strip() or "(tasklist empty)")
else:
print(f"pidfile={pidfile} (missing)")
print(f"--- tail {log} ---")
print(tail(log))
if crash.is_file():
print(f"--- {crash} ---")
print(tail(crash, 40))
else:
print(f"--- {crash} (missing) ---")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+84
View File
@@ -0,0 +1,84 @@
"""Run Work Volume Tracker uvicorn in this process.
Started from Start.bat via `start /b python run_server.py`.
Stdout/stderr are redirected by replacing Python stream objects only.
Do NOT call os.dup2: under `start /b` the inherited Windows stderr HANDLE
may already be invalid, and dup2 then causes
OSError(9, 'Неверный дескриптор') and 'lost sys.stderr'.
"""
from __future__ import annotations
import os
import sys
import traceback
from pathlib import Path
def _open_log(log_path: Path):
log_path.parent.mkdir(parents=True, exist_ok=True)
return open(log_path, "a", encoding="utf-8", buffering=1)
def main() -> int:
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8000
root = Path(__file__).resolve().parents[1]
log_path = root / "data" / "logs" / "wvt.log"
crash_path = root / "data" / "logs" / "wvt-crash.log"
pid_path = root / "data" / "wvt.pid"
log_f = _open_log(log_path)
# Replace Python-level streams (not OS file descriptors).
sys.stdout = log_f
sys.stderr = log_f
sys.__stdout__ = log_f
sys.__stderr__ = log_f
try:
sys.stdin = open(os.devnull, "r", encoding="utf-8")
except Exception:
pass
print(f"run_server pid={os.getpid()} port={port} root={root}", flush=True)
try:
pid_path.write_text(str(os.getpid()) + "\n", encoding="utf-8")
except Exception:
pass
if str(root) not in sys.path:
sys.path.insert(0, str(root))
os.chdir(str(root))
try:
import uvicorn
uvicorn.run("app.main:app", host="127.0.0.1", port=port, log_level="info")
print("run_server: uvicorn returned", flush=True)
return 0
except Exception:
text = traceback.format_exc()
for writer in (
lambda: crash_path.write_text(text, encoding="utf-8"),
lambda: print(text, flush=True),
lambda: (log_f.write(text), log_f.flush()),
):
try:
writer()
except Exception:
pass
return 1
if __name__ == "__main__":
try:
raise SystemExit(main())
except SystemExit:
raise
except Exception:
root = Path(__file__).resolve().parents[1]
try:
crash = root / "data" / "logs" / "wvt-crash.log"
crash.parent.mkdir(parents=True, exist_ok=True)
crash.write_text(traceback.format_exc(), encoding="utf-8")
except Exception:
pass
raise
+44
View File
@@ -0,0 +1,44 @@
"""Save uvicorn PID for the local package (best effort).
Usage: save_pid.py <port> <pidfile>
"""
import subprocess
import sys
from pathlib import Path
def main() -> int:
if len(sys.argv) != 3:
print("usage: save_pid.py <port> <pidfile>", file=sys.stderr)
return 2
port = sys.argv[1]
pidfile = Path(sys.argv[2])
pid = ""
try:
out = subprocess.check_output(
[
"powershell", "-NoProfile", "-Command",
(
"Get-CimInstance Win32_Process -Filter \"Name='python.exe'\" | "
"Where-Object { $_.CommandLine -match 'uvicorn' -and $_.CommandLine -match 'app.main' "
f"-and $_.CommandLine -match '{port}' }} | "
"Select-Object -First 1 -ExpandProperty ProcessId"
),
],
stderr=subprocess.DEVNULL,
timeout=15,
)
text = out.decode("utf-8", errors="replace").strip()
if text:
pid = text.splitlines()[0].strip()
except Exception as exc:
print(f"WARN {type(exc).__name__}", flush=True)
pidfile.parent.mkdir(parents=True, exist_ok=True)
pidfile.write_text(pid + "\n", encoding="utf-8")
print(pid or "PID_NOT_FOUND")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+70
View File
@@ -0,0 +1,70 @@
"""Spawn run_server.py detached with valid file handles (Windows-safe).
The child gets stdout/stderr = log file and stdin = NUL. This avoids:
- OSError(9)/'lost sys.stderr' from broken inherited console handles
- parent hangs when the child keeps an inherited stdout pipe open
Usage: start_server.py <port> [logfile] [pidfile]
"""
from __future__ import annotations
import subprocess
import sys
import traceback
from pathlib import Path
def main() -> int:
if len(sys.argv) not in (2, 3, 4):
print("usage: start_server.py <port> [logfile] [pidfile]", file=sys.stderr)
return 2
port = sys.argv[1]
root = Path(__file__).resolve().parents[1]
log_path = Path(sys.argv[2]) if len(sys.argv) >= 3 else root / "data" / "logs" / "wvt.log"
pid_path = Path(sys.argv[3]) if len(sys.argv) >= 4 else root / "data" / "wvt.pid"
log_path.parent.mkdir(parents=True, exist_ok=True)
python_exe = sys.executable
child = Path(__file__).resolve().parent / "run_server.py"
cmd = [python_exe, str(child), port, str(log_path), str(pid_path)]
flags = 0
if hasattr(subprocess, "DETACHED_PROCESS"):
flags |= subprocess.DETACHED_PROCESS
flags |= subprocess.CREATE_NEW_PROCESS_GROUP
# Two separate unbuffered handles: child writes server output to wvt.log.
out_f = open(log_path, "ab", buffering=0)
err_f = open(log_path, "ab", buffering=0)
proc = subprocess.Popen(
cmd,
cwd=str(root),
stdin=subprocess.DEVNULL,
stdout=out_f,
stderr=err_f,
creationflags=flags,
close_fds=True,
)
out_f.close()
err_f.close()
pid_path.parent.mkdir(parents=True, exist_ok=True)
pid_path.write_text(str(proc.pid) + "\n", encoding="utf-8")
print(f"spawned pid={proc.pid} port={port} log={log_path}")
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except SystemExit:
raise
except Exception:
root = Path(__file__).resolve().parents[1]
try:
crash = root / "data" / "logs" / "wvt-crash.log"
crash.parent.mkdir(parents=True, exist_ok=True)
crash.write_text(traceback.format_exc(), encoding="utf-8")
except Exception:
pass
raise
+40
View File
@@ -0,0 +1,40 @@
"""Stop any python/uvicorn process listening on 127.0.0.1:<port>.
Usage: stop_port.py <port>
"""
import subprocess
import sys
def main() -> int:
if len(sys.argv) != 2:
print("usage: stop_port.py <port>", file=sys.stderr)
return 2
port = sys.argv[1]
stopped = []
try:
out = subprocess.check_output(
[
"powershell", "-NoProfile", "-Command",
(
f"$c=Get-NetTCPConnection -LocalPort {port} -State Listen -ErrorAction SilentlyContinue; "
f"if($c){{ $c | ForEach-Object {{ "
f"$p=Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue; "
f"if($p){{ Stop-Process -Id $_.OwningProcess -Force; "
f"Write-Output $_.OwningProcess }} }} }}"
),
],
stderr=subprocess.DEVNULL,
timeout=20,
)
text = out.decode("utf-8", errors="replace").strip()
if text:
stopped = [line.strip() for line in text.splitlines() if line.strip()]
except Exception as exc:
print(f"WARN {type(exc).__name__}: {exc}", file=sys.stderr)
print("stopped=" + ",".join(stopped) if stopped else "none")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+64
View File
@@ -0,0 +1,64 @@
"""Wait until http://127.0.0.1:<port>/health responds or timeout.
Usage: wait_health.py <port> [timeout_seconds]
Exit: 0 healthy, 1 timeout, 2 bad args.
"""
from __future__ import annotations
import socket
import sys
import time
def healthy(port: int, timeout: float = 1.0) -> bool:
try:
with socket.create_connection(("127.0.0.1", port), timeout=timeout) as sock:
req = f"GET /health HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n"
sock.sendall(req.encode("ascii"))
sock.settimeout(timeout)
data = b""
while True:
try:
chunk = sock.recv(256)
except socket.timeout:
break
if not chunk:
break
data += chunk
if b"\r\n\r\n" in data and len(data) > 32:
break
return b"200" in data.split(b"\r\n", 1)[0]
except OSError:
return False
def main() -> int:
if len(sys.argv) not in (2, 3):
print("usage: wait_health.py <port> [timeout]", file=sys.stderr)
return 2
try:
port = int(sys.argv[1])
except ValueError:
print(f"bad port: {sys.argv[1]}", file=sys.stderr)
return 2
timeout = 30.0
if len(sys.argv) == 3:
try:
timeout = float(sys.argv[2])
except ValueError:
print(f"bad timeout: {sys.argv[2]}", file=sys.stderr)
return 2
deadline = time.time() + timeout
while time.time() < deadline:
if healthy(port):
print("OK")
return 0
time.sleep(0.35)
print("TIMEOUT")
return 1
if __name__ == "__main__":
raise SystemExit(main())
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long