mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-03 09:26:03 +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:
parent
2cf7dbe577
commit
dcd7e32df7
21 changed files with 695 additions and 74 deletions
|
|
@ -27,7 +27,7 @@ from computes.models import Compute
|
|||
from instances.jobs import MOVED, PAUSED_FROZEN, THAW_FAILED, _instance, _log, _snapshot_free_space, record_vm, vm_claims
|
||||
from instances.utils import QUOTA_UNVERIFIED, paths_used_on_other_computes, QUOTA_UNVERIFIED_TEXT, check_user_quota, get_random_mac_address, quota_message
|
||||
from instances.models import Instance
|
||||
from operations import claims
|
||||
from operations import alerts, claims
|
||||
from operations.jobs import Cancelled, Kind, Outcome, Plan, register, register_periodic
|
||||
from operations.models import Claim, Operation
|
||||
from operations.utils import safe_text, say
|
||||
|
|
@ -1581,21 +1581,27 @@ class CheckTarget(Kind):
|
|||
pool.refresh(0)
|
||||
present = set(pool.listVolumes())
|
||||
settled = timezone.now() - CHECK_SETTLE
|
||||
missing = []
|
||||
for backup in target.backups.filter(state__in=(Backup.READY, Backup.MISSING)).prefetch_related("files"):
|
||||
needed = {f.volume for f in backup.files.all()} | {f"{backup.prefix}-manifest.json"}
|
||||
try:
|
||||
needed |= {f["volume"] for f in _base_files(backup)} # a restore copies the chain flat
|
||||
state = Backup.READY if needed <= present else Backup.MISSING
|
||||
except util.OperationError: # its base's row is gone
|
||||
state = Backup.MISSING
|
||||
if state == Backup.MISSING and backup.state == Backup.READY and (backup.finished_at or settled) > settled:
|
||||
continue # just written through another compute: this one may not list its files yet (NFS)
|
||||
if state == Backup.MISSING:
|
||||
missing.append(f"{backup.vm_name} {timezone.localtime(backup.created_at):%Y-%m-%d %H:%M}")
|
||||
# only from the state read: a deletion begun meanwhile is left alone
|
||||
Backup.objects.filter(pk=backup.pk, state=backup.state).update(state=state)
|
||||
BackupTarget.objects.filter(pk=target.pk).update(checked_at=timezone.now())
|
||||
missing, lost = [], [] # lost: found missing at this check
|
||||
# the states and their alert together: a worker stopped between them loses no alert
|
||||
with transaction.atomic():
|
||||
for backup in target.backups.filter(state__in=(Backup.READY, Backup.MISSING)).prefetch_related("files"):
|
||||
needed = {f.volume for f in backup.files.all()} | {f"{backup.prefix}-manifest.json"}
|
||||
try:
|
||||
needed |= {f["volume"] for f in _base_files(backup)} # a restore copies the chain flat
|
||||
state = Backup.READY if needed <= present else Backup.MISSING
|
||||
except util.OperationError: # its base's row is gone
|
||||
state = Backup.MISSING
|
||||
if state == Backup.MISSING and backup.state == Backup.READY and (backup.finished_at or settled) > settled:
|
||||
continue # just written through another compute: this one may not list its files yet (NFS)
|
||||
if state == Backup.MISSING:
|
||||
missing.append(f"{backup.vm_name} {timezone.localtime(backup.created_at):%Y-%m-%d %H:%M}")
|
||||
# only from the state read: a deletion begun meanwhile is left alone
|
||||
if Backup.objects.filter(pk=backup.pk, state=backup.state).update(state=state) and backup.state != state == Backup.MISSING:
|
||||
lost.append(missing[-1])
|
||||
BackupTarget.objects.filter(pk=target.pk).update(checked_at=timezone.now())
|
||||
if lost:
|
||||
alerts.alert(say(_("Backups missing from %(target)s"), target=target.name),
|
||||
say(_("Files of these backups are missing from the target: %(backups)s"), backups=", ".join(lost)))
|
||||
if missing:
|
||||
return {"warning": say(_("Files of these backups are missing from the target: %(backups)s"),
|
||||
backups=", ".join(missing))}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import logging
|
|||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.db import close_old_connections
|
||||
from django.db import close_old_connections, transaction
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.utils import timezone
|
||||
from django.utils.translation import gettext_noop as _
|
||||
|
|
@ -16,7 +16,7 @@ from libvirt import libvirtError
|
|||
|
||||
from computes.models import Compute
|
||||
from computes.utils import refresh_instance_database
|
||||
from operations import claims, jobs
|
||||
from operations import alerts, claims, jobs
|
||||
from operations.models import Operation
|
||||
from operations.utils import safe_text, said, say
|
||||
from vrtManager.util import ConnectionFailed
|
||||
|
|
@ -57,7 +57,8 @@ def run_schedules(now=None):
|
|||
continue
|
||||
in_maintenance = Compute.objects.filter(pk=vm.compute_id, maintenance_since__isnull=False).exists()
|
||||
if not open_:
|
||||
_record(policy, vm, day, BackupRun.SKIPPED, say(IN_MAINTENANCE if in_maintenance else NOT_STARTED))
|
||||
_record(policy, vm, day, BackupRun.SKIPPED, say(IN_MAINTENANCE if in_maintenance else NOT_STARTED),
|
||||
quiet=in_maintenance) # the operator put the host in maintenance
|
||||
elif not in_maintenance: # deferred while the window lasts
|
||||
due.setdefault(vm.compute_id, []).append((policy.pk, vm.pk, day, start))
|
||||
for compute_id in due.keys() | read.keys():
|
||||
|
|
@ -82,9 +83,15 @@ def occurrences(policy, now):
|
|||
yield day, start
|
||||
|
||||
|
||||
def _record(policy, vm, day, state, note=(), operation=None):
|
||||
BackupRun.objects.get_or_create(policy=policy, instance=vm, day=day,
|
||||
defaults={"state": state, "note": list(note), "operation": operation})
|
||||
def _record(policy, vm, day, state, note=(), operation=None, quiet=False):
|
||||
"""The run of the day; one not submitted is an alert unless quiet."""
|
||||
with transaction.atomic(): # the run and its alert together: a worker stopped between them loses neither
|
||||
_run, made = BackupRun.objects.get_or_create(policy=policy, instance=vm, day=day,
|
||||
defaults={"state": state, "note": list(note), "operation": operation})
|
||||
if made and state != BackupRun.SUBMITTED and not quiet:
|
||||
alerts.alert(say(_("Scheduled backup not taken: %(vm)s"), vm=vm.name),
|
||||
say(_("The schedule %(schedule)s did not back up %(vm)s on %(day)s: %(reason)s"),
|
||||
schedule=policy.name, vm=vm.name, day=day.isoformat(), reason=list(note)))
|
||||
|
||||
|
||||
def _active_superuser(user):
|
||||
|
|
|
|||
|
|
@ -19,6 +19,8 @@ from operations.jobs import Context
|
|||
from operations.models import Operation, acquire
|
||||
from operations.utils import words
|
||||
from vmbackups import schedule
|
||||
from appsettings.models import AppSettings
|
||||
from operations.models import Alert
|
||||
from vmbackups.jobs import CheckTarget, DeleteBackup, _beyond_keep
|
||||
from vmbackups.models import Backup, BackupFile, BackupPolicy, BackupRun, BackupTarget, BackupTargetPool
|
||||
from vrtManager.util import OperationError
|
||||
|
|
@ -212,11 +214,24 @@ class ScheduleTests(TransactionTestCase):
|
|||
self.assertEqual(self.creates(), [])
|
||||
|
||||
def test_a_run_not_started_in_its_window_is_skipped(self):
|
||||
AppSettings.objects.update_or_create(key="ALERT_EMAILS", defaults={"value": "ops@example.com"})
|
||||
self.pass_at(at(2026, 11, 17, 8, 1)) # the worker was down from before 02:00
|
||||
run = BackupRun.objects.get()
|
||||
self.assertEqual(run.state, BackupRun.SKIPPED)
|
||||
self.assertIn("6 hours", words(run.note))
|
||||
self.assertEqual(self.creates(), [])
|
||||
(notice,) = Alert.objects.all() # once, with the reason
|
||||
self.assertEqual(words(notice.subject), "Scheduled backup not taken: vm1")
|
||||
self.assertIn("6 hours", words(notice.text))
|
||||
self.pass_at(at(2026, 11, 17, 8, 2))
|
||||
self.assertEqual(Alert.objects.count(), 1)
|
||||
|
||||
def test_a_skip_for_a_host_in_maintenance_is_no_alert(self):
|
||||
AppSettings.objects.update_or_create(key="ALERT_EMAILS", defaults={"value": "ops@example.com"})
|
||||
Compute.objects.filter(pk=self.c1.pk).update(maintenance_since=at(2026, 11, 16))
|
||||
self.pass_at(at(2026, 11, 17, 8, 1))
|
||||
self.assertEqual(BackupRun.objects.get().state, BackupRun.SKIPPED)
|
||||
self.assertFalse(Alert.objects.exists())
|
||||
|
||||
def test_a_new_schedule_does_not_skip_the_times_before_it(self):
|
||||
BackupPolicy.objects.filter(pk=self.policy.pk).update(created_at=at(2026, 11, 17, 10))
|
||||
|
|
@ -576,8 +591,13 @@ class ScheduleTests(TransactionTestCase):
|
|||
Backup.objects.filter(pk=top.pk).update(parent=base)
|
||||
for b in (base, top):
|
||||
BackupFile.objects.create(backup=b, role=BackupFile.DISK, dev="vda", volume=f"{b.prefix}-vda.qcow2")
|
||||
AppSettings.objects.update_or_create(key="ALERT_EMAILS", defaults={"value": "ops@example.com"})
|
||||
self.run_check([f"{base.prefix}-manifest.json", f"{top.prefix}-vda.qcow2", f"{top.prefix}-manifest.json"])
|
||||
self.assertEqual(Backup.objects.get(pk=top.pk).state, Backup.MISSING)
|
||||
(notice,) = Alert.objects.all() # found missing now: told once
|
||||
self.assertEqual(words(notice.subject), "Backups missing from nfs1")
|
||||
self.run_check([f"{base.prefix}-manifest.json", f"{top.prefix}-vda.qcow2", f"{top.prefix}-manifest.json"])
|
||||
self.assertEqual(Alert.objects.count(), 1)
|
||||
|
||||
def test_a_check_that_reaches_no_pool_marks_nothing(self):
|
||||
(backup,) = self.backups(Backup.READY)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue