diff --git a/computes/models.py b/computes/models.py index 645d1c9c..6254d913 100644 --- a/computes/models.py +++ b/computes/models.py @@ -141,12 +141,13 @@ class Compute(Model): def __str__(self): return self.name - def record_host(self): - """Reads and keeps the UUID of the host the compute reaches (host_uuid) - while its connection is still the one read with; its UUID, or "" - when it cannot be read. IntegrityError when another compute is that host.""" + def record_host(self, uuid=None): + """Reads (unless given) and keeps the UUID of the host the compute + reaches (host_uuid) while its connection is still the one read with; + its UUID, or "" when it cannot be read. IntegrityError when another + compute is that host.""" try: - uuid = self.proxy.host_uuid() + uuid = uuid or self.proxy.host_uuid() except libvirtError: return "" with transaction.atomic(): diff --git a/computes/tests/test_cpu_graph.py b/computes/tests/test_cpu_graph.py index 3b78c751..ee3142ee 100644 --- a/computes/tests/test_cpu_graph.py +++ b/computes/tests/test_cpu_graph.py @@ -113,7 +113,7 @@ class GraphScriptTestCase(TestCase): script = (settings.BASE_DIR / "static/js/host_graphs.js").read_text() js = """ const vm = require("vm"); - const charts = [], requests = []; + const charts = [], requests = [], timeouts = []; const element = (dataset) => ({dataset, textContent: "", classList: {add: () => {}, remove: () => {}}}); const elements = {graph_state: element(DATASET), cpu_now: element({}), mem_now: element({})}; @@ -129,7 +129,7 @@ class GraphScriptTestCase(TestCase): this.update = () => {}; charts.push(this); }, {defaults: {}}), - $: {getJSON: (url, params) => { requests.push(params); return {fail() { return this; }}; }}, + $: {ajax: (options) => { requests.push(options.data); timeouts.push(options.timeout); return {fail() { return this; }}; }}, pollWhileVisible: (interval, request, onData) => { poll = {request, onData}; }, }; const context = vm.createContext(page); @@ -144,7 +144,7 @@ class GraphScriptTestCase(TestCase): poll.onData({cpudata: null, memdata: {total: null, usage: null}, timeline: "t"}); poll.request(); const label = charts[0].options.plugins.tooltip.callbacks.label({dataset: {label: "Usage"}, formattedValue: "3", dataIndex: 0}); - console.log(JSON.stringify({requests, label, shown, state: elements.graph_state.textContent, + console.log(JSON.stringify({requests, timeouts, label, shown, state: elements.graph_state.textContent, cpu: charts[0].data.datasets[0].data, mem: charts[1].data.datasets[0].data, memMax: charts[1].options.scales.y.max})); """.replace("SCRIPT", json.dumps(script)).replace("CHARTS", json.dumps(CHARTS_JS.read_text())).replace( @@ -153,6 +153,8 @@ class GraphScriptTestCase(TestCase): self.assertEqual(out.returncode, 0, out.stderr) result = json.loads(out.stdout) self.assertEqual(result["requests"], [{}, {"cpu_sample": "token-1"}, {}]) + # a reading the host keeps waiting ends: the charts then say they are not updated + self.assertEqual(result["timeouts"], [30000] * 3) self.assertEqual(result["cpu"], [3, None]) # a host that could not be read leaves a gap and keeps the memory axis self.assertEqual((result["mem"], result["memMax"]), ([1, None], 2)) diff --git a/computes/tests/test_list_hosts.py b/computes/tests/test_list_hosts.py index ae532790..42f3e3d5 100644 --- a/computes/tests/test_list_hosts.py +++ b/computes/tests/test_list_hosts.py @@ -24,7 +24,7 @@ class ListHostsTests(TestCase): def read(self, compute): if compute.name.startswith("slow"): self.release.wait(5) - return True, None, None + return True, None, None, "" def test_hosts_that_do_not_answer_are_waited_for_together_and_shown_so(self): with patch("computes.views._read_host", side_effect=self.read), patch("computes.views.LIST_WAIT", 0.5): @@ -43,3 +43,33 @@ class ListHostsTests(TestCase): self.client.get(reverse("computes")) self.assertEqual(sorted(call.args[0].name for call in read.call_args_list), ["fast", "fast", "slow-1", "slow-2"]) + + def test_many_hosts_that_do_not_answer_leave_the_others_read(self): + # each host has its own thread: nine stuck hosts, read first, take no place of the one that answers + for number in range(3, 10): + Compute.objects.create(name=f"slow-{number}", hostname="192.0.2.1", login="wvc", password="", type=1, + host_uuid=f"{number}" * 8 + "-0000-0000-0000-000000000000") + Compute.objects.filter(name="fast").update(name="z-fast") # the page lists by name: the last one + with patch("computes.views._read_host", side_effect=self.read), patch("computes.views.LIST_WAIT", 0.5): + response = self.client.get(reverse("computes")) + shown = {compute.name: compute.status for compute in response.context["computes"]} + self.assertIs(shown["z-fast"], True) + self.assertEqual(sum(status is False for status in shown.values()), 9) + + def test_a_compute_given_another_host_is_read_anew(self): + # a read of its old host still running: its answer is not the new host's + old = Compute.objects.get(name="slow-1") + with patch("computes.views._read_host", side_effect=self.read) as read, patch("computes.views.LIST_WAIT", 0.2): + self.client.get(reverse("computes")) + Compute.objects.filter(pk=old.pk).update(hostname="192.0.2.99") + self.client.get(reverse("computes")) + hosts = [call.args[0].hostname for call in read.call_args_list if call.args[0].pk == old.pk] + self.assertEqual(hosts, ["192.0.2.1", "192.0.2.99"]) + + def test_a_host_uuid_is_read_with_the_host_and_kept(self): + # one added before host UUIDs were kept: read within the list's wait, saved after it + Compute.objects.filter(name="fast").update(host_uuid="") + uuid = "abcdabcd-0000-0000-0000-000000000000" + with patch("computes.views._read_host", return_value=(True, None, None, uuid)): + self.client.get(reverse("computes")) + self.assertEqual(Compute.objects.get(name="fast").host_uuid, uuid) diff --git a/computes/views.py b/computes/views.py index 1834649b..3decd515 100644 --- a/computes/views.py +++ b/computes/views.py @@ -1,8 +1,8 @@ import json import logging import threading +import time from contextlib import suppress -from concurrent import futures from copy import copy from admin.decorators import superuser_only @@ -31,7 +31,7 @@ from computes.forms import ( TcpComputeForm, TlsComputeForm, ) -from computes.models import Compute +from computes.models import ENDPOINT, Compute from . import utils @@ -84,41 +84,67 @@ CONNECTIONS = {CONN_TCP: "TCP", CONN_SSH: "SSH", CONN_TLS: "TLS", CONN_SOCKET: " # the Computes page reads its hosts side by side, and waits this long for them in all LIST_WAIT = 10 -LIST_WORKERS = 8 def _read_host(compute): - """Whether the panel reaches the compute, why not, and its capacity (shown_capacity).""" - return compute.status, compute.connection_error, shown_capacity(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 + ("" when it cannot be read): every libvirt read of the list, bounded.""" + uuid = "" + if compute.status is True and not compute.host_uuid: + with suppress(libvirtError): + uuid = compute.proxy.host_uuid() + return compute.status, compute.connection_error, shown_capacity(compute), uuid -# the reads of the Computes pages of this process: one pool, and one read of a host at a time, -# so a host that hangs holds one thread however often the page is loaded -_pool = None -_reading = {} # compute pk: its last read +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 __init__(self, compute): + super().__init__(daemon=True, name=f"wvc-host-{compute.pk}") + self.compute, self.result = compute, None + + def run(self): + self.result = _read_host(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_lock = threading.Lock() +def _read_key(compute): + """A compute as read: a compute whose connection settings change is read anew, not + given what its old host answered.""" + return (compute.pk, *(getattr(compute, field) for field in ENDPOINT)) + + def read_hosts(computes): """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.""" - global _pool with _reading_lock: - if _pool is None: # in the process that serves: a pool's threads do not survive a fork - _pool = futures.ThreadPoolExecutor(max_workers=LIST_WORKERS, thread_name_prefix="wvc-hosts") - for compute in computes: - if compute.pk not in _reading or _reading[compute.pk].done(): - _reading[compute.pk] = _pool.submit(_read_host, copy(compute)) - reads = {compute: _reading[compute.pk] for compute in computes} - futures.wait(reads.values(), timeout=LIST_WAIT) + keys = {compute: _read_key(compute) for compute in computes} + # 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()]: + 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 + for read in reads.values(): + read.join(max(0, deadline - time.monotonic())) for compute, read in reads.items(): - if read.done(): - compute.status, compute.connection_error, compute.shown_capacity = read.result() + 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 = False, None + compute.status, compute.shown_capacity, compute.read_uuid = False, None, "" compute.connection_error = _("The host did not answer within %(seconds)s seconds") % {"seconds": LIST_WAIT} @@ -132,10 +158,10 @@ def computes(request): read_hosts(computes) for compute in computes: compute.connection_name = CONNECTIONS.get(compute.type, "") - if compute.status is True and not compute.host_uuid: + if compute.read_uuid: # one added before host UUIDs were kept (Compute.clean); none for a second record of a host with suppress(IntegrityError): - compute.record_host() + compute.record_host(compute.read_uuid) given = compute.shown_capacity totals["connected"] += compute.status is True if given: diff --git a/static/js/host_graphs.js b/static/js/host_graphs.js index 16e8e3ef..0543c790 100644 --- a/static/js/host_graphs.js +++ b/static/js/host_graphs.js @@ -27,7 +27,9 @@ function stale() { // the CPU sample of the previous answer: usage is taken since then var cpuSample = null; pollWhileVisible(5000, function () { - return $.getJSON(state.dataset.url, cpuSample ? {cpu_sample: cpuSample} : {}).fail(stale); + // a host that keeps a reading waiting: the charts say they are not updated, and the next poll goes out + return $.ajax({url: state.dataset.url, data: cpuSample ? {cpu_sample: cpuSample} : {}, dataType: "json", + timeout: 30000}).fail(stale); }, function (data) { cpuSample = data.cpu_sample || null; cpuWindows.push(data.window);