diff --git a/instances/tests/test_change_xml.py b/instances/tests/test_change_xml.py
index 88515de7..0b5e41df 100644
--- a/instances/tests/test_change_xml.py
+++ b/instances/tests/test_change_xml.py
@@ -7,6 +7,7 @@ from django.test import TestCase
from django.urls import reverse
from instances.models import Instance
from libvirt import libvirtError
+from vrtManager.util import OperationError
from vrtManager.instance import PERSISTENT_XML
from logs.models import Logs
from operations import claims
@@ -27,13 +28,13 @@ class ChangeXmlTestCase(TestCase):
compute = Compute.objects.create(name="xml-compute", hostname="127.0.0.1", login="", password="", type=4)
self.instance = Instance.objects.create(compute=compute, name="xml-vm", uuid=UUID)
- def post(self, status=5, xml=EDITED, base=CURRENT, confirm=False, define_error=None):
+ def post(self, status=5, xml=EDITED, base=CURRENT, confirm=False, define_error=None, current=CURRENT):
data = {"inst_xml": xml, "base": base}
if confirm:
data["confirm"] = "1"
with patch("instances.models.wvmInstance") as wvm:
wvm.return_value.get_status.return_value = status
- wvm.return_value._XMLDesc.side_effect = lambda flags: CURRENT if flags == PERSISTENT_XML else LIVE
+ wvm.return_value._XMLDesc.side_effect = lambda flags: current if flags == PERSISTENT_XML else LIVE
wvm.return_value._defineXML.side_effect = define_error
response = self.client.post(reverse("instances:change_xml", args=[self.instance.id]), data)
return response, wvm.return_value._defineXML
@@ -72,6 +73,41 @@ class ChangeXmlTestCase(TestCase):
row = Logs.objects.get(instance_uuid=self.instance.uuid)
self.assertEqual((row.message, row.success), ("VM xml-vm: change XML: unsupported configuration: bad memory", False))
+ def test_a_host_device_given_or_changed_is_checked_as_the_host_devices_tab_does(self):
+ hostdev = ("")
+ given = EDITED.replace("", hostdev.format("yes") + "")
+ with patch("instances.views.check_hostdevs", side_effect=OperationError("PCI device 0000:00:0a.0 is given to db-1")) \
+ as check:
+ response, define = self.post(confirm=True, xml=given)
+ define.assert_not_called()
+ self.assertIn("is given to db-1", response.json()["error"])
+ self.assertEqual(check.call_args.args[1], "xml-vm")
+ # devices as they were: not checked again, a device the host lost since does not stop an edit
+ check.reset_mock()
+ had = given.replace("2048", "1024")
+ response, define = self.post(confirm=True, xml=given, base=had, current=had)
+ define.assert_called_once_with(given)
+ check.assert_not_called()
+ # managed by libvirt from now on: the host's driver gives it up at the next start
+ self.post(confirm=True, xml=given.replace("'yes'", "'no'"), base=given, current=given)
+ check.assert_called_once()
+
+ def test_a_nic_that_is_a_host_device_and_turns_managed_is_checked(self):
+ nic = ("")
+ had = EDITED.replace("2048", "1024").replace("", nic.format("no") + "")
+ with patch("instances.views.check_hostdevs") as check:
+ self.post(confirm=True, xml=had.replace("'no'", "'yes'"), base=had, current=had)
+ check.assert_called_once()
+
+ def test_a_host_device_address_that_is_no_number_is_refused(self):
+ usb = ""
+ response, define = self.post(confirm=True, xml=EDITED.replace("", usb + ""))
+ self.assertEqual(response.status_code, 400)
+ self.assertIn("The XML is not valid", response.json()["error"])
+ define.assert_not_called()
+
def test_a_running_or_paused_vm_gets_the_definition_for_its_next_start(self):
for status in (1, 3):
with self.subTest(status=status):
@@ -90,7 +126,7 @@ class ChangeXmlTestCase(TestCase):
def test_a_busy_vm_answers_the_dialog_so_the_edit_stays(self):
# the dialog's script sends X-Requested-With; a page form gets the redirect
- with patch("instances.views.libvirt_instance_lock", side_effect=claims.Busy("instance:xml-vm")), \
+ with patch("instances.views.libvirt_compute_lock", side_effect=claims.Busy("compute:1")), \
patch("instances.models.wvmInstance") as wvm:
url = reverse("instances:change_xml", args=[self.instance.id])
data = {"inst_xml": EDITED, "base": CURRENT, "confirm": "1"}
diff --git a/instances/tests/test_vm_audit_rows.py b/instances/tests/test_vm_audit_rows.py
index 66ab2530..3ac1feba 100644
--- a/instances/tests/test_vm_audit_rows.py
+++ b/instances/tests/test_vm_audit_rows.py
@@ -190,6 +190,9 @@ class DefineFromXmlRowTests(TestCase):
def post(self, xml):
conn = libvirt.open("test:///default")
self.addCleanup(conn.close)
+ # the test driver's VMs live as long as the process: the ones defined here go
+ before = {domain.name() for domain in conn.listAllDomains()}
+ self.addCleanup(lambda: [domain.undefine() for domain in conn.listAllDomains() if domain.name() not in before])
compute = Compute.objects.create(name="testdrv", hostname="localhost", login="", password="", type=4)
self.client.force_login(get_user_model().objects.create_superuser("xml", "xml@example.com", "pw"))
Logs.objects.all().delete()
@@ -198,6 +201,14 @@ class DefineFromXmlRowTests(TestCase):
{"create_xml": "", "dom_xml": xml})
return Logs.objects.get()
+ def test_a_host_device_the_host_cannot_give_is_refused(self):
+ with patch("instances.views.check_hostdevs", side_effect=OperationError("PCI device 0000:00:0a.0 is given to db-1")):
+ row = self.post("with-device1024hvm"
+ "")
+ self.assertEqual((row.message, row.success), ("VM with-device: define from XML: PCI device 0000:00:0a.0 is given to db-1",
+ False))
+ self.assertFalse(Instance.objects.filter(name="with-device").exists())
+
def test_a_defined_vm_has_its_uuid(self):
row = self.post("from-xml1024"
"hvm")
diff --git a/instances/views.py b/instances/views.py
index 510c2cf6..b786a9b4 100755
--- a/instances/views.py
+++ b/instances/views.py
@@ -58,7 +58,8 @@ from vrtManager.connection import CONNECT_TIMEOUT
from vrtManager.create import cpu_choices, wvmCreate
from vrtManager.instance import USAGE_MAX_WINDOW, wvmInstances
from vrtManager.interface import wvmInterface
-from vrtManager.nodedevs import device_names, hostdev_problems, node_devices, pci_problems, usb_unmatched
+from vrtManager.nodedevs import (check_hostdevs, device_names, hostdev_problems, hostdev_users, managed_pci,
+ node_devices, pci_problems, usb_unmatched)
from vrtManager.storage import rbd_source_children, wvmStorage
from vrtManager.util import randomPasswd
@@ -1867,7 +1868,7 @@ def set_bootorder(request, pk):
@require_POST
@superuser_only
-@serialize_instance_mutation
+@serialize_compute_mutation # the whole compute: the XML may give the VM a host device
def change_xml(request, pk):
"""
The XML editor's dialog: without confirm, the lines the edited XML changes
@@ -1897,8 +1898,12 @@ def change_xml(request, pk):
diff = difflib.unified_diff(current.splitlines(), new_xml.splitlines(), "current", "new", lineterm="")
return JsonResponse({"diff": list(diff)})
shut_off = instance.proxy.get_status() == 5
+ new_tree = etree.fromstring(new_xml)
try:
with audit_vm(request, instance, "change XML"):
+ # host devices given or changed are checked as the Host devices tab checks them
+ if _hostdevs_of(new_tree) != _hostdevs_of(etree.fromstring(current)):
+ check_hostdevs(instance.proxy, instance.name, [new_tree])
instance.proxy._defineXML(new_xml)
except libvirtError as err:
return JsonResponse({"error": error_text(request, err)}, status=400)
@@ -2081,6 +2086,11 @@ def delete_network(request, pk):
return _back(request, pk, "network")
+def _hostdevs_of(tree):
+ """The host devices a definition gives its VM, and which PCI ones libvirt manages."""
+ return (*hostdev_users([tree]), managed_pci(tree))
+
+
def _host_devices(instance):
"""The host's PCI and USB devices, each with why it cannot be given to
the VM (pci_problems, hostdev_problems; none: it can). A USB device is
@@ -2510,6 +2520,7 @@ def create_instance_select_type(request, compute_id):
else:
with libvirt_compute_lock(compute):
with audit(request, compute, f"VM {name}", "define from XML", instance=name) as entry:
+ check_hostdevs(conn, name, [etree.fromstring(xml)])
conn._defineXML(xml)
refresh_instance_database(compute)
instance = compute.instance_set.get(name=name)
diff --git a/vrtManager/nodedevs.py b/vrtManager/nodedevs.py
index 880d7b53..034eea2d 100644
--- a/vrtManager/nodedevs.py
+++ b/vrtManager/nodedevs.py
@@ -84,9 +84,23 @@ def usb_selector(source):
the parts libvirt picks a device by. An address libvirt resolved for a
running VM (autoAddress, in its migratable XML) is not one of them."""
address = source.find("address")
- given = address is not None and source.get("autoAddress") != "yes"
+ at = None if address is None else (int(address.get("bus")), int(address.get("device")))
return (usb_id(source.xpath("string(vendor/@id)")), usb_id(source.xpath("string(product/@id)")),
- (int(address.get("bus")), int(address.get("device"))) if given else None)
+ None if source.get("autoAddress") == "yes" else at)
+
+
+def element_address(address):
+ return pci_address(address.get("domain", "0"), address.get("bus"), address.get("slot"), address.get("function"))
+
+
+def parsed(parse, element):
+ """parse(element), a definition's host device; one whose address or IDs
+ are not numbers is refused (the XML editor and define from XML take any)."""
+ try:
+ return parse(element)
+ except (TypeError, ValueError):
+ raise util.OperationError(gettext_noop("The XML is not valid: %(err)s"),
+ err=etree.tostring(element, encoding=str, with_tail=False)) from None
def hostdev_users(trees):
@@ -98,8 +112,8 @@ def hostdev_users(trees):
for address in tree.xpath("devices/hostdev[@mode='subsystem'][@type='pci']/source/address"
" | devices/interface[@type='hostdev']/source/address"
" | devices/interface/actual[@type='hostdev']/source/address"):
- pci.add(pci_address(address.get("domain", "0"), address.get("bus"), address.get("slot"), address.get("function")))
- usb.extend(usb_selector(source) for source in tree.xpath("devices/hostdev[@mode='subsystem'][@type='usb']/source"))
+ pci.add(parsed(element_address, address))
+ usb.extend(parsed(usb_selector, source) for source in tree.xpath("devices/hostdev[@mode='subsystem'][@type='usb']/source"))
return pci, usb
@@ -140,10 +154,12 @@ def device_problems(label, vms, resources, vm):
def managed_pci(tree):
- """The PCI addresses a VM's definition gives it as managed host devices:
- libvirt takes them from their host drivers when the VM starts."""
- return {pci_address(a.get("domain", "0"), a.get("bus"), a.get("slot"), a.get("function"))
- for a in tree.xpath("devices/hostdev[@mode='subsystem'][@type='pci'][@managed='yes']/source/address")}
+ """The PCI addresses a VM's definition gives it as managed host devices
+ (a or a NIC that is one): libvirt takes them from their host
+ drivers when the VM starts."""
+ return {parsed(element_address, address)
+ for address in tree.xpath("devices/hostdev[@mode='subsystem'][@type='pci'][@managed='yes']/source/address"
+ " | devices/interface[@type='hostdev'][@managed='yes']/source/address")}
def pci_problems(vm, device, by_address, managed):