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

fix(instances): USB device changes as PCI ones; device refusals name no VM to owners

- A USB device added to or removed from a VM with a saved state applied
  only at the next cold boot: refused now, as for PCI devices, and the
  form says so.
- A USB hot plug or removal that failed half way said only libvirt's
  error: it now says where the device is, as for PCI devices
  (_hostdev_outcome, shared).
- A host device refusal (check_hostdevs) names the other VMs that have
  the device; users who do not see the hosts, such as an owner whose
  snapshot revert is refused, now read that a device is not free and that
  an administrator can see why.
- The host's USB devices named among a PCI device's host resources were
  English in every language.
This commit is contained in:
catborise 2026-11-11 16:22:42 +03:00
parent d07362106a
commit 2db25314ea
12 changed files with 662 additions and 563 deletions

View file

@ -8,13 +8,14 @@
<div class="alert alert-warning">{% blocktrans with problems=unmatched|join:"; " %}The VM does not start until this is fixed: {{ problems }}. Remove the device and add the one the host has.{% endblocktrans %}</div>
{% endif %}
<form method="post" action="{% url 'instances:add_usb_hostdev' instance.id %}" class="d-flex flex-wrap gap-2 mb-2">{% csrf_token %}
<select name="usb_device" class="form-select w-auto mw-100" aria-label="{% trans "USB device of the host" %}" required>
<select name="usb_device" class="form-select w-auto mw-100" aria-label="{% trans "USB device of the host" %}"{% if usb_frozen %} aria-describedby="usb_help"{% endif %} required{% if usb_frozen %} disabled{% endif %}>
<option value="" selected disabled>{% trans "Choose a USB device of the host…" %}</option>
{% for device in host_usb %}
<option value="{{ device.bus }}/{{ device.device }}/{{ device.ids }}"{% if device.problems %} disabled{% endif %}>{{ device.product }} ({{ device.ids }}, {{ device.bus }}/{{ device.device }}){% if device.problems %}: {{ device.problems|join:"; " }}{% endif %}</option>
{% endfor %}
</select>
<button type="submit" class="btn btn-primary">{% bs_icon 'plus-lg' %} {% trans "Add USB device" %}</button>
<button type="submit" class="btn btn-primary"{% if usb_frozen %} disabled{% endif %}>{% bs_icon 'plus-lg' %} {% trans "Add USB device" %}</button>
{% if usb_frozen %}<div class="form-text w-100" id="usb_help">{% trans "A VM with a saved state does not change its USB devices: start it, or start it without its saved state" %}</div>{% endif %}
</form>
<form method="post" action="{% url 'instances:add_pci_hostdev' instance.id %}" class="d-flex flex-wrap gap-2">{% csrf_token %}
<select name="pci_device" class="form-select w-auto mw-100" aria-label="{% trans "PCI device of the host" %}" aria-describedby="pci_help" required{% if pci_frozen %} disabled{% endif %}>

View file

@ -2134,10 +2134,10 @@ def host_devices(request, pk):
state = domain.info()[0]
# the VM's next start takes its USB devices as its definition names them
unmatched = usb_unmatched([etree.fromstring(domain.XMLDesc(VIR_DOMAIN_XML_INACTIVE))], usb)
saved = domain.hasManagedSaveImage(0) # the VM would start from it without the change
context = {"instance": instance, "host_pci": pci, "host_usb": usb, "running": state == VIR_DOMAIN_RUNNING,
"unmatched": [util.render(m["text"], m["values"], _) for m in unmatched],
# paused, or with a saved state the VM would start from without the change
"pci_frozen": state not in (VIR_DOMAIN_RUNNING, VIR_DOMAIN_SHUTOFF) or domain.hasManagedSaveImage(0)}
"unmatched": [util.render(m["text"], m["values"], _) for m in unmatched], "usb_frozen": saved,
"pci_frozen": state not in (VIR_DOMAIN_RUNNING, VIR_DOMAIN_SHUTOFF) or saved}
except libvirtError as err:
context = {"instance": instance, "error": err}
return render(request, "instances/host_devices_form.html", context)

Binary file not shown.

File diff suppressed because it is too large Load diff

Binary file not shown.

File diff suppressed because it is too large Load diff

View file

@ -12,3 +12,12 @@ class PublicErrorTests(SimpleTestCase):
self.assertEqual(public_error_text(PermissionDenied()), "You may no longer do this.")
self.assertEqual(public_error_text(Http404("No Instance matches the given query.")),
"The virtual machine is no longer in the panel.")
def test_a_host_device_refusal_names_no_other_vm(self):
from vrtManager.nodedevs import HostDevicesRefused
from vrtManager.util import message
refused = HostDevicesRefused("%(problems)s", problems=[message("%(device)s is given to %(vms)s",
device="PCI device 0000:00:0a.0", vms="private-db-1")])
self.assertNotIn("private-db-1", public_error_text(refused))
self.assertIn("Host devices tab", public_error_text(refused))

View file

@ -22,6 +22,7 @@ from libvirt import libvirtError
from accounts.models import UserInstance
from appsettings.models import AppSettings
from instances.models import Instance
from vrtManager.nodedevs import HostDevicesRefused
from vrtManager.util import ConnectionFailed, HostBusy, OperationError, render
from . import jobs
@ -57,6 +58,8 @@ HOST_BUSY = gettext_noop("The host of this virtual machine is busy with other re
# a job's checks in the worker (precheck) refuse with Django's exceptions, which have no text
NOT_ALLOWED = gettext_noop("You may no longer do this.")
NOT_FOUND = gettext_noop("The virtual machine is no longer in the panel.")
DEVICES_REFUSED = gettext_noop("A host device of this virtual machine is not free on its host now; an administrator "
"can see why on its Host devices tab.")
BOUNDS = {"WORKER_CONCURRENCY": (1, 16, 4), "JOB_RETENTION_DAYS": (1, 3650, 30), "LOG_RETENTION_DAYS": (1, 3650, 365)}
@ -103,7 +106,8 @@ def words(messages):
def public_error(exception):
"""The error for users who do not see the hosts: a connection error names
the host and how it is reached, so they learn only that it cannot be reached."""
the host and how it is reached, so they learn only that it cannot be
reached; a host device refusal names other VMs and what the host has."""
connection_error = isinstance(exception, ConnectionFailed) or (
isinstance(exception, libvirtError)
and exception.get_error_domain() in TRANSPORT_ERROR_DOMAINS
@ -115,6 +119,8 @@ def public_error(exception):
return say(NOT_ALLOWED)
if isinstance(exception, Http404):
return say(NOT_FOUND)
if isinstance(exception, HostDevicesRefused):
return say(DEVICES_REFUSED)
return say(UNREACHABLE) if connection_error else said(exception)

View file

@ -72,7 +72,7 @@ from lxml import etree
from vrtManager import util
from vrtManager.connection import NVRAM_DIR, wvmConnect
from vrtManager.nodedevs import check_hostdevs, pci_address, usb_selector
from vrtManager.nodedevs import check_hostdevs, pci_address, pci_label, usb_selector, usb_selector_label
from vrtManager.storage import wvmStorage, wvmStorages
logger = logging.getLogger(__name__)
@ -2903,28 +2903,34 @@ class wvmInstance(wvmConnect):
return status == VIR_DOMAIN_RUNNING
def _pci_outcome(self, address, err):
"""An OperationError with err and where the PCI device at address is
now: in the running VM, in its next start; the outcome is unknown
when the VM cannot be read."""
"""_hostdev_outcome of the PCI device at address."""
return self._hostdev_outcome(pci_label(address), lambda flags: self._pci_hostdev(address, flags) is not None, err)
def _usb_outcome(self, selector, err):
"""_hostdev_outcome of the USB device of selector (usb_selector)."""
return self._hostdev_outcome(usb_selector_label(selector),
lambda flags: any(own == selector for _e, own in self._usb_hostdevs(flags)), err)
def _hostdev_outcome(self, device, has, err):
"""An OperationError with err and where the host device (its label)
is now, as has(XMLDesc flags) tells: in the running VM, in its next
start; the outcome is unknown when the VM cannot be read."""
try:
running = self.instance.isActive()
now = running and self._pci_hostdev(address, VIR_DOMAIN_XML_SECURE) is not None
later = self._pci_hostdev(address) is not None
now = running and has(VIR_DOMAIN_XML_SECURE)
later = has(PERSISTENT_XML)
except libvirtError:
return util.OperationError(gettext_noop("%(err)s; whether the VM has PCI device %(address)s now is not known"), err=err, address=address)
return util.OperationError(gettext_noop("%(err)s; whether the VM has %(device)s now is not known"), err=err, device=device)
outcome = {
(False, True): gettext_noop("%(err)s; PCI device %(address)s: the VM is not running, its next start has it"),
(False, False): gettext_noop(
"%(err)s; PCI device %(address)s: the VM is not running, its next start does not have it"),
(True, True): gettext_noop("%(err)s; PCI device %(address)s: the running VM has it, its next start has it"),
(True, False): gettext_noop(
"%(err)s; PCI device %(address)s: the running VM has it, its next start does not have it"),
(None, True): gettext_noop(
"%(err)s; PCI device %(address)s: the running VM does not have it, its next start has it"),
(False, True): gettext_noop("%(err)s; %(device)s: the VM is not running, its next start has it"),
(False, False): gettext_noop("%(err)s; %(device)s: the VM is not running, its next start does not have it"),
(True, True): gettext_noop("%(err)s; %(device)s: the running VM has it, its next start has it"),
(True, False): gettext_noop("%(err)s; %(device)s: the running VM has it, its next start does not have it"),
(None, True): gettext_noop("%(err)s; %(device)s: the running VM does not have it, its next start has it"),
(None, False): gettext_noop(
"%(err)s; PCI device %(address)s: the running VM does not have it, its next start does not have it"),
"%(err)s; %(device)s: the running VM does not have it, its next start does not have it"),
}[(now or None) if running else False, later]
return util.OperationError(outcome, err=err, address=address)
return util.OperationError(outcome, err=err, device=device)
def add_pci_hostdev(self, address):
"""Gives the VM the host's PCI device at address (0000:05:00.0), for
@ -2971,7 +2977,10 @@ class wvmInstance(wvmConnect):
def add_usb_hostdev(self, vendor, product, address=None):
"""Gives the VM the host's USB device of vendor and product, at
address (bus, device) when given: the host has more than one of the
model. Refused without a USB controller."""
model. Refused without a USB controller, and with a saved state (it
would start without the change). A hot plug that fails says where
the device is."""
self._refuse_saved_usb()
for xml_flags, _ in self._definitions():
if not etree.fromstring(self._XMLDesc(xml_flags)).xpath("devices/controller[@type='usb'][not(@model='none')]"):
raise util.OperationError(gettext_noop("The VM has no USB controller"))
@ -2981,17 +2990,32 @@ class wvmInstance(wvmConnect):
etree.SubElement(source, "product", id=product)
if address:
etree.SubElement(source, "address", bus=str(address[0]), device=str(address[1]))
self._attach_device(etree.tostring(hostdev, encoding="unicode"))
try:
self._attach_device(etree.tostring(hostdev, encoding="unicode"))
except libvirtError as err:
if not self.instance.isActive():
raise # one definition: unchanged
raise self._usb_outcome(usb_selector(source), err) from None
def _refuse_saved_usb(self):
if self.instance.hasManagedSaveImage(0):
raise util.OperationError(gettext_noop(
"A VM with a saved state does not change its USB devices: start it, or start it without its saved state"))
def delete_usb_hostdev(self, selector):
"""Takes the USB host device of selector (usb_selector) from each
definition that has it, as that definition describes it."""
definition that has it, as that definition describes it; one that
fails says where the device is."""
self._refuse_saved_usb()
found = False
for xml_flags, affect in self._definitions():
for element, own in self._usb_hostdevs(xml_flags):
if own == selector:
found = True
self.instance.detachDeviceFlags(etree.tostring(element, encoding="unicode"), affect)
try:
self.instance.detachDeviceFlags(etree.tostring(element, encoding="unicode"), affect)
except libvirtError as err:
raise self._usb_outcome(selector, err) from None
if not found:
raise util.OperationError(gettext_noop("The VM has no such USB device"))

View file

@ -63,7 +63,8 @@ def host_resources(name, nodes, children):
elif cap.get("type") == "drm" and cap.findtext("type") == "primary":
found.append(nodes[child].xpath("string(devnode[@type='dev'])"))
elif cap.get("type") == "usb_device" and not usb_hub(child, nodes, children):
found.append(f"USB device {cap.findtext('bus')}/{cap.findtext('device')} ({cap.findtext('product')})")
found.append(_("USB device %(bus)s/%(device)s (%(product)s)") % {
"bus": cap.findtext("bus"), "device": cap.findtext("device"), "product": cap.findtext("product")})
found.extend(host_resources(child, nodes, children))
return found
@ -136,6 +137,15 @@ def pci_label(address):
return [util.message(gettext_noop("PCI device %(address)s"), address=address)]
def usb_selector_label(selector):
"""How a VM's definition names a USB device (usb_selector): by its IDs, and its address where given."""
vendor, product, address = selector
ids = f"{vendor[2:]}:{product[2:]}"
if address is None:
return [util.message(gettext_noop("USB device %(ids)s"), ids=ids)]
return [util.message(gettext_noop("USB device %(ids)s at %(bus)s/%(device)s"), ids=ids, bus=address[0], device=address[1])]
def usb_label(device):
return [util.message(gettext_noop("USB device %(bus)s/%(device)s (%(product)s)"),
bus=device["bus"], device=device["device"], product=device["product"])]
@ -232,13 +242,7 @@ def usb_unmatched(trees, usb, restore=False):
for source in tree.xpath(USB_SOURCES):
picked = usb_picked(source, usb)
matches = [device for device in usb if usb_named(picked, device["model"], (device["bus"], device["device"]))]
vendor, product, given = usb_selector(source)
ids = f"{vendor[2:]}:{product[2:]}"
if given is None:
label = [util.message(gettext_noop("USB device %(ids)s"), ids=ids)]
else:
label = [util.message(gettext_noop("USB device %(ids)s at %(bus)s/%(device)s"), ids=ids,
bus=given[0], device=given[1])]
label = usb_selector_label(usb_selector(source))
if not matches and source.get("startupPolicy") not in dropped:
problems.append(util.message(gettext_noop("%(device)s is not on the host"), device=label))
elif len(matches) > 1:
@ -387,6 +391,11 @@ def device_names(conn):
return names
class HostDevicesRefused(util.OperationError):
"""check_hostdevs's refusal: its reasons name other VMs and what the host
has, for administrators only (operations.utils.public_error)."""
def check_hostdevs(conn, vm, trees, restore=False):
"""Refuses the host devices the definitions trees give the VM named vm,
on the host of conn, when they cannot be (hostdev_problems): each
@ -402,4 +411,4 @@ def check_hostdevs(conn, vm, trees, restore=False):
problems += hostdev_problems(vm, pci, usb, wanted_pci, picked, managed_pci(tree))
if problems:
unique = list({util.render(m["text"], m["values"], str): m for m in problems}.values())
raise util.OperationError(gettext_noop("%(problems)s"), problems=unique)
raise HostDevicesRefused(gettext_noop("%(problems)s"), problems=unique)

View file

@ -72,6 +72,37 @@ class UsbHostdevTests(SimpleTestCase):
proxy.add_usb_hostdev("0x0627", "0x0001")
proxy.instance.attachDeviceFlags.assert_not_called()
def test_a_vm_with_a_saved_state_keeps_its_usb_devices(self):
proxy = vm(domain(CONTROLLER), domain(CONTROLLER, by_model()), active=False)
proxy.instance.hasManagedSaveImage.return_value = 1
for change in (lambda: proxy.add_usb_hostdev("0x0627", "0x0001"),
lambda: proxy.delete_usb_hostdev(("0x0627", "0x0001", None))):
with self.assertRaisesRegex(OperationError, "saved state does not change its USB devices"):
change()
proxy.instance.attachDeviceFlags.assert_not_called()
proxy.instance.detachDeviceFlags.assert_not_called()
def test_a_usb_change_that_fails_half_way_says_where_the_device_is(self):
# the running VM let it go, its next start's removal failed
xml = {"running": domain(CONTROLLER, by_model("<address bus='1' device='3'/>")),
"saved": domain(CONTROLLER, by_model("<address bus='1' device='3'/>"))}
proxy = vm("", "")
proxy.instance.XMLDesc.side_effect = lambda flags=0: xml["saved" if flags & libvirt.VIR_DOMAIN_XML_INACTIVE else "running"]
def detach(_xml, affect):
if affect == libvirt.VIR_DOMAIN_AFFECT_CONFIG:
raise libvirt.libvirtError("cannot save the definition")
xml["running"] = domain(CONTROLLER)
proxy.instance.detachDeviceFlags.side_effect = detach
with self.assertRaisesRegex(OperationError, "cannot save the definition; USB device 0627:0001 at 1/3: "
"the running VM does not have it, its next start has it"):
proxy.delete_usb_hostdev(("0x0627", "0x0001", (1, 3)))
# a hot plug: the running VM got it, its next start did not
xml["running"], xml["saved"] = domain(CONTROLLER, by_model("<address bus='1' device='3'/>")), domain(CONTROLLER)
proxy.instance.attachDeviceFlags.side_effect = libvirt.libvirtError("cannot save the definition")
with self.assertRaisesRegex(OperationError, "the running VM has it, its next start does not have it"):
proxy.add_usb_hostdev("0x0627", "0x0001", (1, 3))
def test_a_device_the_host_has_one_of_is_given_by_model(self):
proxy = vm(domain(CONTROLLER), domain(CONTROLLER))
proxy.add_usb_hostdev("0x0627", "0x0001")

View file

@ -115,6 +115,15 @@ class StartCheckTests(SimpleTestCase):
self.proxy(gone, saved=gone).check_start_hostdevs(restore=False)
class ResourceLanguageTests(SimpleTestCase):
def test_a_usb_device_the_host_has_is_named_in_the_reader_s_language(self):
from django.utils import translation
with translation.override("tr"):
pci_devices, _ = devices()
self.assertEqual(pci_devices[-1]["resources"], ["USB aygıtı 1/2 (QEMU Tablet)", "USB aygıtı 1/3 (QEMU Tablet)"])
class NodeDevicesTests(SimpleTestCase):
def test_pci_devices_by_group_with_what_the_host_has_on_them(self):
pci_devices, _ = devices()