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

feat(computes): a box on the Computes page tells what wants a look

Above the hosts, linked to where each is handled: hosts not answering,
pools filled to 85% (as last measured), VMs with snapshots older than 30
days, backup jobs failed and backups a schedule did not take in the last 7
days (per schedule; not for a host in maintenance), backups missing or
damaged (a new Damaged filter on the Backups page), and jobs that ended
uncertain or wait for over an hour. Nothing to look at: no box. The pools
and snapshots are read on threads of their own, waited for 2 seconds at
most: one slow host leaves out its lines, not the page.
This commit is contained in:
catborise 2026-11-19 22:29:29 +03:00
parent 2c0855cf64
commit 5c7687c60d
13 changed files with 468 additions and 89 deletions

View file

@ -0,0 +1,36 @@
{% load i18n %}{% load bootstrap_icons %}{# what wants a look: views.attention, each with a link to where it is handled #}
{% if attention %}
<div class="alert alert-warning" role="status">
<h2 class="h6">{% bs_icon 'exclamation-triangle' %} {% trans "Needs attention" %}</h2>
<ul class="mb-0 small">
{% for compute in attention.hosts %}
<li><a href="{% url 'overview' compute.pk %}">{{ compute.name }}</a>: {% trans "not answering" %}</li>
{% endfor %}
{% for compute, pool in attention.pools %}
<li><a href="{% url 'storage' compute.pk pool.name %}">{{ compute.name }} / {{ pool.name }}</a>: {% blocktrans with percent=pool.percent %}{{ percent }}% full{% endblocktrans %}</li>
{% endfor %}
{% for compute, vm, snapshots in attention.snapshots %}
<li>{% if vm %}<a href="{% url 'instances:instance' vm.pk %}{% if not vm.is_template %}#snapshots{% endif %}">{{ compute.name }} / {{ vm.name }}</a>{% else %}{{ compute.name }} / {{ snapshots.vm }}{% endif %}:
{% blocktrans count counter=snapshots.count %}{{ counter }} snapshot older than 30 days{% plural %}{{ counter }} snapshots older than 30 days{% endblocktrans %}</li>
{% endfor %}
{% if attention.failed %}
<li><a href="{% url 'operations:jobs' %}?kind=backup.create&amp;state=failed">{% blocktrans count counter=attention.failed %}{{ counter }} backup failed in the last 7 days{% plural %}{{ counter }} backups failed in the last 7 days{% endblocktrans %}</a></li>
{% endif %}
{% for policy, count in attention.not_taken %}
<li><a href="{% url 'vmbackups:policy' policy.pk %}">{{ policy.name }}</a>: {% blocktrans count counter=count %}{{ counter }} scheduled backup not taken in the last 7 days{% plural %}{{ counter }} scheduled backups not taken in the last 7 days{% endblocktrans %}</li>
{% endfor %}
{% if attention.missing %}
<li><a href="{% url 'vmbackups:index' %}?state=missing">{% blocktrans count counter=attention.missing %}{{ counter }} backup missing from its target{% plural %}{{ counter }} backups missing from their targets{% endblocktrans %}</a></li>
{% endif %}
{% if attention.damaged %}
<li><a href="{% url 'vmbackups:index' %}?state=damaged">{% blocktrans count counter=attention.damaged %}{{ counter }} backup damaged{% plural %}{{ counter }} backups damaged{% endblocktrans %}</a></li>
{% endif %}
{% if attention.uncertain %}
<li><a href="{% url 'operations:jobs' %}?state=uncertain">{% blocktrans count counter=attention.uncertain %}{{ counter }} job ended uncertain{% plural %}{{ counter }} jobs ended uncertain{% endblocktrans %}</a></li>
{% endif %}
{% if attention.waiting %}
<li><a href="{% url 'operations:jobs' %}?state=queued">{% blocktrans count counter=attention.waiting %}{{ counter }} job queued for over an hour{% plural %}{{ counter }} jobs queued for over an hour{% endblocktrans %}</a></li>
{% endif %}
</ul>
</div>
{% endif %}

View file

@ -14,6 +14,7 @@
<h3 class="mb-3">{% trans "Computes" %}</h3>
</div>
</div>
{% include "computes/attention.html" %}
{% if not computes %}
<div class="alert alert-warning shadow-sm">
{% bs_icon 'exclamation-triangle'%} <strong>{% trans "Warning" %}:</strong> {% trans "You don't have any computes" %}

View file

@ -0,0 +1,131 @@
"""The box above the Computes page's hosts: what wants a look, each with a link to where it is handled."""
import datetime
import time
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from django.contrib.auth import get_user_model
from libvirt import libvirtError
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from computes import views
from computes.models import Compute
from instances.models import Instance
from operations.models import Operation
from operations.utils import say
from vmbackups.models import Backup, BackupPolicy, BackupRun, BackupTarget
from vmbackups.schedule import IN_MAINTENANCE, NOT_STARTED
from vrtManager.hostdetails import wvmHostDetails
NOW = timezone.now()
class AttentionBoxTests(TestCase):
def setUp(self):
self.admin = get_user_model().objects.create_superuser("at-admin", "at@example.com", "pw")
self.client.force_login(self.admin)
self.up = Compute.objects.create(name="up", hostname="192.0.2.1", login="wvc", password="", type=1,
host_uuid="11111111-0000-0000-0000-000000000000")
self.down = Compute.objects.create(name="down", hostname="192.0.2.2", login="wvc", password="", type=1,
host_uuid="22222222-0000-0000-0000-000000000000")
self.vm = Instance.objects.create(compute=self.up, name="vm1", uuid="33333333-0000-4000-8000-000000000001")
self.addCleanup(lambda: [read.join(5) for read in views._reading.values()]) # none left for the next test
def read(self, compute):
return (False, "refused", None, "") if compute.name == "down" else (True, None, None, "")
def page(self, pools=(), snapshots=()):
with patch("computes.views._read_host", side_effect=self.read), patch(
"computes.views._read_attention", return_value={"pools": list(pools), "snapshots": list(snapshots)}):
return self.client.get(reverse("computes"))
def test_nothing_to_look_at_shows_no_box(self):
self.down.delete()
self.assertNotContains(self.page(), "Needs attention")
def test_hosts_pools_and_snapshots(self):
page = self.page(pools=[{"name": "default", "percent": 91}], snapshots=[{"vm": "vm1", "count": 2}])
self.assertContains(page, "Needs attention")
self.assertContains(page, f'<a href="{reverse("overview", args=[self.down.pk])}">down</a>: not answering',
html=False)
self.assertContains(page, reverse("storage", args=[self.up.pk, "default"]))
self.assertContains(page, "91% full")
self.assertContains(page, reverse("instances:instance", args=[self.vm.pk]) + "#snapshots")
self.assertContains(page, "2 snapshots older than 30 days")
def test_snapshots_slow_to_list_do_not_hold_the_page(self):
slow = {"pools": [{"name": "default", "percent": 91}], "snapshots": []}
with patch("computes.views._read_host", side_effect=self.read), patch("computes.views.ATTENTION_WAIT", 0.2), patch(
"computes.views._read_attention", side_effect=lambda compute: time.sleep(1) or slow):
started = time.monotonic()
page = self.client.get(reverse("computes"))
took = time.monotonic() - started
self.assertLess(took, 0.9)
self.assertEqual({c.name: c.status for c in page.context["computes"]}, {"up": True, "down": False})
self.assertNotContains(page, "91% full") # left out this time
def test_backups_and_jobs(self):
target = BackupTarget.objects.create(name="t")
policy = BackupPolicy.objects.create(name="n", target=target, time=datetime.time(2), keep=1)
def backup(state, days_ago=0, **fields):
b = Backup.objects.create(target=target, instance=self.vm, vm_uuid=self.vm.uuid, vm_name="vm1",
compute_name="up", state=state, **fields)
Backup.objects.filter(pk=b.pk).update(created_at=NOW - datetime.timedelta(days=days_ago))
backup(Backup.MISSING, days_ago=40)
backup(Backup.READY, damage=say("x"))
today = timezone.localdate()
BackupRun.objects.create(policy=policy, instance=self.vm, day=today, state=BackupRun.SKIPPED, note=say(NOT_STARTED))
BackupRun.objects.create(policy=policy, instance=self.vm, day=today - datetime.timedelta(days=1),
state=BackupRun.SKIPPED, note=say(IN_MAINTENANCE)) # the operator's choice
Operation.objects.create(kind="backup.verify", user=self.admin, username="at-admin", submission_key="k1",
resource="r1", state=Operation.UNCERTAIN)
for key, days_ago in (("k4", 0), ("k5", 8)): # a backup job failed this week, one before
Operation.objects.create(kind="backup.create", user=self.admin, username="at-admin", submission_key=key,
resource=key, state=Operation.FAILED,
finished_at=NOW - datetime.timedelta(days=days_ago))
waiting = Operation.objects.create(kind="backup.verify", user=self.admin, username="at-admin",
submission_key="k2", resource="r2", state=Operation.QUEUED)
Operation.objects.filter(pk=waiting.pk).update(created_at=NOW - datetime.timedelta(hours=2))
Operation.objects.create(kind="backup.verify", user=self.admin, username="at-admin", submission_key="k3",
resource="r3", state=Operation.QUEUED) # just queued
self.down.delete()
page = self.page()
for text in ("1 backup failed in the last 7 days", "1 scheduled backup not taken in the last 7 days",
"1 backup missing from its target", "1 backup damaged", "1 job ended uncertain",
"1 job queued for over an hour"):
self.assertContains(page, text)
self.assertContains(page, reverse("operations:jobs") + "?kind=backup.create&amp;state=failed")
self.assertContains(page, f'<a href="{reverse("vmbackups:policy", args=[policy.pk])}">n</a>: 1 scheduled')
self.assertContains(page, reverse("vmbackups:index") + "?state=damaged")
self.assertContains(page, reverse("operations:jobs") + "?state=uncertain")
listed = self.client.get(reverse("vmbackups:index") + "?state=damaged")
self.assertEqual([b.state for b in listed.context["rows"]], [Backup.READY])
class HostAttentionTests(TestCase):
def test_full_pools_and_old_snapshots_of_the_host(self):
def pool(name, capacity, allocation):
return MagicMock(**{"name.return_value": name, "info.return_value": [2, capacity, allocation, 0]})
def snapshot(days_ago):
created = int((NOW - datetime.timedelta(days=days_ago)).timestamp())
return MagicMock(**{"getXMLDesc.return_value": f"<domainsnapshot><creationTime>{created}</creationTime>"
"</domainsnapshot>"})
def domain(name, *snapshots):
return MagicMock(**{"name.return_value": name, "listAllSnapshots.return_value": list(snapshots)})
host = wvmHostDetails.__new__(wvmHostDetails)
gone = MagicMock(**{"info.side_effect": libvirtError("undefined meanwhile")})
deleted = MagicMock(**{"getXMLDesc.side_effect": libvirtError("deleted meanwhile")})
host.wvm = SimpleNamespace(
listAllStoragePools=lambda flags: [pool("default", 100, 90), gone, pool("big", 100, 10), pool("empty", 0, 0)],
listAllDomains=lambda flags: [domain("old", snapshot(40), deleted, snapshot(31), snapshot(1)),
domain("new", snapshot(2))])
self.assertEqual(host.get_attention(85, NOW - datetime.timedelta(days=30)),
{"pools": [{"name": "default", "percent": 90}], "snapshots": [{"vm": "old", "count": 2}]})

View file

@ -52,7 +52,7 @@ class ComputesPageTests(TestCase):
found = {c1.id: {"cpus": 16, "memory": 64 * GIB, "vcpus": {"all": 40, "running": 24},
"assigned": {"all": 48 * GIB, "running": 32 * GIB}, "ratio": 2.5, "vms": VMS}}
with patch.object(Compute, "capacity", new=property(lambda c: found.get(c.id))), \
patch.object(Compute, "status", new=True):
patch.object(Compute, "status", new=True), patch("computes.views._read_attention", return_value=None):
page = html.fromstring(self.client.get(reverse("computes")).content)
headers = [" ".join(th.text_content().split()) for th in page.xpath("//thead//th")]
# no pools: measuring their space scans each pool of each host (views.host_pools)

View file

@ -9,6 +9,7 @@ from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from computes import views
from computes.models import Compute
@ -18,6 +19,10 @@ class ListHostsTests(TestCase):
for number, name in enumerate(("fast", "slow-1", "slow-2")):
Compute.objects.create(name=name, hostname="192.0.2.1", login="wvc", password="", type=1,
host_uuid=f"{number}" * 8 + "-0000-0000-0000-000000000000")
patcher = patch("computes.views._read_attention", return_value=None) # the box's reads: test_attention
patcher.start()
self.addCleanup(patcher.stop) # last: the reads still running end with it
self.addCleanup(lambda: [read.join(5) for read in views._reading.values()])
self.release = threading.Event()
self.addCleanup(self.release.set)

View file

@ -2,6 +2,8 @@ import json
import logging
import threading
import time
from collections import Counter
from datetime import timedelta
from contextlib import suppress
from copy import copy
@ -25,7 +27,9 @@ from libvirt import libvirtError
from logs.audit import audit, changed_fields, snapshot
from operations import claims, jobs
from operations.models import Operation
from operations.utils import busy_message
from operations.utils import busy_message, say
from vmbackups.models import Backup, BackupRun
from vmbackups.schedule import IN_MAINTENANCE
from vrtManager.connection import CONN_SOCKET, CONN_SSH, CONN_TCP, CONN_TLS
from vrtManager.hostdetails import wvmHostDetails
from vrtManager.storage import wvmStorages
@ -93,6 +97,11 @@ CONNECTIONS = {CONN_TCP: "TCP", CONN_SSH: "SSH", CONN_TLS: "TLS", CONN_SOCKET: "
LIST_WAIT = 10
# what the box above the hosts tells of: a pool this full (percent), a snapshot this old
POOL_FULL = 85
SNAPSHOT_OLD = timedelta(days=30)
def _read_host(compute):
"""Whether the panel reaches the compute, why not, its capacity
(shown_capacity) and, for one whose host UUID is not kept yet, that UUID
@ -104,23 +113,35 @@ def _read_host(compute):
return compute.status, compute.connection_error, shown_capacity(compute), uuid
class _HostRead(threading.Thread):
"""One read of a host (_read_host) on a daemon thread: one stuck on its
host does not hold the process when it exits."""
def _read_attention(compute):
"""The compute's full pools and old snapshots (get_attention); None when
they cannot be read."""
if compute.status is True:
with suppress(libvirtError):
return compute.proxy.get_attention(POOL_FULL, timezone.now() - SNAPSHOT_OLD)
return None
def __init__(self, compute):
class _HostRead(threading.Thread):
"""One read of a host (read: _read_host or _read_attention) on a daemon
thread: one stuck on its host does not hold the process when it exits."""
def __init__(self, compute, read):
super().__init__(daemon=True, name=f"wvc-host-{compute.pk}")
self.compute, self.result = compute, None
self.compute, self.read, self.result = compute, read, None
def run(self):
self.result = _read_host(self.compute)
self.result = self.read(self.compute)
# the reads of the Computes pages of this process, one of a host at a time: a host that
# hangs holds one thread however often the page is loaded, and no other host's
_reading = {} # (compute pk, its connection settings): its last read
_reading = {} # (its kind, compute pk, its connection settings): its last read
_reading_lock = threading.Lock()
# the box's reads (_read_attention) are waited for this long at most: one slow does not hold the page
ATTENTION_WAIT = 2
def _read_key(compute):
"""A compute as read: a compute whose connection settings change is read anew, not
@ -128,30 +149,42 @@ def _read_key(compute):
return (compute.pk, *(getattr(compute, field) for field in ENDPOINT))
def read_hosts(computes):
def _start(compute, kind):
"""compute's read of kind ("host": _read_host, "attention": _read_attention): one of an earlier load
still running, else a new one. Callers hold _reading_lock."""
key = (kind, *_read_key(compute))
if key not in _reading or not _reading[key].is_alive():
_reading[key] = _HostRead(copy(compute), _read_host if kind == "host" else _read_attention)
_reading[key].start()
return _reading[key]
def read_hosts(computes, attention=False):
"""Reads each of computes (_read_host) on its own thread: a slow host
holds back only itself, and one not read within LIST_WAIT is shown as
not answering. A host whose read of an earlier load still runs is not
read again: that read is waited for. Each thread reads a copy: one still
running later does not change what the page shows."""
running later does not change what the page shows. With attention, each
one's full pools and old snapshots too (_read_attention, compute.attention),
waited for up to ATTENTION_WAIT: None for one that comes later."""
with _reading_lock:
keys = {compute: _read_key(compute) for compute in computes}
keys = {(kind, *_read_key(compute)) for compute in computes for kind in ("host", "attention")}
# reads ended of computes deleted or changed since: their copies (and credentials) go
for key in [key for key, read in _reading.items() if key not in keys.values() and not read.is_alive()]:
for key in [key for key, read in _reading.items() if key not in keys and not read.is_alive()]:
del _reading[key]
for compute, key in keys.items():
if key not in _reading or not _reading[key].is_alive():
_reading[key] = _HostRead(copy(compute))
_reading[key].start()
reads = {compute: _reading[key] for compute, key in keys.items()}
deadline = time.monotonic() + LIST_WAIT
reads = {compute: _start(compute, "host") for compute in computes}
scans = {compute: _start(compute, "attention") for compute in computes} if attention else {}
started = time.monotonic()
for read in reads.values():
read.join(max(0, deadline - time.monotonic()))
read.join(max(0, started + LIST_WAIT - time.monotonic()))
for scan in scans.values():
scan.join(max(0, started + ATTENTION_WAIT - time.monotonic()))
for compute, read in reads.items():
compute.attention = scans[compute].result if compute in scans else None
if read.result is not None:
compute.status, compute.connection_error, compute.shown_capacity, compute.read_uuid = read.result
else:
compute.status, compute.shown_capacity, compute.read_uuid = False, None, ""
compute.status, compute.shown_capacity, compute.read_uuid, compute.attention = False, None, "", None
compute.connection_error = _("The host did not answer within %(seconds)s seconds") % {"seconds": LIST_WAIT}
@ -162,7 +195,7 @@ def computes(request):
computes = list(Compute.objects.order_by("name").prefetch_related("tags"))
totals = {"hosts": len(computes), "connected": 0, "vms": 0, "running": 0,
"vcpus": 0, "cpus": 0, "assigned": 0, "memory": 0}
read_hosts(computes)
read_hosts(computes, attention=True)
for compute in computes:
compute.connection_name = CONNECTIONS.get(compute.type, "")
if compute.read_uuid:
@ -180,7 +213,31 @@ def computes(request):
totals["memory"] += given["memory"]
return render(request, "computes/list.html",
{"computes": computes, "totals": totals, "job_resource": claims.bulk_migrate_key(),
"tags": Tag.counts(computes)})
"tags": Tag.counts(computes), "attention": attention(computes)})
def attention(computes):
"""What wants a look, for the box above the hosts; empty when nothing: the
computes not answering, their full pools and old snapshots (_read_attention),
the backup jobs that failed and the backups a schedule did not take in the last 7 days
(not for a host in maintenance: the operator's choice), the backups missing
or damaged, and the jobs that ended uncertain or wait for over an hour."""
week = timezone.now() - timedelta(days=7)
vms = {(vm.compute_id, vm.name): vm for vm in Instance.objects.filter(compute__in=computes)}
found = {
"hosts": [c for c in computes if c.status is not True],
"pools": [(c, pool) for c in computes for pool in (c.attention or {}).get("pools", [])],
"snapshots": [(c, vms.get((c.pk, s["vm"])), s) for c in computes for s in (c.attention or {}).get("snapshots", [])],
"failed": Operation.objects.filter(kind="backup.create", state=Operation.FAILED, finished_at__gte=week).count(),
"not_taken": sorted(Counter(run.policy for run in BackupRun.objects.filter(
day__gte=timezone.localtime(week).date(), state__in=(BackupRun.SKIPPED, BackupRun.FAILED)
).select_related("policy") if run.note != say(IN_MAINTENANCE)).items(), key=lambda item: item[0].name),
"missing": Backup.objects.filter(state=Backup.MISSING).count(),
"damaged": Backup.objects.filter(state=Backup.READY).exclude(damage=[]).count(),
"uncertain": Operation.objects.filter(state=Operation.UNCERTAIN).count(),
"waiting": Operation.objects.filter(state=Operation.QUEUED, created_at__lt=timezone.now() - timedelta(hours=1)).count(),
}
return found if any(found.values()) else {}
@superuser_only