process_manager.py 16 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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
"""Managed process lifecycle helpers for the web API runtime."""

from __future__ import annotations

import os
import subprocess
import sys
import threading
import time
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Mapping

import requests
from loguru import logger

from apps.web_api.runtime.engine_registry import ENGINE_RUNTIME_REGISTRY
from apps.web_api.runtime.log_stream import read_process_output, write_log_to_file
from apps.web_api.runtime.process_registry import PROCESS_RUNTIME_REGISTRY, ProcessRuntimeRegistry

HEALTHCHECK_PATH = "/_stcore/health"
HEALTHCHECK_PROXIES = {"http": None, "https": None}
HEALTHCHECK_GRACE_SECONDS = 15


def get_default_streamlit_scripts() -> dict[str, str]:
    """Resolve the current Streamlit script table from the runtime engine registry."""

    return ENGINE_RUNTIME_REGISTRY.streamlit_scripts()


class _StreamlitScriptsCompatibilityView(Mapping[str, str]):
    """Live compatibility view over the current engine-registry script mapping."""

    def __getitem__(self, key: str) -> str:
        return get_default_streamlit_scripts()[key]

    def __iter__(self):
        return iter(get_default_streamlit_scripts())

    def __len__(self) -> int:
        return len(get_default_streamlit_scripts())

    def __repr__(self) -> str:
        return repr(get_default_streamlit_scripts())


# Compatibility export: resolves the current mapping at access time.
STREAMLIT_SCRIPTS: Mapping[str, str] = _StreamlitScriptsCompatibilityView()


@dataclass(frozen=True)
class ProcessCleanupPort:
    """Runtime callbacks required to clean up managed processes."""

    stop_forum_engine: Callable[[], Any]
    mark_system_stopped: Callable[[], None]


def log_shutdown_step(message: str) -> None:
    logger.info(f"[Shutdown] {message}")


def build_healthcheck_url(port: int) -> str:
    return f"http://127.0.0.1:{port}{HEALTHCHECK_PATH}"


class ProcessManager:
    """Object-oriented wrapper around managed process state and operations."""

    def __init__(
        self,
        *,
        process_registry: ProcessRuntimeRegistry | None = None,
        streamlit_scripts: Mapping[str, str] | None = None,
        write_log: Callable[[Path, str, str], None] = write_log_to_file,
        process_output_reader: Callable[..., None] = read_process_output,
        requests_get: Callable[..., Any] = requests.get,
        cwd_getter: Callable[[], str] = os.getcwd,
    ) -> None:
        self._process_registry = process_registry
        resolved_streamlit_scripts = (
            streamlit_scripts if streamlit_scripts is not None else get_default_streamlit_scripts()
        )
        self._streamlit_scripts = dict(resolved_streamlit_scripts)
        self._write_log = write_log
        self._process_output_reader = process_output_reader
        self._requests_get = requests_get
        self._cwd_getter = cwd_getter

    @property
    def process_registry(self) -> ProcessRuntimeRegistry:
        return self._process_registry if self._process_registry is not None else PROCESS_RUNTIME_REGISTRY

    @property
    def streamlit_scripts(self) -> Mapping[str, str]:
        return self._streamlit_scripts

    def describe_running_children(self) -> list[str]:
        running: list[str] = []
        for name, info in self.process_registry.items():
            proc = self.process_registry.get_process(name)
            if proc is not None and proc.poll() is None:
                port_desc = f", port={info.get('port')}" if info.get("port") else ""
                running.append(f"{name}(pid={proc.pid}{port_desc})")
        return running

    def healthcheck_grace_active(self, app_name: str) -> bool:
        if not self.process_registry.contains(app_name):
            return False
        started_at = self.process_registry.get_healthcheck_started_at(app_name)
        if not started_at:
            return False
        return (time.time() - started_at) < HEALTHCHECK_GRACE_SECONDS

    def log_healthcheck_failure(self, app_name: str, exc: Exception) -> None:
        if self.healthcheck_grace_active(app_name):
            logger.debug(f"Skipping transient healthcheck failure while {app_name} is starting: {exc}")
            return
        logger.warning(f"{app_name} healthcheck failed: {exc}")

    def start_streamlit_app(
        self,
        app_name: str,
        script_path: str,
        port: int,
        *,
        log_dir: Path,
        emit_output: Callable[[str, dict], None],
    ) -> tuple[bool, str]:
        try:
            if self.process_registry.get_process(app_name) is not None:
                return False, "application is already running"

            if not os.path.exists(script_path):
                return False, f"file does not exist: {script_path}"

            log_file_path = log_dir / f"{app_name}.log"
            if log_file_path.exists():
                log_file_path.unlink()

            start_msg = f"[{datetime.now().strftime('%H:%M:%S')}] starting {app_name} app..."
            self._write_log(log_dir, app_name, start_msg)

            cmd = [
                sys.executable,
                "-m",
                "streamlit",
                "run",
                script_path,
                "--server.port",
                str(port),
                "--server.headless",
                "true",
                "--browser.gatherUsageStats",
                "false",
                "--logger.level",
                "info",
                "--server.enableCORS",
                "false",
            ]

            env = os.environ.copy()
            env.update(
                {
                    "PYTHONIOENCODING": "utf-8",
                    "PYTHONUTF8": "1",
                    "LANG": "en_US.UTF-8",
                    "LC_ALL": "en_US.UTF-8",
                    "PYTHONUNBUFFERED": "1",
                    "STREAMLIT_BROWSER_GATHER_USAGE_STATS": "false",
                }
            )

            creationflags = 0
            if sys.platform == "win32":
                creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0)

            process = subprocess.Popen(
                cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                bufsize=0,
                universal_newlines=False,
                cwd=self._cwd_getter(),
                env=env,
                encoding=None,
                creationflags=creationflags,
            )

            self.process_registry.set_process(app_name, process)
            self.process_registry.set_status(app_name, "starting")
            self.process_registry.set_output(app_name, [])
            self.process_registry.set_healthcheck_started_at(app_name, time.time())

            output_thread = threading.Thread(
                target=self._process_output_reader,
                kwargs={
                    "process": process,
                    "log_dir": log_dir,
                    "emit_output": emit_output,
                    "app_name": app_name,
                },
                daemon=True,
            )
            output_thread.start()

            return True, f"{app_name} app is starting..."
        except Exception as exc:
            error_msg = f"start failed: {exc}"
            self._write_log(
                log_dir,
                app_name,
                f"[{datetime.now().strftime('%H:%M:%S')}] {error_msg}",
            )
            return False, error_msg

    def stop_streamlit_app(self, app_name: str) -> tuple[bool, str]:
        try:
            process = self.process_registry.get_process(app_name)
            if process is None:
                log_shutdown_step(f"{app_name} is not running; skip stop")
                return False, "application is not running"

            try:
                pid = process.pid
            except Exception:
                pid = "unknown"

            log_shutdown_step(f"Stopping {app_name} (pid={pid})")
            process.terminate()

            try:
                process.wait(timeout=5)
                log_shutdown_step(f"{app_name} exited cleanly, returncode={process.returncode}")
            except subprocess.TimeoutExpired:
                log_shutdown_step(f"{app_name} terminate timed out; forcing kill (pid={pid})")
                process.kill()
                process.wait()
                log_shutdown_step(f"{app_name} force-killed, returncode={process.returncode}")

            self.process_registry.reset_runtime(app_name, status="stopped")
            return True, f"{app_name} app stopped"
        except Exception as exc:
            log_shutdown_step(f"{app_name} stop failed: {exc}")
            return False, f"stop failed: {exc}"

    def check_app_status(self) -> None:
        for app_name, info in self.process_registry.items():
            port = info.get("port")
            if app_name == "forum":
                continue

            healthy = False
            if port:
                try:
                    response = self._requests_get(
                        build_healthcheck_url(port),
                        timeout=2,
                        proxies=HEALTHCHECK_PROXIES,
                    )
                    healthy = response.status_code == 200
                except Exception as exc:
                    self.log_healthcheck_failure(app_name, exc)

            proc = info.get("process")
            if healthy:
                self.process_registry.set_status(app_name, "running")
                if proc is not None and proc.poll() is not None:
                    self.process_registry.clear_process(app_name)
                    self.process_registry.set_healthcheck_started_at(app_name, None)
                continue

            if proc is not None:
                if proc.poll() is None:
                    self.process_registry.set_status(app_name, "starting")
                else:
                    self.process_registry.reset_runtime(app_name, status="stopped")
            else:
                self.process_registry.set_status(app_name, "stopped")

    def wait_for_app_startup(self, app_name: str, max_wait_time: int = 90) -> tuple[bool, str]:
        start_time = time.time()
        while time.time() - start_time < max_wait_time:
            info = self.process_registry.get_entry(app_name)
            if info["process"] is None:
                return False, "process stopped"

            if info["process"].poll() is not None:
                return False, "process startup failed"

            try:
                response = self._requests_get(
                    build_healthcheck_url(info["port"]),
                    timeout=2,
                    proxies=HEALTHCHECK_PROXIES,
                )
                if response.status_code == 200:
                    self.process_registry.set_status(app_name, "running")
                    return True, "startup succeeded"
            except Exception as exc:
                self.log_healthcheck_failure(app_name, exc)

            time.sleep(1)

        return False, "startup timed out"

    def cleanup_processes(
        self,
        *,
        cleanup: ProcessCleanupPort,
    ) -> None:
        log_shutdown_step("Starting serial process cleanup")
        for app_name in self._streamlit_scripts:
            self.stop_streamlit_app(app_name)

        self.process_registry.set_status("forum", "stopped")
        try:
            cleanup.stop_forum_engine()
        except Exception:
            logger.exception("Failed to stop ForumEngine during cleanup")
        log_shutdown_step("Serial process cleanup completed")
        cleanup.mark_system_stopped()

    def cleanup_processes_concurrent(
        self,
        *,
        cleanup: ProcessCleanupPort,
        timeout: float = 6.0,
    ) -> None:
        log_shutdown_step(f"Starting concurrent process cleanup (timeout={timeout}s)")
        running_before = self.describe_running_children()
        if running_before:
            log_shutdown_step("Tracked child processes before cleanup: " + ", ".join(running_before))
        else:
            log_shutdown_step("No tracked child processes detected before cleanup")

        threads: list[threading.Thread] = []

        for app_name in self._streamlit_scripts:
            thread = threading.Thread(target=self.stop_streamlit_app, args=(app_name,), daemon=True)
            threads.append(thread)
            thread.start()

        forum_thread = threading.Thread(target=cleanup.stop_forum_engine, daemon=True)
        threads.append(forum_thread)
        forum_thread.start()

        end_time = time.time() + timeout
        for thread in threads:
            remaining = end_time - time.time()
            if remaining <= 0:
                break
            thread.join(timeout=remaining)

        for app_name in self._streamlit_scripts:
            proc = self.process_registry.get_process(app_name)
            if proc is not None and proc.poll() is None:
                try:
                    log_shutdown_step(f"{app_name} still alive after cleanup; terminating again (pid={proc.pid})")
                    proc.terminate()
                    proc.wait(timeout=1)
                except Exception:
                    try:
                        log_shutdown_step(f"{app_name} terminate retry failed; killing process (pid={proc.pid})")
                        proc.kill()
                        proc.wait(timeout=1)
                    except Exception:
                        logger.warning(f"Failed to force-exit {app_name}; continuing shutdown")
                finally:
                    self.process_registry.reset_runtime(app_name, status="stopped")

        self.process_registry.set_status("forum", "stopped")
        log_shutdown_step("Concurrent process cleanup finished; marking system stopped")
        cleanup.mark_system_stopped()


def build_process_manager(
    *,
    process_registry: ProcessRuntimeRegistry | None = None,
    streamlit_scripts: Mapping[str, str] | None = None,
) -> ProcessManager:
    """Build a process manager bound to the provided runtime registry."""

    return ProcessManager(
        process_registry=process_registry,
        streamlit_scripts=streamlit_scripts,
    )


def describe_running_children(*, process_registry: ProcessRuntimeRegistry | None = None) -> list[str]:
    return build_process_manager(process_registry=process_registry).describe_running_children()


def healthcheck_grace_active(app_name: str) -> bool:
    return build_process_manager().healthcheck_grace_active(app_name)


def log_healthcheck_failure(app_name: str, exc: Exception) -> None:
    build_process_manager().log_healthcheck_failure(app_name, exc)


def start_streamlit_app(
    app_name: str,
    script_path: str,
    port: int,
    *,
    log_dir: Path,
    emit_output: Callable[[str, dict], None],
) -> tuple[bool, str]:
    return build_process_manager().start_streamlit_app(
        app_name,
        script_path,
        port,
        log_dir=log_dir,
        emit_output=emit_output,
    )


def stop_streamlit_app(app_name: str) -> tuple[bool, str]:
    return build_process_manager().stop_streamlit_app(app_name)


def check_app_status(
    *,
    process_registry: ProcessRuntimeRegistry | None = None,
) -> None:
    build_process_manager(process_registry=process_registry).check_app_status()


def wait_for_app_startup(app_name: str, max_wait_time: int = 90) -> tuple[bool, str]:
    return build_process_manager().wait_for_app_startup(app_name, max_wait_time=max_wait_time)


def cleanup_processes(
    *,
    cleanup: ProcessCleanupPort,
) -> None:
    build_process_manager().cleanup_processes(cleanup=cleanup)


def cleanup_processes_concurrent(
    *,
    cleanup: ProcessCleanupPort,
    timeout: float = 6.0,
) -> None:
    build_process_manager().cleanup_processes_concurrent(cleanup=cleanup, timeout=timeout)


__all__ = [
    "ProcessCleanupPort",
    "ProcessManager",
    "STREAMLIT_SCRIPTS",
    "build_healthcheck_url",
    "build_process_manager",
    "check_app_status",
    "cleanup_processes",
    "cleanup_processes_concurrent",
    "describe_running_children",
    "get_default_streamlit_scripts",
    "healthcheck_grace_active",
    "log_healthcheck_failure",
    "log_shutdown_step",
    "start_streamlit_app",
    "stop_streamlit_app",
    "wait_for_app_startup",
]