diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index af6c3a5..f98025d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -130,6 +130,11 @@ python tools/web_update_manifest.py dist/coulobre_panel-0.10.2rc1-py3-none-any.w - Reuse existing templates and styles for controls, focus states, and status labels. Keep form inputs labelled and validation errors close to the field that needs attention. +- Use the shared workspace template for signed-in pages. Place the page + heading first, followed by local tabs and any account, domain, or list + filters. Start the main content below the divider. Keep status updates + separate from forms the operator or customer may be editing. + [Workspace template](src/coulobre/hosting/templates/hosting/workspace_page.html) ## Checks diff --git a/src/coulobre/hosting/access.py b/src/coulobre/hosting/access.py index 16e8952..157e1e7 100644 --- a/src/coulobre/hosting/access.py +++ b/src/coulobre/hosting/access.py @@ -74,7 +74,7 @@ def panel_access(request): ( label for label, links in groups - if any(url == active_link for url, _ in links) + if any(url == active_link for url, _, _ in links) ), "", ) diff --git a/src/coulobre/hosting/health_views.py b/src/coulobre/hosting/health_views.py index a7252ee..5328386 100644 --- a/src/coulobre/hosting/health_views.py +++ b/src/coulobre/hosting/health_views.py @@ -1,18 +1,28 @@ from datetime import timedelta +from pathlib import Path from django.conf import settings +from django.contrib import messages from django.contrib.auth.mixins import PermissionRequiredMixin +from django.core.exceptions import PermissionDenied +from django.http import HttpResponseBadRequest +from django.shortcuts import redirect from django.utils import timezone from django.utils.decorators import method_decorator from django.views.decorators.cache import never_cache from django.views.generic import TemplateView +from coulobre.operator_node import SERVICES as CONTROL_UNITS +from coulobre.operator_node import SOCKET, OperatorRequest from coulobre.service_health import HEALTH_DETAILS, SERVICES, HealthResult from .access import OperatorOnlyMixin -from .models import ServiceHealth +from .models import OperatorOperation, ServiceHealth +from .operator_tools import queue_operator_request STALE_AFTER = timedelta(minutes=5) +SERVICE_ACTIONS = ("reload", "restart") +CONTROL_TARGETS = {unit: target for target, unit in CONTROL_UNITS.items()} STATUS = { HealthResult.ACTIVE: ("Active", "ready"), HealthResult.INACTIVE: ("Unavailable", "suspended"), @@ -29,8 +39,37 @@ class ServiceHealthView( permission_required = "hosting.view_servicehealth" template_name = "hosting/service_health.html" + def can_control(self): + user = self.request.user + return user.is_superuser and user.is_verified() + + def post(self, request, *args, **kwargs): + if not self.can_control(): + raise PermissionDenied + action = request.POST.get("action", "") + target = request.POST.get("target", "") + if action not in SERVICE_ACTIONS or target not in { + CONTROL_TARGETS.get(SERVICES[service][1]) + for node in settings.SERVICE_HEALTH_TARGETS + if node.transport == "local" + for service in node.services + }: + return HttpResponseBadRequest("Choose a controlled local service.") + if not Path(SOCKET).is_socket(): + messages.error( + request, "The local operator worker is unavailable." + ) + else: + queue_operator_request( + request.user, OperatorRequest(action, target) + ) + messages.success(request, "Service operation queued.") + return redirect("panel:service_health") + def get_context_data(self, **kwargs): targets = settings.SERVICE_HEALTH_TARGETS + can_control = self.can_control() + controls_available = can_control and Path(SOCKET).is_socket() readings = { (reading.node, reading.service): reading for reading in ServiceHealth.objects.filter( @@ -48,17 +87,30 @@ class ServiceHealthView( readings.get((target.node, service)), cutoff, ) + | { + "control_target": CONTROL_TARGETS.get( + SERVICES[service][1] + ) + } for service in target.services ], ) for target in targets ], + controls_available=controls_available, + show_operation_history=can_control, + jobs=OperatorOperation.objects.filter( + action__in=SERVICE_ACTIONS, + ).order_by("-pk")[:20] + if can_control + else (), **kwargs, ) def service_row(service, reading, cutoff): row = { + "key": service, "name": SERVICES[service][0], "status": "Unknown", "style": "pending", diff --git a/src/coulobre/hosting/operator_tools.py b/src/coulobre/hosting/operator_tools.py index 78e5f47..c68510b 100644 --- a/src/coulobre/hosting/operator_tools.py +++ b/src/coulobre/hosting/operator_tools.py @@ -3,69 +3,61 @@ from pathlib import Path from django import forms from django.contrib import messages -from django.db import transaction +from django.db import DatabaseError, connection, transaction from django.shortcuts import redirect from django.utils import timezone +from django.utils.decorators import method_decorator +from django.views.decorators.cache import never_cache from django.views.generic import FormView, TemplateView -from coulobre.operator_node import SERVICES, SOCKET, OperatorRequest +from coulobre.operator_node import ( + DATABASE_COUNTERS_QUERY, + DATABASE_VERSION_QUERY, + SOCKET, + OperatorRequest, + database_report_from_rows, +) from .account_administration import OperatorAuthorization from .models import OperatorOperation from .tasks import run_operator_operation from .update_views import inspect_linked_nodes -TOOL_ACTIONS = { - "packages": ( - "Server package updates", - ("package-preview", "package-upgrade"), - ), - "services": ("System services", ("reload", "restart")), - "database": ("Database monitor", ("database-report",)), -} ACTION_LABELS = { "package-preview": "Review available updates", "package-upgrade": "Apply reviewed updates", - "reload": "Reload", - "restart": "Restart", - "database-report": "Collect MariaDB status", } -class OperatorToolForm(forms.Form): - action = forms.ChoiceField() - preview_id = forms.IntegerField(required=False, widget=forms.HiddenInput) - target = forms.ChoiceField( - required=False, - choices=[ - ("", "Select a service"), - *[(key, label) for key, label in SERVICES.items()], - ], +def queue_operator_request(user, spec, *, source=None): + job = OperatorOperation.objects.create( + actor=user, + action=spec.action, + target=spec.target, + plan=spec.plan, + source=source, ) + transaction.on_commit(lambda: run_operator_operation.delay(job.pk)) + + +class ServerUpdateForm(forms.Form): + action = forms.ChoiceField(choices=ACTION_LABELS.items()) + preview_id = forms.IntegerField(required=False, widget=forms.HiddenInput) confirm = forms.BooleanField( required=False, label="I reviewed the change and want to apply it" ) - def __init__(self, *args, actions, preview, **kwargs): + def __init__(self, *args, preview, **kwargs): super().__init__(*args, **kwargs) self.preview = preview self.initial["preview_id"] = preview.pk if preview else None - self.fields["action"].choices = [ - (action, ACTION_LABELS[action]) for action in actions - ] - if "reload" not in actions: - self.fields.pop("target") - if actions == ("database-report",): - self.fields.pop("confirm") def clean(self): data = super().clean() if self.errors: return data action = data["action"] - if action in {"reload", "restart", "package-upgrade"} and not data.get( - "confirm" - ): + if action == "package-upgrade" and not data.get("confirm"): self.add_error( "confirm", "Confirm this change before applying it." ) @@ -80,16 +72,15 @@ class OperatorToolForm(forms.Form): ) plan = self.preview.result.get("fingerprint", "") try: - self.spec = OperatorRequest(action, data.get("target", ""), plan) + self.spec = OperatorRequest(action, plan=plan) except ValueError as error: raise forms.ValidationError(str(error)) from error return data -class OperatorToolsView(OperatorAuthorization, FormView): - form_class = OperatorToolForm - template_name = "hosting/operator_tools.html" - page = "services" +class ServerUpdatesView(OperatorAuthorization, FormView): + form_class = ServerUpdateForm + template_name = "hosting/server_updates.html" def preview(self): return ( @@ -104,20 +95,14 @@ class OperatorToolsView(OperatorAuthorization, FormView): ) def get_form_kwargs(self): - return super().get_form_kwargs() | { - "actions": TOOL_ACTIONS[self.page][1], - "preview": self.preview() if self.page == "packages" else None, - } + return super().get_form_kwargs() | {"preview": self.preview()} def get_context_data(self, **kwargs): - title, actions = TOOL_ACTIONS[self.page] return super().get_context_data( - title=title, - page=self.page, available=Path(SOCKET).is_socket(), - jobs=OperatorOperation.objects.filter(action__in=actions).order_by( - "-pk" - )[:20], + jobs=OperatorOperation.objects.filter( + action__in=ACTION_LABELS + ).order_by("-pk")[:20], **kwargs, ) @@ -145,18 +130,40 @@ class OperatorToolsView(OperatorAuthorization, FormView): "package update.", ) return self.form_invalid(form) - job = OperatorOperation.objects.create( - actor=self.request.user, - action=spec.action, - target=spec.target, - plan=spec.plan, + queue_operator_request( + self.request.user, + spec, source=form.preview if spec.action == "package-upgrade" else None, ) - transaction.on_commit(lambda: run_operator_operation.delay(job.pk)) messages.success(self.request, "Host operation queued.") return redirect(self.request.path) +def current_database_report(): + if connection.vendor != "mysql": + return None + try: + with connection.cursor() as cursor: + cursor.execute(DATABASE_VERSION_QUERY) + version = cursor.fetchone() + cursor.execute(DATABASE_COUNTERS_QUERY) + return database_report_from_rows([version, *cursor.fetchall()]) + except (DatabaseError, ValueError): + return None + + +@method_decorator(never_cache, name="dispatch") +class DatabaseMonitorView(OperatorAuthorization, TemplateView): + template_name = "hosting/database_monitor.html" + + def get_context_data(self, **kwargs): + return super().get_context_data( + report=current_database_report(), + observed_at=timezone.now(), + **kwargs, + ) + + class ConnectedNodesView(OperatorAuthorization, TemplateView): template_name = "hosting/connected_nodes.html" diff --git a/src/coulobre/hosting/static/hosting/panel-appearance.js b/src/coulobre/hosting/static/hosting/panel-appearance.js index f857db3..2633f9c 100644 --- a/src/coulobre/hosting/static/hosting/panel-appearance.js +++ b/src/coulobre/hosting/static/hosting/panel-appearance.js @@ -31,7 +31,7 @@ updatePanelAppearance(); systemAppearance.addEventListener("change", updatePanelAppearance); document.addEventListener("DOMContentLoaded", () => { updatePanelAppearance(); - document.querySelector("[data-theme-toggle]").addEventListener("click", () => { + document.querySelector("[data-theme-toggle]")?.addEventListener("click", () => { panelAppearance = document.documentElement.dataset.appearance === "dark" ? "light" : "dark"; try { localStorage.setItem(appearancePreference, panelAppearance); diff --git a/src/coulobre/hosting/static/hosting/panel-live-status.js b/src/coulobre/hosting/static/hosting/panel-live-status.js new file mode 100644 index 0000000..78aa7d5 --- /dev/null +++ b/src/coulobre/hosting/static/hosting/panel-live-status.js @@ -0,0 +1,56 @@ +"use strict"; + +const liveRegions = [...document.querySelectorAll("[data-live-status]")]; +let statusRefreshTimer; +let statusRefreshStopped = false; + +function scheduleStatusRefresh() { + clearTimeout(statusRefreshTimer); + if (!document.hidden && !statusRefreshStopped) { + statusRefreshTimer = setTimeout(refreshStatus, 15_000); + } +} + +async function refreshStatus() { + try { + const response = await fetch(location.href, { + headers: {"X-Coulobre-Status": "1"}, + cache: "no-store", + signal: AbortSignal.timeout(8_000), + }); + if (response.redirected || [401, 403].includes(response.status)) { + statusRefreshStopped = true; + } + if (statusRefreshStopped || !response.ok || document.hidden) { + return; + } + const page = new DOMParser().parseFromString(await response.text(), "text/html"); + const refreshed = new Map( + [...page.querySelectorAll("[data-live-status]")] + .map(region => [region.dataset.liveStatus, region]) + ); + for (const region of liveRegions) { + const next = refreshed.get(region.dataset.liveStatus); + if (!next || region.contains(document.activeElement) || + region.querySelector("details[open], form input:checked") || + region.innerHTML === next.innerHTML) { + continue; + } + const scrollPositions = [...region.querySelectorAll(".table-scroll")] + .map(table => table.scrollLeft); + region.replaceChildren(...next.childNodes); + region.querySelectorAll(".table-scroll").forEach((table, index) => { + table.scrollLeft = scrollPositions[index] || 0; + }); + } + } catch { + // The current readings remain visible if a refresh fails. + } finally { + scheduleStatusRefresh(); + } +} + +if (liveRegions.length) { + document.addEventListener("visibilitychange", scheduleStatusRefresh); + scheduleStatusRefresh(); +} diff --git a/src/coulobre/hosting/static/hosting/panel.css b/src/coulobre/hosting/static/hosting/panel.css index dfcf4f2..52c484a 100644 --- a/src/coulobre/hosting/static/hosting/panel.css +++ b/src/coulobre/hosting/static/hosting/panel.css @@ -312,49 +312,191 @@ button, input, select, textarea { content: ""; } +.nav-icon-mail { + background: + linear-gradient(35deg, transparent 47%, currentColor 50%, transparent 54%) left top / 50% 68% no-repeat, + linear-gradient(-35deg, transparent 47%, currentColor 50%, transparent 54%) right top / 50% 68% no-repeat; +} + +.nav-icon-network { + height: 1rem; + border-radius: 50%; + background: + linear-gradient(currentColor, currentColor) center / 100% 1px no-repeat, + linear-gradient(currentColor, currentColor) center / 1px 100% no-repeat; +} + +.nav-icon-lock { + position: relative; + height: 0.66rem; + margin-top: 0.35rem; +} + +.nav-icon-lock::before { + position: absolute; + inset: auto 19% 100%; + height: 0.36rem; + border: 1px solid currentColor; + border-radius: 0.6rem 0.6rem 0 0; + content: ""; +} + +.nav-icon-database { + height: 1rem; + border-radius: 50% / 22%; + background: + linear-gradient(currentColor, currentColor) center 35% / 100% 1px no-repeat, + linear-gradient(currentColor, currentColor) center 70% / 100% 1px no-repeat; +} + +.nav-icon-folder { + position: relative; + height: 0.68rem; + margin-top: 0.2rem; +} + +.nav-icon-folder::before { + position: absolute; + inset: auto auto 100% -1px; + width: 0.45rem; + height: 0.24rem; + border: 1px solid currentColor; + border-radius: 2px 2px 0 0; + content: ""; +} + +.nav-icon-settings { + border: 1px dashed currentColor; + border-radius: 50%; + background: radial-gradient(circle, transparent 21%, currentColor 23% 34%, transparent 36%); +} + +.nav-icon-appearance { + border-radius: 50%; + background: linear-gradient(90deg, currentColor 50%, transparent 50%); +} + +.nav-icon-archive { + background: + linear-gradient(currentColor, currentColor) center 28% / 100% 1px no-repeat, + linear-gradient(currentColor, currentColor) center 63% / 38% 1px no-repeat; +} + +.nav-icon-clock { + height: 1rem; + border-radius: 50%; + background: + linear-gradient(currentColor, currentColor) center 27% / 1px 30% no-repeat, + linear-gradient(currentColor, currentColor) 71% center / 30% 1px no-repeat; +} + +.nav-icon-transfer { + border-width: 0 0 1px; + border-radius: 0; + background: linear-gradient(currentColor, currentColor) left 35% / 88% 1px no-repeat; + position: relative; +} + +.nav-icon-transfer::before { + position: absolute; + right: 0.1rem; + top: 0.04rem; + width: 0.4rem; + height: 0.4rem; + transform: rotate(45deg); + border-top: 1px solid currentColor; + border-right: 1px solid currentColor; + content: ""; +} + .sidebar-account { display: grid; - gap: 0.3rem; + gap: 0.55rem; margin-top: auto; - padding: 0.85rem 0.55rem 0; + padding-top: 0.85rem; border-top: 1px solid var(--sidebar-divider); font-size: 0.88rem; } -.operator { - overflow-wrap: anywhere; - font-weight: 650; +.sidebar-account-controls { + display: flex; + align-items: center; + gap: 0.35rem; } -.sidebar-account a { - color: inherit; - text-underline-offset: 0.2em; +.sidebar-identity { + display: flex; + flex: 1; + align-items: center; + gap: 0.4rem; + min-width: 0; + min-height: 2.2rem; + border-radius: 6px; + color: var(--sidebar-text); + font-weight: 650; + text-decoration: none; +} + +a.sidebar-identity:hover { + text-decoration: underline; +} + +.sidebar-avatar { + display: grid; + width: 1.9rem; + height: 1.9rem; + flex: 0 0 auto; + place-items: center; + border-radius: 6px; + background: var(--brand-bg); + color: var(--brand-ink); +} + +.sidebar-account-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .panel-role-switch { display: grid; - gap: 0.3rem; - margin: 0.6rem 0; + grid-template-columns: minmax(0, 1fr) auto; + gap: 0.35rem; font-size: 0.82rem; } .panel-role-switch select { width: 100%; + min-width: 0; + min-height: 2.2rem; background: var(--sidebar-active); color: var(--sidebar-text); border: 1px solid var(--sidebar-control-line); - border-radius: 0.35rem; - padding: 0.35rem; + border-radius: 6px; + padding: 0.35rem 0.45rem; } -.sidebar-account button { - padding: 0; - border: 0; +.sidebar-action { + min-height: 2.2rem; + padding: 0.3rem 0.45rem; + border: 1px solid var(--sidebar-divider); + border-radius: 6px; background: transparent; color: var(--sidebar-account); cursor: pointer; - text-decoration: underline; - text-underline-offset: 0.2em; + font-size: 0.82rem; + white-space: nowrap; +} + +.sidebar-action:hover { + border-color: var(--sidebar-control-line); + background: var(--sidebar-active); + color: var(--sidebar-text); +} + +.appearance-control { + min-width: 2.2rem; + font-size: 1rem; } .main { @@ -411,10 +553,16 @@ h2 { box-shadow: 0 3px 9px var(--surface-shadow); } -.main > section.surface + section.surface { +.main > .surface + .surface { margin-top: var(--section-gap); } +.live-sections { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: var(--section-gap); +} + .button { display: inline-flex; min-height: 2.55rem; @@ -576,6 +724,26 @@ h2 { text-decoration: underline; } +.workspace-heading { + display: grid; + grid-template-columns: minmax(0, 1fr); + gap: 1rem; + border-bottom: 1px solid var(--line); + margin-bottom: 1.25rem; + padding-bottom: 0.6rem; +} + +.workspace-heading > .page-heading, +.workspace-heading > .account-navigation, +.workspace-heading > .workspace-context { + margin-bottom: 0; +} + +.workspace-heading > .account-navigation { + border: 0; + padding-bottom: 0; +} + .pagination { justify-content: flex-end; border-top: 1px solid var(--line); @@ -605,7 +773,7 @@ input::placeholder { color: var(--muted); } -.toolbar input { +.toolbar input, .workspace-context input[type="search"] { width: min(100%, 20rem); } @@ -973,9 +1141,9 @@ dd { position: static; display: grid; height: auto; - grid-template-columns: minmax(0, 1fr) auto auto; - gap: 0.65rem 0.3rem; - padding: 0.65rem 3.55rem 0.65rem 0.75rem; + grid-template-columns: minmax(0, 1fr) auto; + gap: 0.65rem; + padding: 0.65rem 0.75rem; } .brand { @@ -1002,38 +1170,23 @@ dd { } .menu-toggle { - grid-column: 3; + grid-column: 2; grid-row: 1; align-self: center; } .sidebar-account { - grid-column: 2; - grid-row: 1; - max-width: 8.5rem; - justify-items: end; + grid-column: 1 / -1; + grid-row: 3; margin: 0; - padding: 0 0.35rem; - border-top: 0; - text-align: right; + padding-top: 0.6rem; } } -@media (max-width: 375px) { - .sidebar { - grid-template-columns: minmax(0, 1fr) auto; - } - - .menu-toggle { - grid-column: 2; - } - +@media (min-width: 520px) and (max-width: 780px) { .sidebar-account { - grid-column: 1 / -1; - grid-row: 3; - display: flex; - max-width: none; - justify-content: space-between; + grid-template-columns: minmax(0, 1fr) minmax(0, 14rem); + gap: 0.65rem; } } @@ -1042,7 +1195,7 @@ dd { flex-direction: column; } - .toolbar input { + .toolbar input, .workspace-context input[type="search"] { width: auto; flex: 1 1 45%; } @@ -1196,12 +1349,3 @@ dd { .workspace-list li + li { margin-top: 0.4rem; } - -.sidebar-account .appearance-control { - display: block; - margin: 0.35rem 0; -} - -.sidebar-account .appearance-control[hidden] { - display: none; -} diff --git a/src/coulobre/hosting/templates/hosting/account_backup_archives.html b/src/coulobre/hosting/templates/hosting/account_backup_archives.html index 6f07637..46675f5 100644 --- a/src/coulobre/hosting/templates/hosting/account_backup_archives.html +++ b/src/coulobre/hosting/templates/hosting/account_backup_archives.html @@ -1,7 +1,6 @@ -{% extends "hosting/base.html" %} +{% extends "hosting/workspace_page.html" %} {% block title %}Backup archives · Coulobre Panel{% endblock %} -{% block content %} - ← {{ account.name }} +{% block page_header %}

Backup archives

@@ -13,6 +12,11 @@
{% endif %}
+{% endblock %} +{% block page_context %} + ← {{ account.name }} +{% endblock %} +{% block page_content %}
{% if manage_backup_retention %}
diff --git a/src/coulobre/hosting/templates/hosting/account_backup_schedule.html b/src/coulobre/hosting/templates/hosting/account_backup_schedule.html index 703f16f..7d283a2 100644 --- a/src/coulobre/hosting/templates/hosting/account_backup_schedule.html +++ b/src/coulobre/hosting/templates/hosting/account_backup_schedule.html @@ -1,13 +1,17 @@ -{% extends "hosting/base.html" %} +{% extends "hosting/workspace_page.html" %} {% block title %}Backup schedule · Coulobre Panel{% endblock %} -{% block content %} - ← {{ account.name }} +{% block page_header %}

Backup schedule

{{ account.primary_domain }}

+{% endblock %} +{% block page_context %} + ← {{ account.name }} +{% endblock %} +{% block page_content %}
{% csrf_token %} diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index 86b6fbf..9e8cab2 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -1,17 +1,28 @@ -{% extends "hosting/base.html" %} +{% extends "hosting/workspace_page.html" %} {% load static %} {% block title %}{{ account.name }} · Coulobre Panel{% endblock %} -{% block content %} - ← Hosting accounts -
-
-

{{ account.name }}

- -
-
+{% block page_title %}{{ account.name }}{% endblock %} +{% block page_metadata %} + +{% endblock %} +{% block page_actions %} + ← Hosting accounts +{% endblock %} +{% block page_tabs %} + +{% endblock %} +{% block page_content %}
{% if is_tenant or perms.hosting.view_hostingplan %}
Hosting plan
{% if account.hosting_plan %}{{ account.hosting_plan.name }}{% else %}Unassigned{% endif %} @@ -43,15 +54,6 @@ {% endif %}
Added
{{ account.created_at|date:"j M Y, H:i" }} UTC
-