-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathweb_start.py
More file actions
79 lines (72 loc) · 2.63 KB
/
Copy pathweb_start.py
File metadata and controls
79 lines (72 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# InfraForge Web UI — Quick Start
# Run this file to launch the web-based interface
import logging
import os
import signal
import sys
import uvicorn
from src.config import WEB_HOST, WEB_PORT, setup_logging
def kill_existing(port: int) -> None:
"""Kill any process currently listening on the given port."""
if sys.platform == "win32":
import subprocess
# netstat to find PIDs bound to the port
result = subprocess.run(
["netstat", "-ano", "-p", "TCP"],
capture_output=True, text=True,
)
pids: set[int] = set()
for line in result.stdout.splitlines():
if f":{port}" in line and "LISTENING" in line:
parts = line.split()
try:
pid = int(parts[-1])
if pid != 0:
pids.add(pid)
except (ValueError, IndexError):
continue
my_pid = os.getpid()
for pid in pids:
if pid == my_pid:
continue
try:
os.kill(pid, signal.SIGTERM)
_startup_log.info("Killed existing process on port %d (PID %d)", port, pid)
except OSError:
pass
else:
import subprocess
result = subprocess.run(
["lsof", "-ti", f":{port}"],
capture_output=True, text=True,
)
my_pid = os.getpid()
for line in result.stdout.strip().splitlines():
try:
pid = int(line)
if pid != my_pid:
os.kill(pid, signal.SIGTERM)
_startup_log.info("Killed existing process on port %d (PID %d)", port, pid)
except (ValueError, OSError):
continue
# Ensure UTF-8 output (avoids cp1252 crashes with emoji on Windows)
if sys.platform == "win32":
if not os.environ.get("PYTHONIOENCODING"):
os.environ["PYTHONIOENCODING"] = "utf-8"
# Reconfigure stdout/stderr for this process (env var only affects subprocesses)
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
_startup_log = logging.getLogger("infraforge.startup")
if __name__ == "__main__":
# Encoding must be set before logging is configured
setup_logging()
kill_existing(WEB_PORT)
_startup_log.info("InfraForge Web UI starting on http://localhost:%d", WEB_PORT)
_startup_log.info("Open your browser to http://localhost:%d", WEB_PORT)
uvicorn.run(
"src.web:app",
host=WEB_HOST,
port=WEB_PORT,
reload=False,
log_level="info",
)