diff --git a/src/lifecycle_manager.py b/src/lifecycle_manager.py new file mode 100644 index 0000000..8e21505 --- /dev/null +++ b/src/lifecycle_manager.py @@ -0,0 +1,742 @@ +import argparse +import json +import os +import shutil +import signal +import socket +import subprocess +import sys +import threading +import time +import urllib.error +import urllib.request +from pathlib import Path + + +PROJECT_ROOT = Path(__file__).resolve().parent.parent +UNIT_NAME = "wifi-gps-mapper" +APP_HOST = "127.0.0.1" +APP_PORT = 5000 +TILE_HOST = "127.0.0.1" +TILE_PORT = int(os.environ.get("WIFI_GPS_TILESERVER_PORT", "8080")) +TILE_STYLE_URL = ( + f"http://{TILE_HOST}:{TILE_PORT}" + "/styles/server-map/style.json" +) + +TILESERVER_DIR = Path( + os.environ.get( + "WIFI_GPS_TILESERVER_DIR", + str(Path.home() / "Projects" / "server-map") + ) +).expanduser() + +TILESERVER_ENTRY = Path( + os.environ.get( + "WIFI_GPS_TILESERVER_ENTRY", + str( + TILESERVER_DIR + / "node_modules" + / "tileserver-gl-light" + / "src" + / "main.js" + ) + ) +).expanduser() + +TILESERVER_CONFIG = os.environ.get( + "WIFI_GPS_TILESERVER_CONFIG", + "config.json" +) + +STARTUP_TIMEOUT = 30 +POLL_INTERVAL = 0.5 + + +class LifecycleError(RuntimeError): + pass + + +def log(message): + print( + f"[WiFi GPS Mapper] {message}", + flush=True + ) + + +def project_python(): + return PROJECT_ROOT / "venv" / "bin" / "python" + + +def style_is_available(timeout=2): + try: + request = urllib.request.Request( + TILE_STYLE_URL, + headers={"Accept": "application/json"} + ) + + with urllib.request.urlopen( + request, + timeout=timeout + ) as response: + if response.status != 200: + return False + + content_type = response.headers.get( + "Content-Type", + "" + ) + + payload = json.loads( + response.read().decode("utf-8") + ) + + return ( + isinstance(payload, dict) + and "version" in payload + and ( + "sources" in payload + or "layers" in payload + ) + ) + + except ( + OSError, + ValueError, + urllib.error.URLError + ): + return False + + +def port_is_open(host, port): + with socket.socket( + socket.AF_INET, + socket.SOCK_STREAM + ) as connection: + connection.settimeout(0.5) + + return connection.connect_ex( + (host, port) + ) == 0 + + +def start_tileserver(): + if style_is_available(): + log( + "TileServer уже работает. " + "Используется внешний экземпляр." + ) + return None + + if port_is_open(TILE_HOST, TILE_PORT): + raise LifecycleError( + f"Порт {TILE_PORT} занят, но ожидаемый " + "стиль server-map недоступен. " + "Чужой процесс не будет остановлен." + ) + + node = shutil.which("node") + + if node is None: + raise LifecycleError( + "Node.js не найден в PATH." + ) + + if not TILESERVER_ENTRY.is_file(): + raise LifecycleError( + f"Не найден TileServer entry point: " + f"{TILESERVER_ENTRY}" + ) + + config_path = TILESERVER_DIR / TILESERVER_CONFIG + + if not config_path.is_file(): + raise LifecycleError( + f"Не найден TileServer config: {config_path}" + ) + + command = [ + node, + str(TILESERVER_ENTRY), + "--config", + TILESERVER_CONFIG, + "--bind", + TILE_HOST, + "--port", + str(TILE_PORT) + ] + + log("Запускается TileServer...") + + process = subprocess.Popen( + command, + cwd=TILESERVER_DIR, + stdin=subprocess.DEVNULL + ) + + deadline = time.monotonic() + STARTUP_TIMEOUT + + while time.monotonic() < deadline: + if process.poll() is not None: + raise LifecycleError( + "TileServer завершился во время запуска " + f"(код {process.returncode})." + ) + + if style_is_available(): + log( + f"TileServer запущен, PID {process.pid}." + ) + return process + + time.sleep(POLL_INTERVAL) + + process.terminate() + + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + + raise LifecycleError( + "TileServer не стал доступен за " + f"{STARTUP_TIMEOUT} секунд." + ) + + +def stop_owned_tileserver(process): + if process is None or process.poll() is not None: + return + + log("Останавливается принадлежащий менеджеру TileServer.") + + process.terminate() + + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + + +def wait_for_scanner(app_module): + notified = False + + while True: + with app_module.scanner_lock: + starting = app_module.scanner_starting + network_active = app_module.network_action_active + process = app_module.scanner_process + reader = app_module.scanner_output_thread + + running = ( + process is not None + and process.poll() is None + ) + + if not starting and not network_active and not running: + break + + if not notified: + log( + "Ожидание завершения сканера или сетевой операции. " + "Если сканер работает, останови его кнопкой " + "Stop в веб-интерфейсе." + ) + notified = True + + time.sleep(POLL_INTERVAL) + + if process is not None: + process.wait() + + if reader is not None and reader is not threading.current_thread(): + reader.join() + + log("Сканер и поток чтения его вывода завершены.") + + +def stop_gps_test(app_module): + with app_module.gps_test_lock: + service = app_module.gps_test_service + + if service is None: + return + + thread = service.thread + + if thread is None or not thread.is_alive(): + return + + log("Останавливается GPS-тест.") + + service.stop() + + if thread is not threading.current_thread(): + thread.join() + + log("GPS-тест завершён.") + + +def join_background_threads(app_module): + for name in ( + "vendor_update_thread", + "vendor_recalc_thread" + ): + thread = getattr(app_module, name, None) + + if thread is None or thread is threading.current_thread(): + continue + + if thread.is_alive(): + log(f"Ожидание фоновой задачи: {name}.") + thread.join() + + log("Фоновые задачи завершены.") + + +def run_server(): + os.chdir(PROJECT_ROOT) + + if str(PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(PROJECT_ROOT)) + + src_path = str(PROJECT_ROOT / "src") + + if src_path not in sys.path: + sys.path.insert(0, src_path) + + tileserver_process = None + server = None + server_thread = None + app_module = None + + shutdown_event = threading.Event() + shutdown_started = False + + def request_shutdown(signum, frame): + nonlocal shutdown_started + + if shutdown_started: + return + + shutdown_started = True + log("Получен сигнал завершения.") + + if app_module is not None: + app_module.request_lifecycle.begin_shutdown() + + shutdown_event.set() + + signal.signal(signal.SIGTERM, request_shutdown) + signal.signal(signal.SIGINT, request_shutdown) + + try: + tileserver_process = start_tileserver() + + from gui import app as app_module + + if not app_module.check_sudo(): + raise LifecycleError( + "Нет действующей sudo-аутентификации. " + "Запусти CLI-команду через sudo -v." + ) + + app_module.sudo_keepalive_stop_event.clear() + + app_module.sudo_keepalive_thread = threading.Thread( + target=app_module.sudo_keepalive, + args=(app_module.sudo_keepalive_stop_event,), + name="sudo-keepalive", + daemon=True + ) + + app_module.sudo_keepalive_thread.start() + + from werkzeug.serving import make_server + + server = make_server( + APP_HOST, + APP_PORT, + app_module.app, + threaded=True + ) + + server_thread = threading.Thread( + target=server.serve_forever, + name="flask-server", + daemon=False + ) + + server_thread.start() + + log( + f"Веб-интерфейс запущен: " + f"http://{APP_HOST}:{APP_PORT}" + ) + + shutdown_event.wait() + + except Exception: + if app_module is not None: + app_module.request_lifecycle.begin_shutdown() + + raise + + finally: + if app_module is not None: + app_module.request_lifecycle.begin_shutdown() + + log("Ожидание завершения активных HTTP-запросов.") + app_module.request_lifecycle.wait_for_drain() + + stop_gps_test(app_module) + wait_for_scanner(app_module) + join_background_threads(app_module) + + app_module.sudo_keepalive_stop_event.set() + + keepalive = app_module.sudo_keepalive_thread + + if ( + keepalive is not None + and keepalive is not threading.current_thread() + ): + keepalive.join() + + if server is not None: + log("Остановка Flask-сервера.") + server.shutdown() + + if server_thread is not None: + server_thread.join() + + stop_owned_tileserver(tileserver_process) + + log("Менеджер завершил работу.") + + +def run_sudo_validation(): + try: + result = subprocess.run( + ["sudo", "-v"], + check=False + ) + except OSError as error: + raise LifecycleError( + f"Не удалось запустить sudo: {error}" + ) from error + + if result.returncode != 0: + raise LifecycleError( + "Проверка sudo не пройдена." + ) + + +def systemctl_user(*arguments, check=True): + command = [ + "systemctl", + "--user", + *arguments + ] + + return subprocess.run( + command, + check=check, + text=True + ) + + +def unit_is_active(): + result = systemctl_user( + "is-active", + "--quiet", + f"{UNIT_NAME}.service", + check=False + ) + + return result.returncode == 0 + + +def start_service(): + run_sudo_validation() + + if unit_is_active(): + log("Менеджер уже запущен.") + return 0 + + python = project_python() + + if not python.is_file(): + raise LifecycleError( + f"Не найден Python виртуального окружения: {python}" + ) + + command = [ + "systemd-run", + "--user", + f"--unit={UNIT_NAME}", + "--service-type=exec", + "--property=KillMode=process", + "--collect", + f"--working-directory={PROJECT_ROOT}", + str(python), + str(PROJECT_ROOT / "src" / "lifecycle_manager.py"), + "--serve" + ] + + subprocess.run( + command, + check=True + ) + + deadline = time.monotonic() + STARTUP_TIMEOUT + + while time.monotonic() < deadline: + if not unit_is_active(): + raise LifecycleError( + "Сервис завершился во время запуска. " + "Проверь журнал: " + f"journalctl --user -u {UNIT_NAME}.service" + ) + + try: + with urllib.request.urlopen( + f"http://{APP_HOST}:{APP_PORT}/api/status", + timeout=1 + ) as response: + if response.status == 200: + log( + f"Приложение запущено: " + f"http://{APP_HOST}:{APP_PORT}" + ) + return 0 + except OSError: + pass + + time.sleep(POLL_INTERVAL) + + raise LifecycleError( + "Приложение не ответило за время запуска. " + f"Проверь journalctl --user -u {UNIT_NAME}.service" + ) + + +def stop_service(): + run_sudo_validation() + + if not unit_is_active(): + log("Менеджер не запущен.") + return 0 + + systemctl_user( + "kill", + "--kill-whom=main", + "--signal=SIGTERM", + f"{UNIT_NAME}.service" + ) + + log( + "Запрошено штатное завершение. " + "Если сканер активен, останови его в веб-интерфейсе." + ) + + notified = False + + while unit_is_active(): + if not notified: + log( + "Ожидание завершения приложения и фоновых задач..." + ) + notified = True + + time.sleep(1) + + log("Сервис остановлен.") + return 0 + + +def show_status(): + active = unit_is_active() + + print( + "Application:", + "RUNNING" if active else "STOPPED" + ) + + if active: + try: + with urllib.request.urlopen( + f"http://{APP_HOST}:{APP_PORT}/api/status", + timeout=2 + ) as response: + data = json.loads( + response.read().decode("utf-8") + ) + + scanner = data.get("status", {}) + gps = data.get("gps_test", {}) + + print( + "Scanner:", + scanner.get("status", "unknown") + ) + print( + "GPS test:", + gps.get("state", "unknown") + ) + print( + "Network action:", + "BUSY" if data.get("network_actions_busy") else "IDLE" + ) + + except Exception as error: + print(f"Application API: unavailable ({error})") + + print( + "TileServer:", + "AVAILABLE" if style_is_available() else "UNAVAILABLE" + ) + + if active: + result = systemctl_user( + "show", + f"{UNIT_NAME}.service", + "--property=MainPID", + "--property=ActiveState", + check=False + ) + + if result.returncode == 0: + print(result.stdout.strip()) + + +def install(): + python = project_python() + + if not python.is_file(): + raise LifecycleError( + f"Не найдено виртуальное окружение: {python}" + ) + + if shutil.which("systemd-run") is None: + raise LifecycleError("Не найден systemd-run.") + + if shutil.which("systemctl") is None: + raise LifecycleError("Не найден systemctl.") + + if shutil.which("sudo") is None: + raise LifecycleError("Не найден sudo.") + + if shutil.which("node") is None: + raise LifecycleError("Не найден Node.js.") + + if not TILESERVER_ENTRY.is_file(): + raise LifecycleError( + f"Не найден TileServer entry point: {TILESERVER_ENTRY}" + ) + + if not (TILESERVER_DIR / TILESERVER_CONFIG).is_file(): + raise LifecycleError( + "Не найден TileServer config: " + f"{TILESERVER_DIR / TILESERVER_CONFIG}" + ) + + check = subprocess.run( + [ + str(python), + "-c", + "import flask, werkzeug" + ], + check=False + ) + + if check.returncode != 0: + raise LifecycleError( + "Flask или Werkzeug недоступны в venv." + ) + + cli_path = PROJECT_ROOT / "wifi-gps-mapper" + + if not cli_path.is_file(): + raise LifecycleError( + f"Не найден CLI-файл: {cli_path}" + ) + + cli_path.chmod( + cli_path.stat().st_mode | 0o111 + ) + + systemctl_user("show-environment") + + log("Проверка окружения пройдена.") + log(f"CLI: {cli_path}") + log("TileServer не устанавливался и не изменялся.") + + +def main(): + parser = argparse.ArgumentParser( + prog="wifi-gps-mapper" + ) + + parser.add_argument( + "--serve", + action="store_true", + help=argparse.SUPPRESS + ) + + parser.add_argument( + "command", + nargs="?", + choices=( + "install", + "start", + "status", + "stop", + "restart" + ) + ) + + args = parser.parse_args() + + try: + if args.serve: + run_server() + return 0 + + if args.command == "install": + install() + return 0 + + if args.command == "start": + return start_service() + + if args.command == "status": + show_status() + return 0 + + if args.command == "stop": + return stop_service() + + if args.command == "restart": + stop_service() + return start_service() + + parser.print_help() + return 2 + + except ( + LifecycleError, + subprocess.CalledProcessError, + OSError + ) as error: + print( + f"Ошибка: {error}", + file=sys.stderr + ) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main())