diff --git a/computes/tests/test_attention.py b/computes/tests/test_attention.py index 4a9ca307..55170874 100644 --- a/computes/tests/test_attention.py +++ b/computes/tests/test_attention.py @@ -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": "", "base": ""}}}) + 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)]) + diff --git a/computes/views.py b/computes/views.py index f4b59df2..ba6fa53e 100644 --- a/computes/views.py +++ b/computes/views.py @@ -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)) diff --git a/instances/templates/allinstances.html b/instances/templates/allinstances.html index fbc6f014..7c6ca2db 100644 --- a/instances/templates/allinstances.html +++ b/instances/templates/allinstances.html @@ -63,7 +63,8 @@ - +