diff --git a/eco/_smoketest_scope.py b/eco/_smoketest_scope.py new file mode 100644 index 0000000..ac7dc3e --- /dev/null +++ b/eco/_smoketest_scope.py @@ -0,0 +1,8 @@ +"""Throwaway scope module for smoke-testing scripts/eco-box-server end to +end (real subprocess, real network, real box listener) - not part of the +package's public surface, deleted after the smoke test.""" +from eco.elements.adjustable import DummyAdjustable +from eco.utilities.config import Namespace + +namespace = Namespace(name="smoketest") +namespace.append_obj(DummyAdjustable, name="theta", module_name=None) diff --git a/eco/manual_control/box_server.py b/eco/manual_control/box_server.py new file mode 100644 index 0000000..d958f1c --- /dev/null +++ b/eco/manual_control/box_server.py @@ -0,0 +1,292 @@ +"""A small background service that holds this console's connection to the +physical manual-control box, so driving it does not require an interactive +eco session left open. + +Mirrors eco.status_server's shape (a Flask app with /health plus /admin/* +actions, bound immediately, run with ``make_server`` so a restart can hand +the port back cleanly) but is much lighter: there is no namespace init to +run in the background - the box only touches components it is actually +walked into (see eco.manual_control.control_box's manual), so importing the +scope and connecting to the box are both fast. + +Run with: + + python -m eco.manual_control.box_server --scope bernina + +or via the wrapper script (``eco-box-server``, mirroring +``eco-status-server``), or from a checkout with ``eco-dev box-server -s +bernina`` for quick local testing against uncommitted device changes. + +Endpoints: + GET /health state, whether the box is connected, why not + POST /admin/disconnect release the box now (it falls back to its + waiting screen) - the safety button + POST /admin/reconnect offer this session to the box again - the + operator at the box has to accept it, same as + any other session (no special privilege here) + POST /admin/restart re-exec the whole process, so a device module + edited since this process started is picked up + (Python does not re-read a module it already + imported) - same trade-off/mechanism as + eco.status_server's /admin/restart +""" + +from __future__ import annotations + +import argparse +import importlib +import logging +import os +import signal +import sys +import time + +logger = logging.getLogger(__name__) + +DEFAULT_ADMIN_HOST = "0.0.0.0" +DEFAULT_ADMIN_PORT = 8092 + + +def _process_stats(): + """Cheap self-measurements for /health: CPU seconds, resident memory and + thread count, straight from /proc. Mirrors + eco.status_server.namespace_server._process_stats (kept as its own small + copy rather than imported - box_server has no other reason to import + status_server, and this is 15 lines of stdlib, not shared state). + Silently empty where /proc is not Linux's. + """ + try: + with open("/proc/self/stat") as f: + fields = f.read().rsplit(") ", 1)[1].split() + ticks = os.sysconf("SC_CLK_TCK") + utime, stime = int(fields[11]) / ticks, int(fields[12]) / ticks + num_threads = int(fields[17]) + with open("/proc/self/statm") as f: + rss_pages = int(f.read().split()[1]) + return { + "cpu_seconds": utime + stime, + "rss_mb": rss_pages * os.sysconf("SC_PAGE_SIZE") / 1e6, + "n_threads": num_threads, + } + except Exception: + return {} + + +def _restart_argv(): + """The argv to re-exec this process with - see + eco.status_server.namespace_server._restart_argv for why the ``-m`` + form has to be reconstructed rather than just re-using sys.argv[0].""" + spec = getattr(sys.modules.get("__main__"), "__spec__", None) + if spec is not None and getattr(spec, "name", None): + module = spec.parent or spec.name + return [sys.executable, "-m", module] + sys.argv[1:] + return [sys.executable] + sys.argv + + +def _make_server(app, host, port, attempts=15, delay=1.0): + """Bind the WSGI server, retrying a briefly-occupied port - identical + reasoning to eco.status_server.__main__._make_server (a restart's + re-exec can race the old process's socket finishing its close).""" + from werkzeug.serving import make_server + + last = None + for attempt in range(attempts): + try: + return make_server(host, port, app, threaded=True) + except OSError as exc: + last = exc + logger.warning("could not bind %s:%s (%s); retry %d/%d", + host, port, exc, attempt + 1, attempts) + time.sleep(delay) + raise last + + +class BoxServerState: + """Tracks the connection across sessions, since + Namespace.stop_eco_control_box() clears its own bookkeeping (by design - + a fresh interactive .start() should not see a stale session) but /health + should still be able to say why the last connection ended.""" + + def __init__(self, namespace, box_host, box_port, token, token_file): + self.namespace = namespace + self.box_host = box_host + self.box_port = box_port + self.token = token + self.token_file = token_file + self.state = "idle" + self.reason = None + + def _session(self): + return getattr(self.namespace, "_control_box_server", None) + + def _remember(self): + session = self._session() + if session is not None: + self.state = session.state + self.reason = session.reason + + def connect(self): + self.namespace.start_eco_control_box( + box_host=self.box_host, port=self.box_port, + token=self.token, token_file=self.token_file, + ) + self._remember() + + def disconnect(self): + self._remember() # capture state before stop() clears it + self.namespace.stop_eco_control_box() + session = self._session() + if session is None: # the common case: stop() clears it + self.state, self.reason = "idle", "disconnected (admin request)" + + @property + def connected(self): + session = self._session() + return bool(session is not None and session.connected) + + def body(self): + self._remember() + return { + "state": self.state, + "connected": self.connected, + "reason": self.reason, + "box": f"{self.box_host}:{self.box_port}", + } + + +def create_box_app(namespace, box_state, start_time=None, wsgi_server_holder=None): + """Build the Flask app. Split out from main() so tests can drive it with + Flask's test client, no HTTP socket involved - same shape as + eco.status_server.namespace_server.create_namespace_app. + + wsgi_server_holder: a single-item dict {'server': ...} filled in by the + caller once the WSGI server exists, so /admin/restart can close the + listening socket before re-exec'ing (see _make_server's docstring on + why: werkzeug marks it inheritable, so a re-exec without this closes + over a "port already in use" error against itself). + """ + from flask import Flask, jsonify, request + + start_time = start_time if start_time is not None else time.time() + wsgi_server_holder = wsgi_server_holder if wsgi_server_holder is not None else {} + + app = Flask("eco-box-server") + + def _health_body(): + return { + "status": "ok", + "namespace": getattr(namespace, "name", None), + "pid": os.getpid(), + "uptime_s": time.time() - start_time, + **_process_stats(), + **box_state.body(), + } + + @app.get("/health") + def health(): + return jsonify(_health_body()) + + @app.post("/admin/disconnect") + def admin_disconnect(): + box_state.disconnect() + return jsonify({**_health_body(), "message": "disconnected from the box"}) + + @app.post("/admin/reconnect") + def admin_reconnect(): + box_state.connect() + return jsonify({**_health_body(), + "message": "offered this session to the box; " + "accept it there"}) + + @app.post("/admin/restart") + def admin_restart(): + """Re-exec the whole process - see the module docstring.""" + import threading + + delay = float((request.get_json(force=True, silent=True) or {}).get("delay", 0.5)) + + def _restart(): + time.sleep(delay) # let this response flush first + box_state.disconnect() # leave the box in a clean waiting state + server = wsgi_server_holder.get("server") + if server is not None: + try: + server.server_close() + except Exception: + logger.warning("could not close the listening socket", exc_info=True) + argv = _restart_argv() + logger.warning("restarting process on /admin/restart request: %s", argv) + os.execv(sys.executable, argv) + + threading.Thread(target=_restart, name="restart", daemon=True).start() + return jsonify({**_health_body(), "message": "restarting"}), 202 + + return app + + +def _handle_sigterm(signum, frame): + # Default disposition for SIGTERM is immediate termination with no + # Python-level cleanup; raising here turns it into an ordinary Python + # exception (PEP 475: a syscall interrupted by a handler that raises + # propagates the exception instead of being silently retried), so + # serve_forever() unwinds through the same try/finally as SIGINT. + raise SystemExit(0) + + +def main(argv=None): + parser = argparse.ArgumentParser( + description="Hold this console's connection to the physical " + "manual-control box as a background service.") + parser.add_argument( + "-s", "--scope", required=True, + help="scope/instrument to serve, e.g. bernina (imports eco..namespace)", + ) + parser.add_argument("--box-host", default="ecobox", help="the box to call (default: %(default)s)") + parser.add_argument("--box-port", type=int, default=8791) + parser.add_argument("--token", default=None, help="shared secret (default: read --token-file)") + parser.add_argument("--token-file", default="~/.eco/pendant_token") + parser.add_argument("--host", default=DEFAULT_ADMIN_HOST, + help="admin/health HTTP host (default: %(default)s)") + parser.add_argument("--port", type=int, default=DEFAULT_ADMIN_PORT, + help="admin/health HTTP port (default: %(default)s)") + parser.add_argument("--no-connect", action="store_true", + help="start the admin/health API without offering a " + "session to the box (connect later via " + "/admin/reconnect or the GUI)") + parser.add_argument("--log-level", default="INFO") + args = parser.parse_args(argv) + + logging.basicConfig(level=args.log_level) + if hasattr(signal, "SIGTERM"): + signal.signal(signal.SIGTERM, _handle_sigterm) + + logger.warning("importing eco.%s ...", args.scope) + module = importlib.import_module(f"eco.{args.scope}") + namespace = getattr(module, "namespace") + + box_state = BoxServerState(namespace, args.box_host, args.box_port, + args.token, args.token_file) + wsgi_server_holder = {} + app = create_box_app(namespace, box_state, wsgi_server_holder=wsgi_server_holder) + server = _make_server(app, args.host, args.port) + wsgi_server_holder["server"] = server + + if not args.no_connect: + box_state.connect() + + logger.warning("eco box-server for '%s' -> box %s:%s, admin/health on %s:%s", + args.scope, args.box_host, args.box_port, args.host, args.port) + try: + server.serve_forever() + except (KeyboardInterrupt, SystemExit): + pass + finally: + logger.warning("shutting down - disconnecting from the box") + try: + box_state.disconnect() + except Exception: + logger.exception("error while disconnecting on shutdown") + + +if __name__ == "__main__": + main() diff --git a/eco/manual_control/box_server_client.py b/eco/manual_control/box_server_client.py new file mode 100644 index 0000000..e3cc9c3 --- /dev/null +++ b/eco/manual_control/box_server_client.py @@ -0,0 +1,53 @@ +"""Thin HTTP client for eco.manual_control.box_server. + +Small counterpart to eco.status_server.client.StatusServerClient, kept as +its own tiny module (not a copy of that one) since the surface here is a +few endpoints, not a whole namespace API: + + from eco.manual_control.box_server_client import BoxServerClient + c = BoxServerClient("http://saresb-cons-05:8092") + c.health() + c.disconnect() # the safety button + c.reconnect() # offer a session again; the box operator must accept + c.restart() # re-exec the process to pick up new device code +""" + +from __future__ import annotations + +import requests + + +class BoxServerError(RuntimeError): + pass + + +class BoxServerClient: + def __init__(self, base_url, timeout=10.0): + self.base_url = base_url.rstrip("/") + self.timeout = timeout + + def health(self): + r = requests.get(f"{self.base_url}/health", timeout=self.timeout) + r.raise_for_status() + return r.json() + + def disconnect(self): + """Release the box now - it falls back to its waiting screen.""" + r = requests.post(f"{self.base_url}/admin/disconnect", timeout=self.timeout) + r.raise_for_status() + return r.json() + + def reconnect(self): + """Offer this session to the box again. Same as any other session - + the operator standing at the box still has to accept it.""" + r = requests.post(f"{self.base_url}/admin/reconnect", timeout=self.timeout) + r.raise_for_status() + return r.json() + + def restart(self, delay=0.5): + """Re-exec the server process, so device modules edited since it + started are picked up. Disconnects the box first.""" + r = requests.post(f"{self.base_url}/admin/restart", json={"delay": delay}, + timeout=self.timeout) + r.raise_for_status() + return r.json() diff --git a/eco/manual_control/box_server_gui.py b/eco/manual_control/box_server_gui.py new file mode 100644 index 0000000..6716c1f --- /dev/null +++ b/eco/manual_control/box_server_gui.py @@ -0,0 +1,292 @@ +"""A small Qt window for one eco-box-server: connection state, and buttons +to disconnect (safety), reconnect, or restart the process (to pick up +device code changed since it started). + +Standalone on purpose, same reasoning as eco.status_server.gui: it talks to +the server over plain HTTP (BoxServerClient), so it needs no eco import and +starts in under a second, and can run on a different machine than the +server itself (any console that can reach it over the network). + + python -m eco.manual_control.box_server_gui --url http://saresb-cons-05:8092 + +or ``eco-box-server gui``, which does exactly that, detached. + +All network calls run on a background QThread (_Poller / _ActionWorker) and +report back via Qt signals - never on the GUI thread, so a slow or +unreachable server makes the window go stale instead of freezing. +""" + +from __future__ import annotations + +import argparse +import sys +import time + +from qtpy import QtCore, QtWidgets + +from .box_server_client import BoxServerClient + +POLL_HEALTH_S = 2.0 + +COLOR_OK = "#2e7d32" +COLOR_WARN = "#b26a00" +COLOR_BAD = "#b71c1c" +COLOR_MUTED = "#757575" + +# Mirrors the state strings BoxSession/ControlBox use (remote/serve.py): +# "idle" (never connected / cleanly disconnected), "dialling", "waiting for +# the operator", "connected", "closed" (ended, with a reason). +STATE_COLOR = { + "connected": COLOR_OK, + "waiting for the operator": COLOR_WARN, + "dialling": COLOR_WARN, + "closed": COLOR_BAD, + "idle": COLOR_MUTED, +} + + +def _fmt_duration(s): + if s is None: + return "?" + if s < 120: + return f"{s:.0f}s" + return f"{s/60:.1f}min" + + +class _Poller(QtCore.QThread): + health = QtCore.Signal(dict) + health_failed = QtCore.Signal(str) + + def __init__(self, client: BoxServerClient, parent=None): + super().__init__(parent) + self.client = client + self._stop = False + + def stop(self): + self._stop = True + + def run(self): + while not self._stop: + try: + self.health.emit(self.client.health()) + except Exception as exc: # noqa: BLE001 - reported via signal + self.health_failed.emit(f"{type(exc).__name__}: {exc}") + for _ in range(int(POLL_HEALTH_S * 10)): + if self._stop: + return + self.msleep(100) + + +class _ActionWorker(QtCore.QThread): + """Runs one blocking client call (disconnect/reconnect/restart) off the + GUI thread - these are safety-relevant actions and must not appear to + hang the window while the request is in flight.""" + + finished_ok = QtCore.Signal(dict) + finished_error = QtCore.Signal(str) + + def __init__(self, fn, parent=None): + super().__init__(parent) + self._fn = fn + + def run(self): + try: + result = self._fn() + except Exception as exc: # noqa: BLE001 - reported via signal + self.finished_error.emit(f"{type(exc).__name__}: {exc}") + return + self.finished_ok.emit(result or {}) + + +class BoxServerMonitor(QtWidgets.QWidget): + def __init__(self, base_url: str, parent=None): + super().__init__(parent) + self.base_url = base_url + self.client = BoxServerClient(base_url, timeout=10.0) + self.setWindowTitle(f"eco box server - {base_url}") + self.resize(480, 320) + + self._action_worker = None + self._build_ui() + + self._poller = _Poller(self.client, self) + self._poller.health.connect(self._on_health) + self._poller.health_failed.connect(self._on_health_failed) + self._poller.start() + + # -- UI construction -------------------------------------------------- + + def _build_ui(self): + layout = QtWidgets.QVBoxLayout(self) + + header = QtWidgets.QHBoxLayout() + self.dot = QtWidgets.QLabel("●") + self.dot.setStyleSheet(f"color: {COLOR_MUTED}; font-size: 16px;") + header.addWidget(self.dot) + header.addWidget(QtWidgets.QLabel(f"{self.base_url}")) + header.addStretch(1) + self.updated_label = QtWidgets.QLabel("never updated") + self.updated_label.setStyleSheet(f"color: {COLOR_MUTED};") + header.addWidget(self.updated_label) + layout.addLayout(header) + + self.state_label = QtWidgets.QLabel("-") + f = self.state_label.font() + f.setPointSize(f.pointSize() + 3) + f.setBold(True) + self.state_label.setFont(f) + layout.addWidget(self.state_label) + + self.box_label = QtWidgets.QLabel("box: -") + layout.addWidget(self.box_label) + + self.reason_label = QtWidgets.QLabel("") + self.reason_label.setWordWrap(True) + self.reason_label.setStyleSheet(f"color: {COLOR_MUTED};") + layout.addWidget(self.reason_label) + + grid = QtWidgets.QGridLayout() + self.detail_labels = {} + for i, key in enumerate(("namespace", "pid", "uptime_s", "rss_mb", + "n_threads", "cpu_seconds")): + title = QtWidgets.QLabel(key.replace("_", " ")) + title.setStyleSheet(f"color: {COLOR_MUTED};") + value = QtWidgets.QLabel("-") + grid.addWidget(title, i // 2, (i % 2) * 2) + grid.addWidget(value, i // 2, (i % 2) * 2 + 1) + self.detail_labels[key] = value + layout.addLayout(grid) + + buttons = QtWidgets.QHBoxLayout() + self.btn_disconnect = QtWidgets.QPushButton("Disconnect") + self.btn_disconnect.setToolTip( + "Release the box now - it falls back to its waiting screen. " + "Use this to hand it to someone else, or if something looks wrong.") + self.btn_reconnect = QtWidgets.QPushButton("Reconnect") + self.btn_reconnect.setToolTip( + "Offer this session to the box again - the operator standing " + "at the box still has to accept it, same as any first connection.") + self.btn_restart = QtWidgets.QPushButton("Restart process") + self.btn_restart.setToolTip( + "Re-exec the whole server process, so any device code changed " + "since it started is picked up. Disconnects the box first.") + self.btn_disconnect.clicked.connect(self._confirm_disconnect) + self.btn_reconnect.clicked.connect(lambda: self._run_action( + "reconnect", self.client.reconnect)) + self.btn_restart.clicked.connect(self._confirm_restart) + for b in (self.btn_disconnect, self.btn_reconnect, self.btn_restart): + buttons.addWidget(b) + buttons.addStretch(1) + layout.addLayout(buttons) + + self.action_status = QtWidgets.QLabel("") + self.action_status.setStyleSheet(f"color: {COLOR_MUTED};") + layout.addWidget(self.action_status) + layout.addStretch(1) + + # -- polling callbacks ------------------------------------------------- + + def _on_health(self, h: dict): + self.updated_label.setText(time.strftime("updated %H:%M:%S")) + self.dot.setStyleSheet(f"color: {COLOR_OK}; font-size: 16px;") + + state = h.get("state", "?") + connected = h.get("connected") + label = state + (" (box connected)" if connected else "") + self.state_label.setText(label) + self.state_label.setStyleSheet(f"color: {STATE_COLOR.get(state, COLOR_MUTED)};") + self.box_label.setText(f"box: {h.get('box', '-')}") + self.reason_label.setText(h.get("reason") or "") + + for key, w in self.detail_labels.items(): + v = h.get(key) + if key == "rss_mb" and v is not None: + w.setText(f"{v:.0f} MB") + elif key in ("cpu_seconds", "uptime_s") and v is not None: + w.setText(_fmt_duration(v)) + else: + w.setText("-" if v is None else str(v)) + + busy = self._action_worker is not None + self.btn_disconnect.setEnabled(not busy and bool(connected)) + self.btn_reconnect.setEnabled(not busy and not connected) + self.btn_restart.setEnabled(not busy) + + def _on_health_failed(self, message: str): + self.dot.setStyleSheet(f"color: {COLOR_BAD}; font-size: 16px;") + self.updated_label.setText(f"unreachable: {message}") + + # -- actions ------------------------------------------------------------ + + def _confirm_disconnect(self): + if QtWidgets.QMessageBox.question( + self, "Disconnect the box?", + "This releases the box immediately - it goes back to its " + "waiting screen and nobody can drive it until a session " + "connects again.\n\nDisconnect now?", + ) == QtWidgets.QMessageBox.Yes: + self._run_action("disconnect", self.client.disconnect) + + def _confirm_restart(self): + if QtWidgets.QMessageBox.question( + self, "Restart the box server?", + "This disconnects the box and restarts the whole server " + "process to pick up device code changes. The box will show " + "its waiting screen until this session reconnects and the " + "operator accepts it again.\n\nRestart now?", + ) == QtWidgets.QMessageBox.Yes: + self._run_action("restart", self.client.restart) + + def _run_action(self, name, fn): + if self._action_worker is not None: + return + self.action_status.setText(f"{name} requested ...") + self.action_status.setStyleSheet(f"color: {COLOR_WARN};") + self._action_worker = _ActionWorker(fn, self) + self._action_worker.finished_ok.connect( + lambda result: self._on_action_done(name, result)) + self._action_worker.finished_error.connect( + lambda message: self._on_action_error(name, message)) + self._action_worker.start() + + def _on_action_done(self, name, result): + self._action_worker = None + self.action_status.setText(result.get("message") or f"{name} done") + self.action_status.setStyleSheet(f"color: {COLOR_OK};") + + def _on_action_error(self, name, message): + self._action_worker = None + self.action_status.setText(f"{name} failed: {message}") + self.action_status.setStyleSheet(f"color: {COLOR_BAD};") + + def closeEvent(self, event): + # Same reasoning as StatusServerMonitor.closeEvent: destroying a + # QThread mid-request is a hard crash, and an action here can be + # mid-flight (an unreachable server, bounded by client.timeout), so + # the window briefly refuses to close rather than risk it. + if self._action_worker is not None and self._action_worker.isRunning(): + self.action_status.setText("cannot close: an action is still in flight") + self.action_status.setStyleSheet(f"color: {COLOR_BAD};") + event.ignore() + return + self._poller.stop() + self._poller.wait(2000) + super().closeEvent(event) + + +def main(argv=None): + parser = argparse.ArgumentParser( + description="Qt monitor/control panel for one eco.manual_control.box_server" + ) + parser.add_argument("--url", required=True, + help="server base URL, e.g. http://saresb-cons-05:8092") + args = parser.parse_args(argv) + + app = QtWidgets.QApplication.instance() or QtWidgets.QApplication(sys.argv) + win = BoxServerMonitor(args.url) + win.show() + return app.exec_() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/eco-box-server b/scripts/eco-box-server new file mode 100755 index 0000000..20fd9e7 --- /dev/null +++ b/scripts/eco-box-server @@ -0,0 +1,232 @@ +#!/bin/bash +# eco manual-control box server - start/stop/status/gui wrapper. +# +# Mirrors scripts/eco-status-server closely (same start/stop/status/logs/gui +# shape, same env-var-overridable everything, same systemd-ownership guard); +# see that script for the full reasoning behind each piece. The service +# itself is much lighter, though: it holds one TCP connection to the +# physical control box (eco.manual_control.box_server) rather than a whole +# initialized namespace, so there is no minutes-long init to wait for. +# +# Canonical copy lives in the eco repo at scripts/, alongside eco-dev and +# eco-status-server; /sf/bernina/bin/eco-box-server is a symlink to this +# file, so editing the checkout takes effect immediately. +# +# Runs in the FOREGROUND by default, which is what systemd's Type=simple +# wants. Use `-b` to detach for interactive use. +# +# ECO_BOX_SERVER_CHECKOUT eco checkout to run (prepended to PYTHONPATH) +# ECO_BOX_SERVER_SCOPE -s/--scope passed to the server (e.g. bernina) +# ECO_BOX_SERVER_BOX_HOST the physical box to call (default: ecobox) +# ECO_BOX_SERVER_BOX_PORT port the box listens on (default: 8791) +# ECO_BOX_SERVER_TOKEN_FILE shared token file (default: ~/.eco/pendant_token) +# ECO_BOX_SERVER_HOST admin/health HTTP bind address (default: 0.0.0.0) +# ECO_BOX_SERVER_PORT admin/health HTTP port (default: 8092) +# ECO_BOX_SERVER_PYTHON interpreter (needs eco's full dependency set) +# ECO_BOX_SERVER_URL what `status`/`disconnect`/`reconnect`/`gui` talk to +# ECO_BOX_SERVER_LOG log file used by -b +# +# A file at /sf/bernina/config/eco_box_server/env (or $ECO_BOX_SERVER_ENV) +# is sourced first if it exists, so a site can set those in one place. +set -euo pipefail + +ENV_FILE="${ECO_BOX_SERVER_ENV:-/sf/bernina/config/eco_box_server/env}" +# shellcheck source=/dev/null +[ -r "$ENV_FILE" ] && . "$ENV_FILE" + +CHECKOUT="${ECO_BOX_SERVER_CHECKOUT:-/sf/bernina/code/gac-bernina/eco}" +SCOPE="${ECO_BOX_SERVER_SCOPE:-bernina}" +BOX_HOST="${ECO_BOX_SERVER_BOX_HOST:-ecobox}" +BOX_PORT="${ECO_BOX_SERVER_BOX_PORT:-8791}" +TOKEN_FILE="${ECO_BOX_SERVER_TOKEN_FILE:-~/.eco/pendant_token}" +BIND_HOST="${ECO_BOX_SERVER_HOST:-0.0.0.0}" +BIND_PORT="${ECO_BOX_SERVER_PORT:-8092}" +PYTHON="${ECO_BOX_SERVER_PYTHON:-/sf/bernina/applications/python/.pixi/envs/bpy312/bin/python}" +URL="${ECO_BOX_SERVER_URL:-http://$(hostname -s):$BIND_PORT}" +LOG="${ECO_BOX_SERVER_LOG:-$HOME/.eco/box_server_$(hostname -s).log}" + +# Matches only the running server, never this script or an ssh command line +# that mentions it (the bracket keeps the pattern from matching itself). +PGREP_PATTERN='[e]co\.manual_control\.box_server' + +usage() { + cat < [options] + + start [-b] [-- ] run the server (foreground; -b to detach) + stop stop the running server on this host + restart stop, then start detached + status query \$URL/health + disconnect release the box now (the safety button) + reconnect offer this session to the box again + (the operator at the box must accept it) + logs [-f] show the detached-mode log + gui launch the Qt monitor/control panel (detached) + config print the resolved configuration + +Environment (current values): + ECO_BOX_SERVER_CHECKOUT=$CHECKOUT + ECO_BOX_SERVER_SCOPE=$SCOPE + ECO_BOX_SERVER_BOX_HOST=$BOX_HOST + ECO_BOX_SERVER_BOX_PORT=$BOX_PORT + ECO_BOX_SERVER_TOKEN_FILE=$TOKEN_FILE + ECO_BOX_SERVER_HOST=$BIND_HOST + ECO_BOX_SERVER_PORT=$BIND_PORT + ECO_BOX_SERVER_PYTHON=$PYTHON + ECO_BOX_SERVER_URL=$URL + ECO_BOX_SERVER_LOG=$LOG +EOF +} + +die() { echo "$(basename "$0"): $*" >&2; exit 1; } + +check_prereqs() { + [ -d "$CHECKOUT/eco" ] || die "no eco checkout at $CHECKOUT (set ECO_BOX_SERVER_CHECKOUT)" + [ -x "$PYTHON" ] || die "no interpreter at $PYTHON (set ECO_BOX_SERVER_PYTHON)" +} + +server_pid() { pgrep -f "$PGREP_PATTERN" | head -1; } + +# Is this host's server owned by the systemd user service? Same reasoning +# as eco-status-server's managed_by_systemd - see that script. +managed_by_systemd() { + [ -n "${INVOCATION_ID:-}" ] && return 1 + command -v systemctl >/dev/null 2>&1 || return 1 + case "$(systemctl --user is-active eco-box-server 2>/dev/null)" in + active|activating|reloading) return 0 ;; + *) return 1 ;; + esac +} + +server_owner() { + local pid="$1" + [ -n "$pid" ] && ps -o user= -p "$pid" 2>/dev/null | tr -d ' ' +} + +cmd_start() { + local background=0 + if [ "${1:-}" = "-b" ] || [ "${1:-}" = "--background" ]; then background=1; shift; fi + [ "${1:-}" = "--" ] && shift + if managed_by_systemd; then + die "the systemd user service is running this host's server; use + systemctl --user restart eco-box-server +(or 'systemctl --user stop' it first if you really want to run it by hand)" + fi + check_prereqs + local pid; pid="$(server_pid || true)" + if [ -n "$pid" ]; then + local owner; owner="$(server_owner "$pid")" + die "already running (pid $pid, user ${owner:-unknown}); use 'restart' or 'stop' first" + fi + + export PYTHONPATH="$CHECKOUT${PYTHONPATH:+:$PYTHONPATH}" + local args=(-s "$SCOPE" --box-host "$BOX_HOST" --box-port "$BOX_PORT" + --token-file "$TOKEN_FILE" --host "$BIND_HOST" --port "$BIND_PORT") + if [ "$background" -eq 1 ]; then + mkdir -p "$(dirname "$LOG")" + # >"$LOG" 2>&1 & + echo "started pid $! -> $LOG" + else + exec "$PYTHON" -u -m eco.manual_control.box_server "${args[@]}" "$@" /dev/null || { echo "stopped (was pid $pid)"; return 0; } + done + die "pid $pid did not exit after 30 s" +} + +cmd_status() { + local pid; pid="$(server_pid || true)" + if [ -n "$pid" ]; then + local owner; owner="$(server_owner "$pid")" + local managed="unmanaged" + managed_by_systemd && managed="systemd user service" + echo "process: running, pid $pid, user ${owner:-unknown} ($managed)" + else + echo "process: not running on $(hostname -s)" + fi + "$PYTHON" - "$URL" <<'PYEOF' || true +import json, sys, urllib.request + +url = sys.argv[1].rstrip("/") + "/health" +try: + with urllib.request.urlopen(url, timeout=10) as r: + h = json.load(r) +except Exception as exc: + print("health: no answer from %s (%s)" % (url, exc)) + raise SystemExit(1) + +connected = " - box CONNECTED" if h.get("connected") else "" +print(f"state: {h['state']}{connected}") +if h.get("reason"): + print(f"reason: {h['reason']}") +print(f"box: {h.get('box')}") +print(f"process: pid {h.get('pid')}, up {h.get('uptime_s', 0)/60:.1f} min, " + f"{h.get('rss_mb') or 0:.0f} MB, {h.get('n_threads')} threads") +PYEOF +} + +cmd_disconnect() { + "$PYTHON" - "$URL" <<'PYEOF' +import json, sys, urllib.request +req = urllib.request.Request(sys.argv[1].rstrip("/") + "/admin/disconnect", method="POST") +with urllib.request.urlopen(req, timeout=10) as r: + print(json.load(r).get("message", "disconnected")) +PYEOF +} + +cmd_reconnect() { + "$PYTHON" - "$URL" <<'PYEOF' +import json, sys, urllib.request +req = urllib.request.Request(sys.argv[1].rstrip("/") + "/admin/reconnect", method="POST") +with urllib.request.urlopen(req, timeout=10) as r: + print(json.load(r).get("message", "reconnecting")) +PYEOF +} + +cmd_gui() { + check_prereqs + export PYTHONPATH="$CHECKOUT${PYTHONPATH:+:$PYTHONPATH}" + nohup "$PYTHON" -m eco.manual_control.box_server_gui --url "$URL" "$@" \ + /dev/null 2>&1 & + disown + echo "launched (pid $!)" +} + +case "${1:-}" in + start) shift; cmd_start "$@" ;; + stop) cmd_stop ;; + restart) + if managed_by_systemd; then + echo "restarting via systemd" + systemctl --user restart eco-box-server + else + cmd_stop; shift; cmd_start -b "$@" + fi ;; + status) cmd_status ;; + disconnect) cmd_disconnect ;; + reconnect) cmd_reconnect ;; + logs) shift; [ "${1:-}" = "-f" ] && tail -f "$LOG" || tail -n 100 "$LOG" ;; + gui) shift; cmd_gui "$@" ;; + config) usage ;; + ""|-h|--help|help) usage ;; + *) usage; exit 2 ;; +esac diff --git a/tests/test_box_server.py b/tests/test_box_server.py new file mode 100644 index 0000000..b7e11e9 --- /dev/null +++ b/tests/test_box_server.py @@ -0,0 +1,240 @@ +"""Tests for eco.manual_control.box_server: the background service that +holds a console's connection to the physical control box. + +Uses the Flask test client (no HTTP socket) against a real BoxListener on +loopback, exactly like tests/test_manual_control_box.py's own link tests - +the box side is real, only the socket the test client talks to is faked by +Flask. +""" + +import threading +import time + +import pytest + +flask = pytest.importorskip("flask") + +from eco.manual_control.box_server import BoxServerState, create_box_app +from eco.manual_control.demo import build_fake_beamline +from eco.manual_control.remote.box_link import BoxListener +from eco.manual_control.remote.client import RemoteControlClient +from eco.utilities.config import Namespace + +TOKEN = "box-server-test-token" + + +def _listener(port, token=TOKEN): + return BoxListener(port=port, token=token, bind="127.0.0.1") + + +def _next_request(listener, timeout=5.0): + deadline = time.time() + timeout + while time.time() < deadline: + request = listener.pending() + if request is not None: + return request + time.sleep(0.02) + return None + + +def _wait(predicate, timeout=5.0): + deadline = time.time() + timeout + while time.time() < deadline: + if predicate(): + return True + time.sleep(0.02) + return False + + +def _fresh_namespace(): + from eco.elements.adjustable import DummyAdjustable + + ns = Namespace(name="bernina_test") + ns.append_obj(DummyAdjustable, name="theta", module_name=None) + return ns + + +def test_health_before_any_connection_reports_idle(): + ns = _fresh_namespace() + state = BoxServerState(ns, "127.0.0.1", 8760, TOKEN, None) + app = create_box_app(ns, state) + resp = app.test_client().get("/health") + body = resp.get_json() + assert resp.status_code == 200 + assert body["state"] == "idle" + assert body["connected"] is False + assert body["namespace"] == "bernina_test" + assert body["box"] == "127.0.0.1:8760" + + +def test_health_reflects_a_real_accepted_connection(): + listener = _listener(8759) + ns = _fresh_namespace() + state = BoxServerState(ns, "127.0.0.1", 8759, TOKEN, None) + app = create_box_app(ns, state) + client = app.test_client() + try: + resp = client.get("/health") + assert resp.get_json()["state"] == "idle" + + state.connect() # what main() does at startup + assert _wait(lambda: state._session() is not None) + assert _wait(lambda: state._session().state == "waiting for the operator") + assert client.get("/health").get_json()["state"] == "waiting for the operator" + + request = _next_request(listener) + assert request is not None + box_client = RemoteControlClient(request.accept()).start() + assert _wait(lambda: bool(box_client.entries)) + assert _wait(lambda: state.connected) + + body = client.get("/health").get_json() + assert body["state"] == "connected" + assert body["connected"] is True + finally: + ns.stop_eco_control_box() + listener.close() + + +def test_admin_disconnect_releases_the_box_and_it_is_reported(): + """The safety button: /admin/disconnect must actually drop the link, and + the box side must notice (fall back to waiting), not just the console.""" + listener = _listener(8758) + ns = _fresh_namespace() + state = BoxServerState(ns, "127.0.0.1", 8758, TOKEN, None) + app = create_box_app(ns, state) + client = app.test_client() + try: + state.connect() + request = _next_request(listener) + box_client = RemoteControlClient(request.accept()).start() + assert _wait(lambda: bool(box_client.entries)) + assert _wait(lambda: state.connected) + + resp = client.post("/admin/disconnect") + body = resp.get_json() + assert resp.status_code == 200 + assert body["connected"] is False + assert "disconnect" in body["message"] + + # the box side must see this too, not just the console bookkeeping + assert _wait(lambda: not box_client.connected), \ + "the box was not told the session disconnected" + + # health afterwards still reflects "not connected", not a crash + assert client.get("/health").get_json()["connected"] is False + finally: + ns.stop_eco_control_box() + listener.close() + + +def test_admin_reconnect_offers_a_new_session_that_the_box_can_accept(): + listener = _listener(8757) + ns = _fresh_namespace() + state = BoxServerState(ns, "127.0.0.1", 8757, TOKEN, None) + app = create_box_app(ns, state) + client = app.test_client() + try: + # nothing connected yet - /admin/reconnect must offer a session + resp = client.post("/admin/reconnect") + assert resp.get_json()["state"] in ("dialling", "waiting for the operator") + + request = _next_request(listener) + assert request is not None, "/admin/reconnect did not call the box" + box_client = RemoteControlClient(request.accept()).start() + assert _wait(lambda: bool(box_client.entries)) + assert _wait(lambda: state.connected) + finally: + ns.stop_eco_control_box() + listener.close() + + +def test_admin_reconnect_is_idempotent_while_already_connecting(): + """Calling reconnect twice in a row must not open two competing sessions + - Namespace.start_eco_control_box() is already idempotent; this checks + box_server does not bypass that.""" + listener = _listener(8756) + ns = _fresh_namespace() + state = BoxServerState(ns, "127.0.0.1", 8756, TOKEN, None) + app = create_box_app(ns, state) + client = app.test_client() + try: + client.post("/admin/reconnect") + first_session = ns._control_box_server + client.post("/admin/reconnect") + assert ns._control_box_server is first_session + finally: + ns.stop_eco_control_box() + listener.close() + + +def test_admin_restart_disconnects_then_execs(monkeypatch): + """Mirrors test_status_server.py's restart test: the listening socket + must be closed before os.execv (werkzeug marks it inheritable), and - + unlike the plain status server - the box must be told to disconnect + first, so a restarted process does not leave the box thinking it is + still connected to a session that is about to vanish.""" + import types + + from eco.manual_control import box_server as box_server_mod + + listener = _listener(8755) + ns = _fresh_namespace() + state = BoxServerState(ns, "127.0.0.1", 8755, TOKEN, None) + holder = {} + app = create_box_app(ns, state, wsgi_server_holder=holder) + client = app.test_client() + try: + state.connect() + request = _next_request(listener) + box_client = RemoteControlClient(request.accept()).start() + assert _wait(lambda: bool(box_client.entries)) + assert _wait(lambda: state.connected) + + closed = [] + execd = [] + holder["server"] = types.SimpleNamespace(server_close=lambda: closed.append(True)) + monkeypatch.setattr(box_server_mod.os, "execv", lambda exe, argv: execd.append(argv)) + monkeypatch.setattr(box_server_mod.time, "sleep", lambda s: None) + + resp = client.post("/admin/restart", json={"delay": 0}) + assert resp.status_code == 202 + + assert _wait(lambda: bool(execd), timeout=5) + assert closed == [True] + assert _wait(lambda: not box_client.connected), \ + "restart must disconnect the box before re-exec'ing" + finally: + ns.stop_eco_control_box() + listener.close() + + +def test_health_survives_no_control_box_attribute_yet(): + """A namespace that has never called start/stop_eco_control_box (the + attribute genuinely does not exist) must not crash /health.""" + ns = _fresh_namespace() + assert not hasattr(ns, "_control_box_server") + state = BoxServerState(ns, "127.0.0.1", 8754, TOKEN, None) + app = create_box_app(ns, state) + body = app.test_client().get("/health").get_json() + assert body["state"] == "idle" + assert body["connected"] is False + + +def test_restart_argv_reconstructs_module_invocation(monkeypatch): + """Same reasoning/test shape as status_server's equivalent: running the + __main__.py file directly breaks relative imports, so a re-exec must use + `-m eco.manual_control.box_server`, not sys.argv[0] verbatim.""" + import sys + import types + + from eco.manual_control import box_server as box_server_mod + + fake_main = types.ModuleType("__main__") + fake_main.__spec__ = types.SimpleNamespace(name="eco.manual_control.box_server", + parent="eco.manual_control.box_server") + monkeypatch.setitem(sys.modules, "__main__", fake_main) + monkeypatch.setattr(sys, "argv", ["box_server.py", "-s", "bernina"]) + argv = box_server_mod._restart_argv() + assert argv[:3] == [sys.executable, "-m", "eco.manual_control.box_server"] + assert argv[3:] == ["-s", "bernina"] diff --git a/tests/test_box_server_gui.py b/tests/test_box_server_gui.py new file mode 100644 index 0000000..e6d253f --- /dev/null +++ b/tests/test_box_server_gui.py @@ -0,0 +1,201 @@ +"""eco.manual_control.box_server_gui: the display/action logic, driven +directly (no real poller thread, no real HTTP server) - same testing shape +as tests/test_status_server_gui.py.""" + +import pytest + +pytest.importorskip("qtpy") + +from qtpy import QtWidgets + +from eco.manual_control.box_server_gui import COLOR_BAD, COLOR_OK, COLOR_WARN, BoxServerMonitor + + +@pytest.fixture(scope="module") +def qapp(): + return QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) + + +@pytest.fixture +def win(qapp, monkeypatch): + from eco.manual_control import box_server_gui as gui_module + + # Never let the real background poller touch the network during a test. + monkeypatch.setattr(gui_module._Poller, "start", lambda self: None) + w = BoxServerMonitor("http://fake-host:8092") + yield w + w._poller.stop() + + +def _health(**overrides): + h = { + "state": "connected", "connected": True, "reason": None, + "box": "ecobox:8791", "namespace": "bernina", "pid": 12345, + "uptime_s": 90.0, "rss_mb": 150.0, "n_threads": 8, "cpu_seconds": 5.0, + } + h.update(overrides) + return h + + +# -------------------------------------------------------------------------- +# health rendering + + +def test_connected_state_is_shown_in_ok_color(win): + win._on_health(_health()) + assert "connected" in win.state_label.text() + assert "box connected" in win.state_label.text() + assert COLOR_OK in win.state_label.styleSheet() + + +def test_idle_state_shown_muted_with_no_box_connected_suffix(win): + win._on_health(_health(state="idle", connected=False)) + assert "box connected" not in win.state_label.text() + + +def test_waiting_for_operator_shown_in_warn_color(win): + win._on_health(_health(state="waiting for the operator", connected=False)) + assert COLOR_WARN in win.state_label.styleSheet() + + +def test_closed_reason_is_displayed(win): + win._on_health(_health(state="closed", connected=False, + reason="the box was handed to lemke_h@saresc-cons-05")) + assert "handed to" in win.reason_label.text() + + +def test_detail_labels_are_populated(win): + win._on_health(_health(rss_mb=256.0, n_threads=12, pid=999)) + assert "256" in win.detail_labels["rss_mb"].text() + assert win.detail_labels["n_threads"].text() == "12" + assert win.detail_labels["pid"].text() == "999" + + +def test_health_failed_marks_the_dot_red_and_shows_the_error(win): + win._on_health_failed("ConnectionError: refused") + assert COLOR_BAD in win.dot.styleSheet() + assert "refused" in win.updated_label.text() + + +# -------------------------------------------------------------------------- +# button enablement follows connection state + + +def test_buttons_enabled_state_follows_connection(win): + win._on_health(_health(connected=True)) + assert win.btn_disconnect.isEnabled() + assert not win.btn_reconnect.isEnabled() + + win._on_health(_health(connected=False, state="idle")) + assert not win.btn_disconnect.isEnabled() + assert win.btn_reconnect.isEnabled() + + # restart is always available regardless of connection state + assert win.btn_restart.isEnabled() + + +def test_buttons_disabled_while_an_action_is_in_flight(win): + win._on_health(_health(connected=True)) + win._action_worker = object() # anything non-None + win._on_health(_health(connected=True)) + assert not win.btn_disconnect.isEnabled() + assert not win.btn_restart.isEnabled() + win._action_worker = None + + +# -------------------------------------------------------------------------- +# actions: run synchronously, bypassing the worker thread + + +def test_run_action_reports_success(win): + calls = [] + + def fake_disconnect(): + calls.append(1) + return {"message": "disconnected from the box"} + + win._on_action_done("disconnect", fake_disconnect()) + assert calls == [1] + assert "disconnected" in win.action_status.text() + assert COLOR_OK in win.action_status.styleSheet() + assert win._action_worker is None + + +def test_run_action_reports_failure(win): + win._on_action_error("restart", "ConnectionError: refused") + assert "restart failed" in win.action_status.text() + assert COLOR_BAD in win.action_status.styleSheet() + assert win._action_worker is None + + +def test_run_action_is_a_no_op_while_one_is_already_running(win, monkeypatch): + from eco.manual_control import box_server_gui as gui_module + + started = [] + monkeypatch.setattr(gui_module._ActionWorker, "start", lambda self: started.append(1)) + win._action_worker = None + win._run_action("disconnect", lambda: {}) + assert started == [1] + started.clear() + # a second call while one is in flight must not start another worker + win._run_action("disconnect", lambda: {}) + assert started == [] + win._action_worker = None + + +# -------------------------------------------------------------------------- +# confirmation dialogs gate the destructive actions + + +def test_disconnect_requires_confirmation(win, monkeypatch): + from eco.manual_control import box_server_gui as gui_module + + asked = [] + monkeypatch.setattr(QtWidgets.QMessageBox, "question", + lambda *a, **k: (asked.append(1), QtWidgets.QMessageBox.No)[1]) + ran = [] + monkeypatch.setattr(gui_module._ActionWorker, "start", lambda self: ran.append(1)) + + win._confirm_disconnect() + assert asked == [1] + assert ran == [], "disconnect must not run without confirmation" + + +def test_disconnect_runs_after_confirmation(win, monkeypatch): + from eco.manual_control import box_server_gui as gui_module + + monkeypatch.setattr(QtWidgets.QMessageBox, "question", + lambda *a, **k: QtWidgets.QMessageBox.Yes) + ran = [] + monkeypatch.setattr(gui_module._ActionWorker, "start", lambda self: ran.append(1)) + + win._confirm_disconnect() + assert ran == [1] + win._action_worker = None + + +def test_restart_requires_confirmation(win, monkeypatch): + from eco.manual_control import box_server_gui as gui_module + + monkeypatch.setattr(QtWidgets.QMessageBox, "question", + lambda *a, **k: QtWidgets.QMessageBox.No) + ran = [] + monkeypatch.setattr(gui_module._ActionWorker, "start", lambda self: ran.append(1)) + + win._confirm_restart() + assert ran == [], "restart must not run without confirmation" + + +def test_reconnect_does_not_require_confirmation(win, monkeypatch): + """Reconnect is benign - the box operator still has to accept it - so + it must not pop a dialog.""" + from eco.manual_control import box_server_gui as gui_module + + asked = [] + monkeypatch.setattr(QtWidgets.QMessageBox, "question", + lambda *a, **k: (asked.append(1), QtWidgets.QMessageBox.Yes)[1]) + monkeypatch.setattr(gui_module._ActionWorker, "start", lambda self: None) + + win.btn_reconnect.click() + assert asked == [], "reconnect popped a confirmation dialog" + win._action_worker = None