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
+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())