Files
wifi-gps-mapper-public/src/lifecycle_manager.py
T
2026-11-19 00:39:35 +03:00

993 lines
25 KiB
Python

import argparse
import getpass
import json
import os
import shutil
import signal
import socket
import stat
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
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
from tileserver_config import load_tileserver_config
from runtime_paths import get_node_path, get_runtime_env
TILESERVER_CONFIG_DATA = load_tileserver_config(PROJECT_ROOT)
UNIT_NAME = "wifi-gps-mapper"
APP_HOST = "127.0.0.1"
APP_PORT = 5000
TILE_HOST = TILESERVER_CONFIG_DATA["host"]
TILE_PORT = TILESERVER_CONFIG_DATA["port"]
TILE_STYLE_URL = TILESERVER_CONFIG_DATA["style_url"]
TILESERVER_DIR = TILESERVER_CONFIG_DATA["directory"]
TILESERVER_ENTRY = TILESERVER_CONFIG_DATA["entry"]
TILESERVER_CONFIG = TILESERVER_CONFIG_DATA["config"]
TILESERVER_CONFIG_PATH = TILESERVER_CONFIG_DATA["config_path"]
STARTUP_TIMEOUT = 30
POLL_INTERVAL = 0.5
AUTH_SOCKET_PATH = Path(
os.environ.get(
"XDG_RUNTIME_DIR",
f"/run/user/{os.getuid()}"
)
) / "wifi-gps-mapper-auth.sock"
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} занят, но ожидаемый "
f"стиль {TILESERVER_CONFIG_DATA['style']} недоступен. "
"Чужой процесс не будет остановлен."
)
try:
node = str(get_node_path())
except FileNotFoundError as error:
raise LifecycleError(
"Локальный Node.js не найден."
) from error
if not TILESERVER_ENTRY.is_file():
raise LifecycleError(
f"Не найден TileServer entry point: "
f"{TILESERVER_ENTRY}"
)
config_path = TILESERVER_CONFIG_PATH
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,
env=get_runtime_env()
)
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 receive_sudo_authentication(shutdown_event):
runtime_dir = AUTH_SOCKET_PATH.parent
if not runtime_dir.is_dir():
raise LifecycleError(
f"Не найден runtime-каталог: {runtime_dir}"
)
if AUTH_SOCKET_PATH.exists() or AUTH_SOCKET_PATH.is_symlink():
try:
socket_info = AUTH_SOCKET_PATH.lstat()
except OSError as error:
raise LifecycleError(
f"Не удалось проверить Unix-сокет: {error}"
) from error
if (
not stat.S_ISSOCK(socket_info.st_mode)
or socket_info.st_uid != os.getuid()
):
raise LifecycleError(
f"Путь занят посторонним объектом: {AUTH_SOCKET_PATH}"
)
AUTH_SOCKET_PATH.unlink()
auth_socket = socket.socket(
socket.AF_UNIX,
socket.SOCK_STREAM
)
try:
auth_socket.bind(str(AUTH_SOCKET_PATH))
AUTH_SOCKET_PATH.chmod(0o600)
auth_socket.listen(1)
auth_deadline = time.monotonic() + STARTUP_TIMEOUT + 60
auth_socket.settimeout(POLL_INTERVAL)
log("Ожидание sudo-аутентификации от CLI...")
while True:
if shutdown_event.is_set():
raise LifecycleError(
"Ожидание sudo-аутентификации прервано остановкой."
)
if time.monotonic() >= auth_deadline:
raise LifecycleError(
"Не получен пароль sudo за отведённое время."
)
try:
connection, _ = auth_socket.accept()
break
except socket.timeout:
continue
with connection:
connection.settimeout(10)
password = bytearray()
while True:
chunk = connection.recv(1024)
if not chunk:
break
password.extend(chunk)
if len(password) > 4096:
raise LifecycleError(
"Получен недопустимо длинный пароль."
)
if not password:
connection.sendall(b"AUTH_FAILED")
raise LifecycleError(
"Получен пустой пароль sudo."
)
result = subprocess.run(
["sudo", "-S", "-p", "", "-v"],
input=bytes(password) + b"\n",
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
check=False
)
for index in range(len(password)):
password[index] = 0
if result.returncode != 0:
connection.sendall(b"AUTH_FAILED")
raise LifecycleError(
"sudo-аутентификация не пройдена."
)
connection.sendall(b"AUTH_OK")
log("sudo-аутентификация успешно пройдена.")
except socket.timeout as error:
raise LifecycleError(
"Не получен пароль sudo за отведённое время."
) from error
finally:
auth_socket.close()
try:
socket_info = AUTH_SOCKET_PATH.lstat()
if (
stat.S_ISSOCK(socket_info.st_mode)
and socket_info.st_uid == os.getuid()
):
AUTH_SOCKET_PATH.unlink()
except FileNotFoundError:
pass
def send_sudo_authentication():
deadline = time.monotonic() + STARTUP_TIMEOUT
connection = None
while connection is None:
if not unit_is_active():
raise LifecycleError(
"Менеджер завершился до подключения CLI. "
"Проверь журнал: "
f"journalctl --user -u {UNIT_NAME}.service"
)
if time.monotonic() >= deadline:
raise LifecycleError(
"Не удалось подключиться к сокету "
"sudo-аутентификации."
)
candidate = socket.socket(
socket.AF_UNIX,
socket.SOCK_STREAM
)
try:
candidate.settimeout(POLL_INTERVAL)
candidate.connect(str(AUTH_SOCKET_PATH))
connection = candidate
except OSError:
candidate.close()
time.sleep(POLL_INTERVAL)
password = ""
try:
password = getpass.getpass("Введите пароль sudo: ")
connection.settimeout(10)
connection.sendall(password.encode("utf-8") + b"\n")
password = ""
connection.shutdown(socket.SHUT_WR)
response = connection.recv(32)
finally:
password = ""
connection.close()
if response != b"AUTH_OK":
raise LifecycleError(
"Менеджер отклонил sudo-аутентификацию."
)
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:
receive_sudo_authentication(shutdown_event)
tileserver_process = start_tileserver()
from gui import app as app_module
if not app_module.check_sudo():
raise LifecycleError(
"sudo-аутентификация менеджера недоступна."
)
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,
capture_output=True
)
def active_service_project():
result = systemctl_user(
"show",
f"{UNIT_NAME}.service",
"--property=WorkingDirectory",
"--value",
check=False
)
if result.returncode != 0:
return None
working_directory = result.stdout.strip()
if not working_directory:
return None
try:
return Path(working_directory).resolve()
except (OSError, RuntimeError):
return None
def unit_is_active():
result = systemctl_user(
"is-active",
"--quiet",
f"{UNIT_NAME}.service",
check=False
)
return result.returncode == 0
def start_service():
if unit_is_active():
active_project = active_service_project()
if active_project is None:
raise LifecycleError(
"Сервис уже активен, но не удалось определить "
"каталог проекта. Второй экземпляр не будет запущен."
)
if active_project == PROJECT_ROOT:
log("Менеджер уже запущен из текущего проекта.")
else:
log(
"Менеджер уже запущен из другого проекта: "
f"{active_project}. Второй экземпляр не запущен."
)
return 0
if port_is_open(APP_HOST, APP_PORT):
raise LifecycleError(
f"Порт приложения {APP_PORT} занят. "
"Чужой процесс не будет остановлен."
)
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
)
send_sudo_authentication()
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():
if not unit_is_active():
log("Менеджер не запущен.")
return 0
active_project = active_service_project()
if active_project is None:
raise LifecycleError(
"Не удалось определить проект работающего сервиса. "
"Остановка отменена."
)
if active_project != PROJECT_ROOT:
raise LifecycleError(
f"Сервис запущен из другого проекта: {active_project}. "
f"Остановка из {PROJECT_ROOT} отменена."
)
run_sudo_validation()
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:
active_project = active_service_project()
print(
"Active project:",
active_project if active_project is not None else "UNKNOWN"
)
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", {})
scanner_running = scanner.get("running", False)
scanner_health = scanner.get("health", "unknown")
scanner_pid = scanner.get("pid")
if scanner_running:
scanner_state = (
f"RUNNING (PID {scanner_pid}, "
f"health: {scanner_health})"
)
else:
scanner_state = (
f"STOPPED (health: {scanner_health})"
)
print("Scanner:", scanner_state)
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.")
try:
get_node_path()
except FileNotFoundError as error:
raise LifecycleError(
"Локальный Node.js не найден."
) from error
if not TILESERVER_ENTRY.is_file():
raise LifecycleError(
f"Не найден TileServer entry point: {TILESERVER_ENTRY}"
)
if not TILESERVER_CONFIG_PATH.is_file():
raise LifecycleError(
"Не найден TileServer config: "
f"{TILESERVER_CONFIG_PATH}"
)
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())