1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-03 17:36:05 +00:00

feat(alerts): mail and webhook alerts, and /healthz for a monitor

A failed backup, a scheduled backup not taken, backups the daily check
finds missing and a job that ends uncertain could only be seen on the
pages. They are now queued as alerts in the transaction of the change
they tell of (never stopping it) and sent by the worker's periodic pass
to the Settings page's alert e-mail addresses (the server's SMTP
settings) and alert webhook (a JSON POST), each tried again for ten
passes on its own. A skip for a host in maintenance is no alert.
Setting values take 255 characters. /healthz answers 200 while the
database answers and the job worker runs, 503 otherwise, without a
login.
This commit is contained in:
catborise 2026-11-19 15:35:54 +03:00
parent 2cf7dbe577
commit dcd7e32df7
21 changed files with 695 additions and 74 deletions

102
operations/alerts.py Normal file
View file

@ -0,0 +1,102 @@
"""Notices for the operator: a backup that failed, was not taken, is missing or damaged, and a job that ended
uncertain. alert() queues one in the caller's transaction, so a failed send never holds up the change it tells
of; send(), a periodic task of the worker, mails it to the Settings page's alert addresses and POSTs it as JSON
to its alert webhook, trying again at the next passes."""
import json
import logging
import urllib.request
from datetime import timedelta
from django.conf import settings
from django.core.mail import send_mail
from django.db import transaction
from django.utils import timezone, translation
from appsettings.models import AppSettings
from .models import Alert
from .utils import safe_text, words
logger = logging.getLogger(__name__)
TRIES = 10 # passes, about a minute apart, before a notice is given up
ROWS = 20 # notices a pass
KEPT = timedelta(days=30)
def channels():
"""(the alert addresses, the webhook URL) of the Settings page."""
values = dict(AppSettings.objects.filter(key__in=("ALERT_EMAILS", "ALERT_WEBHOOK")).values_list("key", "value"))
return [a.strip() for a in values.get("ALERT_EMAILS", "").split(",") if a.strip()], values.get("ALERT_WEBHOOK", "").strip()
def alert(subject, text):
"""Queue a notice (subject, text: messages, operations.utils.say); none while no channel is set. It never
stops the change it tells of: a failure is logged, in a savepoint of the caller's transaction."""
try:
with transaction.atomic():
if any(channels()):
Alert.objects.create(subject=subject, text=text)
except Exception:
logger.exception("queueing an alert failed")
def send():
"""The notices not sent yet, oldest first, ROWS a pass. A channel that fails is not tried again in the
pass, so a server that does not answer holds the worker's periodic pass (and the backup schedules) for
one timeout at most. Each try is claimed first: a worker that took over meanwhile does not send it
again. Without a channel set the notices wait (or expire)."""
emails, url = channels()
Alert.objects.filter(created_at__lt=timezone.now() - KEPT).delete()
if not (emails or url):
return
down = set()
with translation.override(settings.LANGUAGE_CODE):
# the least tried first: notices a channel keeps refusing do not hold the new ones back
for notice in Alert.objects.filter(sent_at__isnull=True, tries__lt=TRIES).order_by("tries", "pk")[:ROWS]:
wanted = {"mail"} if emails and not notice.mailed else set()
wanted |= {"webhook"} if url and not notice.posted else set()
if wanted <= down:
continue # its channels failed in this pass: not a try of its own
if not Alert.objects.filter(pk=notice.pk, tries=notice.tries).update(tries=notice.tries + 1):
continue
subject, text, errors = words(notice.subject), words(notice.text), []
if emails and not notice.mailed:
errors += _try("mail", down, notice, lambda: send_mail(f"WebVirtCloud: {subject}", text, None, emails))
if url and not notice.posted:
body = json.dumps({"subject": subject, "text": f"{subject}\n{text}",
"time": notice.created_at.isoformat()}).encode()
errors += _try("webhook", down, notice, lambda: _post(url, body))
done = (not emails or notice.mailed) and (not url or notice.posted)
Alert.objects.filter(pk=notice.pk).update(error="; ".join(errors))
if done: # never undone: a worker that took over may have sent it meanwhile
Alert.objects.filter(pk=notice.pk).update(sent_at=timezone.now())
if not done and notice.tries + 1 >= TRIES:
logger.error("alert %s given up: %s", notice.pk, "; ".join(errors))
def _try(channel, down, notice, deliver):
"""Deliver notice by channel (mail, webhook) and record it: [] when done, [the error] otherwise."""
if channel in down:
return [f"{channel}: failed earlier in this pass"]
try:
deliver()
except Exception as err:
down.add(channel)
return [f"{channel}: {safe_text(err)}"]
field = "mailed" if channel == "mail" else "posted"
setattr(notice, field, True)
Alert.objects.filter(pk=notice.pk).update(**{field: True})
return []
class _NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None # urllib would follow with a GET without the body: a redirect is an error
def _post(url, body):
request = urllib.request.Request(url, body, {"Content-Type": "application/json"})
with urllib.request.build_opener(_NoRedirect).open(request, timeout=10):
pass

View file

@ -19,7 +19,7 @@ from logs.audit import write
from vrtManager.util import OperationError
from webvirtcloud.log_context import request_ip
from . import claims, utils
from . import alerts, claims, utils
from .models import Claim, LeaseLost, Operation, fenced
logger = logging.getLogger(__name__)
@ -263,11 +263,33 @@ def finish(op, outcome, *, worker=None):
if (entry := _entry(op, outcome.state)) is not None:
_log(op.username, *entry, {Operation.SUCCEEDED: True, Operation.FAILED: False}.get(outcome.state),
op.client_ip)
_alert(op, outcome)
logger.info("job %s %s: %s", op.pk, op.kind, outcome.state)
op.refresh_from_db()
return True
# kinds whose failure the operator is told of (operations.alerts); every kind's uncertain end too
ALERTED_FAILURES = ("backup.create", "backup.verify")
def _alert(op, outcome):
# the kind's label a message: translated when the notice is sent
job = utils.say(gettext_noop("%(kind)s: %(resource)s"), kind=utils.say(label_of(op.kind)), resource=op.resource_label) \
if op.resource_label else utils.say(label_of(op.kind))
# stored messages, each kept, or text as it is
error = [m if isinstance(m, dict) and "text" in m else utils.say(utils.safe_text(m))[0]
for m in (outcome.error if isinstance(outcome.error, list) else [outcome.error] if outcome.error else [])] \
or utils.say(gettext_noop("No reason was given"))
if outcome.state == Operation.UNCERTAIN:
alerts.alert(utils.say(gettext_noop("Job ended uncertain: %(job)s"), job=job),
utils.say(gettext_noop("Job #%(id)s (%(job)s) ended uncertain; it keeps what it holds until a "
"superuser resolves it on its page. %(error)s"), id=op.pk, job=job, error=error))
elif outcome.state == Operation.FAILED and op.kind in ALERTED_FAILURES:
alerts.alert(utils.say(gettext_noop("Job failed: %(job)s"), job=job),
utils.say(gettext_noop("Job #%(id)s (%(job)s) failed: %(error)s"), id=op.pk, job=job, error=error))
def resolve(op_id, user, outcome_state, note):
if not user.is_superuser:
raise PermissionDenied
@ -306,3 +328,6 @@ def take_remembered(request, resource):
if taken: # untouched otherwise: no session write on every page view
request.session["operations_shown"] = [e for e in entries if e["resource"] != resource]
return taken
register_periodic(alerts.send)

View file

@ -0,0 +1,27 @@
# Generated by Django 5.2.18 on 2026-11-19 12:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('operations', '0004_parent'),
]
operations = [
migrations.CreateModel(
name='Alert',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('subject', models.JSONField()),
('text', models.JSONField()),
('mailed', models.BooleanField(default=False)),
('posted', models.BooleanField(default=False)),
('sent_at', models.DateTimeField(null=True)),
('tries', models.PositiveSmallIntegerField(default=0)),
('error', models.TextField(blank=True)),
],
),
]

View file

@ -138,3 +138,17 @@ def fenced(holder):
if not WorkerLease.objects.select_for_update().filter(name="worker", holder=holder).exists():
raise LeaseLost(holder)
yield
class Alert(models.Model):
"""A notice for the operator (operations.alerts), sent by the worker's periodic pass: by mail to the alert
addresses and as a POST to the alert webhook of the Settings page."""
created_at = models.DateTimeField(auto_now_add=True)
subject = models.JSONField() # messages (operations.utils.say)
text = models.JSONField()
mailed = models.BooleanField(default=False)
posted = models.BooleanField(default=False)
sent_at = models.DateTimeField(null=True) # every channel set took it
tries = models.PositiveSmallIntegerField(default=0)
error = models.TextField(blank=True) # the last try's

View file

@ -0,0 +1,187 @@
"""Alerts: a failed backup, a scheduled backup not taken, backups found missing and an uncertain job are
queued with the change they tell of and sent by mail and webhook; /healthz tells a monitor whether the
worker runs."""
import json
from datetime import timedelta
from unittest.mock import MagicMock, patch
from django.contrib.auth import get_user_model
from django.core import mail
from django.test import TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from appsettings.models import AppSettings
from operations import alerts, jobs
from operations.models import Alert, Operation, WorkerLease
from operations.utils import say
def channels(emails="ops@example.com", webhook=""):
AppSettings.objects.filter(key="ALERT_EMAILS").update(value=emails)
AppSettings.objects.filter(key="ALERT_WEBHOOK").update(value=webhook)
@override_settings(EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend")
class AlertTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_superuser("al_admin", "al@example.com", "pw")
def op(self, kind):
return Operation.objects.create(kind=kind, user=self.user, username="al_admin", state=Operation.RUNNING,
submission_key=f"key-{Operation.objects.count():012d}",
resource="backup:x", resource_label="vm1 2026-11-19 03:00", params={}, intent={})
def test_none_queued_while_no_channel_is_set(self):
channels("", "")
alerts.alert(say("Subject"), say("Text"))
self.assertFalse(Alert.objects.exists())
def test_a_failed_backup_and_an_uncertain_job_are_alerts_a_failed_other_job_is_not(self):
channels()
jobs.finish(self.op("backup.create"), jobs.Outcome(Operation.FAILED, error=say("Disk full")))
jobs.finish(self.op("instance.migrate"), jobs.Outcome(Operation.FAILED, error=say("Refused")))
jobs.finish(self.op("instance.clone"), jobs.Outcome(Operation.UNCERTAIN, error=say("Host gone")))
jobs.finish(self.op("backup.create"), jobs.Outcome(Operation.SUCCEEDED))
alerts.send()
subjects = [m.subject for m in mail.outbox]
self.assertEqual(subjects, ["WebVirtCloud: Job failed: Back up VM: vm1 2026-11-19 03:00",
"WebVirtCloud: Job ended uncertain: Clone VM: vm1 2026-11-19 03:00"])
Alert.objects.all().delete()
mail.outbox.clear()
with override_settings(LANGUAGE_CODE="tr"): # in the panel's language, the kind's label too
jobs.finish(self.op("backup.create"), jobs.Outcome(Operation.FAILED, error=say("Disk full")))
alerts.send()
self.assertEqual(mail.outbox[0].subject, "WebVirtCloud: İş başarısız: Sanal makineyi yedekle: vm1 2026-11-19 03:00")
self.assertIn("Disk full", mail.outbox[0].body)
self.assertEqual(mail.outbox[0].to, ["ops@example.com"])
self.assertTrue(all(a.sent_at for a in Alert.objects.all()))
def test_a_plain_text_error_or_a_failing_queue_never_stops_a_job_ending(self):
channels()
jobs.finish(self.op("instance.clone"), jobs.Outcome(Operation.UNCERTAIN, error=["plain words"]))
op = self.op("backup.create")
with patch("operations.alerts.Alert.objects.create", side_effect=RuntimeError("queue broke")):
jobs.finish(op, jobs.Outcome(Operation.FAILED, error=say("Disk full")))
op.refresh_from_db()
self.assertEqual(op.state, Operation.FAILED)
alerts.send()
self.assertEqual(len(mail.outbox), 1)
self.assertIn("plain words", mail.outbox[0].body)
def test_the_webhook_gets_json_and_a_failing_channel_is_tried_again_alone(self):
channels("ops@example.com", "https://hooks.example.com/x")
alerts.alert(say("Subject"), say("Text"))
with patch("operations.alerts._post", side_effect=OSError("refused")):
alerts.send()
notice = Alert.objects.get()
self.assertEqual((notice.mailed, notice.posted, notice.sent_at, notice.tries), (True, False, None, 1))
self.assertIn("webhook: refused", notice.error)
with patch("operations.alerts._post", MagicMock()) as urlopen:
alerts.send()
self.assertEqual(len(mail.outbox), 1) # not mailed twice
url, body = urlopen.call_args.args
self.assertEqual(url, "https://hooks.example.com/x")
self.assertEqual(json.loads(body)["subject"], "Subject")
self.assertTrue(Alert.objects.get().sent_at)
def test_a_channel_down_is_tried_once_a_pass_and_notices_wait_without_channels(self):
channels("", "https://hooks.example.com/x")
for _ in range(3):
alerts.alert(say("Subject"), say("Text"))
with patch("operations.alerts._post", side_effect=OSError("timed out")) as urlopen:
alerts.send()
self.assertEqual(urlopen.call_count, 1) # one timeout a pass, not one a notice
self.assertEqual(sorted(Alert.objects.values_list("tries", flat=True)), [0, 0, 1]) # the others not tried
alerts.alert(say("Newer"), say("Text"))
with patch("operations.alerts._post") as urlopen:
alerts.send()
self.assertEqual(json.loads(urlopen.call_args_list[0].args[1])["subject"], "Subject") # the least tried first
self.assertEqual(Alert.objects.filter(sent_at__isnull=True).count(), 0)
Alert.objects.update(sent_at=None, posted=False)
channels("", "")
alerts.send()
self.assertFalse(Alert.objects.filter(sent_at__isnull=False).exists())
def test_a_try_another_worker_claimed_is_not_sent_again(self):
channels()
alerts.alert(say("Subject"), say("Text"))
real = Alert.objects.filter
def taken_meanwhile(*args, **kwargs):
if "tries" in kwargs: # the claim: another worker's came first
Alert.objects.update(tries=1)
return real(*args, **kwargs)
with patch.object(Alert.objects, "filter", side_effect=taken_meanwhile):
alerts.send()
self.assertEqual(mail.outbox, [])
def test_a_redirect_is_no_delivery(self):
from http.server import BaseHTTPRequestHandler, HTTPServer
import threading
class Redirect(BaseHTTPRequestHandler):
def do_POST(self):
self.send_response(302)
self.send_header("Location", "/elsewhere")
self.end_headers()
def do_GET(self):
self.send_response(200)
self.end_headers()
def log_message(self, *args):
pass
server = HTTPServer(("127.0.0.1", 0), Redirect)
threading.Thread(target=server.handle_request, daemon=True).start()
self.addCleanup(server.server_close)
with self.assertRaises(Exception):
alerts._post(f"http://127.0.0.1:{server.server_port}/notify", b"{}")
def test_a_notice_is_given_up_after_its_tries_and_old_ones_go(self):
channels("", "https://hooks.example.com/x")
alerts.alert(say("Subject"), say("Text"))
with patch("operations.alerts._post", side_effect=OSError("refused")) as urlopen:
for _ in range(alerts.TRIES + 2):
alerts.send()
self.assertEqual(urlopen.call_count, alerts.TRIES)
Alert.objects.update(created_at=timezone.now() - alerts.KEPT - timedelta(minutes=1))
alerts.send()
self.assertFalse(Alert.objects.exists())
def test_the_settings_page_refuses_a_bad_address_or_url(self):
self.client.force_login(self.user)
for key, value in (("ALERT_EMAILS", "ops@example.com, not-an-address"), ("ALERT_WEBHOOK", "ftp://x.example.com/")):
with self.subTest(key=key):
setting = AppSettings.objects.get(key=key)
self.client.post(reverse("appsettings"), {key: value, f"was-{key}": setting.value})
self.assertEqual(AppSettings.objects.get(key=key).value, "")
self.client.post(reverse("appsettings"), {"ALERT_WEBHOOK": "https://u:secret@hooks.example.com/x", "was-ALERT_WEBHOOK": ""})
self.assertEqual(AppSettings.objects.get(key="ALERT_WEBHOOK").value, "")
self.client.post(reverse("appsettings"), {"ALERT_EMAILS": "a@example.com, b@example.com", "was-ALERT_EMAILS": ""})
self.assertEqual(AppSettings.objects.get(key="ALERT_EMAILS").value, "a@example.com, b@example.com")
url = "https://hooks.slack.example.com/services/T0000000/B0000000/" + "x" * 40
self.client.post(reverse("appsettings"), {"ALERT_WEBHOOK": url, "was-ALERT_WEBHOOK": ""})
self.assertEqual(AppSettings.objects.get(key="ALERT_WEBHOOK").value, url)
from logs.models import Logs
self.assertFalse(Logs.objects.filter(message__contains="x" * 40).exists()) # a secret of its own
self.assertContains(self.client.get(reverse("appsettings")), 'maxlength="255"')
class HealthzTests(TestCase):
def test_without_a_login_it_tells_whether_the_worker_runs(self):
response = self.client.get(reverse("healthz"))
self.assertEqual((response.status_code, response.json()["worker"]), (503, False))
WorkerLease.objects.create(holder="w", host="h", heartbeat_at=timezone.now())
response = self.client.get(reverse("healthz"))
self.assertEqual((response.status_code, response.json()["worker"], response.json()["database"]), (200, True, True))
WorkerLease.objects.update(heartbeat_at=timezone.now() - timedelta(minutes=5))
self.assertEqual(self.client.get(reverse("healthz")).status_code, 503)
from django.db import InterfaceError
with patch("operations.views.last_seen", side_effect=InterfaceError("connection already closed")):
response = self.client.get(reverse("healthz"))
self.assertEqual((response.status_code, response.json()["database"]), (503, False))
self.assertIn("no-store", response["Cache-Control"])

View file

@ -1,11 +1,14 @@
from urllib.parse import urlencode
from django.contrib import messages
from django.contrib.auth.decorators import login_not_required
from django.core.exceptions import PermissionDenied
from django.core.paginator import Paginator
from django.http import Http404
from django.db import Error as DatabaseError
from django.http import Http404, JsonResponse
from django.shortcuts import redirect, render
from django.utils.translation import gettext as _
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_POST
from vrtManager.util import OperationError
@ -84,3 +87,16 @@ def resolve(request, pk):
except OperationError as err:
messages.error(request, words(said(err)))
return redirect("operations:job", pk=op.pk)
@login_not_required
@never_cache
def healthz(request):
"""For a monitor, without a login: 200 while the database answers and the job worker runs, 503 otherwise."""
try:
seen = last_seen()
except DatabaseError:
return JsonResponse({"database": False, "worker": False}, status=503)
running = not worker_gone(seen)
return JsonResponse({"database": True, "worker": running, "worker_seen": seen and seen.isoformat()},
status=200 if running else 503)