1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-03 09:26:03 +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

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