1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 08:56:07 +00:00

fix: the host comparison reads afresh, skips silent hosts and unread listings; bulk form limit

Audit and review (Codex, agy) of the host comparison and the bulk tag:
- a read of what a host's VMs need was used again for 5 minutes without a
  new one, so a network added to fix a line was still reported: each load
  reads again, the last read standing in only when the new one is late;
- a host that stopped answering kept what it said before, and was reported
  both as not answering and as a destination lacking things: only hosts that
  answer are compared;
- one listing of a host that could not be read (its secrets, say) dropped the
  whole host: each listing is read on its own and only those read compared;
- the kept reads no longer keep whole VM definitions (plain strings);
- choosing more VMs than the bulk form takes made Django refuse the form:
  past 500 the buttons are off and the count says so; the tag view refuses
  them as the power view does.
This commit is contained in:
catborise 2026-11-20 13:26:58 +03:00
parent 5c169ca504
commit 1c3993133e
11 changed files with 605 additions and 443 deletions

View file

@ -1,6 +1,7 @@
"""The box above the Computes page's hosts: what wants a look, each with a link to where it is handled."""
import datetime
import threading
import time
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
@ -38,13 +39,79 @@ class AttentionBoxTests(TestCase):
def read(self, compute):
return (False, "refused", None, "") if compute.name == "down" else (True, None, None, "")
def page(self, pools=(), snapshots=(), needs=None):
def page(self, pools=(), snapshots=(), needs=None, read_needs=None, fresh=True):
with patch("computes.views._read_host", side_effect=self.read), patch(
"computes.views._read_attention", return_value={"pools": list(pools), "snapshots": list(snapshots)}), \
patch("computes.views._read_needs", side_effect=lambda compute: (needs or {}).get(compute.name)):
views._reading.clear() # no read of what VMs need kept from another test
patch("computes.views._read_needs", side_effect=read_needs or (lambda compute: (needs or {}).get(compute.name))):
if fresh: # no read of what VMs need kept from another test
views._reading.clear()
return self.client.get(reverse("computes"))
def test_what_vms_need_is_read_on_each_load_the_last_standing_in_when_late(self):
self.down.delete()
Compute.objects.create(name="up2", hostname="192.0.2.3", login="wvc", password="", type=1,
host_uuid="44444444-0000-0000-0000-000000000000")
none = {"networks": [], "filters": [], "secrets": [], "usages": []}
lacking = {"up": {"uses": {**none, "networks": ["lab"]}, "has": {**none, "networks": ["lab"], "filters": {}}},
"up2": {"uses": none, "has": {**none, "filters": {}}}}
fixed = {**lacking, "up2": {"uses": none, "has": {**none, "networks": ["lab"], "filters": {}}}}
held = threading.Event()
self.addCleanup(held.set)
def settle(): # every read of the load ended: the next load starts its own
held.set()
for read in list(views._reading.values()):
read.join(5)
held.clear()
def text(**kwargs):
page = self.page(fresh=False, **kwargs)
settle()
return " ".join(html.fromstring(page.content).text_content().split())
def late(compute): # a read that outlasts the wait, then says the network is added
held.wait(5)
return fixed.get(compute.name)
self.page(needs=lacking)
settle()
self.assertNotIn("could not migrate", text(needs=fixed)) # the network added: told at the next load
# a host whose listing could not be read: the others still count
unread = {**lacking, "up2": {"uses": none, "has": {**none, "networks": None, "filters": {}, "secrets": None,
"usages": None}}}
self.assertNotIn("could not migrate", text(needs=unread))
secrets_unread = {**lacking, "up2": {"uses": none, "has": {**none, "filters": {}, "secrets": None, "usages": None}}}
self.assertIn("could not migrate here: no active network lab", text(needs=secrets_unread))
# a late read: the last stands in, waited for NEEDS_GRACE only, not ATTENTION_WAIT
self.assertIn("could not migrate", text(needs=lacking))
with patch("computes.views.NEEDS_GRACE", 0.1), patch("computes.views.ATTENTION_WAIT", 5):
began = time.monotonic()
page = self.page(fresh=False, read_needs=late)
self.assertLess(time.monotonic() - began, 2)
settle()
self.assertContains(page, "could not migrate")
# a host that stopped answering: its stand-in, with the warning, is not told, nor waited for
self.assertIn("could not migrate", text(needs=lacking))
with patch.object(self, "read", lambda compute: (False, "refused", None, "") if compute.name == "up2"
else (True, None, None, "")), patch("computes.views.NEEDS_GRACE", 5):
began = time.monotonic() # only the silent host's read is late: it would be waited 5 s
page = self.page(fresh=False, read_needs=lambda c: late(c) if c.name == "up2" else lacking.get(c.name))
self.assertLess(time.monotonic() - began, 2)
settle()
shown = " ".join(html.fromstring(page.content).text_content().split())
self.assertIn("up2: not answering", shown)
self.assertNotIn("could not migrate", shown)
# a read that failed leaves no stand-in: a late read after it tells no older warning
self.assertIn("could not migrate", text(needs=lacking))
text(needs={}) # this load's read fails (None)
with patch("computes.views.ATTENTION_WAIT", 0.1):
page = self.page(fresh=False, read_needs=late)
settle()
self.assertNotContains(page, "could not migrate")
def test_what_a_vm_could_not_find_on_another_host(self):
# a network, a filter or a secret its VMs use that another host lacks, or a filter of other rules there
self.down.delete()
@ -70,6 +137,11 @@ class AttentionBoxTests(TestCase):
# its read failing or slow hides no full pool; it reads the host's migration_needs
page = self.page(pools=[{"name": "default", "percent": 91}], needs={})
self.assertContains(page, "91% full")
late = threading.Event()
with patch("computes.views.ATTENTION_WAIT", 0.2):
page = self.page(pools=[{"name": "default", "percent": 91}], read_needs=lambda compute: late.wait(5) and None)
late.set()
self.assertContains(page, "91% full")
compute = SimpleNamespace(status=True, proxy=MagicMock(**{"migration_needs.return_value": {"uses": {}}}))
self.assertEqual(views._read_needs(compute), {"uses": {}})
compute.proxy.migration_needs.side_effect = libvirtError("refused")
@ -200,3 +272,26 @@ class HostAttentionTests(TestCase):
"filters": {"web": "<filter name=\"web\"><rule/><filterref filter=\"base\"/></filter>",
"base": "<filter name=\"base\"><rule x=\"1\"/></filter>"}}})
def test_a_listing_that_cannot_be_read_is_none_and_the_others_count(self):
host = wvmHostDetails.__new__(wvmHostDetails)
refused = MagicMock(side_effect=libvirtError("secrets driver down"))
host.wvm = SimpleNamespace(listAllDomains=lambda flags=0: [], listAllNWFilters=lambda flags=0: [],
listAllSecrets=refused,
listAllNetworks=lambda flags=0: [MagicMock(**{"name.return_value": "prod"})])
has = host.migration_needs()["has"]
self.assertEqual((has["networks"], has["filters"], has["secrets"], has["usages"]), (["prod"], {}, None, None))
def test_a_host_whose_vms_cannot_be_listed_is_still_a_destination(self):
host = wvmHostDetails.__new__(wvmHostDetails)
host.wvm = SimpleNamespace(listAllDomains=MagicMock(side_effect=libvirtError("refused")),
listAllNWFilters=lambda flags=0: [], listAllSecrets=lambda flags=0: [],
listAllNetworks=lambda flags=0: [MagicMock(**{"name.return_value": "prod"})])
needs = host.migration_needs()
self.assertIsNone(needs["uses"])
self.assertEqual(needs["has"]["networks"], ["prod"])
none = {"networks": [], "filters": [], "secrets": [], "usages": []}
source = MagicMock(status=True, maintenance=False, needs={"uses": {**none, "networks": ["lab"]},
"has": {**none, "filters": {}}})
target = MagicMock(status=True, maintenance=False, needs=needs)
self.assertEqual([(t, s) for t, s, _what in views.lacking([source, target])], [(target, source)])

View file

@ -136,9 +136,10 @@ class _HostRead(threading.Thread):
"""One read of a host (read: _read_host, _read_attention or _read_needs) on a daemon
thread: one stuck on its host does not hold the process when it exits."""
def __init__(self, compute, read):
def __init__(self, compute, read, stand_in=(None, 0)):
super().__init__(daemon=True, name=f"wvc-host-{compute.pk}")
self.compute, self.read, self.result, self.ended = compute, read, None, None
self.stand_in = stand_in # a "needs" read's: (the result, when it ended) of the one before, if it read
def run(self):
self.result = self.read(self.compute)
@ -152,9 +153,10 @@ _reading_lock = threading.Lock()
# the box's reads (_read_attention, _read_needs) are waited for this long at most: one slow does not hold the page
ATTENTION_WAIT = 2
# a read of what a host's VMs need is used again for this long (seconds): a host of many VMs, whose
# read outlasts ATTENTION_WAIT, is still compared, and networks and filters seldom change
# what a host's VMs need is read again on each load; the last read that ended stands in for this
# long (seconds) when the new one outlasts ATTENTION_WAIT, so a host of many VMs is still compared
NEEDS_KEPT = 300
NEEDS_GRACE = 0.5 # how long a new read is waited for when one stands in for it (seconds)
READ_KINDS = ("host", "attention", "needs") # _read_host, _read_attention, _read_needs
@ -166,19 +168,26 @@ def _read_key(compute):
def _start(compute, kind):
"""compute's read of kind (READ_KINDS): one of an earlier load still running, or for "needs" one
ended within NEEDS_KEPT, else a new one. Callers hold _reading_lock."""
"""compute's read of kind (READ_KINDS): one of an earlier load still running, else a new one.
Callers hold _reading_lock."""
key = (kind, *_read_key(compute))
read = _reading.get(key)
kept = kind == "needs" and read is not None and read.ended is not None and read.result is not None \
and time.monotonic() - read.ended < NEEDS_KEPT
if read is None or not (read.is_alive() or kept):
if read is None or not read.is_alive():
# a "needs" read that ended stands in for the new one; one that failed leaves none
stand_in = (read.result, read.ended) if kind == "needs" and read is not None and read.result is not None \
else (None, 0)
_reading[key] = _HostRead(copy(compute), {"host": _read_host, "attention": _read_attention,
"needs": _read_needs}[kind])
"needs": _read_needs}[kind], stand_in)
_reading[key].start()
return _reading[key]
def _stand_in(read):
"""What the read of what VMs need before read said, if it ended within NEEDS_KEPT, else None."""
result, ended = read.stand_in
return result if time.monotonic() - ended < NEEDS_KEPT else None
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
@ -195,16 +204,26 @@ def read_hosts(computes, attention=False):
reads = {compute: _start(compute, "host") for compute in computes}
scans = {compute: _start(compute, "attention") for compute in computes} if attention else {}
needs = {compute: _start(compute, "needs") for compute in computes} if attention else {}
stand_ins = {compute: _stand_in(read) for compute, read in needs.items()}
started = time.monotonic()
for read in reads.values():
read.join(max(0, started + LIST_WAIT - time.monotonic()))
for scan in [*scans.values(), *needs.values()]:
for scan in scans.values():
scan.join(max(0, started + ATTENTION_WAIT - time.monotonic()))
# a host's needs with a stand-in are waited for NEEDS_GRACE at most, not ATTENTION_WAIT; those of a
# host that does not answer not at all: they are not told
for compute, read in needs.items():
if reads[compute].result is not None and reads[compute].result[0] is True:
read.join(max(0, started + (ATTENTION_WAIT if stand_ins[compute] is None else NEEDS_GRACE) - time.monotonic()))
for compute, read in reads.items():
compute.attention = scans[compute].result if compute in scans else None
compute.needs = needs[compute].result if compute in needs else None
# this load's read if it ended, else the stand-in
compute.needs = (stand_ins[compute] if needs[compute].is_alive() else needs[compute].result) \
if compute in needs else None
if read.result is not None:
compute.status, compute.connection_error, compute.shown_capacity, compute.read_uuid = read.result
if compute.status is not True: # what it said before it stopped answering is not told
compute.attention = compute.needs = None
else:
compute.status, compute.shown_capacity, compute.read_uuid, compute.attention = False, None, "", None
compute.needs = None
@ -267,24 +286,29 @@ def attention(computes):
def lacking(computes):
"""[(host, other host, [what])]: what the VMs of a host use (migration_needs) that the other
host lacks or has otherwise, so that the migration check refuses moving them there: an active
network, a network filter or one of other rules, a secret (by UUID or usage). Only hosts whose
needs were read; a host in maintenance is no destination, but its VMs still need one."""
needs = {c: c.needs for c in computes if c.needs}
network, a network filter or one of other rules, a secret (by UUID or usage). Only hosts that
answer and whose needs were read, and of these only the listings read; a host in maintenance
is no destination, but its VMs still need one."""
needs = {c: c.needs for c in computes if c.status is True and c.needs}
found = []
for source, need in needs.items():
for target, other in needs.items():
if target is source or target.maintenance:
if target is source or target.maintenance or need["uses"] is None: # its VMs not read: no source
continue
uses, has, own = need["uses"], other["has"], need["has"]["filters"]
usages = {tuple(usage) for usage in has["usages"]}
what = [(gettext_noop("no active network %(names)s"), sorted(set(uses["networks"]) - set(has["networks"]))),
(gettext_noop("no network filter %(names)s"), sorted(set(uses["filters"]) - set(has["filters"]))),
# compared only with the source's own filter: one it lacks too is not another's rules
(gettext_noop("network filter %(names)s with other rules"),
sorted(n for n in uses["filters"] if n in has["filters"] and n in own and has["filters"][n] != own[n])),
(gettext_noop("no secret %(names)s"),
sorted([*(set(uses["secrets"]) - set(has["secrets"])),
*(usage for usage_type, usage in uses["usages"] if (usage_type, usage) not in usages)]))]
uses, has, own = need["uses"], other["has"], need["has"]["filters"] or {}
what = []
if has["networks"] is not None:
what.append((gettext_noop("no active network %(names)s"), sorted(set(uses["networks"]) - set(has["networks"]))))
if has["filters"] is not None:
what.append((gettext_noop("no network filter %(names)s"), sorted(set(uses["filters"]) - set(has["filters"]))))
# compared only with the source's own filter: one it lacks too is not another's rules
what.append((gettext_noop("network filter %(names)s with other rules"),
sorted(n for n in uses["filters"] if n in has["filters"] and n in own and has["filters"][n] != own[n])))
if has["secrets"] is not None:
usages = {tuple(usage) for usage in has["usages"]}
what.append((gettext_noop("no secret %(names)s"),
sorted([*(set(uses["secrets"]) - set(has["secrets"])),
*(usage for usage_type, usage in uses["usages"] if (usage_type, usage) not in usages)])))
what = [_(text) % {"names": ", ".join(names)} for text, names in what if names]
if what:
found.append((target, source, what))

View file

@ -63,7 +63,8 @@
<input class="form-check-input" type="checkbox" id="bulk-power-shown">
<label class="form-check-label" for="bulk-power-shown">{% trans "Choose the VMs shown" %}</label>
</div>
<span class="small text-body-secondary" id="bulk-power-count" data-text="{% trans "%(count)s chosen" %}" aria-live="polite"></span>
<span class="small text-body-secondary" id="bulk-power-count" data-text="{% trans "%(count)s chosen" %}"
data-too-many="{% blocktrans with max=bulk_max %}%(count)s chosen: at most {{ max }} at once{% endblocktrans %}" data-max="{{ bulk_max }}" aria-live="polite"></span>
<div class="btn-group btn-group-sm" role="group" aria-label="{% trans "Power the chosen VMs" %}">
<button type="submit" class="btn btn-outline-primary" name="action" value="start" disabled>{% trans "Start" %}</button>
<button type="submit" class="btn btn-outline-primary" name="action" value="shutdown" disabled

View file

@ -48,6 +48,10 @@ class BulkTagTestCase(TestCase):
self.assertIn("A tag is letters a-z", self.post("tag_add", "no spaces", self.vms)[0])
self.assertEqual(self.post("tag_remvoe", "web", self.vms), ["Choose the VMs and write the tag"]) # no add
self.assertEqual(self.post("tag_remove", "none", self.vms), ["There is no tag none"])
many = self.client.post(reverse("instances:bulk_tag"), {"action": "tag_add", "tag": "web",
"vm": [str(n) for n in range(1, 502)]})
self.assertIn("at most 500 VMs", " ".join(map(str, get_messages(many.wsgi_request))))
self.client.cookies.pop("messages", None)
self.assertEqual(self.vm_tags(), [[], []])
Instance.objects.filter(pk__in=[vm.pk for vm in self.vms]).delete()
self.assertEqual(self.post("tag_add", "fresh", self.vms), ["Choose the VMs and write the tag"]) # VMs gone

View file

@ -135,6 +135,7 @@ def index(request):
# the VMs this user may power (_power_instance): theirs, or every one for a superuser
# a superuser's bulk tag box offers every tag, as the Settings tab's picker
"tag_names": list(Tag.objects.order_by("name").values_list("name", flat=True)) if request.user.is_superuser else [],
"bulk_max": BULK_MAX,
"powerable": {i.pk for i in instances} if request.user.is_superuser else
set(UserInstance.objects.filter(user=request.user).values_list("instance_id", flat=True))},
)
@ -701,8 +702,8 @@ def _power_instance(user, pk):
return instance
# the most VMs the VM list's bulk power form takes at once
BULK_POWER_MAX = 500
# the most VMs the VM list's bulk form takes at once (a form of more fields Django refuses: 1000)
BULK_MAX = 500
def _chosen_vms(request):
@ -720,6 +721,9 @@ def bulk_tag(request):
if action not in ("tag_add", "tag_remove") or not vms:
messages.error(request, _("Choose the VMs and write the tag"))
return redirect("instances:index")
if len(vms) > BULK_MAX:
messages.error(request, _("Choose at most %(count)s VMs at once") % {"count": BULK_MAX})
return redirect("instances:index")
remove, changed = action == "tag_remove", 0
with transaction.atomic():
lock_ownership()
@ -757,8 +761,8 @@ def bulk_power(request):
if action not in POWER or not vms or not KEY_RE.fullmatch(key) or len(key) > 50:
messages.error(request, _("Choose the VMs you may power, and Start, Shut down or Force off"))
return redirect("instances:index")
if len(vms) > BULK_POWER_MAX:
messages.error(request, _("Choose at most %(count)s VMs at once") % {"count": BULK_POWER_MAX})
if len(vms) > BULK_MAX:
messages.error(request, _("Choose at most %(count)s VMs at once") % {"count": BULK_MAX})
return redirect("instances:index")
names = dict(Instance.objects.filter(pk__in=vms).values_list("pk", "name"))
seen = names if request.user.is_superuser else dict(Instance.objects.filter(

Binary file not shown.

File diff suppressed because it is too large Load diff

Binary file not shown.

File diff suppressed because it is too large Load diff

View file

@ -13,8 +13,9 @@
function update() {
var boxes = onScreen();
var chosen = boxes.filter(function (box) { return box.checked; }).length;
form.querySelectorAll("button[name='action']").forEach(function (button) { button.disabled = chosen === 0; });
count.textContent = chosen ? count.dataset.text.replace("%(count)s", chosen) : "";
var tooMany = chosen > Number(count.dataset.max); // the server takes at most that many
form.querySelectorAll("button[name='action']").forEach(function (button) { button.disabled = chosen === 0 || tooMany; });
count.textContent = chosen ? (tooMany ? count.dataset.tooMany : count.dataset.text).replace("%(count)s", chosen) : "";
shown.disabled = boxes.length === 0;
shown.checked = boxes.length > 0 && chosen === boxes.length;
shown.indeterminate = chosen > 0 && chosen < boxes.length;
@ -48,12 +49,17 @@
}
});
}
form.addEventListener("submit", function () {
form.addEventListener("submit", function (event) {
document.querySelectorAll("input[name='vm'][form='bulk-power']:checked").forEach(function (box) {
if (!box.getClientRects().length) {
box.checked = false; // hidden: not sent
}
});
// counted again: rows may have come on screen since the buttons were last set
if (document.querySelectorAll("input[name='vm'][form='bulk-power']:checked").length > Number(count.dataset.max)) {
event.preventDefault();
update();
}
});
update();
})();

View file

@ -89,35 +89,53 @@ class wvmHostDetails(wvmConnect):
"has": {"networks" (active), "filters" {name: rules}, "secrets", "usages"}}. A VM's
running definition and the one for its next start count; its filters include those
these reference here; a secret is named by UUID ("secrets") or by usage type and
usage ("usages", [type, usage]). A VM or filter gone meanwhile is passed over."""
usage ("usages", [type, usage]). A VM or filter gone meanwhile is passed over; a
listing that cannot be read is None (its VMs': "uses"), and the others still count."""
def read(listing):
try:
return listing()
except libvirtError:
return None
networks, filters_used, secrets, usages = set(), set(), set(), set()
for _name, trees in self.domain_trees():
for tree in trees:
networks.update(tree.xpath("devices/interface[@type='network']/source/@network"))
filters_used.update(tree.xpath("devices/interface/filterref/@filter"))
for ref in tree.xpath("devices//secret"):
if ref.get("uuid"):
secrets.add(ref.get("uuid").lower())
elif ref.get("usage"):
usages.add((REF_USAGE_TYPES.get(ref.get("type")), ref.get("usage")))
secrets.update(uuid.lower() for uuid in tree.xpath("devices/tpm/backend/encryption/@secret"))
filters = {}
for nwfilter in self.wvm.listAllNWFilters(0):
with suppress(libvirtError): # undefined meanwhile
filters[nwfilter.name()] = filter_rules(nwfilter)
def uses(): # one VM's definitions at a time
for _name, trees in self.domain_trees():
for tree in trees: # plain strings: none keeps its definition's tree alive
networks.update(tree.xpath("devices/interface[@type='network']/source/@network", smart_strings=False))
filters_used.update(tree.xpath("devices/interface/filterref/@filter", smart_strings=False))
for ref in tree.xpath("devices//secret"):
if ref.get("uuid"):
secrets.add(ref.get("uuid").lower())
elif ref.get("usage"):
usages.add((REF_USAGE_TYPES.get(ref.get("type")), ref.get("usage")))
secrets.update(uuid.lower() for uuid in tree.xpath("devices/tpm/backend/encryption/@secret",
smart_strings=False))
return True
vms_read = read(uses)
def own_filters():
filters = {}
for nwfilter in self.wvm.listAllNWFilters(0):
with suppress(libvirtError): # undefined meanwhile
filters[nwfilter.name()] = filter_rules(nwfilter)
return filters
filters = read(own_filters)
todo = list(filters_used)
while todo: # and those they reference
for ref in filters.get(todo.pop(), ("", []))[1]:
for ref in (filters or {}).get(todo.pop(), ("", []))[1]:
if ref not in filters_used:
filters_used.add(ref)
todo.append(ref)
have = self.get_secrets_info()
return {"uses": {"networks": sorted(networks), "filters": sorted(filters_used), "secrets": sorted(secrets),
"usages": sorted(usages, key=str)},
"has": {"networks": sorted(n.name() for n in self.wvm.listAllNetworks(VIR_CONNECT_LIST_NETWORKS_ACTIVE)),
"filters": {name: rules for name, (rules, _refs) in filters.items()},
"secrets": sorted(secret["uuid"].lower() for secret in have),
"usages": sorted(((secret["usage_type"], secret["usage"]) for secret in have), key=str)}}
have = read(self.get_secrets_info)
active = read(lambda: self.wvm.listAllNetworks(VIR_CONNECT_LIST_NETWORKS_ACTIVE))
return {"uses": None if vms_read is None else {"networks": sorted(networks), "filters": sorted(filters_used),
"secrets": sorted(secrets), "usages": sorted(usages, key=str)},
"has": {"networks": None if active is None else sorted(n.name() for n in active),
"filters": None if filters is None else {name: rules for name, (rules, _refs) in filters.items()},
"secrets": None if have is None else sorted(secret["uuid"].lower() for secret in have),
"usages": None if have is None else sorted(((s["usage_type"], s["usage"]) for s in have), key=str)}}
def get_memory_usage(self):
"""