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

feat(instances): a VM a fault stopped or paused says why

libvirt gives each state its reason; the panel showed only the state, so a
VM QEMU paused because its storage filled up read "Suspended" like one an
administrator paused.

- instances.states.REASONS: the fault reasons told (disk error, watchdog,
  guest crash or kernel panic, a crash of the guest or its QEMU process,
  libvirt stopping it after a restart, failed post-copy migration, libvirt
  error, failed start); the ordinary ones (user, migration, snapshot) are not
- the lists read the reason with the state in their one getAllDomainStats
  call (get_domain_rows, get_domain_states: a change of reason reloads a
  list) and show it under the state badge
- the VM page reads state and reason in one virDomainGetState (a reason
  means something only with its own state) and tells it in an alert; a VM
  paused by a disk error names each disk and what it met
  (virDomainGetDiskErrors), and when a storage has no free space, what to
  do: an administrator frees space and resumes it. Disk errors are read
  only then: libvirt keeps the last one after a resume. The page's poll
  reloads on a change of reason too

Checked live on a Vagrant host: a guest filling a disk on a 40 MiB pool was
paused (I/O error, vda: no space); the page said so, and after the pool grew
and the VM was resumed the alert was gone.
This commit is contained in:
catborise 2026-11-22 21:03:22 +03:00
parent 7408a575d6
commit bdc5569cc8
17 changed files with 330 additions and 18 deletions

View file

@ -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), \

View file

@ -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()

View file

@ -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."""

View file

@ -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 #}
<section class="card mb-3" aria-labelledby="vm-name" id="vm-summary" data-status="{{ instance.status }}"
<section class="card mb-3" aria-labelledby="vm-name" id="vm-summary" data-status="{{ instance.status }}" data-reason="{{ instance.state_and_reason.1 }}"
data-status-url="{% url 'instances:status' instance.id %}" data-osinfo-url="{% url 'instances:osinfo' instance.id %}"
data-opens-on="{% if instance.is_template and can_clone %}#clone{% endif %}"
data-random-mac-url="{% url 'instances:random_mac_address' %}"
@ -46,6 +46,16 @@
</div>
{# shown by instance_status.js while the VM's state cannot be read #}
<div class="alert alert-warning small py-2 mt-2 mb-0" id="vm-host-lost" role="status" hidden>{% trans "This page could not be refreshed: its state and figures may be out of date." %}</div>
{# a VM a fault stopped or paused says why; a full storage pauses it until there is space #}
{% if instance.state_reason %}
<div class="alert alert-danger small py-2 mt-2 mb-0" role="status">
<strong>{{ instance.state_reason }}</strong>
{% for error in instance.disk_error_texts %}<div>{{ error }}</div>{% endfor %}
{% if instance.disk_full %}
<div>{% 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 %}</div>
{% endif %}
</div>
{% endif %}
{% if not instance.is_template %}
<div class="d-flex flex-wrap column-gap-3 row-gap-1 small mt-2">
{% if not instance.guest_agent %}

View file

@ -1,3 +1,4 @@
{% load vm_states %}
{% if instance.info %}{% vm_state instance.info.0 as state %}{% else %}{% vm_state None as state %}{% endif %}
<span class="badge text-bg-{{ state.1 }}" data-state="{{ state.0 }}">{{ state.0 }}</span>
{% if instance.state_reason %}<div class="small text-danger">{{ instance.state_reason }}</div>{% endif %}

View file

@ -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]))

View file

@ -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 "<domain><memory>4194304</memory><currentMemory>2097152</currentMemory><vcpu>2</vcpu></domain>"
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)})

View file

@ -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

View file

@ -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):

Binary file not shown.

View file

@ -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."

Binary file not shown.

View file

@ -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 "需要管理员在其存储上释放空间并恢复它。"

View file

@ -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();
}
});

View file

@ -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):

View file

@ -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

View file

@ -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})