diff --git a/admin-web/server.py b/admin-web/server.py index b1a9972..acebd8c 100644 --- a/admin-web/server.py +++ b/admin-web/server.py @@ -16,6 +16,7 @@ import mimetypes import os import re import secrets +import socket import subprocess import time import urllib.error @@ -152,7 +153,11 @@ def write_telemt_users(users: dict[str, str]) -> None: def restart_service(name: str) -> bool: code, _, _ = run(["systemctl", "restart", name], timeout=25) - return code == 0 + if code != 0: + return False + if name == "telemt": + return wait_tcp_port(read_telemt_port(), timeout=90) + return True def service_status(name: str) -> str: @@ -168,6 +173,38 @@ def service_status(name: str) -> str: return "stopped" +def read_telemt_port() -> int: + if not TELEMT_CONFIG.exists(): + return 443 + in_server = False + for raw in TELEMT_CONFIG.read_text(encoding="utf-8", errors="ignore").splitlines(): + line = raw.strip() + if line == "[server]": + in_server = True + continue + if in_server and line.startswith("["): + break + if in_server and line.startswith("port") and "=" in line: + try: + return int(line.split("=", 1)[1].strip().split("#", 1)[0]) + except ValueError: + return 443 + return 443 + + +def wait_tcp_port(port: int, timeout: int = 90) -> bool: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if service_status("telemt") not in {"running", "activating"}: + return False + try: + with socket.create_connection(("127.0.0.1", port), timeout=0.6): + return True + except OSError: + time.sleep(1) + return False + + def public_ip() -> str: code, stdout, _ = run(["curl", "-s", "-4", "--max-time", "3", "https://api.ipify.org"], timeout=5) ip = stdout.strip()