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/templates/hosting/database_monitor.html b/src/coulobre/hosting/templates/hosting/database_monitor.html
new file mode 100644
index 0000000..8f1c06a
--- /dev/null
+++ b/src/coulobre/hosting/templates/hosting/database_monitor.html
@@ -0,0 +1,26 @@
+{% extends "hosting/workspace_page.html" %}
+{% block title %}Database monitor · Coulobre Panel{% endblock %}
+{% block page_title %}Database monitor{% endblock %}
+{% block page_actions %}
+ Refresh status
+{% endblock %}
+{% block page_content %}
+ MariaDB measurements are unavailable on this installation. Requested by {{ job.actor }} {{ job.problem }} {{ job.result.count }} package{{ job.result.count|pluralize }} ready to update. No operations yet.MariaDB status
+ {% if report %}{% endif %}
+
+
+ {% else %}
+ Operation history
{{ job.requested_at|date:"j M Y H:i" }} UTC · {{ job.action|capfirst }}{% if job.target %} {{ job.target }}{% endif %} · {{ job.state|capfirst }}
+ {% if job.actor %}{% for package in job.result.packages %}
+ {% endif %}
+ {{ package }}{{ title }}
{{ message }}
{% endfor %} -Enable the operator service on the host to run these operations.
{% endif %} -{{ job.problem }}
{% endif %} - {% if job.action == 'package-preview' and job.result.fingerprint %} -{{ job.result.count }} package{{ job.result.count|pluralize }} ready to update.
-{{ package }}MariaDB {{ job.result.database_version }} · Slow query logging {{ job.result.slow_logging|yesno:"enabled,disabled" }}
-No operations yet.
{% endfor %} -No packages are ready to update.
{% endif %} + {{ form.preview_id.errors }} + {% endif %} + {% else %}Enable the operator service on the host to review server updates.
{% endif %} +Enable the local operator worker to reload or restart services.
+ {% endif %} {% for node, services in nodes %}Set COULOBRE_SERVICE_HEALTH in /etc/coulobre/panel.env and enable coulobre-health.timer to collect service observations.