diff --git a/computes/tests/test_maintenance.py b/computes/tests/test_maintenance.py index feb2bf6b..624c505e 100644 --- a/computes/tests/test_maintenance.py +++ b/computes/tests/test_maintenance.py @@ -266,6 +266,7 @@ class MaintenanceWithMigrationTests(TestCase): def read_list_rows(instances, computes): # a running VM, without asking a host for instance in instances: instance.__dict__["info"] = [1, 131072, 131072, 1, 0] + instance.__dict__["state_reason"] = None with patch("computes.views.utils.refresh_instance_database"), \ patch("computes.views.read_list_rows", side_effect=read_list_rows), \ diff --git a/instances/models.py b/instances/models.py index fce1a95d..39c33746 100644 --- a/instances/models.py +++ b/instances/models.py @@ -3,6 +3,9 @@ from django.db import models from django.utils.functional import cached_property from django.utils.translation import gettext_lazy as _ from libvirt import ( + VIR_DOMAIN_DISK_ERROR_NO_SPACE, + VIR_DOMAIN_PAUSED, + VIR_DOMAIN_PAUSED_IOERROR, VIR_DOMAIN_SNAPSHOT_LIST_EXTERNAL, VIR_DOMAIN_SNAPSHOT_LIST_INTERNAL, libvirtError, @@ -11,6 +14,8 @@ from operations import claims from operations.models import Claim from vrtManager.instance import PERSISTENT_XML, wvmInstance +from .states import DISK_ERRORS, REASONS + class Flavor(models.Model): label = models.CharField(_("label"), max_length=12, unique=True) @@ -81,6 +86,41 @@ class Instance(models.Model): except libvirtError: return None + @cached_property + def state_and_reason(self) -> tuple: + """virDomainGetState: (state, reason) of one read, as a reason means + something only with its own state; () if the VM cannot be read.""" + try: + return tuple(self.proxy.get_state()) + except libvirtError: + return () + + @cached_property + def state_reason(self): + """Why the VM stopped or paused, when a fault did it (states.REASONS); + else None. The lists set it from their one read of the host.""" + return REASONS.get(self.state_and_reason) + + @cached_property + def disk_errors(self) -> dict: + """{target: virDomainDiskErrorCode} of a VM a disk error paused; read + only then, as libvirt keeps the last error after a resume.""" + if self.state_and_reason != (VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_IOERROR): + return {} + try: + return self.proxy.get_disk_errors() + except libvirtError: + return {} + + @property + def disk_error_texts(self) -> list: + return [DISK_ERRORS[code] % {"dev": dev} for dev, code in sorted(self.disk_errors.items()) if code in DISK_ERRORS] + + @property + def disk_full(self) -> bool: + """A disk error came from a storage with no free space: freeing some is the way out.""" + return VIR_DOMAIN_DISK_ERROR_NO_SPACE in self.disk_errors.values() + @cached_property def status(self) -> int: return self.proxy.get_status() diff --git a/instances/states.py b/instances/states.py index 6cd90943..3c5e35de 100644 --- a/instances/states.py +++ b/instances/states.py @@ -3,6 +3,7 @@ libvirt VM states: their labels, and the actions each one allows a user. The lists and the VM page use these through templatetags/vm_states.py. """ +import libvirt from django.utils.translation import gettext_lazy as _ # state (virDomainState): label, Bootstrap color @@ -18,6 +19,23 @@ STATES = { } UNKNOWN = (_("Unknown"), "secondary") # the VM cannot be read +# (state, reason): why a VM stopped or paused that nobody asked for; the +# ordinary reasons (a user, a migration, a snapshot) are not told +REASONS = { + # a write error, or a read error where the disk's policy is to stop + (libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_PAUSED_IOERROR): _("Paused by a disk error"), + (libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_PAUSED_WATCHDOG): _("Paused by its watchdog"), + (libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_PAUSED_CRASHED): _("Paused: the guest crashed"), + (libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_PAUSED_POSTCOPY_FAILED): _("Paused: its migration failed midway"), + (libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_PAUSED_API_ERROR): _("Paused by a libvirt error"), + # the guest, or its QEMU process (killed on the host: out of memory) + (libvirt.VIR_DOMAIN_SHUTOFF, libvirt.VIR_DOMAIN_SHUTOFF_CRASHED): _("Stopped: it crashed"), + # libvirt could not take it back after restarting + (libvirt.VIR_DOMAIN_SHUTOFF, libvirt.VIR_DOMAIN_SHUTOFF_DAEMON): _("Stopped by libvirt"), + (libvirt.VIR_DOMAIN_SHUTOFF, libvirt.VIR_DOMAIN_SHUTOFF_FAILED): _("Stopped: it failed to start"), + (libvirt.VIR_DOMAIN_CRASHED, libvirt.VIR_DOMAIN_CRASHED_PANICKED): _("The guest's kernel panicked"), +} + RUNNING = {"suspend", "poweroff", "powercycle", "force_off", "console"} # the states the power tab shows as its strip: active, blocked, suspended, off, PM suspended POWER_STATES = (1, 2, 3, 5, 7) @@ -39,6 +57,17 @@ def state_label(state): """(label, color) of a state; None for a VM that cannot be read.""" return UNKNOWN if state is None else STATES.get(state, STATES[0]) +# a disk error (virDomainGetDiskErrors) of a VM paused by one +DISK_ERRORS = { + libvirt.VIR_DOMAIN_DISK_ERROR_NO_SPACE: _("%(dev)s: its storage has no free space"), + libvirt.VIR_DOMAIN_DISK_ERROR_UNSPEC: _("%(dev)s: an I/O error"), +} + + +def state_reason(state, reason): + """Why the VM is in its state, when that is a fault (REASONS); else None.""" + return REASONS.get((state, reason)) + def manages(user, instance): """Superusers and a VM's owners: the users its power actions are for.""" diff --git a/instances/templates/instance.html b/instances/templates/instance.html index 4c6c47f2..6791b693 100644 --- a/instances/templates/instance.html +++ b/instances/templates/instance.html @@ -16,7 +16,7 @@ {% block content %} {# the VM at a glance in one card: who and where it is, what it has, and its sections as the card's footer #} -
{# shown by instance_status.js while the VM's state cannot be read #} + {# a VM a fault stopped or paused says why; a full storage pauses it until there is space #} + {% if instance.state_reason %} +
+ {{ instance.state_reason }} + {% for error in instance.disk_error_texts %}
{{ error }}
{% endfor %} + {% if instance.disk_full %} +
{% if request.user.is_superuser %}{% trans "Free space on its storage, then resume it." %}{% else %}{% trans "An administrator has to free space on its storage and resume it." %}{% endif %}
+ {% endif %} +
+ {% endif %} {% if not instance.is_template %}
{% if not instance.guest_agent %} diff --git a/instances/templates/instance_state.html b/instances/templates/instance_state.html index d7539fa2..3b26271f 100644 --- a/instances/templates/instance_state.html +++ b/instances/templates/instance_state.html @@ -1,3 +1,4 @@ {% load vm_states %} {% if instance.info %}{% vm_state instance.info.0 as state %}{% else %}{% vm_state None as state %}{% endif %} {{ state.0 }} +{% if instance.state_reason %}
{{ instance.state_reason }}
{% endif %} diff --git a/instances/tests/test_list_unreachable.py b/instances/tests/test_list_unreachable.py index 160907a4..aca4982a 100644 --- a/instances/tests/test_list_unreachable.py +++ b/instances/tests/test_list_unreachable.py @@ -103,7 +103,7 @@ class UnreachableListTests(TestCase): AppSettings.objects.filter(key="VIEW_INSTANCES_LIST_STYLE").update(value="nongrouped") # vm-b is gone from its host - response = self.get(reverse("instances:index"), {self.vm_a.uuid: (UP_INFO, "")}) + response = self.get(reverse("instances:index"), {self.vm_a.uuid: (UP_INFO, "", 0)}) self.assert_unknown(response, [self.vm_b]) self.assertContains(response, reverse("instances:poweroff", args=[self.vm_a.id])) diff --git a/instances/tests/test_states.py b/instances/tests/test_states.py index fdf64ca0..04eb0bf2 100644 --- a/instances/tests/test_states.py +++ b/instances/tests/test_states.py @@ -4,6 +4,7 @@ and the user's permissions allow.""" from types import SimpleNamespace from unittest.mock import PropertyMock, patch +import libvirt from accounts.models import UserInstance from appsettings.models import AppSettings from computes.models import Compute @@ -14,6 +15,7 @@ from django.urls import reverse from instances.models import Instance from instances.states import allowed_actions from lxml import html +from vrtManager.connection import wvmConnect LABELS = {0: "No state", 1: "Active", 2: "Blocked", 3: "Suspended", 4: "Shutting down", 5: "Off", 6: "Crashed", 7: "PM suspended"} # actions offered per state, for a superuser @@ -54,7 +56,7 @@ class StateTests(TestCase): AppSettings.objects.filter(key="VIEW_INSTANCES_LIST_STYLE").update(value="nongrouped") def get(self, user, url): - rows = {vm.uuid: (Domain(state).info(), "") for state, vm in self.vms.items()} + rows = {vm.uuid: (Domain(state).info(), "", 0) for state, vm in self.vms.items()} self.client.force_login(user) props = {"status": True, "connection_error": None, "cpu_count": 1, "ram_size": 1, "ram_usage": 0, @@ -279,3 +281,106 @@ class EmptyListTests(TestCase): response = self.client.get(reverse("instances:index")) self.assertContains(response, "There are no VMs here yet.") self.assertNotContains(response, "searchable") # no VM table + + +class FaultReasonTests(TestCase): + """A VM a fault stopped or paused says why: the lists in a line under its + state, its page with what each disk met and what to do about it.""" + + def setUp(self): + User = get_user_model() + self.admin = User.objects.create_superuser("fr-admin", "fr@example.com", "pw") + self.owner = User.objects.create_user("fr-owner", password="pw") + self.compute = Compute.objects.create(name="fr", hostname="192.0.2.30", login="u", password="p", type=1) + self.vm = Instance.objects.create(compute=self.compute, name="fr-vm", uuid="12121212-0000-0000-0000-000000000000") + UserInstance.objects.create(user=self.owner, instance=self.vm, is_change=True) + + def list_page(self, state, reason): + rows = {self.vm.uuid: ([state, 4194304, 2097152, 2], "", reason)} + self.client.force_login(self.admin) + props = {"status": True, "connection_error": None, "cpu_count": 1, "ram_size": 1, "ram_usage": 0, + "proxy": SimpleNamespace(get_domain_rows=lambda uuids=None: rows, get_domain_states=dict)} + with patch("instances.views.refresh_instance_database"), \ + patch.multiple(Compute, **{k: PropertyMock(return_value=v) for k, v in props.items()}): + response = self.client.get(reverse("instances:index")) + self.assertEqual(response.status_code, 200) + return " ".join(html.fromstring(response.content).xpath("string(//tr[@host])").split()) + + def vm_page(self, user, status, reason, errors, read=None): + self.client.force_login(user) + with patch("instances.models.wvmInstance") as wvm, \ + patch.object(Compute, "status", new_callable=PropertyMock, return_value=True): + proxy = wvm.return_value + proxy.get_memory.return_value = proxy.get_cur_memory.return_value = 1024 + proxy.get_max_memory.return_value = 4096 + for name in ("get_networks", "get_ifaces", "get_storages", "get_disk_devices", "get_media_devices", "get_net_devices"): + getattr(proxy, name).return_value = [] + proxy.get_hostdevs.return_value = ([], [], []) + proxy.get_status.return_value = status + proxy.get_state.return_value = read or [status, reason] + proxy.get_disk_errors.return_value = errors + response = self.client.get(reverse("instances:instance", args=[self.vm.id])) + self.assertEqual(response.status_code, 200) + summary = html.fromstring(response.content).get_element_by_id("vm-summary") + return " ".join(" ".join(summary.itertext()).split()), proxy + + def test_the_list_says_why_a_fault_paused_or_stopped_it(self): + cases = [ + (libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_PAUSED_IOERROR, "Paused by a disk error"), + (libvirt.VIR_DOMAIN_SHUTOFF, libvirt.VIR_DOMAIN_SHUTOFF_CRASHED, "Stopped: it crashed"), + (libvirt.VIR_DOMAIN_SHUTOFF, libvirt.VIR_DOMAIN_SHUTOFF_DAEMON, "Stopped by libvirt"), + (libvirt.VIR_DOMAIN_CRASHED, libvirt.VIR_DOMAIN_CRASHED_PANICKED, "The guest's kernel panicked"), + (libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_PAUSED_USER, None), # an administrator paused it + (libvirt.VIR_DOMAIN_SHUTOFF, libvirt.VIR_DOMAIN_SHUTOFF_SHUTDOWN, None), + ] + for state, reason, told in cases: + with self.subTest(state=state, reason=reason): + row = self.list_page(state, reason) + for text in {text for _state, _reason, text in cases if text}: + self.assertEqual(text in row, text == told, row) + + def test_the_page_names_the_full_disk_and_what_to_do(self): + errors = {"vda": libvirt.VIR_DOMAIN_DISK_ERROR_NO_SPACE, "vdb": libvirt.VIR_DOMAIN_DISK_ERROR_UNSPEC} + text, _proxy = self.vm_page(self.admin, libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_PAUSED_IOERROR, errors) + self.assertIn("Paused by a disk error vda: its storage has no free space vdb: an I/O error " + "Free space on its storage, then resume it.", text) + text, _proxy = self.vm_page(self.owner, libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_PAUSED_IOERROR, errors) + self.assertIn("An administrator has to free space on its storage and resume it.", text) + + def test_an_io_error_without_a_full_storage_is_told_without_freeing_space(self): + text, _proxy = self.vm_page(self.admin, libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_PAUSED_IOERROR, + {"vda": libvirt.VIR_DOMAIN_DISK_ERROR_UNSPEC}) + self.assertIn("Paused by a disk error vda: an I/O error", text) + self.assertNotIn("Free space", text) + + def test_the_reason_goes_with_the_state_of_its_own_read(self): + # read paused, then resumed before the reason was read: RUNNING_UNPAUSED (5) is not PAUSED_IOERROR (5) + text, proxy = self.vm_page(self.admin, libvirt.VIR_DOMAIN_PAUSED, libvirt.VIR_DOMAIN_PAUSED_IOERROR, {}, + read=[libvirt.VIR_DOMAIN_RUNNING, libvirt.VIR_DOMAIN_RUNNING_UNPAUSED]) + self.assertNotIn("disk error", text) + proxy.get_disk_errors.assert_not_called() + + def test_a_vm_that_is_not_paused_has_its_disk_errors_left_unread(self): + # libvirt keeps the last disk error after a resume: only a paused VM's is told + text, proxy = self.vm_page(self.admin, libvirt.VIR_DOMAIN_RUNNING, libvirt.VIR_DOMAIN_RUNNING_UNPAUSED, + {"vda": libvirt.VIR_DOMAIN_DISK_ERROR_NO_SPACE}) + self.assertNotIn("vda:", text) + proxy.get_disk_errors.assert_not_called() + + def test_the_host_reads_give_the_reason(self): + class Dom: + def UUIDString(self): + return "12121212-0000-0000-0000-000000000000" + + def name(self): + return "fr-vm" + + def XMLDesc(self, flags): + return "419430420971522" + + conn = wvmConnect.__new__(wvmConnect) + stats = {"state.state": libvirt.VIR_DOMAIN_PAUSED, "state.reason": libvirt.VIR_DOMAIN_PAUSED_IOERROR} + conn.wvm = SimpleNamespace(getAllDomainStats=lambda kinds: [(Dom(), stats)]) + uuid = "12121212-0000-0000-0000-000000000000" + self.assertEqual(conn.get_domain_states(), {uuid: ["fr-vm", 3, 5]}) + self.assertEqual(conn.get_domain_rows(), {uuid: ([3, 4194304, 2097152, 2], "", 5)}) diff --git a/instances/utils.py b/instances/utils.py index e4af9f2c..093b02a2 100644 --- a/instances/utils.py +++ b/instances/utils.py @@ -25,6 +25,7 @@ from vrtManager.instance import wvmInstance, wvmInstances from vrtManager.util import ConnectionFailed, HostBusy, message, vol_dev_type from .models import Instance +from .states import state_reason def can_open_console(user, instance): @@ -441,7 +442,8 @@ def read_list_rows(instances, computes): except libvirtError: rows[compute.pk] = {} for inst in instances: - inst.info, inst.title = rows[inst.compute_id].get(inst.uuid, (None, "")) + inst.info, inst.title, why = rows[inst.compute_id].get(inst.uuid, (None, "", None)) + inst.state_reason = state_reason(inst.info[0], why) if inst.info else None # how long a VM list and its poll wait for a host's VMs, all hosts asked at once diff --git a/instances/views.py b/instances/views.py index 5039ea48..595a5427 100755 --- a/instances/views.py +++ b/instances/views.py @@ -467,7 +467,8 @@ def _instance_page(request, pk, instance, compute): def status(request, pk): instance = get_instance(request.user, pk) - return JsonResponse({"status": instance.proxy.get_status()}) + state, reason = instance.proxy.get_state() + return JsonResponse({"status": state, "reason": reason}) def nic_addresses(request, pk): diff --git a/locale/tr/LC_MESSAGES/django.mo b/locale/tr/LC_MESSAGES/django.mo index 4889b981..69826809 100644 Binary files a/locale/tr/LC_MESSAGES/django.mo and b/locale/tr/LC_MESSAGES/django.mo differ diff --git a/locale/tr/LC_MESSAGES/django.po b/locale/tr/LC_MESSAGES/django.po index 9bf61bdc..bf713042 100644 --- a/locale/tr/LC_MESSAGES/django.po +++ b/locale/tr/LC_MESSAGES/django.po @@ -13039,3 +13039,58 @@ msgstr "İş işleyicisi çalışmıyor; en son %(when)s görüldü. İşler o y #: operations/templatetags/operations.py:99 msgid "The job worker has not run yet. Jobs wait until it runs." msgstr "İş işleyicisi henüz hiç çalışmadı. İşler o çalışana kadar bekler." + + +#: instances/states.py:27 +msgid "Paused by a disk error" +msgstr "Bir disk hatası nedeniyle duraklatıldı" + +#: instances/states.py:28 +msgid "Paused by its watchdog" +msgstr "Watchdog aygıtı tarafından duraklatıldı" + +#: instances/states.py:29 +msgid "Paused: the guest crashed" +msgstr "Duraklatıldı: konuk çöktü" + +#: instances/states.py:30 +msgid "Paused: its migration failed midway" +msgstr "Duraklatıldı: taşıma yarıda başarısız oldu" + +#: instances/states.py:31 +msgid "Paused by a libvirt error" +msgstr "Bir libvirt hatası nedeniyle duraklatıldı" + +#: instances/states.py:33 +msgid "Stopped: it crashed" +msgstr "Durdu: çöktü" + +#: instances/states.py:35 +msgid "Stopped by libvirt" +msgstr "libvirt tarafından durduruldu" + +#: instances/states.py:36 +msgid "Stopped: it failed to start" +msgstr "Durdu: başlatılamadı" + +#: instances/states.py:37 +msgid "The guest's kernel panicked" +msgstr "Konuğun çekirdeği panik verdi" + +#: instances/states.py:42 +#, python-format +msgid "%(dev)s: its storage has no free space" +msgstr "%(dev)s: depolamasında boş alan yok" + +#: instances/states.py:43 +#, python-format +msgid "%(dev)s: an I/O error" +msgstr "%(dev)s: G/Ç hatası" + +#: instances/templates/instance.html:55 +msgid "Free space on its storage, then resume it." +msgstr "Depolamasında yer açın, ardından sanal makineyi devam ettirin." + +#: instances/templates/instance.html:55 +msgid "An administrator has to free space on its storage and resume it." +msgstr "Bir yöneticinin depolamasında yer açıp sanal makineyi devam ettirmesi gerekir." diff --git a/locale/zh/LC_MESSAGES/django.mo b/locale/zh/LC_MESSAGES/django.mo index b675b67c..e667bb65 100644 Binary files a/locale/zh/LC_MESSAGES/django.mo and b/locale/zh/LC_MESSAGES/django.mo differ diff --git a/locale/zh/LC_MESSAGES/django.po b/locale/zh/LC_MESSAGES/django.po index 85c68c41..04dead64 100644 --- a/locale/zh/LC_MESSAGES/django.po +++ b/locale/zh/LC_MESSAGES/django.po @@ -12314,3 +12314,58 @@ msgstr "工作进程未在运行;最后在线时间 %(when)s。任务将等待 #: operations/templatetags/operations.py:99 msgid "The job worker has not run yet. Jobs wait until it runs." msgstr "工作进程尚未运行过。任务将等待它运行。" + + +#: instances/states.py:27 +msgid "Paused by a disk error" +msgstr "因磁盘错误而暂停" + +#: instances/states.py:28 +msgid "Paused by its watchdog" +msgstr "已被其看门狗设备暂停" + +#: instances/states.py:29 +msgid "Paused: the guest crashed" +msgstr "已暂停:客户机崩溃" + +#: instances/states.py:30 +msgid "Paused: its migration failed midway" +msgstr "已暂停:迁移中途失败" + +#: instances/states.py:31 +msgid "Paused by a libvirt error" +msgstr "因 libvirt 错误而暂停" + +#: instances/states.py:33 +msgid "Stopped: it crashed" +msgstr "已停止:已崩溃" + +#: instances/states.py:35 +msgid "Stopped by libvirt" +msgstr "已被 libvirt 停止" + +#: instances/states.py:36 +msgid "Stopped: it failed to start" +msgstr "已停止:启动失败" + +#: instances/states.py:37 +msgid "The guest's kernel panicked" +msgstr "客户机内核发生 panic" + +#: instances/states.py:42 +#, python-format +msgid "%(dev)s: its storage has no free space" +msgstr "%(dev)s:其存储没有可用空间" + +#: instances/states.py:43 +#, python-format +msgid "%(dev)s: an I/O error" +msgstr "%(dev)s:I/O 错误" + +#: instances/templates/instance.html:55 +msgid "Free space on its storage, then resume it." +msgstr "请在其存储上释放空间,然后恢复它。" + +#: instances/templates/instance.html:55 +msgid "An administrator has to free space on its storage and resume it." +msgstr "需要管理员在其存储上释放空间并恢复它。" diff --git a/static/js/instance_status.js b/static/js/instance_status.js index 4a924cf3..7288753e 100644 --- a/static/js/instance_status.js +++ b/static/js/instance_status.js @@ -4,6 +4,8 @@ backgroundJobRunning = false; // not "status": that is window.status, which the browser may not keep var vm_summary = document.getElementById("vm-summary"); var vm_status = Number(vm_summary.dataset.status); +// why it is in its state (libvirt's reason): a VM paused by hand that pauses again on a disk error stays paused +var vm_reason = vm_summary.dataset.reason; var host_lost = document.getElementById("vm-host-lost"); function reloadWhenFree() { @@ -24,7 +26,7 @@ var status_poll = pollWhileVisible(5000, function () { }); }, function get_status(data) { host_lost.hidden = true; - if (data['status'] != vm_status) { + if (data['status'] != vm_status || String(data['reason']) !== vm_reason) { reloadWhenFree(); } }); diff --git a/vrtManager/connection.py b/vrtManager/connection.py index f83ac80d..dd4d3cd1 100644 --- a/vrtManager/connection.py +++ b/vrtManager/connection.py @@ -1173,14 +1173,15 @@ class wvmConnect(object): return instances def get_domain_states(self): - """{uuid: [name, state]} of every domain, in one call.""" - return {dom.UUIDString(): [dom.name(), stats["state.state"]] + """{uuid: [name, state, reason]} of every domain, in one call.""" + return {dom.UUIDString(): [dom.name(), stats["state.state"], stats["state.reason"]] for dom, stats in self.wvm.getAllDomainStats(libvirt.VIR_DOMAIN_STATS_STATE)} def get_domain_rows(self, uuids=None): - """{uuid: (info, title)} of every domain, or of those in uuids, as the - VM lists show them: info in virDomainGetInfo's shape (state, max - memory KiB, memory KiB, vCPUs), the states in one call and the rest + """{uuid: (info, title, reason)} of every domain, or of those in uuids, + as the VM lists show them: info in virDomainGetInfo's shape (state, max + memory KiB, memory KiB, vCPUs), reason the state's (virDomainGetState), + the states in one call and the rest from each domain's live XML, which the title needs anyway. A domain gone meanwhile is left out.""" rows = {} @@ -1194,7 +1195,7 @@ class wvmConnect(object): vcpu = doc.find("vcpu") info = [stats["state.state"], int(doc.findtext("memory")), int(doc.findtext("currentMemory")), int(vcpu.get("current", vcpu.text))] - rows[dom.UUIDString()] = (info, doc.findtext("title") or "") + rows[dom.UUIDString()] = (info, doc.findtext("title") or "", stats["state.reason"]) return rows def domain_trees(self, running_only=False): diff --git a/vrtManager/instance.py b/vrtManager/instance.py index 2a86e5ab..555d7a96 100644 --- a/vrtManager/instance.py +++ b/vrtManager/instance.py @@ -920,6 +920,14 @@ class wvmInstance(wvmConnect): self._read_cache.clear() return self.wvm.defineXML(xml) + def get_state(self): + """[state, reason] of the domain (virDomainGetState), in one read.""" + return self.instance.state() + + def get_disk_errors(self): + """{target: virDomainDiskErrorCode} of the disks QEMU stopped on (virDomainGetDiskErrors).""" + return self.instance.diskErrors() + def get_status(self): """ VIR_DOMAIN_NOSTATE = 0 diff --git a/webvirtcloud/tests/test_poll_js.py b/webvirtcloud/tests/test_poll_js.py index aeb77976..6ee94deb 100644 --- a/webvirtcloud/tests/test_poll_js.py +++ b/webvirtcloud/tests/test_poll_js.py @@ -43,7 +43,7 @@ class PollTestCase(unittest.TestCase): self.assertIn("pollWhileVisible(", source) @unittest.skipUnless(shutil.which("node"), "node is not installed") - def test_the_vm_page_reloads_only_when_the_state_changes_or_the_vm_is_gone_and_it_is_not_in_use(self): + def test_the_vm_page_reloads_only_when_the_state_or_its_reason_changes_or_the_vm_is_gone_and_it_is_not_in_use(self): # every failed read shows the page's notice; another one than 404 leaves the page # "status" is a property of the browser's window: a page variable of # that name holds what the browser makes of it (a string, or nothing) @@ -51,13 +51,15 @@ class PollTestCase(unittest.TestCase): js = """ const vm = require("vm"); const results = {}; - for (const [answer, inUse] of [[1, false], [5, false], [5, true], [404, false], [404, true], [500, false]]) { + // answer: the state, or the HTTP error of the read; reason: the state's reason (the page has 1) + for (const [answer, inUse, reason] of [[1, false, 1], [1, false, 5], [5, false, 1], [5, true, 1], [404, false], + [404, true], [500, false]]) { let reloads = 0; // the summary and the notice a failed read shows - const element = {dataset: {status: "1", statusUrl: "/instances/1/status/"}, hidden: true}; + const element = {dataset: {status: "1", reason: "1", statusUrl: "/instances/1/status/"}, hidden: true}; const page = { pollWhileVisible: (interval, request, onData) => { - if (answer >= 400) { request(); } else { onData({status: answer}); } + if (answer >= 400) { request(); } else { onData({status: answer, reason: reason}); } return {stop() {}}; }, pageInUse: () => inUse, @@ -67,12 +69,12 @@ class PollTestCase(unittest.TestCase): page.window = {location: {reload: () => reloads++}}; Object.defineProperty(page, "status", {get: () => "", set: () => {}}); vm.runInNewContext(SCRIPT, vm.createContext(page)); - results[answer + (inUse ? " in use" : "")] = reloads; + results[answer + (reason === 5 ? " reason 5" : "") + (inUse ? " in use" : "")] = reloads; if (answer >= 400) { results[answer + " notice"] = !element.hidden; } } console.log(JSON.stringify(results)); """.replace("SCRIPT", json.dumps(script)) out = subprocess.run(["node", "-e", js], capture_output=True, text=True, timeout=30) self.assertEqual(out.returncode, 0, out.stderr) - self.assertEqual(json.loads(out.stdout), {"1": 0, "5": 1, "5 in use": 0, "404": 1, "404 in use": 0, + self.assertEqual(json.loads(out.stdout), {"1": 0, "1 reason 5": 1, "5": 1, "5 in use": 0, "404": 1, "404 in use": 0, "404 notice": True, "500": 0, "500 notice": True})