Improve package status and sidebar navigation #169

Merged
parkel merged 2 commits from fix/package-review-and-sidebar into main 2026-11-24 01:16:23 +01:00
19 changed files with 425 additions and 274 deletions

No files matched your search

+3 -2
View File
@@ -2888,8 +2888,9 @@ sudo systemctl enable --now coulobre-operator-apply.socket \
``` ```
To enable APT actions, set `COULOBRE_SERVER_PACKAGE_UPDATES=1` in To enable APT actions, set `COULOBRE_SERVER_PACKAGE_UPDATES=1` in
`/etc/coulobre/panel.env`. Open **System → Updates → Server package updates** `/etc/coulobre/panel.env` and restart `coulobre-panel`. Open
and request a preview. The receiver refreshes package indexes and records the **System → Updates → Server packages** and check for updates. The receiver
refreshes package indexes and records the
proposed versions. Applying a preview requires confirmation and a fresh proposed versions. Applying a preview requires confirmation and a fresh
matching package plan. Use the job history and the host's package logs to matching package plan. Use the job history and the host's package logs to
review the result. review the result.
+57 -36
View File
@@ -2,11 +2,14 @@ from datetime import timedelta
from pathlib import Path from pathlib import Path
from django import forms from django import forms
from django.conf import settings
from django.contrib import messages from django.contrib import messages
from django.contrib.auth import get_user_model
from django.db import DatabaseError, connection, transaction from django.db import DatabaseError, connection, transaction
from django.shortcuts import redirect from django.shortcuts import redirect
from django.utils import timezone from django.utils import timezone
from django.utils.decorators import method_decorator from django.utils.decorators import method_decorator
from django.utils.functional import cached_property
from django.views.decorators.cache import never_cache from django.views.decorators.cache import never_cache
from django.views.generic import FormView, TemplateView from django.views.generic import FormView, TemplateView
@@ -20,15 +23,24 @@ from coulobre.operator_node import (
from .account_administration import OperatorAuthorization from .account_administration import OperatorAuthorization
from .models import OperatorOperation from .models import OperatorOperation
from .tasks import run_operator_operation from .tasks import OPERATOR_OPERATION_LEASE, run_operator_operation
from .update_views import inspect_linked_nodes from .update_views import inspect_linked_nodes
ACTION_LABELS = { ACTION_LABELS = {
"package-preview": "Review available updates", "package-preview": "Check for package updates",
"package-upgrade": "Apply reviewed updates", "package-upgrade": "Apply reviewed updates",
} }
def package_operation_pending(job):
return (
job is not None
and job.finished_at is None
and (job.started_at or job.requested_at)
> timezone.now() - OPERATOR_OPERATION_LEASE
)
def queue_operator_request(user, spec, *, source=None): def queue_operator_request(user, spec, *, source=None):
job = OperatorOperation.objects.create( job = OperatorOperation.objects.create(
actor=user, actor=user,
@@ -78,64 +90,73 @@ class ServerUpdateForm(forms.Form):
return data return data
@method_decorator(never_cache, name="dispatch")
class ServerUpdatesView(OperatorAuthorization, FormView): class ServerUpdatesView(OperatorAuthorization, FormView):
form_class = ServerUpdateForm form_class = ServerUpdateForm
template_name = "hosting/server_updates.html" template_name = "hosting/server_updates.html"
def preview(self): def package_jobs(self):
return ( return OperatorOperation.objects.filter(
OperatorOperation.objects.filter( action__in=ACTION_LABELS
action="package-preview", ).order_by("-pk")
actor=self.request.user,
problem="", @cached_property
finished_at__gte=timezone.now() - timedelta(minutes=15), def latest(self):
) return self.package_jobs().filter(actor=self.request.user).first()
.order_by("-pk")
.first() def preview(self, job):
) if (
job is not None
and job.action == "package-preview"
and not job.problem
and job.finished_at is not None
and job.finished_at >= timezone.now() - timedelta(minutes=15)
):
return job
return None
def get_form_kwargs(self): def get_form_kwargs(self):
return super().get_form_kwargs() | {"preview": self.preview()} kwargs = super().get_form_kwargs()
return kwargs | {"preview": self.preview(self.latest)}
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
latest = self.latest
return super().get_context_data( return super().get_context_data(
available=Path(SOCKET).is_socket(), available=Path(SOCKET).is_socket(),
jobs=OperatorOperation.objects.filter( enabled=settings.SERVER_PACKAGE_UPDATES,
action__in=ACTION_LABELS latest=latest,
).order_by("-pk")[:20], pending=package_operation_pending(latest),
jobs=self.package_jobs().select_related("actor")[:20],
**kwargs, **kwargs,
) )
@transaction.atomic @transaction.atomic
def form_valid(self, form): def form_valid(self, form):
if not Path(SOCKET).is_socket(): if not settings.SERVER_PACKAGE_UPDATES or not Path(SOCKET).is_socket():
form.add_error(
None,
"Enable the local operator service before requesting "
"an operation.",
)
return self.form_invalid(form) return self.form_invalid(form)
# Serialize an operator's submissions before checking the plan.
user = self.request.user
get_user_model().objects.select_for_update().get(pk=user.pk)
latest = self.package_jobs().filter(actor=user).first()
if package_operation_pending(latest):
return redirect(self.request.path)
spec = form.spec spec = form.spec
if form.preview is not None and spec.action == "package-upgrade": preview = form.preview if spec.action == "package-upgrade" else None
OperatorOperation.objects.select_for_update().get( if preview is not None and (
pk=form.preview.pk self.preview(latest) != preview
) or not preview.result.get("count")
recent = OperatorOperation.objects.filter( or OperatorOperation.objects.filter(source=preview).exists()
source=form.preview ):
).exists()
if recent:
form.add_error( form.add_error(
None, None,
"Collect a new preview before starting another " "Check for updates and review the current package list.",
"package update.",
) )
return self.form_invalid(form) return self.form_invalid(form)
queue_operator_request( queue_operator_request(
self.request.user, user,
spec, spec,
source=form.preview if spec.action == "package-upgrade" else None, source=preview,
) )
messages.success(self.request, "Host operation queued.")
return redirect(self.request.path) return redirect(self.request.path)
@@ -0,0 +1,75 @@
<!-- SPDX-License-Identifier: Apache-2.0 -->
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="accounts" viewBox="0 0 24 24">
<rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18m-14 5h4"/>
</symbol>
<symbol id="customers" viewBox="0 0 24 24">
<circle cx="12" cy="7" r="3"/><path d="M5 21v-2a7 7 0 0 1 14 0v2z"/>
</symbol>
<symbol id="resellers" viewBox="0 0 24 24">
<rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="8" cy="9" r="2"/><path d="M5 16a3 3 0 0 1 6 0m3-7h4m-4 5h4"/>
</symbol>
<symbol id="plans" viewBox="0 0 24 24">
<path d="M6 3h8l4 4v14H6zM14 3v5h4M9 12h6m-6 4h6"/>
</symbol>
<symbol id="packages" viewBox="0 0 24 24">
<path d="m3 7 9-4 9 4v10l-9 4-9-4zM3 7l9 4 9-4m-9 4v10M8 5l9 4v4"/>
</symbol>
<symbol id="network" viewBox="0 0 24 24">
<circle cx="12" cy="12" r="9"/><ellipse cx="12" cy="12" rx="4" ry="9"/><path d="M3 12h18"/>
</symbol>
<symbol id="nodes" viewBox="0 0 24 24">
<rect x="9" y="3" width="6" height="5" rx="1"/><rect x="3" y="16" width="6" height="5" rx="1"/><rect x="15" y="16" width="6" height="5" rx="1"/><path d="M12 8v4m-6 4v-4h12v4"/>
</symbol>
<symbol id="lock" viewBox="0 0 24 24">
<rect x="5" y="10" width="14" height="11" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3m-4 4v3"/>
</symbol>
<symbol id="database" viewBox="0 0 24 24">
<ellipse cx="12" cy="6" rx="8" ry="3"/><path d="M4 6v12a8 3 0 0 0 16 0V6M4 12a8 3 0 0 0 16 0"/>
</symbol>
<symbol id="folder" viewBox="0 0 24 24">
<path d="M3 19V5h7l2 3h9v11z"/>
</symbol>
<symbol id="settings" viewBox="0 0 24 24">
<path d="M4 6h9m4 0h3M4 12h3m4 0h9M4 18h11m4 0h1"/><circle cx="15" cy="6" r="2"/><circle cx="9" cy="12" r="2"/><circle cx="17" cy="18" r="2"/>
</symbol>
<symbol id="appearance" viewBox="0 0 24 24">
<circle cx="12" cy="12" r="9"/><path d="M12 3v18m0-13h5m-5 4h8m-8 4h5"/>
</symbol>
<symbol id="mail" viewBox="0 0 24 24">
<rect x="3" y="5" width="18" height="14" rx="2"/><path d="m4 7 8 6 8-6"/>
</symbol>
<symbol id="message" viewBox="0 0 24 24">
<path d="M3 5h18v12H9l-6 4zM7 9h10m-10 4h7"/>
</symbol>
<symbol id="shield" viewBox="0 0 24 24">
<path d="M12 3 4 6v6c0 4 3 7 8 9 5-2 8-5 8-9V6zM9 12l2 2 4-4"/>
</symbol>
<symbol id="queue" viewBox="0 0 24 24">
<path d="M4 5h16M4 9h16M4 13h16v6H4zM8 16h3"/>
</symbol>
<symbol id="archive" viewBox="0 0 24 24">
<path d="M3 4h18v5H3zm2 5v11h14V9m-10 4h6"/>
</symbol>
<symbol id="health" viewBox="0 0 24 24">
<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M5 12h3l2-4 3 8 2-4h4"/>
</symbol>
<symbol id="chart" viewBox="0 0 24 24">
<path d="M4 4v16h16M8 16v-4m4 4V8m4 8v-6m4 6V6"/>
</symbol>
<symbol id="information" viewBox="0 0 24 24">
<circle cx="12" cy="12" r="9"/><path d="M12 11v6m0-10v.1"/>
</symbol>
<symbol id="clock" viewBox="0 0 24 24">
<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>
</symbol>
<symbol id="transfer" viewBox="0 0 24 24">
<path d="M4 8h15m-4-4 4 4-4 4m5 4H5m4-4-4 4 4 4"/>
</symbol>
<symbol id="download" viewBox="0 0 24 24">
<path d="M12 3v12m-4-4 4 4 4-4M4 16v4h16v-4"/>
</symbol>
<symbol id="sign-out" viewBox="0 0 24 24">
<path d="M11 4H4v16h7m-1-8h10m-4-4 4 4-4 4"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 3.4 KiB

@@ -3,15 +3,18 @@
const liveRegions = [...document.querySelectorAll("[data-live-status]")]; const liveRegions = [...document.querySelectorAll("[data-live-status]")];
let statusRefreshTimer; let statusRefreshTimer;
let statusRefreshStopped = false; let statusRefreshStopped = false;
let statusRefreshRunning = false;
function scheduleStatusRefresh() { function scheduleStatusRefresh() {
clearTimeout(statusRefreshTimer); clearTimeout(statusRefreshTimer);
if (!document.hidden && !statusRefreshStopped) { if (!document.hidden && !statusRefreshStopped && !statusRefreshRunning) {
statusRefreshTimer = setTimeout(refreshStatus, 15_000); const pending = document.querySelector("[data-live-pending]");
statusRefreshTimer = setTimeout(refreshStatus, pending ? 2_000 : 15_000);
} }
} }
async function refreshStatus() { async function refreshStatus() {
statusRefreshRunning = true;
try { try {
const response = await fetch(location.href, { const response = await fetch(location.href, {
headers: {"X-Coulobre-Status": "1"}, headers: {"X-Coulobre-Status": "1"},
@@ -32,8 +35,15 @@ async function refreshStatus() {
for (const region of liveRegions) { for (const region of liveRegions) {
const next = refreshed.get(region.dataset.liveStatus); const next = refreshed.get(region.dataset.liveStatus);
if (!next || region.contains(document.activeElement) || if (!next || region.contains(document.activeElement) ||
region.querySelector("details[open], form input:checked") || region.querySelector("details[open]:not([data-live-detail]), form input:checked")) {
region.innerHTML === next.innerHTML) { continue;
}
const openDetails = new Set([...region.querySelectorAll("details[open][data-live-detail]")]
.map(detail => detail.dataset.liveDetail));
for (const detail of next.querySelectorAll("details[data-live-detail]")) {
detail.open = openDetails.has(detail.dataset.liveDetail);
}
if (region.innerHTML === next.innerHTML) {
continue; continue;
} }
const scrollPositions = [...region.querySelectorAll(".table-scroll")] const scrollPositions = [...region.querySelectorAll(".table-scroll")]
@@ -46,6 +56,7 @@ async function refreshStatus() {
} catch { } catch {
// The current readings remain visible if a refresh fails. // The current readings remain visible if a refresh fails.
} finally { } finally {
statusRefreshRunning = false;
scheduleStatusRefresh(); scheduleStatusRefresh();
} }
} }
@@ -31,6 +31,23 @@ navigation.addEventListener("keydown", (event) => {
compactLayout.addEventListener("change", updateMenuLayout); compactLayout.addEventListener("change", updateMenuLayout);
updateMenuLayout(); updateMenuLayout();
const roleSwitch = document.querySelector("[data-role-switch]");
if (roleSwitch) {
const picker = roleSwitch.querySelector("select");
const currentRole = picker.value;
roleSwitch.classList.add("role-switch-on-change");
roleSwitch.querySelector("button").hidden = true;
picker.setAttribute("aria-label", "Panel role (switches when selected)");
picker.addEventListener("change", () => {
if (picker.value !== currentRole) {
roleSwitch.requestSubmit();
}
});
window.addEventListener("pageshow", () => {
picker.value = currentRole;
});
}
const accountTabs = document.querySelector("[data-account-tabs]"); const accountTabs = document.querySelector("[data-account-tabs]");
if (accountTabs) { if (accountTabs) {
const panels = [...document.querySelectorAll("[data-account-section]")]; const panels = [...document.querySelectorAll("[data-account-section]")];
+46 -160
View File
@@ -142,7 +142,6 @@ button, input, select, textarea {
display: flex; display: flex;
height: 100dvh; height: 100dvh;
flex-direction: column; flex-direction: column;
overflow-y: auto;
padding: 1.65rem 1.1rem 1.1rem; padding: 1.65rem 1.1rem 1.1rem;
background: linear-gradient(160deg, var(--sidebar-gradient), var(--sidebar) 55%); background: linear-gradient(160deg, var(--sidebar-gradient), var(--sidebar) 55%);
color: var(--sidebar-text); color: var(--sidebar-text);
@@ -196,6 +195,17 @@ button, input, select, textarea {
margin-top: 1.4rem; margin-top: 1.4rem;
} }
@media (min-width: 781px) {
.navigation {
min-height: 0;
align-content: start;
overflow-y: auto;
overscroll-behavior: contain;
padding: 0.15rem;
scrollbar-width: thin;
}
}
.navigation a { .navigation a {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -245,175 +255,35 @@ button, input, select, textarea {
display: none; display: none;
} }
.nav-icon { .nav-icon,
display: inline-block; .sidebar-icon-action svg {
display: block;
width: 1rem; width: 1rem;
height: 0.85rem; height: 1rem;
flex: 0 0 auto; flex: 0 0 1rem;
border: 1px solid currentColor; fill: none;
border-radius: 2px; stroke: currentColor;
stroke-width: 1.6px;
stroke-linecap: round;
stroke-linejoin: round;
}
.nav-icon {
color: var(--sidebar-icon); color: var(--sidebar-icon);
} }
.nav-icon-accounts { .navigation a:hover .nav-icon,
background: linear-gradient(currentColor, currentColor) center / 100% 1px no-repeat; .navigation a[aria-current] .nav-icon {
} color: currentColor;
.nav-icon-plans {
width: 0.8rem;
height: 1rem;
margin-inline: 0.1rem;
background:
linear-gradient(currentColor, currentColor) center 35% / 55% 1px no-repeat,
linear-gradient(currentColor, currentColor) center 65% / 55% 1px no-repeat;
}
.nav-icon-packages {
background: linear-gradient(currentColor, currentColor) center 35% / 40% 1px no-repeat;
}
.nav-icon-resellers {
background:
linear-gradient(currentColor, currentColor) center 35% / 55% 1px no-repeat,
linear-gradient(currentColor, currentColor) center 65% / 75% 1px no-repeat;
}
.nav-icon-health {
background:
linear-gradient(currentColor, currentColor) 25% bottom / 1px 40% no-repeat,
linear-gradient(currentColor, currentColor) center bottom / 1px 70% no-repeat,
linear-gradient(currentColor, currentColor) 75% bottom / 1px 55% no-repeat;
}
.nav-icon-information {
display: grid;
place-content: center;
border-radius: 50%;
font-size: 0.7rem;
font-weight: 700;
}
.nav-icon-customers {
position: relative;
height: 0.46rem;
margin-top: 0.47rem;
border-radius: 0.4rem 0.4rem 2px 2px;
}
.nav-icon-customers::before {
position: absolute;
left: 50%;
bottom: calc(100% + 2px);
width: 0.39rem;
height: 0.39rem;
transform: translateX(-50%);
border: 1px solid currentColor;
border-radius: 50%;
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 { .sidebar-account {
display: grid; display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 0.55rem; gap: 0.55rem;
flex: 0 0 auto;
margin-top: auto; margin-top: auto;
padding-top: 0.85rem; padding-top: 0.7rem;
border-top: 1px solid var(--sidebar-divider); border-top: 1px solid var(--sidebar-divider);
font-size: 0.88rem; font-size: 0.88rem;
} }
@@ -465,6 +335,10 @@ a.sidebar-identity:hover {
font-size: 0.82rem; font-size: 0.82rem;
} }
.panel-role-switch.role-switch-on-change {
display: block;
}
.panel-role-switch select { .panel-role-switch select {
width: 100%; width: 100%;
min-width: 0; min-width: 0;
@@ -494,6 +368,13 @@ a.sidebar-identity:hover {
color: var(--sidebar-text); color: var(--sidebar-text);
} }
.sidebar-icon-action {
display: grid;
width: 2.2rem;
padding: 0;
place-items: center;
}
.appearance-control { .appearance-control {
min-width: 2.2rem; min-width: 2.2rem;
font-size: 1rem; font-size: 1rem;
@@ -616,6 +497,11 @@ h2 {
overflow-wrap: anywhere; overflow-wrap: anywhere;
} }
.package-controls {
display: grid;
gap: 0.75rem;
}
.update-release { .update-release {
padding: 0.75rem 0.9rem; padding: 0.75rem 0.9rem;
border: 1px solid var(--line); border: 1px solid var(--line);
+2 -1
View File
@@ -123,6 +123,7 @@ from .website_jobs import (
REDISPATCH_AFTER = timedelta(minutes=5) REDISPATCH_AFTER = timedelta(minutes=5)
ACCOUNT_BACKUP_LEASE = timedelta(seconds=BACKUP_TIMEOUT_SECONDS + 60) ACCOUNT_BACKUP_LEASE = timedelta(seconds=BACKUP_TIMEOUT_SECONDS + 60)
ACCOUNT_RESTORE_LEASE = timedelta(seconds=RESTORE_TIMEOUT_SECONDS + 60) ACCOUNT_RESTORE_LEASE = timedelta(seconds=RESTORE_TIMEOUT_SECONDS + 60)
OPERATOR_OPERATION_LEASE = timedelta(minutes=35)
ACCOUNT_BACKUP_QUEUE = "coulobre-account-backups" ACCOUNT_BACKUP_QUEUE = "coulobre-account-backups"
UNCONFIRMED_RESTORE = ( UNCONFIRMED_RESTORE = (
"Could not confirm the restore on the local backup node. " "Could not confirm the restore on the local backup node. "
@@ -1338,7 +1339,7 @@ def run_operator_operation(job_id):
apply, apply,
"The operator service did not report a result. " "The operator service did not report a result. "
"Check the service journal.", "Check the service journal.",
lease=timedelta(minutes=35), lease=OPERATOR_OPERATION_LEASE,
) )
@@ -27,12 +27,7 @@
</div> </div>
{% endblock %} {% endblock %}
{% block page_content %} {% block page_content %}
{% if health_summary %} {% if is_reseller %}
<section class="surface section-heading" aria-label="Server status">
<p>{% if not health_summary.configured %}Service checks need setup.{% elif health_summary.needs_attention %}{{ health_summary.needs_attention }} of {{ health_summary.configured }} service checks need attention.{% else %}All {{ health_summary.configured }} service checks are healthy.{% endif %}</p>
<a class="button secondary" href="{% url 'panel:service_health' %}">Service health</a>
</section>
{% elif is_reseller %}
<section class="surface section-heading" aria-label="Customer access"> <section class="surface section-heading" aria-label="Customer access">
<p>Manage the logins for your assigned customers.</p> <p>Manage the logins for your assigned customers.</p>
<a class="button secondary" href="{% url 'panel:customers' %}">My customers</a> <a class="button secondary" href="{% url 'panel:customers' %}">My customers</a>
@@ -1,15 +1,15 @@
{% load static %}<!doctype html> {% load static panel_assets %}<!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}Coulobre Panel{% endblock %}</title> <title>{% block title %}Coulobre Panel{% endblock %}</title>
<link rel="icon" type="image/svg+xml" href="{% static 'hosting/coulobre-mark.svg' %}"> <link rel="icon" type="image/svg+xml" href="{% static 'hosting/coulobre-mark.svg' %}">
<link rel="stylesheet" href="{% static 'hosting/panel.css' %}"> <link rel="stylesheet" href="{% panel_asset 'hosting/panel.css' %}">
{% if custom_panel_theme %}<link rel="stylesheet" href="{% url 'panel:theme_stylesheet' %}">{% endif %} {% if custom_panel_theme %}<link rel="stylesheet" href="{% url 'panel:theme_stylesheet' %}">{% endif %}
{% if has_user_theme %}<link rel="stylesheet" href="{% url 'panel:user_stylesheet' %}">{% endif %} {% if has_user_theme %}<link rel="stylesheet" href="{% url 'panel:user_stylesheet' %}">{% endif %}
{% block extra_styles %}{% endblock %} {% block extra_styles %}{% endblock %}
<script src="{% static 'hosting/panel-appearance.js' %}"></script> <script src="{% panel_asset 'hosting/panel-appearance.js' %}"></script>
</head> </head>
<body> <body>
{% if request.user.is_authenticated and not auth_screen %} {% if request.user.is_authenticated and not auth_screen %}
@@ -27,6 +27,7 @@
{% include "hosting/workspace_navigation.html" %} {% include "hosting/workspace_navigation.html" %}
</nav> </nav>
<div class="sidebar-account"> <div class="sidebar-account">
{% panel_asset 'hosting/panel-icons.svg' as panel_icons %}
<div class="sidebar-account-controls"> <div class="sidebar-account-controls">
{% if request.impersonation %} {% if request.impersonation %}
<span class="sidebar-identity"> <span class="sidebar-identity">
@@ -44,11 +45,13 @@
{% endif %} {% endif %}
<form class="sidebar-sign-out" method="post" action="{% url 'panel:logout' %}"> <form class="sidebar-sign-out" method="post" action="{% url 'panel:logout' %}">
{% csrf_token %} {% csrf_token %}
<button class="sidebar-action" type="submit">Sign out</button> <button class="sidebar-action sidebar-icon-action" type="submit" aria-label="Sign out" title="Sign out">
<svg aria-hidden="true" focusable="false"><use href="{{ panel_icons }}#sign-out"></use></svg>
</button>
</form> </form>
</div> </div>
{% if not request.impersonation and request.panel_role_options|length > 1 %} {% if not request.impersonation and request.panel_role_options|length > 1 %}
<form method="post" class="panel-role-switch" action="{% url 'panel:switch_panel_role' %}"> <form method="post" class="panel-role-switch" action="{% url 'panel:switch_panel_role' %}" data-role-switch>
{% csrf_token %} {% csrf_token %}
<label class="visually-hidden" for="panel-role">Panel role</label> <label class="visually-hidden" for="panel-role">Panel role</label>
<select name="role" id="panel-role"> <select name="role" id="panel-role">
@@ -56,7 +59,7 @@
<option value="{{ value }}"{% if request.active_panel_role == value %} selected{% endif %}>{{ label }}</option> <option value="{{ value }}"{% if request.active_panel_role == value %} selected{% endif %}>{{ label }}</option>
{% endfor %} {% endfor %}
</select> </select>
<button class="sidebar-action" type="submit" aria-label="Switch role">Switch</button> <button class="sidebar-action" type="submit">Switch role</button>
</form> </form>
{% endif %} {% endif %}
</div> </div>
@@ -83,7 +86,7 @@
{% block content %}{% endblock %} {% block content %}{% endblock %}
</main> </main>
</div> </div>
<script src="{% static 'hosting/panel-navigation.js' %}" defer></script> <script src="{% panel_asset 'hosting/panel-navigation.js' %}" defer></script>
{% block extra_scripts %}{% endblock %} {% block extra_scripts %}{% endblock %}
{% else %} {% else %}
{% block public_content %}{% endblock %} {% block public_content %}{% endblock %}
@@ -1,8 +1,8 @@
<section class="surface" aria-labelledby="operation-history" data-live-status="operator-history"> <section class="surface" aria-labelledby="operation-history" data-live-status="operator-history">
<header class="section-heading"><h2 id="operation-history">Operation history</h2></header> <header class="section-heading"><h2 id="operation-history">Operation history</h2></header>
{% for job in jobs %} {% for job in jobs %}
<details class="section-text"> <details class="section-text" data-live-detail="{{ job.pk }}">
<summary>{{ job.requested_at|date:"j M Y H:i" }} UTC · {{ job.action|capfirst }}{% if job.target %} {{ job.target }}{% endif %} · {{ job.state|capfirst }}</summary> <summary>{{ job.requested_at|date:"j M Y H:i" }} UTC · {% if job.action == 'package-preview' %}Package check{% elif job.action == 'package-upgrade' %}Package update{% else %}{{ job.action|capfirst }}{% endif %}{% if job.target %} {{ job.target }}{% endif %} · {% if job.state == 'configured' %}Completed{% else %}{{ job.state|capfirst }}{% endif %}</summary>
{% if job.actor %}<p>Requested by {{ job.actor }}</p>{% endif %} {% if job.actor %}<p>Requested by {{ job.actor }}</p>{% endif %}
{% if job.problem %}<p>{{ job.problem }}</p>{% endif %} {% if job.problem %}<p>{{ job.problem }}</p>{% endif %}
{% if job.action == 'package-preview' and job.result.fingerprint %} {% if job.action == 'package-preview' and job.result.fingerprint %}
@@ -1,33 +1,63 @@
{% extends "hosting/update_workspace.html" %} {% extends "hosting/update_workspace.html" %}
{% block title %}Server package updates · Coulobre Panel{% endblock %} {% block title %}Server package updates · Coulobre Panel{% endblock %}
{% block page_content %} {% block page_content %}
<section class="surface editor-surface" data-live-status="package-preview"> <section class="surface" aria-labelledby="server-package-heading">
{% if available %} <header class="section-heading"><h2 id="server-package-heading">Package updates</h2></header>
<div class="section-text" data-live-status="package-status" role="status" aria-atomic="true">
{% if not enabled %}
<p>Server package updates are disabled. To enable them, set
<code>COULOBRE_SERVER_PACKAGE_UPDATES=1</code> in
<code>/etc/coulobre/panel.env</code> and restart
<code>coulobre-panel</code>.</p>
{% elif not available %}
<p>The local operator service is unavailable.</p>
{% elif pending %}
<p data-live-pending>
{% if latest.action == 'package-preview' %}
{% if latest.started_at %}Checking for package updates…{% else %}Package check queued.{% endif %}
{% else %}
{% if latest.started_at %}Applying package updates…{% else %}Package update queued.{% endif %}
{% endif %}
</p>
{% elif latest and not latest.finished_at %}
<p>The operator service did not report a result. Check its journal before retrying.</p>
{% elif latest.problem %}
<p><strong>{% if latest.action == 'package-preview' %}Package check failed.{% else %}Package update failed.{% endif %}</strong>
{{ latest.problem }}</p>
{% elif latest.action == 'package-upgrade' %}
<p>Package update complete. {{ latest.result.upgrades_remaining }} update{{ latest.result.upgrades_remaining|pluralize }} remaining.</p>
{% elif latest.action == 'package-preview' and not latest.result.count %}
<p>No package updates are available.</p>
{% elif form.preview %}
<p>{{ form.preview.result.count }} package update{{ form.preview.result.count|pluralize }} ready to review.</p>
{% elif latest %}
<p>The package review expired. Check again for the current list.</p>
{% else %}
<p>Check for available operating system and service package updates.</p>
{% endif %}
</div>
{% if form.errors %}<div class="section-text" role="alert">{{ form.errors }}</div>{% endif %}
{% if available and enabled %}
<div class="section-text package-controls" data-live-status="package-preview">
<form method="post" class="form-actions"> <form method="post" class="form-actions">
{% csrf_token %} {% csrf_token %}
<button class="button secondary" name="action" value="package-preview" type="submit">Review available updates</button> <button class="button secondary" name="action" value="package-preview" type="submit"{% if pending %} disabled{% endif %}>Check for package updates</button>
</form> </form>
{{ form.non_field_errors }}
{{ form.action.errors }}
{% if form.preview.result.count %} {% if form.preview.result.count %}
<form method="post" class="editor"> <form method="post" class="editor">
{% csrf_token %} {% csrf_token %}
{{ form.preview_id }} {{ form.preview_id }}
{{ form.preview_id.errors }}
<ul class="workspace-list"> <ul class="workspace-list">
{% for package in form.preview.result.packages %}<li><code>{{ package }}</code></li>{% endfor %} {% for package in form.preview.result.packages %}<li><code>{{ package }}</code></li>{% endfor %}
</ul> </ul>
<div> <div>
<label for="{{ form.confirm.id_for_label }}">{{ form.confirm }} {{ form.confirm.label }}</label> <label for="{{ form.confirm.id_for_label }}">{{ form.confirm }} {{ form.confirm.label }}</label>
{{ form.confirm.errors }}
</div> </div>
<button class="button primary" name="action" value="package-upgrade" type="submit">Apply reviewed updates</button> <button class="button primary" name="action" value="package-upgrade" type="submit">Apply reviewed updates</button>
</form> </form>
{% else %}
{% if form.preview %}<p>No packages are ready to update.</p>{% endif %}
{{ form.preview_id.errors }}
{% endif %} {% endif %}
{% else %}<p>Enable the operator service on the host to review server updates.</p>{% endif %} </div>
{% endif %}
</section> </section>
{% include "hosting/operator_operation_history.html" %} {% include "hosting/operator_operation_history.html" %}
{% endblock %} {% endblock %}
@@ -11,7 +11,7 @@
<section class="surface" aria-labelledby="health-{{ node.node }}"> <section class="surface" aria-labelledby="health-{{ node.node }}">
<header class="section-heading"> <header class="section-heading">
<h2 id="health-{{ node.node }}">{{ node.node }}</h2> <h2 id="health-{{ node.node }}">{{ node.node }}</h2>
<span class="muted">{% if node.transport == 'local' %}Local{% else %}Remote{% endif %}</span> <span class="muted">{% if node.transport == 'local' %}Local{% else %}Remote · monitoring only{% endif %}</span>
</header> </header>
<div class="table-scroll"> <div class="table-scroll">
<table> <table>
@@ -40,7 +40,7 @@
<button type="submit" class="button secondary" name="action" value="reload" aria-label="Reload {{ service.name }}">Reload</button> <button type="submit" class="button secondary" name="action" value="reload" aria-label="Reload {{ service.name }}">Reload</button>
<button type="submit" class="button secondary" name="action" value="restart" aria-label="Restart {{ service.name }}">Restart</button> <button type="submit" class="button secondary" name="action" value="restart" aria-label="Restart {{ service.name }}">Restart</button>
</form> </form>
{% else %}—{% endif %} {% else %}<span class="muted">Manage on host</span>{% endif %}
</td> </td>
{% endif %} {% endif %}
</tr> </tr>
@@ -1,9 +1,11 @@
{% load panel_assets %}
{% panel_asset 'hosting/panel-icons.svg' as panel_icons %}
{% for title, entries in navigation_groups %} {% for title, entries in navigation_groups %}
<details class="sidebar-group"{% if title == open_workspace_group or not open_workspace_group and forloop.first %} open{% endif %}> <details class="sidebar-group"{% if title == open_workspace_group or not open_workspace_group and forloop.first %} open{% endif %}>
<summary>{{ title }}</summary> <summary>{{ title }}</summary>
{% for href, label, icon in entries %} {% for href, label, icon in entries %}
<a href="{{ href }}"{% if active_navigation_link == href %} aria-current="page"{% endif %}> <a href="{{ href }}"{% if active_navigation_link == href %} aria-current="page"{% endif %}>
<span class="nav-icon nav-icon-{{ icon }}" aria-hidden="true">{% if icon == 'information' %}i{% endif %}</span> <svg class="nav-icon" aria-hidden="true" focusable="false"><use href="{{ panel_icons }}#{{ icon }}"></use></svg>
<span>{{ label }}</span> <span>{{ label }}</span>
</a> </a>
{% endfor %} {% endfor %}
@@ -1,7 +1,7 @@
{% extends "hosting/base.html" %} {% extends "hosting/base.html" %}
{% load static %} {% load panel_assets %}
{% block extra_scripts %} {% block extra_scripts %}
<script src="{% static 'hosting/panel-live-status.js' %}" defer></script> <script src="{% panel_asset 'hosting/panel-live-status.js' %}" defer></script>
{% endblock %} {% endblock %}
{% block account_selector %}{% endblock %} {% block account_selector %}{% endblock %}
{% block content %} {% block content %}
@@ -0,0 +1,17 @@
from functools import cache
from hashlib import sha256
from importlib.resources import files
from django import template
from django.templatetags.static import static
register = template.Library()
@register.simple_tag
@cache
def panel_asset(name):
"""Keep cached shell assets in step with the installed templates."""
asset = files("coulobre.hosting").joinpath("static", name)
revision = sha256(asset.read_bytes()).hexdigest()[:16]
return f"{static(name)}?v={revision}"
@@ -1,12 +1,14 @@
import json import json
from datetime import timedelta
from io import BytesIO, StringIO from io import BytesIO, StringIO
from types import SimpleNamespace from types import SimpleNamespace
from unittest.mock import patch from unittest.mock import patch
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.core.files.uploadedfile import SimpleUploadedFile from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import SimpleTestCase, TestCase from django.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse from django.urls import reverse
from django.utils import timezone
from django_otp.plugins.otp_totp.models import TOTPDevice from django_otp.plugins.otp_totp.models import TOTPDevice
from coulobre.mail_queue import MailQueueAction, change_queue_entry from coulobre.mail_queue import MailQueueAction, change_queue_entry
@@ -146,3 +148,114 @@ class DatabaseMonitorTests(TestCase):
self.assertContains(response, "Enabled") self.assertContains(response, "Enabled")
self.assertFalse(OperatorOperation.objects.exists()) self.assertFalse(OperatorOperation.objects.exists())
self.assertIn("no-store", response["Cache-Control"]) self.assertIn("no-store", response["Cache-Control"])
@override_settings(SERVER_PACKAGE_UPDATES=True)
class ServerPackageTests(TestCase):
def setUp(self):
self.operator = get_user_model().objects.create_superuser("operator")
self.client.force_login(self.operator)
device = TOTPDevice.objects.create(user=self.operator, name="test")
session = self.client.session
session["otp_device_id"] = device.persistent_id
session.save()
self.url = reverse("panel:server_updates")
socket = patch("coulobre.hosting.operator_tools.Path")
socket.start().return_value.is_socket.return_value = True
self.addCleanup(socket.stop)
def preview(self, count):
return OperatorOperation.objects.create(
actor=self.operator,
action="package-preview",
finished_at=timezone.now(),
result={
"count": count,
"fingerprint": "a" * 64,
"packages": ["Inst example-package"] if count else [],
},
)
@override_settings(SERVER_PACKAGE_UPDATES=False)
def test_disabled_configuration_explains_setup_and_blocks_post(self):
response = self.client.post(self.url, {"action": "package-preview"})
self.assertContains(response, "COULOBRE_SERVER_PACKAGE_UPDATES=1")
self.assertNotContains(response, 'value="package-preview"')
self.assertFalse(OperatorOperation.objects.exists())
def test_package_check_updates_state_and_deduplicates_pending_post(self):
with (
patch(
"coulobre.hosting.operator_tools.run_operator_operation.delay"
) as dispatch,
self.captureOnCommitCallbacks(execute=True),
):
for _ in range(2):
response = self.client.post(
self.url, {"action": "package-preview"}
)
self.assertRedirects(
response, self.url, fetch_redirect_response=False
)
job = OperatorOperation.objects.get()
dispatch.assert_called_once_with(job.pk)
response = self.client.get(self.url, HTTP_X_COULOBRE_STATUS="1")
self.assertContains(response, "Package check queued.")
self.assertContains(response, "data-live-pending")
job.started_at = timezone.now()
job.save(update_fields=["started_at"])
self.assertContains(
self.client.get(self.url), "Checking for package updates"
)
job.finished_at = timezone.now()
job.problem = "APT could not refresh its package indexes."
job.save(update_fields=["finished_at", "problem"])
response = self.client.get(self.url)
self.assertContains(response, "Package check failed.")
self.assertContains(response, job.problem)
self.assertNotContains(response, "data-live-pending")
def test_empty_preview_reports_success_and_cannot_be_applied(self):
job = self.preview(0)
self.assertContains(
self.client.get(self.url), "No package updates are available."
)
response = self.client.post(
self.url,
{"action": "package-upgrade", "preview_id": job.pk, "confirm": 1},
)
self.assertContains(response, "review the current package list")
self.assertEqual(OperatorOperation.objects.count(), 1)
def test_an_unconfirmed_check_can_be_retried_after_the_worker_lease(self):
OperatorOperation.objects.create(
actor=self.operator,
action="package-preview",
requested_at=timezone.now() - timedelta(hours=1),
)
self.assertContains(
self.client.get(self.url), "operator service did not report"
)
self.assertRedirects(
self.client.post(self.url, {"action": "package-preview"}), self.url
)
self.assertEqual(OperatorOperation.objects.count(), 2)
def test_only_the_latest_confirmed_preview_can_be_applied(self):
previous = self.preview(1)
current = self.preview(1)
data = {"action": "package-upgrade", "preview_id": previous.pk}
response = self.client.post(self.url, data | {"confirm": 1})
self.assertContains(response, "review a current package update")
data["preview_id"] = current.pk
response = self.client.post(self.url, data)
self.assertContains(response, "Confirm this change")
self.assertRedirects(
self.client.post(self.url, data | {"confirm": 1}), self.url
)
job = OperatorOperation.objects.get(action="package-upgrade")
self.assertEqual(job.source, current)
self.assertEqual(job.plan, current.result["fingerprint"])
self.assertNotContains(
self.client.get(self.url), "Apply reviewed updates"
)
-26
View File
@@ -15,7 +15,6 @@ from django.http import (
) )
from django.shortcuts import get_object_or_404, redirect from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse, reverse_lazy from django.urls import reverse, reverse_lazy
from django.utils import timezone
from django.utils.functional import cached_property from django.utils.functional import cached_property
from django.views import View from django.views import View
from django.views.generic import ( from django.views.generic import (
@@ -31,7 +30,6 @@ from coulobre.dns_node import MAX_SOA_SERIAL
from coulobre.mail_dns import MANAGED_DKIM_SELECTOR, matches_version from coulobre.mail_dns import MANAGED_DKIM_SELECTOR, matches_version
from coulobre.mail_node import INVALID_LOCAL_PART from coulobre.mail_node import INVALID_LOCAL_PART
from coulobre.php_runtime import available_php_versions from coulobre.php_runtime import available_php_versions
from coulobre.service_health import HealthResult
from coulobre.sftp_keys import public_key_fingerprint from coulobre.sftp_keys import public_key_fingerprint
from .access import ( from .access import (
@@ -81,7 +79,6 @@ from .dns_forms import (
) )
from .dns_publication import queue_dns_publication from .dns_publication import queue_dns_publication
from .domain_policies import require_managed from .domain_policies import require_managed
from .health_views import STALE_AFTER
from .impersonation import ( from .impersonation import (
CUSTOMER_WRITE_PERMISSIONS, CUSTOMER_WRITE_PERMISSIONS,
EndReason, EndReason,
@@ -116,7 +113,6 @@ from .models import (
HostingMailbox, HostingMailbox,
HostingPlan, HostingPlan,
Reseller, Reseller,
ServiceHealth,
WebProvisioningPlan, WebProvisioningPlan,
WebsiteAlias, WebsiteAlias,
WebsiteDomain, WebsiteDomain,
@@ -401,28 +397,6 @@ class AccountList(TenantScopeMixin, PermissionRequiredMixin, ListView):
"limit": reseller.account_limit, "limit": reseller.account_limit,
"may_create": reseller.may_create_accounts(), "may_create": reseller.may_create_accounts(),
} }
elif (
not self.request.GET
and not is_tenant(self.request.user)
and self.request.user.has_perm("hosting.view_servicehealth")
):
targets = settings.SERVICE_HEALTH_TARGETS
checks = {
(node.node, service)
for node in targets
for service in node.services
}
healthy = set(
ServiceHealth.objects.filter(
node__in={node.node for node in targets},
result=HealthResult.ACTIVE,
observed_at__gt=timezone.now() - STALE_AFTER,
).values_list("node", "service")
)
context["health_summary"] = {
"configured": len(checks),
"needs_attention": len(checks - healthy),
}
return context return context
+15 -13
View File
@@ -244,7 +244,7 @@ NAVIGATION_ICONS = {
"all_users": "customers", "all_users": "customers",
"customers": "customers", "customers": "customers",
"customer_onboarding": "customers", "customer_onboarding": "customers",
"move_accounts": "customers", "move_accounts": "transfer",
"operator_create": "customers", "operator_create": "customers",
"resellers": "resellers", "resellers": "resellers",
"reseller_create": "resellers", "reseller_create": "resellers",
@@ -252,9 +252,9 @@ NAVIGATION_ICONS = {
"manager_packages": "packages", "manager_packages": "packages",
"reseller_profiles": "packages", "reseller_profiles": "packages",
"domains": "network", "domains": "network",
"dns": "network", "dns": "nodes",
"dns_defaults": "network", "dns_defaults": "nodes",
"connected_nodes": "network", "connected_nodes": "nodes",
"account_security": "lock", "account_security": "lock",
"certificates": "lock", "certificates": "lock",
"operator_certificates": "lock", "operator_certificates": "lock",
@@ -266,23 +266,25 @@ NAVIGATION_ICONS = {
"operator_settings": "settings", "operator_settings": "settings",
"http_defaults": "settings", "http_defaults": "settings",
"theme_management": "appearance", "theme_management": "appearance",
"announcements": "mail", "announcements": "message",
"email": "mail", "email": "mail",
"forwarders": "mail", "forwarders": "transfer",
"replies": "mail", "replies": "message",
"spam": "mail", "spam": "shield",
"mail_queue_index": "mail", "mail_queue_index": "queue",
"mail_delivery": "mail", "mail_delivery": "mail",
"backups": "archive", "backups": "archive",
"operator_backups": "archive", "operator_backups": "archive",
"system_backup": "archive", "system_backup": "archive",
"service_health": "health", "service_health": "health",
"statistics": "health", "statistics": "chart",
"installation": "information", "installation": "information",
"tasks": "clock", "tasks": "clock",
"updates": "transfer", "updates": "download",
"directadmin_guide": "transfer", "directadmin_guide": "download",
"redirects": "transfer", "redirects": "transfer",
"plans": "plans",
"logs": "plans",
} }
@@ -295,7 +297,7 @@ def link(route, label, *args):
return ( return (
reverse(f"panel:{route}", args=args), reverse(f"panel:{route}", args=args),
label, label,
NAVIGATION_ICONS.get(key, "plans"), NAVIGATION_ICONS[key],
) )
+3
View File
@@ -224,6 +224,9 @@ WEB_FILE_MANAGER = os.environ.get("COULOBRE_WEB_FILE_MANAGER") == "1"
WEBSITE_JOBS = os.environ.get("COULOBRE_WEBSITE_JOBS") == "1" WEBSITE_JOBS = os.environ.get("COULOBRE_WEBSITE_JOBS") == "1"
LOCAL_WEB_SFTP = os.environ.get("COULOBRE_LOCAL_WEB_SFTP") == "1" LOCAL_WEB_SFTP = os.environ.get("COULOBRE_LOCAL_WEB_SFTP") == "1"
SYSTEM_BACKUPS = os.environ.get("COULOBRE_SYSTEM_BACKUPS") == "1" SYSTEM_BACKUPS = os.environ.get("COULOBRE_SYSTEM_BACKUPS") == "1"
SERVER_PACKAGE_UPDATES = (
os.environ.get("COULOBRE_SERVER_PACKAGE_UPDATES") == "1"
)
LOCAL_FOLDER_SFTP = ( LOCAL_FOLDER_SFTP = (
LOCAL_WEB_SFTP and os.environ.get("COULOBRE_LOCAL_FOLDER_SFTP") == "1" LOCAL_WEB_SFTP and os.environ.get("COULOBRE_LOCAL_FOLDER_SFTP") == "1"
) )