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

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