feat(bec_status_box): show grouped service rows with details and a server restart

This commit is contained in:
wyzula_j authored and Jan Wyzula committed 2026-11-09 15:08:05 +01:00
1 parent af92642460
commit 277f15fb5d
7 files changed
+1682 -413

No files matched your search

+1 -1
View File
@@ -535,7 +535,7 @@ class BECStatusBox(RPCBase):
@rpc_call
def get_server_state(self) -> "str":
"""
Get the state ("RUNNING", "BUSY", "IDLE", "ERROR") of the BEC server
Get the state ("RUNNING", "BUSY", "IDLE", "ERROR", "NOTCONNECTED") of the BEC server
"""
@rpc_call
+11
View File
@@ -64,6 +64,7 @@ __all__ = [
"rpc_register",
"bec_dispatcher",
"clean_singleton",
"service_status_poller_reset",
"suppress_message_box",
"mocked_client",
"mocked_client_with_dap",
@@ -161,6 +162,16 @@ def notification_broker_reset(bec_dispatcher):
BECNotificationBroker.reset_singleton()
@pytest.fixture(autouse=True)
def service_status_poller_reset(bec_dispatcher):
"""Drop the service status poller the status boxes of a client share, with its last result."""
yield
# pylint: disable=import-outside-toplevel
from bec_widgets.widgets.services.bec_status_box.bec_status_box import BECServiceStatusMixin
BECServiceStatusMixin.reset_shared()
@pytest.fixture(autouse=True)
def clean_singleton():
error_popups._popup_utility_instance = None
@@ -1,27 +1,49 @@
"""This module contains the BECStatusBox widget, which displays the status of different BEC services in a collapsible tree widget.
"""This module contains the BECStatusBox widget, which displays the status of different BEC services.
The widget automatically updates the status of all running BEC services, and displays their status.
"""
from __future__ import annotations
from collections import defaultdict
import time
import weakref
from dataclasses import dataclass
from typing import TYPE_CHECKING
from bec_lib.endpoints import MessageEndpoints
from bec_lib.logger import bec_logger
from bec_lib.utils.import_utils import lazy_import_from
from pydantic import BaseModel
from qtpy.QtCore import QObject, QTimer, Signal, Slot
from qtpy.QtWidgets import QHBoxLayout, QTreeWidget, QTreeWidgetItem, QWidget
from qtpy.QtCore import QObject, QThreadPool, QTimer, Signal
from qtpy.QtWidgets import QHBoxLayout, QMessageBox, QWidget
from bec_widgets.utils.bec_connector import Worker
from bec_widgets.utils.bec_widget import BECWidget
from bec_widgets.widgets.services.bec_status_box.status_item import StatusItem
from bec_widgets.utils.error_popups import SafeSlot
from bec_widgets.widgets.services.bec_status_box.status_box_widgets import StatusBoxWidgetView
from bec_widgets.widgets.services.bec_status_box.status_model import (
RestartState,
ServiceStatusModel,
build_rows,
friendly_name,
)
if TYPE_CHECKING: # pragma: no cover
from bec_lib.client import BECClient
from bec_lib.messages import BECStatus, ServiceMetricMessage, StatusMessage
from bec_lib.messages import (
BECStatus,
ServiceMetricMessage,
ServiceRequestMessage,
StatusMessage,
)
else:
# TODO : Put normal imports back when Pydantic gets faster
BECStatus = lazy_import_from("bec_lib.messages", ("BECStatus",))
BECStatus, ServiceRequestMessage = lazy_import_from(
"bec_lib.messages", ("BECStatus", "ServiceRequestMessage")
)
logger = bec_logger.logger
RESTART_TIMEOUT_S = 120
@dataclass
@@ -35,43 +57,120 @@ class BECServiceInfoContainer:
class BECServiceStatusMixin(QObject):
"""Mixin to receive the latest service status from the BEC server and emit it via services_update signal.
"""Polls the service status of the BEC server and emits it via the services_update signal.
The status boxes and server pills of one client share one poller (``shared``): it reads only
while at least one of them is shown (``add_viewer`` / ``remove_viewer``), every
POLL_INTERVAL_MS, and hands each new viewer the last result at once. A poller made directly
starts polling right away and is cleaned up by its owner.
Args:
client (BECClient): The client object to connect to the BEC server.
start (bool): Start polling right away. The shared poller waits for its first viewer.
"""
services_update = Signal(dict, dict)
ICON_NAME = "dns"
# the services publish their status every 3 s; polling faster would show nothing new
POLL_INTERVAL_MS = 3000
def __init__(self, parent, client: BECClient):
_shared: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
def __init__(self, parent, client: BECClient, start: bool = True):
super().__init__(parent)
self.client = client
# the Redis reads run on the thread pool, one at a time, so a slow Redis never blocks the GUI
self._worker: Worker | None = None
self._viewers: set[int] = set()
self.last_update: tuple[dict, dict] | None = None
self._service_update_timer = QTimer()
self._service_update_timer.setInterval(self.POLL_INTERVAL_MS)
self._service_update_timer.timeout.connect(self._get_service_status)
self._service_update_timer.start(1000)
if start:
self._service_update_timer.start()
@classmethod
def shared(cls, client: BECClient) -> BECServiceStatusMixin:
"""The poller shared by all status boxes and pills of a client."""
poller = cls._shared.get(client)
if poller is None:
poller = cls(None, client, start=False)
cls._shared[client] = poller
return poller
@classmethod
def reset_shared(cls) -> None:
"""Stop and drop all shared pollers, e.g. between tests."""
for poller in list(cls._shared.values()):
poller.cleanup()
cls._shared.clear()
def add_viewer(self, viewer: QObject) -> None:
"""Poll while this widget shows the status; the first viewer starts with a read."""
self._viewers.add(id(viewer))
if not self._service_update_timer.isActive():
self._service_update_timer.start()
self._get_service_status()
def remove_viewer(self, viewer: QObject) -> None:
"""Stop polling once no widget shows the status any more."""
self._viewers.discard(id(viewer))
if not self._viewers:
self._service_update_timer.stop()
@property
def polling(self) -> bool:
"""Whether the poller reads the service status periodically."""
return self._service_update_timer.isActive()
def _get_service_status(self):
"""Get the latest service status from the BEC server."""
"""Read the latest service status from the BEC server off the GUI thread."""
if self._worker is not None:
return
# pylint: disable=protected-access
self.client._update_existing_services()
self.services_update.emit(self.client._services_info, self.client._services_metric)
self._worker = Worker(self.client._update_existing_services)
self._worker.signals.completed.connect(self._on_service_status)
self._worker.signals.failed.connect(self._on_read_failed)
QThreadPool.globalInstance().start(self._worker)
@SafeSlot()
def _on_service_status(self):
self._worker = None
# pylint: disable=protected-access
self.last_update = (self.client._services_info, self.client._services_metric)
self.services_update.emit(*self.last_update)
@SafeSlot(str)
def _on_read_failed(self, _error: str):
self._worker = None
def cleanup(self):
"""Cleanup the BECServiceStatusMixin."""
self._viewers.clear()
self._service_update_timer.stop()
self._service_update_timer.deleteLater()
if self._worker is not None:
for signal in (self._worker.signals.completed, self._worker.signals.failed):
try:
signal.disconnect()
except (TypeError, RuntimeError):
pass
class BECStatusBox(BECWidget, QWidget):
"""An autonomous widget to display the status of BEC services.
The header shows the overall state of BEC, the list groups the core services and the other
services (clients, data processing). Clicking a service shows its host, user, uptime, load and
versions inline, with a button to copy them.
Args:
parent Optional : The parent widget for the BECStatusBox. Defaults to None.
box_name Optional(str): The name of the top service label. Defaults to "BEC Server".
client Optional(BECClient): The client object to connect to the BEC server. Defaults to None
config Optional(BECStatusBoxConfig | dict): The configuration for the status box. Defaults to None.
bec_service_status_mixin Optional(BECServiceStatusMixin): Source of the service updates.
Defaults to the poller shared by all status boxes of the client.
gui_id Optional(str): The unique id for the widget. Defaults to None.
"""
@@ -93,226 +192,265 @@ class BECStatusBox(BECWidget, QWidget):
):
super().__init__(parent=parent, client=client, gui_id=gui_id, **kwargs)
self.main_layout = QHBoxLayout(self)
self.main_layout.setContentsMargins(0, 0, 0, 0)
self.box_name = box_name
self.status_container = defaultdict(lambda: {"info": None, "item": None, "widget": None})
self.status_container: dict[str, BECServiceInfoContainer] = {}
self.core_state = "IDLE"
self.model = ServiceStatusModel(self)
# a poller handed in belongs to this box; the shared one only counts it as a viewer
self._owns_poller = bool(bec_service_status_mixin)
if not bec_service_status_mixin:
bec_service_status_mixin = BECServiceStatusMixin(self, client=self.client)
bec_service_status_mixin = BECServiceStatusMixin.shared(self.client)
self.bec_service_status = bec_service_status_mixin
self.init_ui()
self.view = StatusBoxWidgetView(self.model, self)
self.view.setMinimumSize(280, 220)
self.main_layout.addWidget(self.view)
self.model.restart_requested.connect(self.confirm_restart)
self._restart_requested_at: float | None = None
self._restart_timeout = QTimer(self)
self._restart_timeout.setSingleShot(True)
self._restart_timeout.timeout.connect(self._restart_timed_out)
self._restart_clear = QTimer(self)
self._restart_clear.setSingleShot(True)
self._restart_clear.timeout.connect(lambda: self.model.set_restart(RestartState.NONE))
self.bec_service_status.services_update.connect(self.update_service_status)
self._poller_connected = True
self.bec_core_state.connect(self.update_top_item_status)
self.tree.itemDoubleClicked.connect(self.on_tree_item_double_clicked)
self.main_layout.addWidget(self.tree)
last_update = getattr(self.bec_service_status, "last_update", None)
if isinstance(last_update, tuple):
self.update_service_status(*last_update) # what another box already read
def init_ui(self) -> None:
"""Init the UI for the BECStatusBox widget, should only take place once."""
self.init_ui_tree_widget()
top_label = self._create_status_widget(self.box_name, status=BECStatus.IDLE)
tree_item = QTreeWidgetItem()
tree_item.setExpanded(True)
tree_item.setDisabled(True)
self.status_container[self.box_name].update({"item": tree_item, "widget": top_label})
self.tree.addTopLevelItem(tree_item)
self.tree.setItemWidget(tree_item, 0, top_label)
self.service_update.connect(top_label.update_config)
self._initialized = True
def showEvent(self, event): # pylint: disable=invalid-name
super().showEvent(event)
self.bec_service_status.add_viewer(self)
def init_ui_tree_widget(self) -> None:
"""Initialise the tree widget for the status box."""
self.tree = QTreeWidget(self)
self.tree.setHeaderHidden(True)
# TODO probably here is a problem still with setting the stylesheet
self.tree.setStyleSheet(
"QTreeWidget::item:!selected "
"{ "
"border: 1px solid gainsboro; "
"border-left: none; "
"border-top: none; "
"}"
"QTreeWidget::item:selected {}"
)
def hideEvent(self, event): # pylint: disable=invalid-name
super().hideEvent(event)
self.bec_service_status.remove_viewer(self)
def get_server_state(self) -> str:
"""Get the state ("RUNNING", "BUSY", "IDLE", "ERROR") of the BEC server"""
return self.status_container[self.box_name]["info"].status
"""Get the state ("RUNNING", "BUSY", "IDLE", "ERROR", "NOTCONNECTED") of the BEC server"""
return self.core_state
def _create_status_widget(
self, service_name: str, status=BECStatus, info: dict = None, metrics: dict = None
) -> StatusItem:
"""Creates a StatusItem (QWidget) for the given service, and stores all relevant
information about the service in the status_container.
@SafeSlot(str)
def update_top_item_status(self, status: str) -> None:
"""Update the combined state of the core services.
Args:
service_name (str): The name of the service.
status (BECStatus): The status of the service.
info Optional(dict): The information about the service. Default is {}
metric Optional(dict): Metrics for the respective service. Default is None
Returns:
StatusItem: The status item widget.
status (str): The state of the core services.
"""
if info is None:
info = {}
self._update_status_container(service_name, status, info, metrics)
item = StatusItem(parent=self, config=self.status_container[service_name]["info"])
return item
@Slot(str)
def update_top_item_status(self, status: BECStatus) -> None:
"""Method to update the status of the top item in the tree widget.
Gets the status from the Signal 'bec_core_state' and updates the StatusItem via the signal 'service_update'.
Args:
status (BECStatus): The state of the core services.
"""
self.status_container[self.box_name]["info"].status = status
self.service_update.emit(self.status_container[self.box_name]["info"])
if status == self.core_state:
return
self.core_state = status
self._refresh_model()
def _update_status_container(
self, service_name: str, status: BECStatus, info: dict, metrics: dict = None
self, service_name: str, status: BECStatus | str, info: dict, metrics: dict = None
) -> None:
"""Update the status_container with the newest status and metrics for the BEC service.
If information about the service already exists, it will create a new entry.
"""Store the newest status and metrics of a BEC service.
Args:
service_name (str): The name of the service.
status (BECStatus): The status of the service.
status (BECStatus | str): The status of the service.
info (dict): The information about the service.
metrics (dict): The metrics of the service.
"""
container = self.status_container[service_name].get("info", None)
status = status.name if isinstance(status, BECStatus) else status
container = self.status_container.get(service_name)
if container:
container.status = status.name
container.status = status
container.info = info
container.metrics = metrics
return
service_info_item = BECServiceInfoContainer(
service_name=service_name,
status=status.name if isinstance(status, BECStatus) else status,
info=info,
metrics=metrics,
)
self.status_container[service_name].update({"info": service_info_item})
else:
container = BECServiceInfoContainer(
service_name=service_name, status=status, info=info, metrics=metrics
)
self.status_container[service_name] = container
self.service_update.emit(container)
@Slot(dict, dict)
@SafeSlot(dict, dict)
def update_service_status(
self,
services_info: dict[str, StatusMessage],
services_metric: dict[str, ServiceMetricMessage],
) -> None:
"""Callback function services_metric from BECServiceStatusMixin.
It updates the status of all services.
"""Callback for BECServiceStatusMixin.services_update. Updates the status of all services.
Args:
services_info (dict): A dictionary containing the service status for all running BEC services.
services_metric (dict): A dictionary containing the service metrics for all running BEC services.
services_info (dict): The service status for all running BEC services.
services_metric (dict): The service metrics for all running BEC services.
"""
checked = [self.box_name]
services_info = dict(services_info)
checked = list(self.CORE_SERVICES)
# FIXME: We simply replace the pydantic message with dict for now until we refactor the widget
for val in services_info.values():
val.info = val.info.model_dump() if isinstance(val.info, BaseModel) else val.info
services_info = self.update_core_services(services_info, services_metric)
checked.extend(self.CORE_SERVICES)
services_info = self.update_core_services(services_info, services_metric, refresh=False)
for service_name, msg in sorted(services_info.items()):
checked.append(service_name)
metric_msg = services_metric.get(service_name, None)
metrics = metric_msg.metrics if metric_msg else None
if service_name in self.status_container:
if not msg:
self.add_tree_item(service_name, "NOTCONNECTED", {}, metrics)
continue
self._update_status_container(service_name, msg.status, msg.info, metrics)
self.service_update.emit(self.status_container[service_name]["info"])
if not msg:
self._update_status_container(service_name, "NOTCONNECTED", {}, metrics)
continue
self._update_status_container(service_name, msg.status, msg.info, metrics)
self.remove_stale_services(checked)
self._refresh_model()
self.add_tree_item(service_name, msg.status, msg.info, metrics)
self.check_redundant_tree_items(checked)
def update_core_services(self, services_info: dict, services_metric: dict) -> dict:
"""Update the core services of BEC, and emit the updated status to the BECStatusBox.
def update_core_services(
self, services_info: dict, services_metric: dict, refresh: bool = True
) -> dict:
"""Update the core services of BEC and emit their combined state.
Args:
services_info (dict): A dictionary containing the service status of different services.
services_metric (dict): A dictionary containing the service metrics of different services.
services_info (dict): The service status of different services.
services_metric (dict): The service metrics of different services.
refresh (bool): Whether to refresh the view right away.
Returns:
dict: The services_info dictionary after removing the info updates related to the CORE_SERVICES
dict: The services_info dictionary without the CORE_SERVICES entries.
"""
core_state = BECStatus.RUNNING
for service_name in sorted(self.CORE_SERVICES):
for service_name in self.CORE_SERVICES:
metric_msg = services_metric.get(service_name, None)
metrics = metric_msg.metrics if metric_msg else None
msg = services_info.pop(service_name, None)
if service_name not in self.status_container:
if not msg:
self.add_tree_item(service_name, "NOTCONNECTED", {}, metrics)
continue
self.add_tree_item(service_name, msg.status, msg.info, metrics)
continue
if not msg:
self.status_container[service_name]["info"].status = "NOTCONNECTED"
self._update_status_container(service_name, "NOTCONNECTED", {}, metrics)
core_state = None
else:
self._update_status_container(service_name, msg.status, msg.info, metrics)
if core_state:
core_state = msg.status if msg.status.value < core_state.value else core_state
continue
info = msg.info.model_dump() if isinstance(msg.info, BaseModel) else msg.info
self._update_status_container(service_name, msg.status, info, metrics)
if core_state and msg.status.value < core_state.value:
core_state = msg.status
self.service_update.emit(self.status_container[service_name]["info"])
self.bec_core_state.emit(core_state.name if core_state else "NOTCONNECTED")
self.core_state = core_state.name if core_state else "NOTCONNECTED"
self.bec_core_state.emit(self.core_state)
if refresh:
self._refresh_model()
return services_info
def check_redundant_tree_items(self, checked: list) -> None:
"""Utility method to check and remove redundant objects from the BECStatusBox.
def remove_stale_services(self, checked: list) -> None:
"""Remove services that are no longer reported by BEC.
Args:
checked (list): A list of services that are currently running.
checked (list): The services that are currently known.
"""
to_be_deleted = [key for key in self.status_container if key not in checked]
for key in [key for key in self.status_container if key not in checked]:
self.status_container.pop(key)
for key in to_be_deleted:
obj = self.status_container.pop(key)
item = obj["item"]
self.status_container[self.box_name]["item"].removeChild(item)
def _refresh_model(self) -> None:
rows = build_rows(self.status_container.values(), self.CORE_SERVICES)
self.model.set_rows(rows, self.core_state)
scihub = self.status_container.get("SciHub")
self.model.set_can_restart(scihub is not None and scihub.status != "NOTCONNECTED")
self._check_restart_progress()
def add_tree_item(
self, service_name: str, status: BECStatus, info: dict = None, metrics: dict = None
) -> None:
"""Method to add a new QTreeWidgetItem together with a StatusItem to the tree widget.
# ---- server restart -----------------------------------------------------------------------
@SafeSlot()
def confirm_restart(self) -> None:
"""Ask the user to confirm, then request a restart of the BEC server."""
answer = QMessageBox.warning(
self,
"Restart BEC server",
"Restart all BEC server services?\n\n"
"A running scan is aborted, and devices are reloaded. "
"Clients stay connected and continue after the restart.",
QMessageBox.StandardButton.Cancel | QMessageBox.StandardButton.Yes,
QMessageBox.StandardButton.Cancel,
)
if answer == QMessageBox.StandardButton.Yes:
self.request_restart()
def request_restart(self) -> None:
"""Request a restart of all BEC server services through SciHub.
The progress is shown in the header: a service counts as restarted once it reports
RUNNING with a process start time after the request.
"""
if not self.model.can_restart:
return
self._restart_requested_at = time.time()
self.client.connector.send(
MessageEndpoints.service_request(), ServiceRequestMessage(action="restart")
)
logger.info("BEC server restart requested from the status box")
self._restart_clear.stop()
self._restart_timeout.start(int(RESTART_TIMEOUT_S * 1000))
self.model.set_restart(
RestartState.RUNNING, f"Restarting BEC server · 0/{len(self.CORE_SERVICES)}"
)
def _restarted_services(self) -> list[str]:
restarted = []
for name in self.CORE_SERVICES:
container = self.status_container.get(name)
if container is None or container.status not in ("RUNNING", "BUSY"):
continue
started = (container.metrics or {}).get("create_time")
if started is not None and started >= self._restart_requested_at:
restarted.append(name)
return restarted
def _check_restart_progress(self) -> None:
if self._restart_requested_at is None:
return
done = len(self._restarted_services())
total = len(self.CORE_SERVICES)
if done < total:
self.model.set_restart(RestartState.RUNNING, f"Restarting BEC server · {done}/{total}")
return
self._restart_requested_at = None
self._restart_timeout.stop()
self.model.set_restart(RestartState.DONE, "BEC server restarted")
self._restart_clear.start(6000)
self.submit_task(self._reload_client)
def _reload_client(self) -> None:
"""Reload scans and devices in this client after a restart (runs off the GUI thread)."""
# pylint: disable=protected-access
try:
self.client._load_scans()
self.client.device_manager._reload_action()
except Exception as exc: # pylint: disable=broad-except
logger.warning(f"Reloading the client after the server restart failed: {exc}")
def _restart_timed_out(self) -> None:
if self._restart_requested_at is None:
return
missing = [n for n in self.CORE_SERVICES if n not in self._restarted_services()]
self._restart_requested_at = None
names = ", ".join(friendly_name(n)[0] for n in missing)
self.model.set_restart(
RestartState.FAILED, f"Restart not finished: {names} did not come back"
)
self._restart_clear.start(15000)
@SafeSlot(str)
def apply_theme(self, theme: str):
"""Restyle the view after a theme change.
Args:
service_name (str): The name of the service.
status (BECStatus): The status of the service.
info (dict): The information about the service.
metrics (dict): The metrics of the service.
theme (str): The name of the new theme.
"""
item_widget = self._create_status_widget(service_name, status, info, metrics)
item = QTreeWidgetItem()
self.service_update.connect(item_widget.update_config)
self.status_container[self.box_name]["item"].addChild(item)
self.tree.setItemWidget(item, 0, item_widget)
self.status_container[service_name].update({"item": item, "widget": item_widget})
@Slot(QTreeWidgetItem, int)
def on_tree_item_double_clicked(self, item: QTreeWidgetItem, column: int) -> None:
"""Callback function for double clicks on individual QTreeWidgetItems in the collapsed section.
Args:
item (QTreeWidgetItem): The item that was double clicked.
column (int): The column that was double clicked.
"""
for _, objects in self.status_container.items():
if objects["item"] == item:
objects["widget"].show_popup()
self.view.apply_theme()
def cleanup(self):
"""Cleanup the BECStatusBox widget."""
self.bec_service_status.cleanup()
self.bec_service_status.remove_viewer(self)
if self._poller_connected:
self._poller_connected = False
self.bec_service_status.services_update.disconnect(self.update_service_status)
if self._owns_poller:
self.bec_service_status.cleanup()
self._restart_timeout.stop()
self._restart_clear.stop()
self.view.cleanup()
return super().cleanup()
@@ -0,0 +1,572 @@
"""QWidget view of the BEC status box.
An overall state header and grouped, expandable service rows. Rows are kept and updated in place
when the model changes, instead of being rebuilt.
"""
from __future__ import annotations
from qtpy.QtCore import QSize, Qt, QTimer, Signal
from qtpy.QtGui import QColor, QPainter, QPixmap, QTransform
from qtpy.QtWidgets import (
QFrame,
QGridLayout,
QHBoxLayout,
QLabel,
QScrollArea,
QSizePolicy,
QToolButton,
QVBoxLayout,
QWidget,
)
from bec_widgets.utils.colors import get_theme_name
from bec_widgets.utils.theme_utils import DPR_EVENTS, crisp_icon, crisp_pixmap, css, theme_colors
from bec_widgets.widgets.progress.stage_bar import Tone
from bec_widgets.widgets.services.bec_status_box.status_model import (
SEVERITY_TONE,
RestartState,
ServiceRow,
ServiceStatusModel,
)
def tone_color(colors: dict[str, QColor], tone: Tone | str) -> QColor:
"""Map a tone to a theme colour; neutral is the muted colour."""
return {
Tone.OK: colors["ok"],
Tone.WARN: colors["warn"],
Tone.BAD: colors["bad"],
Tone.ACCENT: colors["primary"],
Tone.RUN: colors["run"],
}.get(Tone(tone), colors["muted"])
def rotated_pixmap(pixmap: QPixmap, angle: float) -> QPixmap:
"""A pixmap rotated about its centre and cropped back to its size, at its pixel ratio."""
if not angle:
return pixmap
rotated = pixmap.transformed(
QTransform().rotate(angle), Qt.TransformationMode.SmoothTransformation
)
x = (rotated.width() - pixmap.width()) // 2
y = (rotated.height() - pixmap.height()) // 2
cropped = rotated.copy(x, y, pixmap.width(), pixmap.height())
cropped.setDevicePixelRatio(pixmap.devicePixelRatio())
return cropped
class _Dot(QWidget):
"""A small filled circle that can pulse."""
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedSize(12, 12)
self._color = QColor("gray")
self._opacity = 1.0
def set_color(self, color: QColor) -> None:
self._color = QColor(color)
self.update()
def set_opacity(self, opacity: float) -> None:
self._opacity = opacity
self.update()
def paintEvent(self, _event):
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setOpacity(self._opacity)
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(self._color)
painter.drawEllipse(self.rect())
class ElidedLabel(QLabel):
"""A label that elides its text instead of growing the layout."""
def __init__(self, parent=None, mode=Qt.TextElideMode.ElideRight):
super().__init__(parent)
self._mode = mode
self.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)
self.setMinimumWidth(0)
def paintEvent(self, _event):
painter = QPainter(self)
painter.setPen(self.palette().color(self.foregroundRole()))
rect = self.contentsRect()
text = self.fontMetrics().elidedText(self.text(), self._mode, rect.width())
painter.drawText(rect, int(self.alignment()), text)
class StatusHeader(QFrame):
"""Overall state of BEC: a colored dot, a headline and a detail line."""
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("StatusHeader")
self.setFixedHeight(56)
layout = QHBoxLayout(self)
layout.setContentsMargins(12, 0, 12, 0)
layout.setSpacing(10)
self.dot = _Dot(self)
text = QVBoxLayout()
text.setSpacing(2)
self.headline = ElidedLabel(self)
self.headline.setObjectName("headline")
self.detail = ElidedLabel(self)
self.detail.setObjectName("detail")
text.addStretch()
text.addWidget(self.headline)
text.addWidget(self.detail)
text.addStretch()
self.spinner = QLabel(self)
self.spinner.setFixedSize(16, 16)
self.spinner.setVisible(False)
self.restart_button = QToolButton(self)
self.restart_button.setObjectName("restartButton")
self.restart_button.setAutoRaise(True)
self.restart_button.setIconSize(QSize(18, 18))
self.restart_button.setCursor(Qt.CursorShape.PointingHandCursor)
layout.addWidget(self.dot)
layout.addWidget(self.spinner)
layout.addLayout(text, 1)
layout.addWidget(self.restart_button)
self._angle = 0
self._spin = QTimer(self)
self._spin.setInterval(80)
self._spin.timeout.connect(self._step_spinner)
self._tone = Tone.NEUTRAL
self._pulse_up = False
self._pulse = QTimer(self)
self._pulse.setInterval(50)
self._pulse.timeout.connect(self._step_pulse)
def set_restart(self, state: RestartState, can_restart: bool) -> None:
"""Show the restart action and spinner for the model's restart state."""
running = state == RestartState.RUNNING
self.restart_button.setEnabled(can_restart)
self.restart_button.setToolTip(
"Restart BEC server"
if can_restart
else "Restart in progress" if running else "Restart needs SciHub to be running"
)
self.spinner.setVisible(running)
self.dot.setVisible(not running)
if running:
self._spin.start()
else:
self._spin.stop()
def _step_spinner(self):
self._angle = (self._angle + 30) % 360
self._paint_spinner()
def _paint_spinner(self):
color = theme_colors()["primary"]
pixmap = crisp_pixmap("progress_activity", 16, color, widget=self.spinner)
self.spinner.setPixmap(rotated_pixmap(pixmap, self._angle))
def set_summary(self, headline: str, detail: str, tone: Tone) -> None:
"""Show the summary of the model."""
self.headline.setText(headline)
self.detail.setText(detail)
self._tone = Tone(tone)
if self._tone == Tone.BAD:
self._pulse.start()
else:
self._pulse.stop()
self.dot.set_opacity(1.0)
self.apply_theme()
def _step_pulse(self):
step = 0.65 / 14
opacity = self.dot._opacity + (step if self._pulse_up else -step)
if opacity <= 0.35 or opacity >= 1.0:
self._pulse_up = not self._pulse_up
self.dot.set_opacity(min(1.0, max(0.35, opacity)))
def apply_theme(self) -> None:
"""Restyle with the current theme colors."""
colors = theme_colors()
accent = tone_color(colors, self._tone)
alpha = 41 if get_theme_name() != "light" else 31
self.dot.set_color(accent)
self.restart_button.setIcon(
crisp_icon("restart_alt", 18, colors["fg"], widget=self.restart_button)
)
self._paint_spinner()
self.setStyleSheet(
f"#StatusHeader {{ background: {css(accent, alpha / 255)}; border: 1px solid "
f"{css(accent, 115 / 255)}; border-radius: 8px; }}"
f"#headline {{ color: {colors['fg'].name()}; font-size: 14px; font-weight: bold; }}"
f"#detail {{ color: {colors['muted'].name()}; font-size: 11px; }}"
)
def stop(self) -> None:
"""Stop the pulse and spinner timers."""
self._pulse.stop()
self._spin.stop()
class ServiceRowWidget(QFrame):
"""One service: status icon, name, subtitle, status chip and expandable details."""
toggled = Signal(str)
copy_requested = Signal(str)
def __init__(self, row: ServiceRow, parent=None):
super().__init__(parent)
self.setObjectName("ServiceRow")
self.setCursor(Qt.CursorShape.PointingHandCursor)
self.setAttribute(Qt.WidgetAttribute.WA_Hover)
# keep rows at their natural height so short lists do not spread out
self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Maximum)
self.row = None
self.expanded = False
self._hovered = False
self._angle = 0
outer = QVBoxLayout(self)
outer.setContentsMargins(0, 0, 0, 0)
outer.setSpacing(0)
main = QWidget(self)
main.setFixedHeight(44)
line = QHBoxLayout(main)
line.setContentsMargins(8, 0, 8, 0)
line.setSpacing(10)
self.icon = QLabel(main)
self.icon.setFixedSize(20, 20)
names = QVBoxLayout()
names.setSpacing(1)
self.name = ElidedLabel(main)
self.name.setObjectName("name")
self.subtitle = ElidedLabel(main)
self.subtitle.setObjectName("subtitle")
names.addStretch()
names.addWidget(self.name)
names.addWidget(self.subtitle)
names.addStretch()
self.mismatch = QLabel(main)
self.mismatch.setObjectName("mismatch")
self.chip = QLabel(main)
self.chip.setObjectName("chip")
self.chip.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.chip.setFixedHeight(20)
self.mismatch.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.mismatch.setFixedHeight(18)
self.chevron = QLabel(main)
self.chevron.setFixedSize(16, 16)
line.addWidget(self.icon)
line.addLayout(names, 1)
line.addWidget(self.mismatch)
line.addWidget(self.chip)
line.addWidget(self.chevron)
outer.addWidget(main)
self.details = QWidget(self)
details_layout = QHBoxLayout(self.details)
details_layout.setContentsMargins(38, 0, 8, 8)
self.details_grid = QGridLayout()
self.details_grid.setHorizontalSpacing(12)
self.details_grid.setVerticalSpacing(3)
self.copy_button = QToolButton(self.details)
self.copy_button.setToolTip("Copy details")
self.copy_button.setAutoRaise(True)
self.copy_button.setIconSize(QSize(16, 16))
self.copy_button.clicked.connect(lambda: self.copy_requested.emit(self.row.service_name))
self.copy_button.clicked.connect(self._show_copied)
details_layout.addLayout(self.details_grid, 1)
details_layout.addWidget(self.copy_button, 0, Qt.AlignmentFlag.AlignTop)
self.details.setVisible(False)
outer.addWidget(self.details)
self._detail_labels: list[tuple[QLabel, QLabel]] = []
self._copied = False
self.set_row(row)
def set_row(self, row: ServiceRow) -> None:
"""Update the widget for a new version of its row, restyling only when the state changed."""
previous = getattr(self, "row", None)
restyle = previous is None or (previous.tone, previous.icon) != (row.tone, row.icon)
self.row = row
self.name.setText(row.display_name)
self.subtitle.setText(row.subtitle)
self.subtitle.setVisible(bool(row.subtitle))
self.chip.setText(row.status_label)
self.mismatch.setText(f"v{row.version}")
self.mismatch.setToolTip(f"bec_lib {row.version} differs from the other services")
self.mismatch.setVisible(row.version_mismatch)
if self.expanded:
self._fill_details()
if restyle:
self.apply_theme()
@property
def busy(self) -> bool:
"""Whether the status icon spins."""
return self.row.status == "BUSY"
def set_expanded(self, expanded: bool) -> None:
"""Show or hide the details."""
self.expanded = expanded
if expanded:
self._fill_details()
self.details.setVisible(expanded)
self.apply_theme()
def _fill_details(self):
details = self.row.details
while len(self._detail_labels) < len(details):
key, value = QLabel(self.details), QLabel(self.details)
key.setObjectName("detailKey")
value.setObjectName("detailValue")
value.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)
value.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
idx = len(self._detail_labels)
self.details_grid.addWidget(key, idx, 0)
self.details_grid.addWidget(value, idx, 1)
self._detail_labels.append((key, value))
for idx, (key, value) in enumerate(self._detail_labels):
visible = idx < len(details)
key.setVisible(visible)
value.setVisible(visible)
if visible:
key.setText(details[idx][0])
value.setText(details[idx][1])
self.details_grid.setColumnStretch(1, 1)
def _show_copied(self):
self._copied = True
self.copy_button.setToolTip("Copied")
self._paint_copy_icon()
QTimer.singleShot(1500, self._reset_copied)
def _reset_copied(self):
self._copied = False
self.copy_button.setToolTip("Copy details")
self._paint_copy_icon()
def _paint_copy_icon(self):
colors = theme_colors()
self.copy_button.setIcon(
crisp_icon(
"check" if self._copied else "content_copy",
16,
colors["muted"],
widget=self.copy_button,
)
)
def rotate_icon(self) -> None:
"""Advance the busy spinner by one step."""
self._angle = (self._angle + 30) % 360
self._paint_status_icon()
def _paint_status_icon(self):
accent = tone_color(theme_colors(), self.row.tone)
pixmap = crisp_pixmap(self.row.icon, 20, accent, filled=True, widget=self.icon)
self.icon.setPixmap(rotated_pixmap(pixmap, self._angle if self.busy else 0))
def apply_theme(self) -> None:
"""Restyle with the current theme colors."""
colors = theme_colors()
accent = tone_color(colors, self.row.tone)
if not self.busy:
self._angle = 0
self._paint_status_icon()
self._paint_copy_icon()
self.chevron.setPixmap(
crisp_pixmap(
"expand_less" if self.expanded else "expand_more",
16,
colors["muted"],
widget=self.chevron,
)
)
highlighted = self.expanded or self._hovered
background = colors["card"].name() if highlighted else "transparent"
border = colors["border"].name() if self.expanded else "transparent"
self.setStyleSheet(
f"#ServiceRow {{ background: {background}; border: 1px solid {border};"
f" border-radius: 6px; }}"
f"#name {{ color: {colors['fg'].name()}; font-size: 13px; }}"
f"#subtitle, #detailKey {{ color: {colors['muted'].name()}; font-size: 11px; }}"
f"#detailValue {{ color: {colors['fg'].name()}; font-size: 11px; }}"
f"#chip {{ color: {accent.name()}; background: {css(accent, 38 / 255)};"
f" border-radius: 10px; padding: 0px 8px; font-size: 11px; font-weight: bold; }}"
f"#mismatch {{ color: {colors['warn'].name()}; border: 1px solid"
f" {colors['warn'].name()}; border-radius: 9px; padding: 0px 6px;"
f" font-size: 10px; }}"
)
def event(self, event):
if event.type() == event.Type.HoverEnter:
self._hovered = True
self.apply_theme()
elif event.type() == event.Type.HoverLeave:
self._hovered = False
self.apply_theme()
return super().event(event)
def mouseReleaseEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton and event.position().y() <= 44:
self.toggled.emit(self.row.service_name)
super().mouseReleaseEvent(event)
class StatusBoxWidgetView(QWidget):
"""QWidget view bound to a ServiceStatusModel."""
def __init__(self, model: ServiceStatusModel, parent=None):
super().__init__(parent)
self.model = model
self.expanded_service = ""
self.rows: dict[str, ServiceRowWidget] = {}
self.section_labels: dict[str, QLabel] = {}
layout = QVBoxLayout(self)
layout.setContentsMargins(8, 8, 8, 4)
layout.setSpacing(4)
self.header = StatusHeader(self)
layout.addWidget(self.header)
self.scroll = QScrollArea(self)
self.scroll.setWidgetResizable(True)
self.scroll.setFrameShape(QFrame.Shape.NoFrame)
self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.list_widget = QWidget(self.scroll)
self.list_widget.setObjectName("serviceList")
self.list_layout = QVBoxLayout(self.list_widget)
self.list_layout.setContentsMargins(0, 0, 0, 0)
self.list_layout.setSpacing(2)
self.list_layout.addStretch()
self.scroll.setWidget(self.list_widget)
layout.addWidget(self.scroll, 1)
self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Expanding)
self._spinner = QTimer(self)
self._spinner.setInterval(100)
self._spinner.timeout.connect(self._spin)
model.rows_changed.connect(self.sync)
model.summary_changed.connect(self._update_summary)
model.restart_changed.connect(self._update_summary)
self.header.restart_button.clicked.connect(model.request_restart)
self._update_summary()
self.sync()
self.apply_theme()
def _update_summary(self):
state = self.model.restart_state
if state != RestartState.NONE:
tone = {RestartState.RUNNING: Tone.ACCENT, RestartState.DONE: Tone.OK}.get(
state, Tone.BAD
)
self.header.set_summary(self.model.restart_text, self.model.detail, tone)
else:
tone = SEVERITY_TONE[self.model.severity]
self.header.set_summary(self.model.headline, self.model.detail, tone)
self.header.set_restart(state, self.model.can_restart)
def sync(self) -> None:
"""Bring the row widgets in line with the model, reusing existing widgets."""
rows = self.model.rows
names = {row.service_name for row in rows}
for name in list(self.rows):
if name not in names:
widget = self.rows.pop(name)
self.list_layout.removeWidget(widget)
widget.deleteLater()
if self.expanded_service not in names:
self.expanded_service = ""
position = 0
current_group = None
for row in rows:
if row.group != current_group:
current_group = row.group
label = self._section_label(row.group)
self._place(label, position)
position += 1
widget = self.rows.get(row.service_name)
if widget is None:
widget = ServiceRowWidget(row, self.list_widget)
widget.toggled.connect(self._toggle)
widget.copy_requested.connect(self.model.copy_details)
self.rows[row.service_name] = widget
elif widget.row != row:
widget.set_row(row)
self._place(widget, position)
position += 1
groups = {row.group for row in rows}
for group, label in self.section_labels.items():
label.setVisible(group in groups)
if any(widget.busy for widget in self.rows.values()):
if not self._spinner.isActive():
self._spinner.start()
else:
self._spinner.stop()
def _place(self, widget: QWidget, position: int):
if self.list_layout.indexOf(widget) != position:
self.list_layout.removeWidget(widget)
self.list_layout.insertWidget(position, widget)
widget.setVisible(True)
def _section_label(self, group: str) -> QLabel:
label = self.section_labels.get(group)
if label is None:
label = QLabel(group.upper(), self.list_widget)
label.setObjectName("section")
label.setContentsMargins(4, 10, 0, 4)
self.section_labels[group] = label
self._style_section(label)
return label
def _style_section(self, label: QLabel):
colors = theme_colors()
label.setStyleSheet(
f"#section {{ color: {colors['muted'].name()}; font-size: 10px;"
f" font-weight: bold; letter-spacing: 0.8px; }}"
)
def _toggle(self, service_name: str):
previous = self.rows.get(self.expanded_service)
if previous is not None:
previous.set_expanded(False)
if self.expanded_service == service_name:
self.expanded_service = ""
return
self.expanded_service = service_name
self.rows[service_name].set_expanded(True)
def _spin(self):
for widget in self.rows.values():
if widget.busy:
widget.rotate_icon()
def event(self, event):
if event.type() in DPR_EVENTS:
# moved to a screen with another pixel ratio: render the icons again
self.apply_theme()
return super().event(event)
def apply_theme(self) -> None:
"""Restyle all parts with the current theme colors."""
colors = theme_colors()
self.setStyleSheet(f"StatusBoxWidgetView {{ background: {colors['bg'].name()}; }}")
self.scroll.setStyleSheet(
"QScrollArea { background: transparent; } #serviceList { background: transparent; }"
)
self.header.apply_theme()
for label in self.section_labels.values():
self._style_section(label)
for widget in self.rows.values():
widget.apply_theme()
def cleanup(self) -> None:
"""Stop the timers."""
self._spinner.stop()
self.header.stop()
@@ -1,158 +0,0 @@
"""Module for a StatusItem widget to display status and metrics for a BEC service.
The widget is bound to be used with the BECStatusBox widget."""
import enum
import os
from datetime import datetime
from bec_lib.utils.import_utils import lazy_import_from
from bec_qthemes import material_icon
from qtpy.QtCore import Qt, Slot
from qtpy.QtGui import QIcon, QPainter
from qtpy.QtWidgets import QDialog, QHBoxLayout, QLabel, QVBoxLayout, QWidget
import bec_widgets
from bec_widgets.utils.colors import get_accent_colors
# TODO : Put normal imports back when Pydantic gets faster
BECStatus = lazy_import_from("bec_lib.messages", ("BECStatus",))
MODULE_PATH = os.path.dirname(bec_widgets.__file__)
class IconsEnum(enum.Enum):
"""Enum class for icons in the status item widget."""
RUNNING = "done_outline"
BUSY = "progress_activity"
IDLE = "progress_activity"
ERROR = "emergency_home"
NOTCONNECTED = "signal_disconnected"
class StatusItem(QWidget):
"""A widget to display the status of a service.
Args:
parent: The parent widget.
config (dict): The configuration for the service, must be a BECServiceInfoContainer.
"""
def __init__(self, parent: QWidget = None, config=None):
QWidget.__init__(self, parent=parent)
if config is None:
# needed because we need parent to be the first argument for QT Designer
raise ValueError(
"Please initialize the StatusItem with a BECServiceInfoContainer for config, received None."
)
self.accent_colors = get_accent_colors()
self.config = config
self.parent = parent
self.layout = None
self._label = None
self._icon = None
self.icon_size = (24, 24)
self._popup_label_ref = {}
self.init_ui()
def init_ui(self) -> None:
"""Init the UI for the status item widget."""
self.layout = QHBoxLayout()
self.layout.setContentsMargins(5, 5, 5, 5)
self.setLayout(self.layout)
self._label = QLabel()
self._icon = QLabel()
self.layout.addWidget(self._label)
self.layout.addWidget(self._icon)
self.update_ui()
@Slot(dict)
def update_config(self, config) -> None:
"""Update the config of the status item widget.
Args:
config (dict): Config updates from parent widget, must be a BECServiceInfoContainer.
"""
if self.config is None or config.service_name != self.config.service_name:
return
self.config = config
self.update_ui()
def update_ui(self) -> None:
"""Update the UI of the labels, and popup dialog."""
if self.config is None:
return
self.set_text()
self.set_status()
self._set_popup_text()
def set_text(self) -> None:
"""Set the text of the QLabel basae on the config."""
service = self.config.service_name
status = self.config.status
if len(service.split("/")) > 1 and service.split("/")[0].startswith("BEC"):
service = service.split("/", maxsplit=1)[0] + "/..." + service.split("/")[1][-4:]
if status == "NOTCONNECTED":
status = "NOT CONNECTED"
text = f"{service} is {status}"
self._label.setText(text)
def set_status(self) -> None:
"""Set the status icon for the status item widget."""
status = self.config.status
if status in ["RUNNING", "BUSY"]:
color = self.accent_colors.success
elif status == "IDLE":
color = self.accent_colors.warning
elif status in ["ERROR", "NOTCONNECTED"]:
color = self.accent_colors.emergency
icon = QIcon(material_icon(IconsEnum[status].value, filled=True, color=color))
self._icon.setPixmap(icon.pixmap(*self.icon_size))
self._icon.setAlignment(Qt.AlignmentFlag.AlignRight)
def show_popup(self) -> None:
"""Method that is invoked when the user double clicks on the StatusItem widget."""
dialog = QDialog(self)
dialog.setWindowTitle(f"{self.config.service_name} Details")
layout = QVBoxLayout()
popup_label = self._make_popup_label()
self._set_popup_text()
layout.addWidget(popup_label)
dialog.setLayout(layout)
dialog.finished.connect(self._cleanup_popup_label)
dialog.exec()
def _make_popup_label(self) -> QLabel:
"""Create a QLabel for the popup dialog.
Returns:
QLabel: The label for the popup dialog.
"""
label = QLabel()
label.setWordWrap(True)
self._popup_label_ref.update({"label": label})
return label
def _set_popup_text(self) -> None:
"""Compile the metrics text for the status item widget."""
if self._popup_label_ref.get("label") is None:
return
metrics_text = (
f"<b>SERVICE:</b> {self.config.service_name}<br><b>STATUS:</b> {self.config.status}<br>"
)
if "version" in self.config.info:
metrics_text += f"<b>BEC_LIB VERSION:</b> {self.config.info['version']}<br>"
if "versions" in self.config.info:
for component, version in self.config.info["versions"].items():
metrics_text += f"<b>{component.upper()} VERSION:</b> {version}<br>"
if self.config.metrics:
for key, value in self.config.metrics.items():
if key == "create_time":
value = datetime.fromtimestamp(value).strftime("%Y-%m-%d %H:%M:%S")
metrics_text += f"<b>{key.upper()}:</b> {value}<br>"
self._popup_label_ref["label"].setText(metrics_text)
def _cleanup_popup_label(self) -> None:
"""Cleanup the popup label."""
self._popup_label_ref.clear()
@@ -0,0 +1,389 @@
"""View-independent data layer of the BEC status box.
``ServiceStatusModel`` turns the raw service info of the BEC client into display rows and an overall
summary. The status box view and the status-bar pill read the same model.
"""
from __future__ import annotations
import re
import time
from collections import Counter
from dataclasses import dataclass, field
from datetime import datetime
from enum import StrEnum
from qtpy.QtCore import QObject, Signal
from qtpy.QtWidgets import QApplication
from bec_widgets.widgets.containers.main_window.addons.status_pill import ToolSeverity
from bec_widgets.widgets.progress.stage_bar import Tone
# status -> (label, tone, material icon)
STATUS_STYLE = {
"RUNNING": ("Running", Tone.OK, "check_circle"),
"BUSY": ("Busy", Tone.OK, "progress_activity"),
"IDLE": ("Idle", Tone.WARN, "pause_circle"),
"ERROR": ("Error", Tone.BAD, "error"),
"NOTCONNECTED": ("Not connected", Tone.BAD, "cloud_off"),
}
# colour of the overall state in the header and its dot
SEVERITY_TONE = {
ToolSeverity.OK: Tone.OK,
ToolSeverity.INFO: Tone.NEUTRAL,
ToolSeverity.WARNING: Tone.WARN,
ToolSeverity.CRITICAL: Tone.BAD,
}
class RestartState(StrEnum):
"""Progress of a BEC server restart requested from the status box."""
NONE = ""
RUNNING = "running"
DONE = "done"
FAILED = "failed"
FRIENDLY_NAMES = {
"DeviceServer": "Device server",
"ScanServer": "Scan server",
"ScanBundler": "Scan bundler",
"FileWriterManager": "File writer",
"SciHub": "SciHub",
"DAPServer": "Data processing",
"CLIBECClient": "IPython client",
"BECIPythonClient": "IPython client",
"BECClient": "Client",
"BECGuiClient": "GUI client",
}
def friendly_name(service_name: str) -> tuple[str, str]:
"""Return a readable name and a short instance id for a BEC service name.
Args:
service_name (str): The raw service name, e.g. "DeviceServer" or "CLIBECClient/<uuid>".
Returns:
tuple[str, str]: The display name and the short instance id ("" for unique services).
"""
base, _, instance = service_name.partition("/")
name = FRIENDLY_NAMES.get(base)
if name is None:
name = re.sub(r"(?<=[a-z])(?=[A-Z])", " ", base)
name = name[:1].upper() + name[1:].lower() if name else service_name
return name, instance[:6]
def format_duration(seconds: float) -> str:
"""Format a duration in seconds as a short human readable string.
Args:
seconds (float): The duration.
Returns:
str: For example "45 s", "12 min", "3 h 5 min" or "2 d 4 h".
"""
seconds = max(0, int(seconds))
if seconds < 60:
return f"{seconds} s"
minutes = seconds // 60
if minutes < 60:
return f"{minutes} min"
hours, minutes = divmod(minutes, 60)
if hours < 24:
return f"{hours} h {minutes} min"
days, hours = divmod(hours, 24)
return f"{days} d {hours} h"
@dataclass
class ServiceRow:
"""One display row of the status box."""
service_name: str
display_name: str
instance: str
group: str
status: str
status_label: str
tone: Tone
icon: str
host: str = ""
user: str = ""
version: str = ""
version_mismatch: bool = False
uptime: str = ""
cpu: str = ""
memory: str = ""
details: list[tuple[str, str]] = field(default_factory=list)
@property
def subtitle(self) -> str:
"""The secondary line: who runs the service and where."""
parts = []
if self.user and self.host:
parts.append(f"{self.user}@{self.host}")
elif self.host:
parts.append(self.host)
if self.instance:
parts.append(f"#{self.instance}")
if not parts and self.status == "NOTCONNECTED":
parts.append("No heartbeat from this service")
return " · ".join(parts)
def details_text(self) -> str:
"""Plain text version of the details, used for the copy button."""
lines = [f"{self.service_name}: {self.status_label}"]
lines += [f"{key}: {value}" for key, value in self.details]
return "\n".join(lines)
CORE_GROUP = "Core services"
OTHER_GROUP = "Clients and other services"
def build_rows(services, core_services: list[str], now: float | None = None) -> list[ServiceRow]:
"""Build display rows from the status box's service info containers.
Args:
services: Iterable of BECServiceInfoContainer-like objects (service_name, status, info,
metrics).
core_services (list[str]): Names of the core services, shown first in their own group.
now (float | None): Current time, for uptime. Defaults to time.time().
Returns:
list[ServiceRow]: Core services in the given order, then all other services by name.
"""
now = time.time() if now is None else now
services = list(services)
rows = []
for svc in services:
info = svc.info or {}
metrics = svc.metrics or {}
status = svc.status if svc.status in STATUS_STYLE else "NOTCONNECTED"
label, tone, icon = STATUS_STYLE[status]
name, instance = friendly_name(svc.service_name)
versions = info.get("versions") or {}
version = versions.get("bec_lib", "") or info.get("version", "")
row = ServiceRow(
service_name=svc.service_name,
display_name=name,
instance=instance,
group=CORE_GROUP if svc.service_name in core_services else OTHER_GROUP,
status=status,
status_label=label,
tone=tone,
icon=icon,
host=str(info.get("hostname") or metrics.get("hostname") or ""),
user=str(info.get("user") or metrics.get("username") or ""),
version=str(version),
)
if "create_time" in metrics:
row.uptime = format_duration(now - metrics["create_time"])
if "cpu_percent" in metrics:
row.cpu = f"{metrics['cpu_percent']:.0f} %"
if "memory_in_mb" in metrics:
row.memory = f"{metrics['memory_in_mb']:.0f} MB"
details = [("Service", svc.service_name)]
for key, value in (
("Host", row.host),
("User", row.user),
("PID", metrics.get("pid", "")),
("Uptime", row.uptime),
("CPU", row.cpu),
("Memory", row.memory),
("Threads", metrics.get("num_threads", "")),
):
if value not in ("", None):
details.append((key, str(value)))
if "create_time" in metrics:
started = datetime.fromtimestamp(metrics["create_time"]).strftime("%Y-%m-%d %H:%M:%S")
details.append(("Started", started))
for package, pkg_version in versions.items():
details.append((package, str(pkg_version)))
row.details = details
rows.append(row)
# flag services whose bec_lib version differs from the one most services run
versions = Counter(row.version for row in rows if row.version)
if len(versions) > 1:
common = versions.most_common(1)[0][0]
for row in rows:
row.version_mismatch = bool(row.version) and row.version != common
core_order = {name: idx for idx, name in enumerate(core_services)}
rows.sort(
key=lambda r: (
r.group != CORE_GROUP,
core_order.get(r.service_name, 0),
r.display_name,
r.instance,
)
)
return rows
def summarize(rows: list[ServiceRow], core_state: str) -> tuple[str, str, ToolSeverity]:
"""Summarize the overall state for the header and the status-bar pill.
Args:
rows (list[ServiceRow]): The display rows.
core_state (str): The combined state of the core services.
Returns:
tuple[str, str, ToolSeverity]: (headline, detail line, severity).
"""
core = [row for row in rows if row.group == CORE_GROUP]
others = [row for row in rows if row.group != CORE_GROUP]
down = [row for row in core if row.status in ("NOTCONNECTED", "ERROR")]
idle = [row for row in core if row.status == "IDLE"]
if down:
if len(down) == 1:
headline = f"{down[0].display_name}: {down[0].status_label.lower()}"
else:
headline = f"{len(down)} core services down"
severity = ToolSeverity.CRITICAL
elif idle:
headline = (
f"{idle[0].display_name} is idle" if len(idle) == 1 else f"{len(idle)} services idle"
)
severity = ToolSeverity.WARNING
elif core and core_state in ("RUNNING", "BUSY"):
headline = "All core services running"
severity = ToolSeverity.OK
else:
headline = "Waiting for BEC services"
severity = ToolSeverity.INFO
ok = sum(1 for row in core if row.tone == Tone.OK)
detail = f"{ok}/{len(core)} core services up"
if others:
detail += f" · {len(others)} other" if len(others) == 1 else f" · {len(others)} others"
mismatched = [row for row in rows if row.version_mismatch]
if mismatched:
detail += f" · {len(mismatched)} version mismatch"
return headline, detail, severity
def core_services_down(rows: list[ServiceRow]) -> int:
"""Number of core services that are not connected or in error."""
return sum(
1 for row in rows if row.group == CORE_GROUP and row.status in ("NOTCONNECTED", "ERROR")
)
class ServiceStatusModel(QObject):
"""The rows, the overall summary and the restart progress of the BEC services.
Signals:
rows_changed(): The rows were replaced.
summary_changed(): The headline, the detail line or the severity changed.
restart_changed(): The restart progress or whether a restart is possible changed.
restart_requested(): The view asks for a restart; the owner confirms and requests it.
"""
rows_changed = Signal()
summary_changed = Signal()
restart_changed = Signal()
restart_requested = Signal()
def __init__(self, parent: QObject | None = None):
super().__init__(parent)
self._rows: list[ServiceRow] = []
self._headline = "Waiting for BEC services"
self._detail = ""
self._severity = ToolSeverity.INFO
self._restart_state = RestartState.NONE
self._restart_text = ""
self._can_restart = False
@property
def rows(self) -> list[ServiceRow]:
"""The current display rows."""
return list(self._rows)
def set_rows(self, rows: list[ServiceRow], core_state: str) -> None:
"""Replace the rows and update the summary.
Args:
rows (list[ServiceRow]): The new rows, already sorted.
core_state (str): The combined state of the core services.
"""
self._rows = list(rows)
summary = summarize(self._rows, core_state)
if summary != (self._headline, self._detail, self._severity):
self._headline, self._detail, self._severity = summary
self.summary_changed.emit()
self.rows_changed.emit()
@property
def headline(self) -> str:
"""The one-line overall state, e.g. "All core services running"."""
return self._headline
@property
def detail(self) -> str:
"""The secondary summary line with counts."""
return self._detail
@property
def severity(self) -> ToolSeverity:
"""The overall severity: ok, info, warning or critical."""
return self._severity
@property
def services_down(self) -> int:
"""Number of core services that are not connected or in error."""
return core_services_down(self._rows)
def set_restart(self, state: RestartState | str, text: str = "") -> None:
"""Set the restart progress shown in the header and the pill.
Args:
state (RestartState | str): none, running, done or failed.
text (str): The line shown while the state is set.
"""
state = RestartState(state)
if (state, text) != (self._restart_state, self._restart_text):
self._restart_state, self._restart_text = state, text
self.restart_changed.emit()
def set_can_restart(self, can_restart: bool) -> None:
"""Enable or disable the restart action."""
if can_restart != self._can_restart:
self._can_restart = can_restart
self.restart_changed.emit()
@property
def restart_state(self) -> RestartState:
"""The restart progress."""
return self._restart_state
@property
def restart_text(self) -> str:
"""The restart progress line."""
return self._restart_text
@property
def can_restart(self) -> bool:
"""Whether a restart can be requested now (SciHub is up and no restart is running)."""
return self._can_restart and self._restart_state != RestartState.RUNNING
def request_restart(self) -> None:
"""Ask the owner widget to confirm and request a BEC server restart."""
if self.can_restart:
self.restart_requested.emit()
def copy_details(self, service_name: str) -> None:
"""Copy the details of a service to the clipboard.
Args:
service_name (str): The raw service name.
"""
for row in self._rows:
if row.service_name == service_name:
QApplication.clipboard().setText(row.details_text())
return
+409 -92
View File
@@ -1,47 +1,83 @@
# pylint: skip-file
import time
from unittest import mock
import pytest
from bec_lib.endpoints import MessageEndpoints
from bec_lib.messages import BECStatus, ServiceInfo, ServiceMetricMessage, StatusMessage
from qtpy.QtWidgets import QApplication, QMessageBox
from bec_widgets.tests.client_mocks import mocked_client
from bec_widgets.tests.utils import create_widget
from bec_widgets.widgets.containers.main_window.addons.status_pill import ToolSeverity
from bec_widgets.widgets.progress.stage_bar import Tone
from bec_widgets.widgets.services.bec_status_box.bec_status_box import (
BECServiceInfoContainer,
BECStatusBox,
)
from bec_widgets.widgets.services.bec_status_box.status_box_widgets import StatusBoxWidgetView
from bec_widgets.widgets.services.bec_status_box.status_model import (
CORE_GROUP,
OTHER_GROUP,
RestartState,
build_rows,
format_duration,
friendly_name,
)
def _versions(lib="3.39.5"):
return {
"bec_lib": lib,
"bec_server": lib,
"bec_ipython_client": lib,
"bec_widgets": "3.39.5",
"ophyd_devices": "1.51.0",
}
def _status(name, status=BECStatus.RUNNING, lib="3.39.5"):
info = ServiceInfo(user="e12345", hostname="console", versions=_versions(lib))
return StatusMessage(name=name, status=status, info=info)
def _metrics(name, **extra):
metrics = {"pid": 42, "cpu_percent": 4.2, "memory_in_mb": 120.0, "create_time": time.time()}
metrics.update(extra)
return ServiceMetricMessage(name=name, metrics=metrics)
def _all_services(extra=(), skip=(), core_status=BECStatus.RUNNING):
names = [n for n in BECStatusBox.CORE_SERVICES if n not in skip] + list(extra)
info = {
n: _status(n, core_status if n in BECStatusBox.CORE_SERVICES else BECStatus.RUNNING)
for n in names
}
metrics = {n: _metrics(n) for n in names}
return info, metrics
@pytest.fixture
def service_status_fixture():
yield mock.MagicMock()
@pytest.fixture
def status_box(qtbot, mocked_client, service_status_fixture):
widget = BECStatusBox(client=mocked_client, bec_service_status_mixin=service_status_fixture)
qtbot.addWidget(widget)
qtbot.waitExposed(widget)
def status_box(qtbot, mocked_client):
widget = create_widget(
qtbot, BECStatusBox, client=mocked_client, bec_service_status_mixin=mock.MagicMock()
)
yield widget
def test_initial_state(status_box):
assert status_box.get_server_state() == "IDLE"
assert status_box.model.rows == []
assert status_box.model.headline == "Waiting for BEC services"
def test_view_type(status_box):
assert isinstance(status_box.view, StatusBoxWidgetView)
def test_update_top_item(status_box):
assert status_box.tree.children()[0].children()[0].config.status == "IDLE"
name = status_box.box_name
status_box.update_top_item_status(status="RUNNING")
assert status_box.status_container[name]["info"].status == "RUNNING"
assert status_box.tree.children()[0].children()[0].config.status == "RUNNING"
def test_create_status_widget(status_box):
name = "test_service"
status = BECStatus.IDLE
info = {"test": "test"}
metrics = {"metric": "test_metric"}
item = status_box._create_status_widget(name, status, info, metrics)
assert item.config.service_name == name
assert item.config.status == status.name
assert item.config.info == info
assert item.config.metrics == metrics
assert status_box.get_server_state() == "RUNNING"
def test_bec_service_container(status_box):
@@ -52,78 +88,359 @@ def test_bec_service_container(status_box):
expected_return = BECServiceInfoContainer(
service_name=name, status=status.name, info=info, metrics=metrics
)
assert status_box.box_name in status_box.status_container
assert len(status_box.status_container) == 1
status_box._update_status_container(name, status, info, metrics)
assert len(status_box.status_container) == 2
assert status_box.status_container[name]["info"] == expected_return
with mock.patch.object(status_box, "service_update") as service_update:
status_box._update_status_container(name, status, info, metrics)
service_update.emit.assert_called_once_with(expected_return)
assert status_box.status_container[name] == expected_return
def test_add_tree_item(status_box):
name = "test_service"
status = BECStatus.IDLE
info = {"test": "test"}
metrics = {"metric": "test_metric"}
assert len(status_box.tree.children()[0].children()) == 1
status_box.add_tree_item(name, status, info, metrics)
assert len(status_box.tree.children()[0].children()) == 2
assert name in status_box.status_container
def test_all_core_running(status_box):
status_box.update_service_status(*_all_services(extra=["CLIBECClient/abcdef123"]))
model = status_box.model
assert status_box.get_server_state() == "RUNNING"
assert model.headline == "All core services running"
assert model.severity == ToolSeverity.OK
assert model.services_down == 0
assert model.detail == "5/5 core services up · 1 other"
rows = model.rows
assert [r.service_name for r in rows[:5]] == BECStatusBox.CORE_SERVICES
assert rows[5].display_name == "IPython client"
assert rows[5].group == OTHER_GROUP
assert rows[5].subtitle == "e12345@console · #abcdef"
def test_update_service_status(status_box):
"""Also checks check redundant tree items"""
name = "test_service"
status = BECStatus.IDLE
info = StatusMessage(name=name, status=status, info=ServiceInfo(user="test", hostname="host"))
metrics = {"metric": "test_metric"}
status_box.add_tree_item(name, status, info, {})
not_connected_name = "invalid_service"
status_box.add_tree_item(not_connected_name, status, info, metrics)
services_status = {
name: StatusMessage(
name=name, status=status, info=ServiceInfo(user="test", hostname="host")
)
}
services_metrics = {name: ServiceMetricMessage(name=name, metrics=metrics)}
with mock.patch.object(status_box, "update_core_services", return_value=services_status):
assert not_connected_name in status_box.status_container
status_box.update_service_status(services_status, services_metrics)
assert status_box.status_container[name]["widget"].config.metrics == metrics
assert not_connected_name not in status_box.status_container
def test_core_service_missing(status_box):
status_box.update_service_status(*_all_services(skip=["ScanBundler"]))
model = status_box.model
assert status_box.get_server_state() == "NOTCONNECTED"
assert model.headline == "Scan bundler: not connected"
assert model.severity == ToolSeverity.CRITICAL
assert model.services_down == 1
row = next(r for r in model.rows if r.service_name == "ScanBundler")
assert row.status_label == "Not connected"
assert row.subtitle == "No heartbeat from this service"
def test_update_core_services(status_box):
status_box.CORE_SERVICES = ["test_service"]
name = "test_service"
status = BECStatus.RUNNING
info = ServiceInfo(user="test", hostname="host")
metrics = {"metric": "test_metric"}
services_status = {name: StatusMessage(name=name, status=status, info=info)}
services_metrics = {name: ServiceMetricMessage(name=name, metrics=metrics)}
status_box.update_core_services(services_status, services_metrics)
assert status_box.tree.children()[0].children()[0].config.status == "RUNNING"
assert status_box.status_container[name]["widget"].config.metrics == metrics
status = BECStatus.IDLE
services_status = {name: StatusMessage(name=name, status=status, info=info)}
services_metrics = {name: ServiceMetricMessage(name=name, metrics=metrics)}
status_box.update_core_services(services_status, services_metrics)
assert status_box.tree.children()[0].children()[0].config.status == status.name
assert status_box.status_container[name]["widget"].config.metrics == metrics
def test_stale_services_removed(status_box):
status_box.update_service_status(*_all_services(extra=["CLIBECClient/1", "CLIBECClient/2"]))
assert len(status_box.model.rows) == 7
status_box.update_service_status(*_all_services(extra=["CLIBECClient/2"]))
assert len(status_box.model.rows) == 6
assert "CLIBECClient/1" not in status_box.status_container
def test_double_click_item(status_box):
name = "test_service"
status = BECStatus.IDLE
info = ServiceInfo(user="test", hostname="host")
metrics = {"MyData": "This should be shown nicely"}
status_box.add_tree_item(name, status, info, metrics)
container = status_box.status_container[name]
item = container["item"]
status_item = container["widget"]
with mock.patch.object(status_item, "show_popup") as mock_show_popup:
status_box.tree.itemDoubleClicked.emit(item, 0)
assert mock_show_popup.call_count == 1
def test_rows_updated_in_place(status_box):
"""A status change updates the existing row widget instead of rebuilding the list."""
status_box.update_service_status(*_all_services())
view = status_box.view
row_widget = view.rows["ScanServer"]
info, metrics = _all_services()
info["ScanServer"] = _status("ScanServer", BECStatus.BUSY)
status_box.update_service_status(info, metrics)
idx = BECStatusBox.CORE_SERVICES.index("ScanServer")
assert status_box.model.rows[idx].status_label == "Busy"
assert view.rows["ScanServer"] is row_widget
assert row_widget.chip.text() == "Busy"
assert row_widget.busy and view._spinner.isActive()
def test_version_mismatch(status_box):
info, metrics = _all_services(extra=["CLIBECClient/old"])
info["CLIBECClient/old"] = _status("CLIBECClient/old", lib="3.0.0")
status_box.update_service_status(info, metrics)
mismatched = [r.service_name for r in status_box.model.rows if r.version_mismatch]
assert mismatched == ["CLIBECClient/old"]
assert "1 version mismatch" in status_box.model.detail
def test_copy_details(status_box):
status_box.update_service_status(*_all_services())
status_box.model.copy_details("DeviceServer")
text = QApplication.clipboard().text()
assert text.startswith("DeviceServer: Running")
assert "Host: console" in text
assert "PID: 42" in text
def test_widget_view_expand_and_reuse(qtbot, mocked_client):
box = create_widget(
qtbot, BECStatusBox, client=mocked_client, bec_service_status_mixin=mock.MagicMock()
)
box.update_service_status(*_all_services())
view = box.view
row_widget = view.rows["DeviceServer"]
view._toggle("DeviceServer")
assert row_widget.expanded and not row_widget.details.isHidden()
view._toggle("ScanServer")
assert not row_widget.expanded
assert view.rows["ScanServer"].expanded
box.update_service_status(*_all_services())
assert view.rows["DeviceServer"] is row_widget
assert view.rows["ScanServer"].expanded
def test_friendly_name():
assert friendly_name("DeviceServer") == ("Device server", "")
assert friendly_name("CLIBECClient/0123456789") == ("IPython client", "012345")
assert friendly_name("MyNewService") == ("My new service", "")
def test_format_duration():
assert format_duration(5) == "5 s"
assert format_duration(125) == "2 min"
assert format_duration(3 * 3600 + 300) == "3 h 5 min"
assert format_duration(2 * 86400 + 4 * 3600) == "2 d 4 h"
def test_build_rows_order_and_groups():
services = [
BECServiceInfoContainer("CLIBECClient/b", "RUNNING", {}, None),
BECServiceInfoContainer("ScanServer", "ERROR", {}, None),
BECServiceInfoContainer("DeviceServer", "IDLE", {}, None),
BECServiceInfoContainer("Weird", "SOMETHING", {}, None),
]
rows = build_rows(services, ["DeviceServer", "ScanServer"])
assert [r.service_name for r in rows] == [
"DeviceServer",
"ScanServer",
"CLIBECClient/b",
"Weird",
]
assert [r.group for r in rows] == [CORE_GROUP, CORE_GROUP, OTHER_GROUP, OTHER_GROUP]
assert rows[1].tone == Tone.BAD
assert rows[3].status == "NOTCONNECTED"
def test_widget_view_follows_theme(qtbot, mocked_client):
from bec_widgets.utils.colors import apply_theme
box = create_widget(
qtbot, BECStatusBox, client=mocked_client, bec_service_status_mixin=mock.MagicMock()
)
box.update_service_status(*_all_services())
apply_theme("dark")
dark = box.view.styleSheet()
apply_theme("light")
qtbot.waitUntil(lambda: box.view.styleSheet() != dark)
apply_theme("dark")
qtbot.waitUntil(lambda: box.view.styleSheet() == dark)
def _restarted(started):
info, metrics = _all_services()
for name in BECStatusBox.CORE_SERVICES:
metrics[name].metrics["create_time"] = started
return info, metrics
@pytest.fixture
def send(status_box):
with mock.patch.object(status_box.client.connector, "send") as send_mock:
yield send_mock
def test_restart_needs_scihub(status_box, send):
status_box.update_service_status(*_all_services(skip=["SciHub"]))
assert not status_box.model.can_restart
status_box.model.request_restart()
send.assert_not_called()
status_box.update_service_status(*_all_services())
assert status_box.model.can_restart
def test_restart_confirm_cancel(status_box, send):
status_box.update_service_status(*_all_services())
with mock.patch(
"bec_widgets.widgets.services.bec_status_box.bec_status_box.QMessageBox.warning",
return_value=QMessageBox.StandardButton.Cancel,
) as dialog:
status_box.model.request_restart()
dialog.assert_called_once()
send.assert_not_called()
def test_restart_progress_and_done(qtbot, status_box, send):
status_box.update_service_status(*_all_services())
with (
mock.patch(
"bec_widgets.widgets.services.bec_status_box.bec_status_box.QMessageBox.warning",
return_value=QMessageBox.StandardButton.Yes,
),
mock.patch.object(status_box, "_reload_client") as reload_client,
):
status_box.model.request_restart()
endpoint, msg = send.call_args[0]
assert endpoint == MessageEndpoints.service_request()
assert msg.action == "restart"
model = status_box.model
assert model.restart_state == RestartState.RUNNING
assert not model.can_restart
# old processes are still reporting: nothing counts as restarted yet
status_box.update_service_status(*_restarted(time.time() - 100))
assert model.restart_text.endswith("0/5")
status_box.update_service_status(*_all_services(skip=BECStatusBox.CORE_SERVICES))
assert model.restart_state == RestartState.RUNNING
status_box.update_service_status(*_restarted(time.time() + 1))
assert model.restart_state == RestartState.DONE
assert model.can_restart
# the client reload runs on the thread pool
qtbot.waitUntil(lambda: reload_client.called)
reload_client.assert_called_once()
def test_restart_timeout(status_box, send):
status_box.update_service_status(*_all_services())
with mock.patch.object(status_box.model, "restart_requested"):
status_box.request_restart()
status_box._restart_timed_out()
assert status_box.model.restart_state == RestartState.FAILED
assert "Device server" in status_box.model.restart_text
def test_header_follows_restart(status_box):
status_box.update_service_status(*_all_services())
header = status_box.view.header
assert header._tone == Tone.OK
status_box.model.set_restart(RestartState.RUNNING, "Restarting BEC server · 1/5")
assert header.headline.text() == "Restarting BEC server · 1/5"
assert header._tone == Tone.ACCENT
assert header._spin.isActive() and not header.restart_button.isEnabled()
status_box.model.set_restart(RestartState.FAILED, "Restart not finished")
assert header._tone == Tone.BAD and header._pulse.isActive()
status_box.model.set_restart(RestartState.NONE)
assert header.headline.text() == "All core services running"
assert not header._pulse.isActive() and not header._spin.isActive()
def test_service_status_read_off_the_gui_thread(qtbot):
import threading
from bec_widgets.widgets.services.bec_status_box.bec_status_box import BECServiceStatusMixin
client = mock.MagicMock()
read_threads, release = [], threading.Event()
def read():
read_threads.append(threading.get_ident())
release.wait(5)
client._services_info = {"DeviceServer": "info"}
client._services_metric = {"DeviceServer": "metric"}
client._update_existing_services.side_effect = read
service_status = BECServiceStatusMixin(None, client)
try:
updates = []
service_status.services_update.connect(lambda info, metric: updates.append((info, metric)))
service_status._get_service_status()
# a tick while the read is still running does not start a second one
service_status._get_service_status()
qtbot.waitUntil(lambda: bool(read_threads))
assert read_threads[0] != threading.main_thread().ident
assert not updates
release.set()
qtbot.waitUntil(lambda: bool(updates))
assert updates == [({"DeviceServer": "info"}, {"DeviceServer": "metric"})]
assert client._update_existing_services.call_count == 1
assert service_status._worker is None
finally:
release.set()
service_status.cleanup()
def test_service_status_poller_is_shared_and_follows_its_viewers(qtbot, mocked_client):
"""Two status boxes (e.g. in two windows) share one poller; it reads only while one is shown."""
from bec_widgets.widgets.services.bec_status_box.bec_status_box import BECServiceStatusMixin
first = create_widget(qtbot, BECStatusBox, client=mocked_client)
second = create_widget(qtbot, BECStatusBox, client=mocked_client)
poller = first.bec_service_status
assert poller is second.bec_service_status is BECServiceStatusMixin.shared(mocked_client)
assert poller._service_update_timer.interval() == 3000
assert not poller.polling # nothing shown yet
with mock.patch.object(poller, "_get_service_status") as read:
first.show()
qtbot.waitExposed(first)
assert poller.polling
read.assert_called_once() # the first viewer starts with a read
second.show()
qtbot.waitExposed(second)
read.assert_called_once() # the second one shares the running poll
first.hide()
assert poller.polling
second.hide()
assert not poller.polling # nothing shows the status: no polling
first.show()
qtbot.waitExposed(first)
assert poller.polling and read.call_count == 2 # resumes with a fresh read
first.close()
second.close()
assert not poller.polling
def test_a_new_status_box_gets_the_last_result_at_once(qtbot, mocked_client):
from bec_widgets.widgets.services.bec_status_box.bec_status_box import BECServiceStatusMixin
poller = BECServiceStatusMixin.shared(mocked_client)
poller.last_update = _all_services()
box = create_widget(qtbot, BECStatusBox, client=mocked_client)
assert box.get_server_state() == "RUNNING"
assert len(box.model.rows) == len(BECStatusBox.CORE_SERVICES)
def test_cleanup_of_one_box_keeps_the_shared_poll_for_the_other(qtbot, mocked_client):
first = create_widget(qtbot, BECStatusBox, client=mocked_client)
second = create_widget(qtbot, BECStatusBox, client=mocked_client)
poller = first.bec_service_status
with mock.patch.object(poller, "_get_service_status"):
first.show()
second.show()
qtbot.waitExposed(second)
first.cleanup()
assert poller.polling # the second box still shows it
updates = []
poller.services_update.connect(lambda *_: updates.append(True))
with mock.patch.object(first, "update_service_status") as first_update:
poller.services_update.emit(*_all_services())
first_update.assert_not_called() # the cleaned-up box is disconnected
second.cleanup()
assert not poller.polling
second.close()
def test_icons_render_at_the_screen_pixel_ratio(status_box, monkeypatch):
"""The icons are drawn at the device pixel ratio, so they are sharp on HiDPI screens."""
from qtpy.QtGui import QColor
from bec_widgets.utils import theme_utils
from bec_widgets.widgets.services.bec_status_box.status_box_widgets import rotated_pixmap
asked = []
def ratio(widget):
asked.append(widget)
return 2.0
# QLabel.pixmap() hands back a copy at the label's own ratio, so check the lookup instead
monkeypatch.setattr(theme_utils, "_device_pixel_ratio", ratio)
info, metrics = _all_services()
info["ScanServer"] = _status("ScanServer", BECStatus.BUSY)
status_box.update_service_status(info, metrics)
view = status_box.view
view.apply_theme()
row, busy = view.rows["DeviceServer"], view.rows["ScanServer"]
busy.rotate_icon()
for widget in (
row.icon,
row.chevron,
row.copy_button,
busy.icon,
view.header.spinner,
view.header.restart_button,
):
assert widget in asked
# a spinning icon keeps its pixel ratio and its size after the rotation
pixmap = theme_utils.crisp_pixmap("progress_activity", 20, QColor("red"), widget=busy.icon)
turned = rotated_pixmap(pixmap, 30)
assert turned.devicePixelRatio() == 2.0
assert turned.size() == pixmap.size()