diff --git a/doc/configuration.md b/doc/configuration.md index 632ef51d..df0e35a8 100644 --- a/doc/configuration.md +++ b/doc/configuration.md @@ -134,7 +134,7 @@ The QR code is mailed as a link to a page that shows it, good for one hour: the ## Alerts -On the Settings page (Alerts), **Alert e-mail addresses** get a mail, through the server's SMTP settings (`EMAIL_HOST` and the others, as for OTP), and **Alert webhook** a JSON POST (`subject`, `text`, `time`; Slack and Mattermost take it) when a backup job fails, a scheduled backup is not taken (not for a host in maintenance), the daily target check finds backups missing, a verification finds a backup damaged, or a job ends uncertain. The job worker sends them within a minute and tries a failed channel again for ten minutes. +On the Settings page (Alerts), **Alert e-mail addresses** get a mail, through the server's SMTP settings (`EMAIL_HOST` and the others, as for OTP), and **Alert webhook** a JSON POST (`subject`, `text`, `time`; Slack and Mattermost take it) when a backup job fails, a scheduled backup is not taken (not for a host in maintenance), the daily target check finds backups missing, a verification finds a backup damaged, a job ends uncertain, or a fault stops or pauses a VM (a disk error, a crash, a kernel panic: the reasons the VM page shows; once a fault, read every minute from each host, so told within two minutes). The job worker sends them within a minute and tries a failed channel again for ten minutes. ## Health check diff --git a/instances/jobs.py b/instances/jobs.py index 5d58a317..ac193739 100644 --- a/instances/jobs.py +++ b/instances/jobs.py @@ -31,10 +31,11 @@ from appsettings.settings import app_settings from computes.models import Compute from instances import addresses, utils from instances.models import Instance +from instances.states import state_reason from logs.audit import write -from operations import claims +from operations import alerts, claims from operations.utils import REPORTED, safe_text, say -from operations.jobs import Cancelled, Kind, Outcome, Plan, register +from operations.jobs import Cancelled, Kind, Outcome, Plan, register, register_periodic from operations.models import Claim, Operation @@ -1660,3 +1661,34 @@ class ForceOffVM(_Power): def done(self, dom): # shut off, or gone: a transient VM is removed as it stops return dom is None or not dom.isActive() + + +VM_FAULT = _("VM fault: %(vm)s") +VM_FAULT_TEXT = _("%(vm)s on %(host)s: %(reason)s") + + +def watch_faults(): + """Alerts once when a fault stops or pauses a VM (instances.states.REASONS), while an alert channel is set: + each host's VMs read in one call, all hosts at once (utils.host_domain_states); a host that does not answer + is read again at the next pass. Without a channel nothing is told, nor kept as told.""" + if not any(alerts.channels()): + Instance.objects.exclude(fault="").update(fault="") + return + computes = list(Compute.objects.all()) + states = utils.host_domain_states(computes) + for compute in computes: + domains = states[compute.pk] + if domains is None: + continue + for vm in Instance.objects.filter(compute=compute): + _name, state, reason = domains.get(vm.uuid, (None, None, None)) + why = state_reason(state, reason) + fault = f"{state}:{reason}" if why else "" + if fault == vm.fault: + continue + if why: + alerts.alert(say(VM_FAULT, vm=vm.name), say(VM_FAULT_TEXT, vm=vm.name, host=compute.name, reason=str(why))) + Instance.objects.filter(pk=vm.pk).update(fault=fault) + + +register_periodic(watch_faults) diff --git a/instances/migrations/0021_instance_fault.py b/instances/migrations/0021_instance_fault.py new file mode 100644 index 00000000..73e5050e --- /dev/null +++ b/instances/migrations/0021_instance_fault.py @@ -0,0 +1,18 @@ +# Generated by Django 5.2.18 on 2026-11-25 06:27 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('instances', '0020_tombstone_keeps'), + ] + + operations = [ + migrations.AddField( + model_name='instance', + name='fault', + field=models.CharField(blank=True, default='', max_length=16), + ), + ] diff --git a/instances/models.py b/instances/models.py index ae2f67e8..b827ffac 100644 --- a/instances/models.py +++ b/instances/models.py @@ -43,6 +43,8 @@ class Instance(models.Model): created = models.DateTimeField(_("created"), auto_now_add=True) drbd = models.CharField(_("drbd"), max_length=24, default="None") tags = models.ManyToManyField("computes.Tag", blank=True, related_name="instances", verbose_name=_("tags")) + # "state:reason" of the fault (instances.states.REASONS) last alerted; empty without one (instances.jobs.watch_faults) + fault = models.CharField(max_length=16, blank=True, default="") objects = InstanceManager() diff --git a/instances/tests/test_fault_alerts.py b/instances/tests/test_fault_alerts.py new file mode 100644 index 00000000..2ba59511 --- /dev/null +++ b/instances/tests/test_fault_alerts.py @@ -0,0 +1,59 @@ +from unittest import mock + +import libvirt +from django.test import TestCase + +from appsettings.models import AppSettings +from computes.models import Compute +from instances import jobs +from instances.models import Instance +from operations.models import Alert +from operations.utils import words + +PAUSED_IOERROR = (libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_PAUSED_IOERROR) +RUNNING = (libvirt.VIR_DOMAIN_RUNNING, libvirt.VIR_DOMAIN_RUNNING_BOOTED) +PAUSED_BY_USER = (libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_PAUSED_USER) + + +class FaultAlertTests(TestCase): + def setUp(self): + AppSettings.objects.update_or_create(key="ALERT_WEBHOOK", defaults={"name": "Alert webhook", + "value": "http://192.0.2.9/hook"}) + self.compute = Compute.objects.create(name="h1", hostname="192.0.2.71", login="u", password="p", type=1) + self.vm = Instance.objects.create(compute=self.compute, name="vm1", uuid="71717171-0000-4000-8000-000000000001") + + def watch(self, state): + """One pass with the host's VM in state (state, reason), or the host not answering (None).""" + answer = None if state is None else {self.vm.uuid: ["vm1", *state]} + with mock.patch.object(jobs.utils, "host_domain_states", return_value={self.compute.pk: answer}): + jobs.watch_faults() + self.vm.refresh_from_db() + + def test_a_fault_is_alerted_once_and_again_after_the_vm_recovers(self): + self.watch(PAUSED_IOERROR) + self.assertEqual([(words(a.subject), words(a.text)) for a in Alert.objects.all()], + [("VM fault: vm1", "vm1 on h1: Paused by a disk error")]) + self.watch(PAUSED_IOERROR) + self.watch(None) # a host that does not answer changes nothing + self.assertEqual(Alert.objects.count(), 1) + self.watch(RUNNING) + self.assertEqual(self.vm.fault, "") + self.watch(PAUSED_IOERROR) + self.assertEqual(Alert.objects.count(), 2) + + def test_no_alert_for_an_ordinary_state_nor_without_a_channel(self): + self.watch(PAUSED_BY_USER) + self.assertFalse(Alert.objects.exists()) + AppSettings.objects.filter(key="ALERT_WEBHOOK").update(value="") + with mock.patch.object(jobs.utils, "host_domain_states") as read: + jobs.watch_faults() + read.assert_not_called() # no host is read for nobody + + def test_a_fault_is_told_again_after_the_channels_were_off(self): + self.watch(PAUSED_IOERROR) + AppSettings.objects.filter(key="ALERT_WEBHOOK").update(value="") + self.watch(PAUSED_IOERROR) + self.assertEqual(self.vm.fault, "") # nobody heard of what happens meanwhile + AppSettings.objects.filter(key="ALERT_WEBHOOK").update(value="http://192.0.2.9/hook") + self.watch(PAUSED_IOERROR) + self.assertEqual(Alert.objects.count(), 2) diff --git a/locale/tr/LC_MESSAGES/django.mo b/locale/tr/LC_MESSAGES/django.mo index 3bd39902..72c1e168 100644 Binary files a/locale/tr/LC_MESSAGES/django.mo and b/locale/tr/LC_MESSAGES/django.mo differ diff --git a/locale/tr/LC_MESSAGES/django.po b/locale/tr/LC_MESSAGES/django.po index 83eaf235..96881e5f 100644 --- a/locale/tr/LC_MESSAGES/django.po +++ b/locale/tr/LC_MESSAGES/django.po @@ -13350,3 +13350,11 @@ msgstr "%(n)s atlandı" #: vmbackups/models.py:15 msgid "The job was cancelled" msgstr "İş iptal edildi" + +#: instances/jobs.py:1666 +msgid "VM fault: %(vm)s" +msgstr "Sanal makine arızası: %(vm)s" + +#: instances/jobs.py:1667 +msgid "%(vm)s on %(host)s: %(reason)s" +msgstr "%(host)s üzerindeki %(vm)s: %(reason)s" diff --git a/locale/uk/LC_MESSAGES/django.mo b/locale/uk/LC_MESSAGES/django.mo index 17654ecf..152b5a83 100644 Binary files a/locale/uk/LC_MESSAGES/django.mo and b/locale/uk/LC_MESSAGES/django.mo differ diff --git a/locale/uk/LC_MESSAGES/django.po b/locale/uk/LC_MESSAGES/django.po index 3791d39f..b3629637 100644 --- a/locale/uk/LC_MESSAGES/django.po +++ b/locale/uk/LC_MESSAGES/django.po @@ -13442,3 +13442,11 @@ msgstr "Усі інтерфейси" #: vmbackups/models.py:15 msgid "The job was cancelled" msgstr "Завдання скасовано" + +#: instances/jobs.py:1666 +msgid "VM fault: %(vm)s" +msgstr "Збій ВМ: %(vm)s" + +#: instances/jobs.py:1667 +msgid "%(vm)s on %(host)s: %(reason)s" +msgstr "ВМ %(vm)s на хості %(host)s: %(reason)s" diff --git a/locale/zh/LC_MESSAGES/django.mo b/locale/zh/LC_MESSAGES/django.mo index 1432ed98..0ab2074e 100644 Binary files a/locale/zh/LC_MESSAGES/django.mo and b/locale/zh/LC_MESSAGES/django.mo differ diff --git a/locale/zh/LC_MESSAGES/django.po b/locale/zh/LC_MESSAGES/django.po index 084a41e2..8dc250ef 100644 --- a/locale/zh/LC_MESSAGES/django.po +++ b/locale/zh/LC_MESSAGES/django.po @@ -12482,3 +12482,11 @@ msgstr "%(n)s 台已跳过" #: vmbackups/models.py:15 msgid "The job was cancelled" msgstr "作业已取消" + +#: instances/jobs.py:1666 +msgid "VM fault: %(vm)s" +msgstr "虚拟机故障:%(vm)s" + +#: instances/jobs.py:1667 +msgid "%(vm)s on %(host)s: %(reason)s" +msgstr "%(host)s 上的 %(vm)s:%(reason)s" diff --git a/operations/alerts.py b/operations/alerts.py index 56c39306..7b0afa2a 100644 --- a/operations/alerts.py +++ b/operations/alerts.py @@ -1,7 +1,8 @@ -"""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.""" +"""Notices for the operator: a backup that failed, was not taken, is missing or damaged, a job that ended +uncertain, and a VM a fault stopped or paused (instances.jobs.watch_faults). 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