ii-assistent/hunter/serve.py

82 lines
2.3 KiB
Python

"""Supervise web and scheduler in a single-container MVP deployment."""
import os
import secrets
import signal
import subprocess
import sys
import time
from pathlib import Path
def main():
database = Path(os.getenv("DATABASE_PATH", "/data/hunter.sqlite3"))
database.parent.mkdir(parents=True, exist_ok=True)
if not os.getenv("SECRET_KEY"):
path = database.parent / ".session-secret"
try:
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
except FileExistsError:
pass
else:
with os.fdopen(fd, "w") as output:
output.write(secrets.token_hex(32))
os.environ["SECRET_KEY"] = path.read_text()
from hunter import create_app
create_app()
port = int(os.getenv("PORT", "3000"))
if not 1 <= port <= 65535:
raise ValueError("Invalid PORT")
children = []
stopping = False
def stop(signum, frame):
nonlocal stopping
stopping = True
for child in children:
child.terminate()
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
# Commands and their options are constructed locally, never from user input.
children.append(
subprocess.Popen( # noqa: S603 -- fixed interpreter/module; validated integer port
[
sys.executable,
"-m",
"gunicorn",
"hunter:create_app()",
"--bind",
f"0.0.0.0:{port}",
"--workers",
"1",
"--threads",
"4",
"--timeout",
"180",
"--access-logfile",
"-",
]
)
)
if os.getenv("ENABLE_SCHEDULER", "1") == "1":
children.append(subprocess.Popen([sys.executable, "-m", "hunter.monitor"])) # noqa: S603
while not stopping and all(child.poll() is None for child in children):
time.sleep(0.5)
stop(None, None)
failed = False
for child in children:
try:
code = child.wait(timeout=20)
failed = failed or code not in (0, -signal.SIGTERM)
except subprocess.TimeoutExpired:
child.kill()
child.wait()
failed = True
return int(failed)
if __name__ == "__main__":
raise SystemExit(main())