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

feat(instances): alert when a fault stops or pauses a VM

The VM page shows why a VM paused or stopped when nobody asked (a disk
error, a crash, a kernel panic: instances.states.REASONS), but nobody
learnt of it until they opened the page. While an alert channel is set,
the worker reads every host's VM states each minute (one call a host,
all hosts at once, 10 s at most) and queues one alert per fault; the VM
keeps the fault it was alerted for, so a fault is told once and again
only after the VM recovered.
This commit is contained in:
catborise 2026-11-25 09:30:44 +03:00
parent c5a04e040d
commit de9f37a20d
12 changed files with 143 additions and 7 deletions

View file

@ -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

View file

@ -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)

View file

@ -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),
),
]

View file

@ -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()

View file

@ -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)

Binary file not shown.

View file

@ -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"

Binary file not shown.

View file

@ -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"

Binary file not shown.

View file

@ -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"

View file

@ -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