8000 Implement `StatusOverviewWidget` by yakutovicha · Pull Request #239 · aiidalab/aiidalab-home · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 1 addition & 88 deletions control.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -57,94 +57,7 @@
"id": "4",
"metadata": {},
"outputs": [],
"source": [
"sections = {\n",
" \"Status\": control.StatusOverviewWidget,\n",
" \"Resources\": control.SystemResourcesWidget,\n",
" \"Storage\": control.StorageWidget,\n",
" \"Daemon\": control.DaemonControlWidget,\n",
" \"Processes\": control.ProcessControlWidget,\n",
" \"Profiles\": control.ProfileControlWidget,\n",
" \"Danger zone\": control.DangerZoneWidget,\n",
"}\n",
"\n",
"placeholders = [\n",
" ipw.VBox([ipw.HTML(\"Loading... <i class='fa fa-spinner fa-spin'></i>\")])\n",
" for _ in sections\n",
"]\n",
"section_names = list(sections)\n",
"section_instances = {}\n",
"\n",
"tabs = ipw.Tab(children=placeholders, titles=section_names)\n",
"\n",
"\n",
"def open_section(index):\n",
" name = section_names[index]\n",
" placeholder = placeholders[index]\n",
" widget = section_instances.get(name)\n",
" if widget is None:\n",
" try:\n",
" widget = sections[name]()\n",
" except Exception as exc:\n",
" # Show the error but do NOT cache it: revisiting the tab retries.\n",
" placeholder.children = [\n",
" ipw.HTML(\n",
" f'<div class=\"alert alert-danger\" role=\"alert\">'\n",
" f'Failed to open the \"{name}\" section: {exc}</div>'\n",
" )\n",
" ]\n",
" return\n",
" section_instances[name] = widget\n",
" placeholder.children = [widget]\n",
"\n",
" # First open and every revisit both probe for fresh data.\n",
" refresher = getattr(widget, \"refresh\", None)\n",
" if callable(refresher):\n",
" refresher()\n",
"\n",
"\n",
"def on_tab_change(change):\n",
" open_section(change[\"new\"])\n",
"\n",
"\n",
"tabs.observe(on_tab_change, names=\"selected_index\")\n",
"\n",
"try:\n",
" _logo_svg = Path(\"aiidalab_logo_v4.svg\").read_text()\n",
"except OSError:\n",
" header = ipw.HTML(\n",
" \"<div style='margin:4px 0 12px 0;'>\"\n",
" \"<h1 style='margin:0;font-size:26px;'>AiiDAlab control</h1>\"\n",
" \"<div style='color:gray;'>Manage your AiiDAlab installation.</div>\"\n",
" \"</div>\"\n",
" )\n",
"else:\n",
" _logo_svg = _logo_svg.split(\"?>\", 1)[-1].strip()\n",
" _logo_svg = re.sub(\n",
" r\"<svg\\b[^>]*>\",\n",
" lambda m: re.sub(r'\\s(width|height)=\"[^\"]*\"', \"\", m.group(0)),\n",
" _logo_svg,\n",
" count=1,\n",
" )\n",
" header = ipw.HTML(\n",
" \"<div style='display:flex;align-items:center;gap:16px;margin:4px 0 12px 0;'>\"\n",
" f\"<div style='width:56px;flex:none;'>{_logo_svg}</div>\"\n",
" \"<div>\"\n",
" \"<h1 style='margin:0;font-size:26px;'>AiiDAlab control</h1>\"\n",
" \"<div style='color:gray;'>Manage your AiiDAlab installation.</div>\"\n",
" \"</div></div>\"\n",
" )\n",
"\n",
"tabs.layout = ipw.Layout(max_width=\"1100px\")\n",
"header.layout = ipw.Layout(max_width=\"1100px\")\n",
"\n",
"display(header)\n",
"display(tabs)\n",
"# selected_index is already 0, so the observer never fired for the landing\n",
"# tab; fill it explicitly AFTER display so the page shell (tab bar +\n",
"# \"Loading...\") paints before the first, potentially slow, section probe runs.\n",
"open_section(0)"
]
"source": "sections = {\n \"AiiDA status\": control.AiidaStatusOverviewWidget,\n \"Resources\": control.SystemResourcesWidget,\n \"Storage\": control.StorageWidget,\n \"Daemon\": control.DaemonControlWidget,\n \"Processes\": control.ProcessControlWidget,\n \"Profiles\": control.ProfileControlWidget,\n \"Danger zone\": control.DangerZoneWidget,\n}\n\nplaceholders = [\n ipw.VBox([ipw.HTML(\"Loading... <i class='fa fa-spinner fa-spin'></i>\")])\n for _ in sections\n]\nsection_names = list(sections)\nsection_instances = {}\n\ntabs = ipw.Tab(children=placeholders, titles=section_names)\n\n\ndef open_section(index):\n name = section_names[index]\n placeholder = placeholders[index]\n widget = section_instances.get(name)\n if widget is None:\n try:\n widget = sections[name]()\n except Exception as exc:\n # Show the error but do NOT cache it: revisiting the tab retries.\n placeholder.children = [\n ipw.HTML(\n f'<div class=\"alert alert-danger\" role=\"alert\">'\n f'Failed to open the \"{name}\" section: {exc}</div>'\n )\n ]\n return\n section_instances[name] = widget\n placeholder.children = [widget]\n\n # First open and every revisit both probe for fresh data.\n refresher = getattr(widget, \"refresh\", None)\n if callable(refresher):\n refresher()\n\n\ndef on_tab_change(change):\n open_section(change[\"new\"])\n\n\ntabs.observe(on_tab_change, names=\"selected_index\")\n\ntry:\n _logo_svg = Path(\"aiidalab_logo_v4.svg\").read_text()\nexcept OSError:\n header = ipw.HTML(\n \"<div style='margin:4px 0 12px 0;'>\"\n \"<h1 style='margin:0;font-size:26px;'>AiiDAlab control</h1>\"\n \"<div style='color:gray;'>Manage your AiiDAlab installation.</div>\"\n \"</div>\"\n )\nelse:\n _logo_svg = _logo_svg.split(\"?>\", 1)[-1].strip()\n _logo_svg = re.sub(\n r\"<svg\\b[^>]*>\",\n lambda m: re.sub(r'\\s(width|height)=\"[^\"]*\"', \"\", m.group(0)),\n _logo_svg,\n count=1,\n )\n header = ipw.HTML(\n \"<div style='display:flex;align-items:center;gap:16px;margin:4px 0 12px 0;'>\"\n f\"<div style='width:56px;flex:none;'>{_logo_svg}</div>\"\n \"<div>\"\n \"<h1 style='margin:0;font-size:26px;'>AiiDAlab control</h1>\"\n \"<div style='color:gray;'>Manage your AiiDAlab installation.</div>\"\n \"</div></div>\"\n )\n\ntabs.layout = ipw.Layout(max_width=\"1100px\")\nheader.layout = ipw.Layout(max_width=\"1100px\")\n\ndisplay(header)\ndisplay(tabs)\n# selected_index is already 0, so the observer never fired for the landing\n# tab; fill it explicitly AFTER display so the page shell (tab bar +\n# \"Loading...\") paints before the first, potentially slow, section probe runs.\nopen_section(0)"
}
],
"metadata": {
Expand Down
209 changes: 197 additions & 12 deletions home/control.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,51 @@
from __future__ import annotations

import html
import json
import logging
import re
import threading
from datetime import datetime
from enum import Enum
from typing import Protocol

import aiida
import ipywidgets as ipw
from aiida import get_profile, manage, orm
from aiida.engine.daemon.client import DaemonException

from home.themes import ThemeDefault as Theme

_STATE_COLORS = {
"ok": Theme.COLORS.CHECK,
"warning": Theme.COLORS.AIIDALAB_ORANGE,
"error": Theme.COLORS.DANGER,
}
logger = logging.getLogger(__name__)


class _DaemonClient(Protocol):
"""The subset of `DaemonClient` that `_probe_daemon` relies on."""

@property
def is_daemon_running(self) -> bool: ...

def get_number_of_workers(self) -> int: ...


class State(str, Enum):
color: str
icon: str

def __new__(cls, value, color, icon):
obj = str.__new__(cls, value)
obj._value_ = value
obj.color = color
obj.icon = icon
return obj

OK = "ok", Theme.COLORS.CHECK, Theme.ICONS.CHECK
WARNING = "warning", Theme.COLORS.AIIDALAB_ORANGE, Theme.ICONS.WARNING
ERROR = "error", Theme.COLORS.DANGER, Theme.ICONS.TIMES_CIRCLE


def _state_span(state, text) -> str:
return f"<span style='color:{_STATE_COLORS[state]}'>{html.escape(text)}</span>"
def _state_span(state: State, text) -> str:
return f"<span style='color:{state.color}'>{html.escape(text)}</span>"


class ControlSectionWidget(ipw.VBox):
Expand Down Expand Up @@ -59,13 +90,13 @@ def __init__(self, children, show_refresh_button=True):
self.layout.padding = "8px 0 0 0"

def show_success(self, text):
self.info.value = _state_span("ok", text)
self.info.value = _state_span(State.OK, text)

def show_warning(self, text):
self.info.value = _state_span("warning", text)
self.info.value = _state_span(State.WARNING, text)

def show_error(self, text):
self.info.value = _state_span("error", text)
self.info.value = _state_span(State.ERROR, text)

def show_plain(self, text):
self.info.value = html.escape(text)
Expand Down Expand Up @@ -116,11 +147,165 @@ def __init__(self):
super().__init__([ipw.HTML("To be implemented.")])


class StatusOverviewWidget(ControlSectionWidget):
def _storage_summary(profile) -> str | None:
"""Compact, credential-free one-line summary of a profile's storage.

Returns None for a backend it doesn't recognize, leaving it to the
caller to fall back to `str(storage)`.

Never renders `profile.storage_config` raw — it contains
`database_password`.
"""
backend = profile.storage_backend
try:
if backend == "core.psql_dos":
config = profile.storage_config
return (
f"PostgreSQL {config['database_name']} @ "
f"{config['database_hostname']}:{config['database_port']} "
"+ file repository"
)
if backend == "core.sqlite_dos":
return "SQLite database + file repository"
except KeyError:
pass
return None


def _current_default_profile_name() -> str | None:
"""Read the on-disk config's default profile name directly.

Bypasses AiiDA's cached config object, which does not pick up a
default changed by another process (e.g. `verdi profile setdefault`
run in a terminal) for the lifetime of this kernel.
"""
with open(manage.get_config().filepath) as handle:
return json.load(handle).get("default_profile")


def _sanitize_broker_url(url) -> str:
"""Strip credentials (`user:pass@`) from a broker URL, e.g. an AMQP URL.

Matches through the last `@` so a password containing `@` isn't
partially leaked.
"""
return re.sub(r"://[^/ ]+@", "://", url)


class AiidaStatusOverviewWidget(ControlSectionWidget):
description = "Health of the services behind AiiDA."

def __init__(self):
super().__init__([ipw.HTML("To be implemented.")])
self._daemon: _DaemonClient = manage.get_manager().get_daemon_client()
self._status = ipw.HTML()
super().__init__([self._status])

@classmethod
def _status_row(cls, state: State, label, text, tooltip=None):
icon = state.icon
color = state.color
text_color = "inherit" if state == State.OK else color
title_attr = f" title='{html.escape(tooltip)}'" if tooltip else ""
return (
f"<tr>"
f"<td style='padding:1px 8px;'>"
f"<span style='color:{color}'>{icon}</span></td>"
f"<td style='padding:1px 8px;'><b>{html.escape(label)}</b></td>"
f"<td style='color:{text_color};padding:1px 8px;'{title_attr}>"
f"{html.escape(text)}</td>"
f"</tr>"
)

def _get_aiida_version(self):
return self._status_row(State.OK, "version", f"AiiDA v{aiida.__version__}")

def _get_config_dir(self):
return self._status_row(State.OK, "config", manage.get_config().dirpath)

def _probe_profile(self):
# Stashed for `_probe_storage`, which needs to know whether a
# profile is loaded; reset at the top of every `_do_refresh`.
if self._profile is None:
return self._status_row(State.ERROR, "profile", "No profile loaded")

try:
default_name = _current_default_profile_name()
except Exception:
logger.exception("Status overview: could not read on-disk default profile")
default_name = None

if default_name is not None and default_name != self._profile.name:
return self._status_row(
State.WARNING,
"profile",
"Change of profile detected - reload the page to apply",
)
return self._status_row(State.OK, "profile", self._profile.name)

def _probe_storage(self):
if self._profile is None:
return self._status_row(State.ERROR, "storage", "No profile loaded")
# The storage object is cached, so it does not re-verify the
# connection; run a cheap query to actually probe the database.
orm.QueryBuilder().append(orm.User).count()
storage = manage.get_manager().get_profile_storage()
storage_text = str(storage)
summary = _storage_summary(self._profile) or storage_text
return self._status_row(State.OK, "storage", summary, tooltip=storage_text)

def _probe_broker(self):
broker = manage.get_manager().get_broker()
if broker is None:
return self._status_row(State.WARNING, "broker", "No broker configured")
sanitized = _sanitize_broker_url(str(broker))
return self._status_row(State.OK, "broker", sanitized, tooltip=sanitized)

def _probe_daemon(self):
@yakutovicha yakutovicha Aug 19, 2026 •
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@danielhollas, just a small heads-up: since you asked to display information about the workers' CPU utilization.

I intend to add this to the DaemonControlWidget -- see the class placeholder above ⬆️.

"""Fetch the daemon status and return a row for the status table."""
client = self._daemon
if not client.is_daemon_running:
< B2A1 /td> return self._status_row(State.WARNING, "daemon", "Daemon is not running")
try:
workers = client.get_number_of_workers()
except DaemonException:
# The daemon stopped between the check and the call.
return self._status_row(State.WARNING, "daemon", "Daemon is not running")
if workers == 0:
# The supervisor process is up, but with no workers nothing
# picks jobs off the queue — indistinguishable from not running.
return self._status_row(
State.WARNING, "daemon", "Daemon is running with 0 workers"
)
return self._status_row(
State.OK, "daemon", f"Daemon is running with {workers} worker(s)"
)

def _run_probe(self, label, probe):
"""Run `probe()` and return its row, or an error row if it raises."""
try:
return probe()
except Exception as exc:
logger.exception("Status overview: %s probe failed", label)
return self._status_row(State.ERROR, label, str(exc))

def _do_refresh(self):
try:
self._profile = get_profile()
except Exception:
logger.exception("Status overview: profile probe failed")
self._profile = None
probes = (
("version", self._get_aiida_version),
("config", self._get_config_dir),
("profile", self._probe_profile),
("storage", self._probe_storage),
("broker", self._probe_broker),
("daemon", self._probe_daemon),
)
rows = [self._run_probe(label, probe) for label, probe in probes]
self._status.value = (
"<table style='border-collapse:collapse;'>" + "".join(rows) + "</table>"
)


class SystemResourcesWidget(ControlSectionWidget):
Expand Down
Loading
0