Spaces:
Paused
Paused
File size: 11,707 Bytes
5e0b58b | 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 | """Typed cross-platform launcher for Brain-5D.
Usage:
python scripts/brain5d_launcher.py start [options] # Start simulation
python scripts/brain5d_launcher.py stop # Stop all processes
python scripts/brain5d_launcher.py --help # Show help
The launcher starts exactly one Brain-5D application process (src.main),
which owns the simulation, runtime controller, OperatorBridge and dashboard.
Important architecture rule:
src.main owns the dashboard server. The launcher must therefore NOT start
``python -m src.dashboard`` as a second process. Starting a separate
dashboard process would create a second Python memory space without
access to the OperatorBridge.
"""
from __future__ import annotations
import argparse
import csv
import os
import signal
import socket
import subprocess
import sys
import webbrowser
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 8765
PID_FILE = ROOT / "artifacts" / "brain5d.pid"
# ============================================================================
# Helpers
# ============================================================================
def _ensure_artifacts_dir() -> None:
"""Ensure the artifacts directory exists for PID file."""
(ROOT / "artifacts").mkdir(parents=True, exist_ok=True)
def _read_pid() -> int | None:
"""Read the stored PID, or return None if no PID file exists."""
pid_path = PID_FILE
if not pid_path.exists():
return None
try:
return int(pid_path.read_text(encoding="utf-8").strip())
except (ValueError, OSError):
return None
def _write_pid(pid: int) -> None:
"""Write the PID file."""
_ensure_artifacts_dir()
PID_FILE.write_text(str(pid), encoding="utf-8")
def _remove_pid() -> None:
"""Remove the PID file."""
try:
PID_FILE.unlink(missing_ok=True)
except OSError:
pass
def pid_is_running(pid: int) -> bool:
"""Return whether a process with *pid* is currently alive."""
if os.name == "nt":
result = subprocess.run(
["tasklist", "/FI", f"PID eq {pid}", "/FO", "CSV", "/NH"],
capture_output=True,
timeout=10,
)
if result.returncode != 0:
return False
output = result.stdout.decode(errors="replace")
return any(
len(row) > 1 and row[1].strip() == str(pid)
for row in csv.reader(output.splitlines())
)
try:
os.kill(pid, 0)
except OSError:
return False
return True
def port_is_available(host: str, port: int) -> bool:
"""Return whether a TCP listener can bind to the requested address."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
try:
probe.bind((host, port))
except OSError:
return False
return True
def spawn(
command: list[str],
*,
cwd: Path = ROOT,
) -> subprocess.Popen[bytes]:
"""Start one Brain-5D child process with concrete Popen argument types."""
creationflags = 0
if os.name == "nt":
creationflags = subprocess.CREATE_NEW_PROCESS_GROUP
return subprocess.Popen(
command,
cwd=str(cwd),
stdin=subprocess.DEVNULL,
stdout=None,
stderr=None,
shell=False,
creationflags=creationflags,
)
def build_command(args: argparse.Namespace) -> list[str]:
"""Build the single Brain-5D application command.
``src.main`` is the application composition root. It owns:
- NeuralNetwork
- learning engine
- homeostasis engine
- runtime/controller integration
- OperatorBridge
- dashboard state
- dashboard HTTP server
Therefore no independent dashboard process is started here.
"""
command = [
sys.executable,
"-m",
"src.main",
"--config",
str(args.config),
]
if args.observe:
command.append("--observe")
if args.benchmark:
command.append("--benchmark")
if args.no_learning:
command.append("--no-learning")
if args.no_homeostasis:
command.append("--no-homeostasis")
if args.ticks is not None:
command.extend(["--ticks", str(args.ticks)])
# src.main starts its integrated dashboard by default.
# Only explicitly disable it when --dashboard was not requested.
if not args.dashboard:
command.append("--no-dashboard")
else:
command.extend(["--dashboard-host", str(args.host)])
command.extend(["--dashboard-port", str(args.port)])
return command
def dashboard_url(args: argparse.Namespace) -> str:
"""Return the dashboard URL used for browser launch."""
return f"http://{args.host}:{args.port}"
# ============================================================================
# Subcommand: start
# ============================================================================
def add_start_parser(subparsers: Any) -> None:
"""Add the ``start`` subcommand parser."""
parser: argparse.ArgumentParser = subparsers.add_parser(
"start",
help="Start the Brain-5D simulation",
description="Start the Brain-5D simulation with optional dashboard.",
)
parser.set_defaults(func=_cmd_start)
parser.add_argument(
"--dashboard",
action="store_true",
help="Start Brain-5D with the integrated operator dashboard.",
)
parser.add_argument(
"--open-browser",
action="store_true",
help="Open the dashboard in the default browser after startup.",
)
parser.add_argument(
"--host",
default=DEFAULT_HOST,
help=f"Dashboard bind host (default: {DEFAULT_HOST}; use 0.0.0.0 for LAN).",
)
parser.add_argument(
"--port",
type=int,
default=DEFAULT_PORT,
help=f"Dashboard port for browser URL (default: {DEFAULT_PORT}).",
)
parser.add_argument(
"--config",
type=Path,
default=Path("configs/poc_config.yaml"),
help="Brain-5D configuration file.",
)
parser.add_argument(
"--observe",
action="store_true",
help="Enable the observatory.",
)
parser.add_argument(
"--benchmark",
action="store_true",
help="Enable runtime benchmarking.",
)
parser.add_argument(
"--no-learning",
action="store_true",
help="Disable the learning engine.",
)
parser.add_argument(
"--no-homeostasis",
action="store_true",
help="Disable the homeostasis engine.",
)
parser.add_argument(
"--ticks",
type=int,
default=None,
help="Override the configured simulation tick count.",
)
def _cmd_start(args: argparse.Namespace) -> int:
"""Execute the ``start`` subcommand."""
# Validate
if args.port < 1 or args.port > 65535:
print("Error: --port must be in the range 1..65535", file=sys.stderr)
return 1
if args.ticks is not None and args.ticks < 1:
print("Error: --ticks must be greater than zero", file=sys.stderr)
return 1
if args.open_browser and not args.dashboard:
print("Error: --open-browser requires --dashboard", file=sys.stderr)
return 1
if args.dashboard:
if not args.host.strip():
print("Error: --host must not be empty", file=sys.stderr)
return 1
# Check if already running
existing_pid = _read_pid()
if existing_pid is not None:
if pid_is_running(existing_pid):
print(
f"Error: Brain-5D is already running (PID {existing_pid}).",
file=sys.stderr,
)
return 1
_remove_pid()
if args.dashboard and not port_is_available(args.host, args.port):
print(
f"Error: dashboard address {args.host}:{args.port} is already in use.",
file=sys.stderr,
)
return 1
command = build_command(args)
try:
process = spawn(command)
except OSError as exc:
print(
f"Failed to start Brain-5D: {type(exc).__name__}: {exc}",
file=sys.stderr,
)
return 1
_write_pid(process.pid)
print(f"Brain-5D started (PID {process.pid})")
print(f" Command: {' '.join(command)}")
if args.dashboard:
url = dashboard_url(args)
print(f" Dashboard bind: {url}")
browser_url = (
f"http://{DEFAULT_HOST}:{args.port}"
if args.host in {"0.0.0.0", "::"}
else url
)
print(f" Dashboard local: {browser_url}")
if args.open_browser:
try:
webbrowser.open(browser_url)
except webbrowser.Error as exc:
print(
f" Warning: could not open browser: {exc}",
file=sys.stderr,
)
return 0
# ============================================================================
# Subcommand: stop
# ============================================================================
def add_stop_parser(subparsers: Any) -> None:
"""Add the ``stop`` subcommand parser."""
parser: argparse.ArgumentParser = subparsers.add_parser(
"stop",
help="Stop the Brain-5D simulation",
description="Stop the running Brain-5D simulation process.",
)
parser.set_defaults(func=_cmd_stop)
def _cmd_stop(_args: argparse.Namespace) -> int:
"""Execute the ``stop`` subcommand."""
pid = _read_pid()
if pid is None:
print("No Brain-5D process found (no PID file).", file=sys.stderr)
return 1
if not pid_is_running(pid):
print(f"Brain-5D process {pid} not found (already exited).")
_remove_pid()
return 0
try:
if os.name == "nt":
result = subprocess.run(
["taskkill", "/PID", str(pid), "/T", "/F"],
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
timeout=15,
)
if result.returncode != 0:
message = result.stderr.decode(errors="replace").strip()
raise OSError(message or f"taskkill exited with {result.returncode}")
else:
os.kill(pid, signal.SIGTERM)
print(f"Brain-5D process {pid} stopped.")
_remove_pid()
return 0
except ProcessLookupError:
print(f"Brain-5D process {pid} not found (already exited).")
_remove_pid()
return 0
except OSError as exc:
print(f"Failed to stop Brain-5D process {pid}: {exc}", file=sys.stderr)
return 1
# ============================================================================
# Entry point
# ============================================================================
def main() -> int:
"""Parse arguments and dispatch to the appropriate subcommand."""
parser = argparse.ArgumentParser(
description="Brain-5D application launcher",
)
subparsers = parser.add_subparsers(
dest="command",
title="commands",
description="Available commands. Use 'start' to run, 'stop' to terminate.",
)
add_start_parser(subparsers)
add_stop_parser(subparsers)
# Default: if no subcommand given, show help
if len(sys.argv) < 2:
parser.print_help()
return 0
args = parser.parse_args()
if hasattr(args, "func"):
return args.func(args)
parser.print_help()
return 0
if __name__ == "__main__":
raise SystemExit(main())
|