8000 Implement the Danger zone section on the Control page by yakutovicha · Pull Request #262 · 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
29 commits
Select commit Hold shift + click to select a range
daf6aca
Implement Danger zone control section
yakutovicha Sep 28, 2026
3056d7e
Describe the reset trigger without a command
yakutovicha Sep 28, 2026
1ddd757
Test the Danger zone's unreadable-flag paths
yakutovicha Sep 28, 2026
0efc3ef
Show the factory-reset confirmation phrase
yakutovicha Sep 28, 2026
6078664
Adapt the Danger zone to the single `local` reset mode
yakutovicha Oct 23, 2026
64eed04
Fit the Danger zone buttons to their labels
yakutovicha Oct 23, 2026
e5d9aa8
Call the Danger zone reset a package reset
yakutovicha Oct 23, 2026
47e0ba3
Show only the package reset notice on the home page
yakutovicha Oct 23, 2026
54bd585
Share the package reset notice between both pages
yakutovicha Oct 23, 2026
f66fa03
Test the package reset module directly
yakutovicha Oct 23, 2026
7432bef
Test the package reset notice once, directly
yakutovicha Oct 23, 2026
99852e4
Merge the Danger zone's schedule failure tests
yakutovicha Oct 23, 2026
7568a46
Say what the package reset notice actually blocks
yakutovicha Oct 23, 2026
d0a5389
Parse the reset mode like the container does
yakutovicha Oct 23, 2026
7732dca
Give the package reset a title and a one-line explanation
yakutovicha Oct 23, 2026
4d30de5
List how to restart the container in the reset notice
yakutovicha Oct 23, 2026
ebea949
Name the aiidalab-launch profile in the restart command
yakutovicha Oct 23, 2026
48b342c
Point to aiidalab-launch status for the profile name
yakutovicha Oct 23, 2026
ec4e068
Update home/control.py
yakutovicha Oct 23, 2026
24df05c
Update home/package_reset.py
yakutovicha Oct 26, 2026
f726ecb
Remove extra space from reset message
edan-bainglass Oct 26, 2026
1918737
Apply batched suggestions from code review
yakutovicha Oct 27, 2026
9476b59
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 27, 2026
843b920
Point to the reset script's new location
yakutovicha Oct 27, 2026
8903c96
Drop the read-back check when scheduling a reset
yakutovicha Oct 27, 2026
f4ccce5
Show terminal link just in case something goes terribly wrong.
yakutovicha Oct 27, 2026
f561422
Treat a bad reset flag file as no reset, like the container
yakutovicha Oct 27, 2026
2bacb5c
Refresh the Danger zone synchronously
yakutovicha Oct 27, 2026
80416fd
Merge branch 'main' into feature/danger-zone-tab
yakutovicha Oct 27, 2026
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
77 changes: 75 additions & 2 deletions home/control.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from aiida import get_profile, manage, orm
from aiida.engine.daemon.client import DaemonException

from home import package_reset
from home.themes import ThemeDefault as Theme

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -518,8 +519,80 @@ def __init__(self):
super().__init__([ipw.HTML("To be implemented.")])


_RESET_CONFIRM_PHRASE = "reset-packages"


class DangerZoneWidget(ControlSectionWidget):
description = "Irreversible actions that can lead to data loss."
description = "Actions that reset parts of your AiiDAlab environment."

def __init__(self):
super().__init__([ipw.HTML("To be implemented.")])
self._confirm_text = ipw.Text(layout=ipw.Layout(width="220px"))
self._confirm_text.observe(self._on_confirm_text_change, names="value")
self._schedule_button = ipw.Button(
description="Schedule package reset",
button_style="danger",
icon="exclamation-triangle",
disabled=True,
layout=ipw.Layout(width="fit-content"),
)
Comment thread
yakutovicha marked this conversation as resolved.
Resolved
self._schedule_button.on_click(self._on_schedule)
self._schedule_box = ipw.VBox(
[
ipw.HTML(
"<div style='font-size:15px;font-weight:600;'>"
f"{html.escape(package_reset.RESET_LABEL)}</div>"
f"<div style='color:{Theme.COLORS.GRAY};font-size:13px;"
"margin:2px 0 10px 0;'>"
"On the next restart of the AiiDAlab container, ~/.local "
"will move to ~/.local~&lt;date&gt;. Apps, AiiDA data, "
"and profiles remain untouched.</div>"
),
ipw.HTML(f"To confirm, type <code>{_RESET_CONFIRM_PHRASE}</code>:"),
ipw.HBox(
[self._confirm_text, self._schedule_button],
layout=ipw.Layout(align_items="center"),
),
]
)

# Built once and only shown or hidden: its content does not change.
self._notice = package_reset.PackageResetNotice(on_cancelled=self._on_cancelled)

super().__init__([self._schedule_box, self._notice])
self.layout.border = f"1px solid {Theme.COLORS.DANGER}"
self.layout.padding = "12px"
# Unlike other sections, refreshing is instant, so show the right view
# from the start.
self.refresh()

def _on_confirm_text_change(self, change):
self._schedule_button.disabled = change["new"].strip() != _RESET_CONFIRM_PHRASE

def _on_schedule(self, _=None):
try:
package_reset.schedule()
except Exception as exc:
self.show_error(f"Failed to schedule the package reset: {exc}")
else:
self.info.value = ""
self._confirm_text.value = ""
# Show what is on disk now, whether or not the write went through.
self.refresh()

def _on_cancelled(self):
self.info.value = ""
self.refresh()

def refresh(self, _=None):
# Checking the flag file is instant, so refresh synchronously, not on
# the base class's background thread: nothing races the buttons.
scheduled = package_reset.is_scheduled()
if not scheduled:
# Don't show a stale cancel error when the notice comes back.
self._notice.error.value = ""
self._schedule_box.layout.display = "none" if scheduled else ""
self._notice.layout.display = "" if scheduled else "none"
if self._last_updated is not None:
self._last_updated.value = (
f"Last updated: {datetime.now().strftime('%H:%M:%S')}"
)
133 changes: 133 additions & 0 deletions home/package_reset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
"""The package reset that the AiiDAlab container performs on its next start.

Kept free of heavy imports: the home page checks it before rendering anything.
"""

import html
import os
from pathlib import Path

import ipywidgets as ipw

from home.themes import ThemeDefault as Theme

# The container's entrypoint hook (from aiidalab-docker-stack), at
# /usr/local/bin/before-notebook.d/05_factory-reset.sh, reads this file on
# start, performs the reset mode it contains and removes it.
_FACTORY_RESET_FILE = Path.home() / "AIIDALAB_FACTORY_RESET"

# The only reset mode of that script; it ignores any other content.
_RESET_MODE = "local"
RESET_LABEL = "Reset user-installed Python packages"


def is_scheduled() -> bool:
"""Whether the container performs the reset on its next start.

Applies the script's own rule, so that nothing it would ignore blocks the
home page: a regular file, not a symlink, whose first 64 bytes are the
mode, ignoring whitespace. Compared as bytes, so any content is safe.
"""
if _FACTORY_RESET_FILE.is_symlink() or not _FACTORY_RESET_FILE.is_file():
return False
try:
with _FACTORY_RESET_FILE.open("rb") as f:
content = f.read(64)
except OSError:
return False
return b"".join(content.split()) == _RESET_MODE.encode()


def schedule():
# Replace whatever is there rather than write through a symlink.
_FACTORY_RESET_FILE.unlink(missing_ok=True)
_FACTORY_RESET_FILE.write_text(_RESET_MODE)


def cancel():
_FACTORY_RESET_FILE.unlink(missing_ok=True)


def scheduled_message() -> str:
"""An alert describing the scheduled reset and how to perform it."""
# Set by JupyterHub in the environment of the user's server.
hub_home = os.environ.get("JUPYTERHUB_BASE_URL", "/") + "hub/home"
return f"""
<div class="alert alert-warning" role="alert">
<div style="line-height: 1.5">
A reset has been scheduled: <b>{html.escape(RESET_LABEL)}</b>
<br />
Please restart your AiiDAlab container.
</div>
<div>
<h2>How to restart</h2>
<h3>On an AiiDAlab server</h3>
<ul style="margin: 0; padding-left: 20px; line-height: 1.8">
<li>
Open the
<a class="alert-link" href="{html.escape(hub_home)}" target="_blank">
Control Panel</a
>.
</li>
<li>Click <b>Stop My Server</b> and wait.</li>
<li>Once available, click <b>Start My Server</b>.</li>
</ul>
<h3>On a local machine</h3>
<h4>Using aiidalab-launch</h4>
<ul style="margin: 0; padding-left: 20px; line-height: 1.8">
<li>
Find your active profile with
<code>aiidalab-launch status</code>
</li>
<li>
Run <code>aiidalab-launch start --restart -p &lt;profile&gt;</code>
</li>
</ul>
<h4>Using Docker directly</h4>
<ul style="margin: 0; padding-left: 20px; line-height: 1.8">
<li>Find your active container with <code>docker ps</code></li>
<li>Run <code>docker restart &lt;container&gt;</code></li>
</ul>
</div>
</div>
"""


class PackageResetNotice(ipw.VBox):
"""Notice of a scheduled package reset, with a way to cancel it."""

def __init__(self, on_cancelled):
self._on_cancelled = on_cancelled
self.cancel_button = ipw.Button(
description="Cancel package reset",
icon="undo",
layout=ipw.Layout(width="fit-content"),
)
self.cancel_button.on_click(self._on_cancel)
self.error = ipw.HTML()
# The home page hides the terminal link while a reset is scheduled.
fallback = ipw.HTML(
f"<div style='color:{Theme.COLORS.GRAY};font-size:13px;margin-top:8px;'>"
"<b>If cancelling fails:</b> open a "
"<a href='./terminal.ipynb' target='_blank'>terminal</a> and run "
f"<code>rm {html.escape(str(_FACTORY_RESET_FILE))}</code></div>"
)
super().__init__(
children=[
ipw.HTML(scheduled_message()),
self.cancel_button,
self.error,
fallback,
]
)

def _on_cancel(self, _=None):
try:
cancel()
except Exception as exc:
self.error.value = (
f"<span style='color: {Theme.COLORS.DANGER}'>"
f"Failed to cancel the package reset: {html.escape(str(exc))}</span>"
)
else:
self._on_cancelled()
16 changes: 12 additions & 4 deletions home/start_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from aiidalab.config import AIIDALAB_APPS
from markdown import Markdown

from home import package_reset
from home.utils import load_widget
from home.widgets import AppStatusInfoWidget

Expand Down Expand Up @@ -73,8 +74,17 @@ def read_config(self):
return {"order": [], "hidden": []} # default config

def render(self):
"""Rendering all apps."""
"""Rendering all apps, or only the notice of a scheduled package reset."""
if package_reset.is_scheduled():
# Nothing should be done in an environment that is about to be reset.
self.output.children = [
package_reset.PackageResetNotice(on_cancelled=self.render)
]
else:
self.output.children = self._create_app_children()
return self.output

def _create_app_children(self):
home = self._create_home_widget()
children = [home]

Expand All @@ -95,9 +105,7 @@ def render(self):

children.append(self._app_widgets[name])

self.output.children = children

return self.output
return children

def load_apps(self):
"""Load apps according to the order defined in the config file."""
Expand Down
24 changes: 24 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,37 @@
from collections.abc import Mapping
from pathlib import Path

import pytest
from aiida import engine, orm
from aiida.common import LinkType
from aiida.workflows.arithmetic.multiply_add import MultiplyAddWorkChain
from plumpy import ProcessState

import home.package_reset

pytest_plugins = ["aiida.manage.tests.pytest_fixtures"]

# The container resets ~/.local on its next start while this file exists.
_REAL_RESET_FLAG_FILE = Path.home() / "AIIDALAB_FACTORY_RESET"


@pytest.fixture(scope="session", autouse=True)
def _real_reset_flag_file_untouched():
"""Fail the session if a test wrote the real ~/AIIDALAB_FACTORY_RESET."""
existed = _REAL_RESET_FLAG_FILE.exists()
yield
assert existed or not _REAL_RESET_FLAG_FILE.exists(), (
f"a test created {_REAL_RESET_FLAG_FILE}; remove it"
)


@pytest.fixture
def reset_flag_file(tmp_path, monkeypatch):
"""A temporary path in place of the package reset's flag file."""
flag_file = tmp_path / "AIIDALAB_FACTORY_RESET"
monkeypatch.setattr(home.package_reset, "_FACTORY_RESET_FILE", flag_file)
return flag_file


@pytest.fixture
def generate_calc_job_node(aiida_localhost):
Expand Down
79 changes: 79 additions & 0 deletions tests/test_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
from aiida.engine.daemon.client import DaemonException

import home.control as control_module
from home import package_reset
from home.control import (
AiidaStatusOverviewWidget,
ControlSectionWidget,
DangerZoneWidget,
State,
SystemResourcesWidget,
_cpu_status,
Expand Down Expand Up @@ -444,3 +446,80 @@ def _raise():
# ...but CPU and disk still updated independently.
assert widget._cpu_bar.bar_style == "success"
assert widget._disk_bar.bar_style == "success"


@pytest.fixture
def danger_zone(reset_flag_file):
"""A DangerZoneWidget whose flag file is a temporary path."""
return DangerZoneWidget()


def _schedule_visible(widget):
return widget._schedule_box.layout.display != "none"


def test_danger_zone_shows_what_is_on_disk_right_away(reset_flag_file):
# From the start, and on every refresh, without a background thread.
reset_flag_file.write_text("local")
widget = DangerZoneWidget()
assert not _schedule_visible(widget)
# E.g. removed from a terminal, then the Refresh button clicked.
reset_flag_file.unlink()
assert widget.refresh_button is not None
assert widget._last_updated is not None
widget.refresh_button.click()
assert _schedule_visible(widget)
assert "Last updated" in widget._last_updated.value


def test_danger_zone_button_needs_confirmation_phrase(danger_zone):
widget = danger_zone
assert widget._schedule_button.disabled is True
widget._confirm_text.value = "reset"
assert widget._schedule_button.disabled is True
widget._confirm_text.value = " reset-packages "
assert widget._schedule_button.disabled is False
widget._confirm_text.value = "reset-packages!"
assert widget._schedule_button.disabled is True


def test_danger_zone_schedule_and_cancel(danger_zone, reset_flag_file):
widget = danger_zone
assert _schedule_visible(widget)

widget._confirm_text.value = "reset-packages"
widget._schedule_button.click()

assert reset_flag_file.read_text() == "local"
assert not _schedule_visible(widget)
assert "Reset user-installed Python packages" in widget._notice.children[0].value
# The confirmation is cleared, so the button is disabled again.
assert widget._confirm_text.value == ""
assert widget._schedule_button.disabled is True

widget._notice.cancel_button.click()
assert not reset_flag_file.exists()
assert _schedule_visible(widget)
assert widget.info.value == ""


@pytest.mark.parametrize("written", [None, "loc", "local"])
def test_danger_zone_schedule_failure(
danger_zone, reset_flag_file, monkeypatch, written
):
def _schedule():
if written is not None:
reset_flag_file.write_text(written)
raise OSError("disk trouble")

monkeypatch.setattr(package_reset, "schedule", _schedule)
widget = danger_zone
widget._confirm_text.value = "reset-packages"
widget._schedule_button.click()

assert State.ERROR.color in widget.info.value
assert "disk trouble" in widget.info.value
# The confirmation is kept, so the user can retry right away.
assert widget._confirm_text.value == "reset-packages"
# What is on disk is shown: only a complete flag file is a scheduled reset.
assert _schedule_visible(widget) == (written != "local")
Loading
Loading
0