1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-11-11 12:46:49 +00:00

feat(instances): PCI devices of the host given to a shut-off VM

- The Host devices tab gives a shut-off VM a PCI device of its host and
  takes it back; libvirt binds the device to vfio-pci when the VM starts
  and gives it back when it stops (managed). The VM's PCI devices are
  listed with whether the running VM and its next start have them.
- A device is offered, and accepted on the server under the compute's
  claim, only when it is no bridge of any kind (bridge header, PCIe port,
  or of the bridge class: host bridge, LPC), the host has none of its own
  network interfaces, disks or graphics card on it (else: bind it to
  vfio-pci on the host first), no other VM names it, and every other
  endpoint of its IOMMU group is the VM's too or has no driver or
  vfio-pci and no other VM; bridges in the group stay with pcieport, and
  a member that cannot be read keeps the group. Nothing in the group is
  taken implicitly.
- A snapshot revert checks the PCI devices of the snapshot with the same
  rules; migration and clones already leave host devices out.
- The add forms of the tab load together, when the tab opens.
This commit is contained in:
catborise 2026-10-29 13:45:27 +03:00
parent ac8ff62e7e
commit 80dd145bcf
19 changed files with 509 additions and 103 deletions

View file

@ -428,19 +428,19 @@
});
</script>
<script>
// the Host devices tab's add form: loaded once, when the tab first opens
var hostUsb = document.getElementById("host-usb");
if (hostUsb) {
// the Host devices tab's add forms: loaded once, when the tab first opens
var hostDevices = document.getElementById("host-devices");
if (hostDevices) {
document.querySelector('[data-bs-target="#hostdevs"]').addEventListener("shown.bs.tab", function () {
if (hostUsb.dataset.loaded) return;
hostUsb.dataset.loaded = "true";
fetch(hostUsb.dataset.url).then(function (response) {
if (hostDevices.dataset.loaded) return;
hostDevices.dataset.loaded = "true";
fetch(hostDevices.dataset.url).then(function (response) {
if (!response.ok) throw new Error(response.statusText);
return response.text();
}).then(function (html) {
hostUsb.innerHTML = html;
hostDevices.innerHTML = html;
}).catch(function () {
hostUsb.textContent = "{{ _("The host's USB devices could not be read.")|escapejs }}";
hostDevices.textContent = "{{ _("The host's devices could not be read.")|escapejs }}";
});
});
}

View file

@ -0,0 +1,29 @@
{% load i18n %}
{% load bootstrap_icons %}
{# the add forms of the Host devices tab: each choice disabled with the reasons it cannot be given #}
{% if error %}
<div class="alert alert-warning mb-0">{% blocktrans %}The host's devices could not be read: {{ error }}{% endblocktrans %}</div>
{% else %}
<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>
<option value="" selected disabled>{% trans "Choose a USB device of the host…" %}</option>
{% for device in host_usb %}
<option value="{{ device.bus }}/{{ device.device }}"{% 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>
</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 running %} disabled{% endif %}>
<option value="" selected disabled>{% trans "Choose a PCI device of the host…" %}</option>
{% for device in host_pci %}
<option value="{{ device.address }}"{% if device.problems %} disabled{% endif %}>{{ device.product }} ({{ device.address }}, {{ device.driver|default:_("no driver") }}){% if device.problems %}: {{ device.problems|join:"; " }}{% endif %}</option>
{% endfor %}
</select>
<button type="submit" class="btn btn-primary"{% if running %} disabled{% endif %}>{% bs_icon 'plus-lg' %} {% trans "Add PCI device" %}</button>
<div class="form-text w-100" id="pci_help">
{% if running %}{% trans "Shut the VM down, without a saved state, to change its PCI devices." %}
{% else %}{% trans "libvirt binds the device to vfio-pci when the VM starts, and gives it back to the host when the VM stops; a device bound to vfio-pci before stays bound to it." %}{% endif %}
</div>
</form>
{% endif %}

View file

@ -1,15 +0,0 @@
{% load i18n %}
{% load bootstrap_icons %}
{% if error %}
<div class="alert alert-warning mb-0">{% blocktrans %}The host's devices could not be read: {{ error }}{% endblocktrans %}</div>
{% else %}
<form method="post" action="{% url 'instances:add_usb_hostdev' instance.id %}" class="d-flex flex-wrap gap-2">{% csrf_token %}
<select name="usb_device" class="form-select w-auto mw-100" aria-label="{% trans "USB device of the host" %}" required>
<option value="" selected disabled>{% trans "Choose a USB device of the host…" %}</option>
{% for device in host_usb %}
<option value="{{ device.bus }}/{{ device.device }}"{% 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>
</form>
{% endif %}

View file

@ -598,9 +598,9 @@
<div role="tabpanel" class="tab-pane border border-top-0 p-3" id="hostdevs">
<p class="small text-body-secondary">{% trans "Devices of the host given to the VM. The VM starts only on a host that has them; it is not migrated while it has them, and its clones get none." %}</p>
{% if request.user.is_superuser %}
{# the add form comes when the tab opens: its choices scan every VM of the host #}
<div id="host-usb" class="mb-3" data-url="{% url 'instances:host_usb' instance.id %}">
<span class="small text-body-secondary">{% trans "Reading the host's USB devices…" %}</span>
{# the add forms come when the tab opens: their choices scan every VM of the host #}
<div id="host-devices" class="mb-3" data-url="{% url 'instances:host_devices' instance.id %}">
<span class="small text-body-secondary">{% trans "Reading the host's devices…" %}</span>
</div>
{% endif %}
{% if usb_hostdevs %}
@ -640,13 +640,46 @@
</table>
</div>
{% endif %}
{% if pci_hostdevs %}
<div class="table-responsive position-relative">
<table class="table align-middle">
<thead>
<tr>
<th scope="col">{% trans "PCI device" %}</th>
<th scope="col">{% trans "Running VM" %}</th>
<th scope="col">{% trans "Next start" %}</th>
{% if request.user.is_superuser %}<th scope="col"><span class="visually-hidden">{% trans "Actions" %}</span></th>{% endif %}
</tr>
</thead>
<tbody>
{% for device in pci_hostdevs %}
<tr>
<td>{{ device.name|default:"–" }} <span class="small text-body-secondary font-monospace">{{ device.address }}</span></td>
<td>{% if device.now %}{% trans "Has it" %}{% else %}–{% endif %}</td>
<td>{% if device.next %}{% trans "Yes" %}{% else %}{% trans "No" %}{% endif %}</td>
{% if request.user.is_superuser %}
<td class="text-end">
<form method="post" action="{% url 'instances:delete_pci_hostdev' instance.id %}">{% csrf_token %}
<input type="hidden" name="address" value="{{ device.address }}">
<button type="submit" class="btn btn-sm btn-outline-danger" aria-label="{% trans "Remove the PCI device" %}"
{% if instance.status != 5 or not device.next %}disabled title="{% trans "Shut the VM down to change its PCI devices" %}"{% endif %}
data-confirm="{% trans "Remove this PCI device from the VM?" %}" onclick="return confirm(this.dataset.confirm)">{% bs_icon 'trash' %}</button>
</form>
</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
{% for device in other_hostdevs %}
<p class="mb-1">
{% if device.type == "nic" %}{% trans "Network interface" %}{% else %}{{ device.type|upper }}{% endif %} <span class="font-monospace">{{ device.address }}</span>
<span class="small text-body-secondary">{% if device.now and device.next %}{% trans "running VM and next start" %}{% elif device.now %}{% trans "running VM only" %}{% else %}{% trans "next start only" %}{% endif %}; {% trans "changed in the XML editor" %}</span>
</p>
{% endfor %}
{% if not usb_hostdevs and not other_hostdevs %}
{% if not usb_hostdevs and not pci_hostdevs and not other_hostdevs %}
<p class="small text-body-secondary mb-0">{% trans "The VM has no host devices." %}</p>
{% endif %}
</div>
@ -808,7 +841,7 @@
{% if can_clone %}
<div role="tabpanel" class="tab-pane border border-top-0 p-3" id="clone">
<p class="fw-bold">{% trans "Create a clone" %}</p>
{% if usb_hostdevs or other_hostdevs %}<p class="small text-body-secondary">{% trans "The clone gets none of the VM's host devices: one VM holds a device of the host." %}</p>{% endif %}
{% if usb_hostdevs or pci_hostdevs or other_hostdevs %}<p class="small text-body-secondary">{% trans "The clone gets none of the VM's host devices: one VM holds a device of the host." %}</p>{% endif %}
<form class="form" action="{% url 'instances:clone' instance.id %}" method="post" role="form" aria-label="Create clone form">{% csrf_token %}{% submission_key %}
<div class="row">
<label class="col-sm-3 col-form-label fw-normal">{% trans "Clone Name" %}</label>

View file

@ -69,7 +69,7 @@ class ConsoleListenerTests(TestCase):
proxy.get_console_listener_addr.return_value = "127.0.0.1"
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_hostdevs.return_value = ([], [], [])
proxy.get_status.return_value = 5
response = self.client.get(reverse("instances:instance", args=[self.vm.id]))
form = response.context["console_form"]

View file

@ -61,7 +61,7 @@ class ConsoleSettingsAccessTestCase(TestCase):
proxy.get_max_memory.return_value = 4096
proxy.get_networks.return_value = []
proxy.get_ifaces.return_value = []
proxy.get_hostdevs.return_value = ([], [])
proxy.get_hostdevs.return_value = ([], [], [])
proxy.get_storages.return_value = []
proxy.get_console_passwd.return_value = VNC_PASSWORD
proxy.get_console_type.return_value = "vnc"

View file

@ -38,7 +38,7 @@ def vm(running, saved, active=True, migratable=None):
the migratable XML marks it), and whose next start is saved."""
proxy = wvmInstance.__new__(wvmInstance)
proxy._read_cache = None
proxy.instance = MagicMock(**{"isActive.return_value": active})
proxy.instance = MagicMock(**{"isActive.return_value": active, "hasManagedSaveImage.return_value": 0})
def describe(flags=0):
if flags & libvirt.VIR_DOMAIN_XML_INACTIVE:
@ -53,9 +53,9 @@ class UsbHostdevTests(SimpleTestCase):
# the running VM writes the address libvirt resolved; only its migratable XML marks it
proxy = vm(domain(CONTROLLER, by_model("<address bus='1' device='3'/>")), domain(CONTROLLER, by_model()),
migratable=domain(CONTROLLER, by_model("<address bus='1' device='3'/>", " autoAddress='yes'")))
usb, others = proxy.get_hostdevs()
usb, pci, others = proxy.get_hostdevs()
self.assertEqual(usb, [{"vendor": "0x0627", "product": "0x0001", "address": None, "now": (1, 3), "next": True}])
self.assertEqual(others, [])
self.assertEqual((pci, others), ([], []))
def test_a_device_is_taken_from_each_definition_as_it_describes_it(self):
proxy = vm(domain(CONTROLLER, by_model("<address bus='1' device='3'/>")), domain(CONTROLLER, by_model()),
@ -93,13 +93,38 @@ class UsbHostdevTests(SimpleTestCase):
"<address type='pci' domain='0x0000' bus='0x00' slot='0x0c' function='0x1'/></source></actual></interface>")
mdev = "<hostdev mode='subsystem' type='mdev'><source><address uuid='{}'/></source></hostdev>"
running = domain(pci, nic, network_nic, mdev.format("00000000-0000-4000-8000-00000000a001"))
_, others = vm(running, domain(nic, mdev.format("00000000-0000-4000-8000-00000000a002"))).get_hostdevs()
self.assertEqual(others, [{"type": "pci", "address": "0000:00:0a.0", "now": True, "next": False},
{"type": "nic", "address": "0000:00:0b.0", "now": True, "next": True},
_, pci_rows, others = vm(running, domain(nic, mdev.format("00000000-0000-4000-8000-00000000a002"))).get_hostdevs()
self.assertEqual(pci_rows, [{"address": "0000:00:0a.0", "now": True, "next": False, "managed": False}])
self.assertEqual(others, [{"type": "nic", "address": "0000:00:0b.0", "now": True, "next": True},
{"type": "nic", "address": "0000:00:0c.1", "now": True, "next": False},
{"type": "mdev", "address": "00000000-0000-4000-8000-00000000a001", "now": True, "next": False},
{"type": "mdev", "address": "00000000-0000-4000-8000-00000000a002", "now": False, "next": True}])
def test_a_pci_device_is_given_and_taken_back_only_while_the_vm_is_shut_off(self):
proxy = vm("", domain(), active=False)
proxy.add_pci_hostdev("0000:05:00.0")
xml, flags = proxy.instance.attachDeviceFlags.call_args.args
self.assertEqual(flags, libvirt.VIR_DOMAIN_AFFECT_CONFIG)
self.assertEqual((etree.fromstring(xml).get("managed"), dict(etree.fromstring(xml).find("source/address").attrib)),
("yes", {"domain": "0x0000", "bus": "0x05", "slot": "0x00", "function": "0x0"}))
pci = "<hostdev mode='subsystem' type='pci' managed='yes'><source><address domain='0x0000' bus='0x05' slot='0x00' function='0x0'/></source></hostdev>"
proxy = vm("", domain(pci), active=False)
proxy.delete_pci_hostdev("0000:05:00.0")
self.assertEqual(proxy.instance.detachDeviceFlags.call_args.args[1], libvirt.VIR_DOMAIN_AFFECT_CONFIG)
with self.assertRaisesRegex(OperationError, "no PCI device 0000:06:00.0"):
proxy.delete_pci_hostdev("0000:06:00.0")
running = vm(domain(pci), domain(pci))
for change in (running.add_pci_hostdev, running.delete_pci_hostdev):
with self.assertRaisesRegex(OperationError, "Shut the VM down"):
change("0000:05:00.0")
running.instance.attachDeviceFlags.assert_not_called()
running.instance.detachDeviceFlags.assert_not_called()
# a saved state would start the VM without the change
saved = vm("", domain(pci), active=False)
saved.instance.hasManagedSaveImage.return_value = 1
with self.assertRaisesRegex(OperationError, "without a saved state"):
saved.add_pci_hostdev("0000:06:00.0")
def test_a_nic_that_is_a_host_device_is_left_to_the_xml_editor(self):
nic = "<interface type='hostdev'><mac address='52:54:00:00:00:0a'/><source><address type='pci' bus='0x00' slot='0x0a'/></source></interface>"
proxy = vm(domain(nic), domain(nic))
@ -142,17 +167,18 @@ class HostUsbViewTests(TestCase):
"XMLDesc.return_value": domain(by_model("<address bus='1' device='3'/>"))})
self.proxy.wvm.listAllDevices.return_value = [node(*n) for n in NODES]
self.proxy.domain_trees.side_effect = lambda: [("db-1", [etree.fromstring(other.XMLDesc())])]
self.proxy.get_hostdevs.return_value = ([], [], [])
def test_the_form_offers_what_can_be_given_and_says_why_not(self):
page = html.fromstring(self.client.get(reverse("instances:host_usb", args=[self.instance.id])).content)
options = {o.get("value"): (o.get("disabled") is not None, o.text_content()) for o in page.xpath("//option[@value!='']")}
page = html.fromstring(self.client.get(reverse("instances:host_devices", args=[self.instance.id])).content)
options = {o.get("value"): (o.get("disabled") is not None, o.text_content()) for o in page.xpath("//select[@name='usb_device']/option[@value!='']")}
self.assertEqual(sorted(options), ["1/1", "1/2", "1/3"])
self.assertTrue(options["1/1"][0] and "is a hub" in options["1/1"][1])
self.assertTrue(options["1/3"][0] and "is given to db-1" in options["1/3"][1])
self.assertFalse(options["1/2"][0])
# a device the VM has already
self.proxy.domain_trees.side_effect = lambda: [("kiosk-1", [etree.fromstring(domain(by_model("<address bus='1' device='2'/>")))])]
page = html.fromstring(self.client.get(reverse("instances:host_usb", args=[self.instance.id])).content)
page = html.fromstring(self.client.get(reverse("instances:host_devices", args=[self.instance.id])).content)
self.assertEqual(page.xpath("//option[@value='1/2']/@disabled"), ["disabled"])
def test_a_device_is_given_by_address_when_the_host_has_several_of_its_model(self):
@ -172,6 +198,23 @@ class HostUsbViewTests(TestCase):
self.client.post(reverse("instances:add_usb_hostdev", args=[self.instance.id]), {"usb_device": "1/2"})
self.proxy.add_usb_hostdev.assert_called_once_with("0x0627", "0x0001", None)
def test_a_pci_device_is_given_when_it_can_be(self):
url = reverse("instances:add_pci_hostdev", args=[self.instance.id])
# the host's own NIC: refused with the reason
response = self.client.post(url, {"pci_device": "0000:00:06.0"})
self.assertIn("holds the host's eth0", " ".join(str(m) for m in get_messages(response.wsgi_request)))
self.proxy.add_pci_hostdev.assert_not_called()
self.client.post(url, {"pci_device": "0000:00:0a.0"}) # bound to vfio-pci, alone in its group
self.proxy.add_pci_hostdev.assert_called_once_with("0000:00:0a.0")
self.client.post(reverse("instances:delete_pci_hostdev", args=[self.instance.id]), {"address": "0000:00:0a.0"})
self.proxy.delete_pci_hostdev.assert_called_once_with("0000:00:0a.0")
def test_the_pci_form_waits_for_a_shut_off_vm(self):
self.proxy.instance.isActive.return_value = True
page = html.fromstring(self.client.get(reverse("instances:host_devices", args=[self.instance.id])).content)
self.assertEqual(page.xpath("//select[@name='pci_device']/@disabled"), ["disabled"])
self.assertIn("Shut the VM down", page.text_content())
def test_a_device_is_taken_back_by_its_selector(self):
url = reverse("instances:delete_usb_hostdev", args=[self.instance.id])
self.client.post(url, {"vendor": "0x0627", "product": "0x0001", "address": ""})
@ -181,9 +224,13 @@ class HostUsbViewTests(TestCase):
def test_only_superusers(self):
self.client.force_login(get_user_model().objects.create_user("hd-user", "u@example.com", "pw"))
self.assertEqual(self.client.get(reverse("instances:host_usb", args=[self.instance.id])).status_code, 403)
self.assertEqual(self.client.get(reverse("instances:host_devices", args=[self.instance.id])).status_code, 403)
self.client.post(reverse("instances:add_usb_hostdev", args=[self.instance.id]), {"usb_device": "1/2"})
self.client.post(reverse("instances:add_pci_hostdev", args=[self.instance.id]), {"pci_device": "0000:00:0a.0"})
self.client.post(reverse("instances:delete_pci_hostdev", args=[self.instance.id]), {"address": "0000:00:0a.0"})
self.proxy.add_usb_hostdev.assert_not_called()
self.proxy.add_pci_hostdev.assert_not_called()
self.proxy.delete_pci_hostdev.assert_not_called()
class RevertTests(TestCase):

View file

@ -72,7 +72,7 @@ class PageControls:
"get_media_devices", "get_net_devices", "get_snapshot",
"get_snapshot_jobs"):
getattr(proxy, getter).return_value = []
proxy.get_hostdevs.return_value = ([], [])
proxy.get_hostdevs.return_value = ([], [], [])
proxy.get_console_type.return_value = "vnc"
proxy.get_status.return_value = status
response = self.client.get(reverse("instances:instance", args=[self.instance.id]))

View file

@ -47,7 +47,7 @@ class PendingEditsTestCase(TestCase):
for getter in ("get_networks", "get_ifaces", "get_storages", "get_media_devices", "get_net_devices",
"get_snapshot", "get_snapshot_jobs"):
getattr(proxy, getter).return_value = []
proxy.get_hostdevs.return_value = ([], [])
proxy.get_hostdevs.return_value = ([], [], [])
proxy.get_disk_devices.side_effect = lambda **kw: config if kw.get("config") else live
proxy.get_all_qos.side_effect = lambda **kw: qos[1] if kw.get("config") else qos[0]
proxy.get_console_type.return_value = "vnc"

View file

@ -205,7 +205,7 @@ class DetailPageQuotaTests(TestCase):
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_hostdevs.return_value = ([], [], [])
proxy.get_status.return_value = 5
response = self.client.get(reverse("instances:instance", args=[vm.id]))
self.assertEqual(response.status_code, 200)

View file

@ -101,7 +101,7 @@ class SnapshotTabTestCase(TestCase):
for getter in ("get_networks", "get_ifaces", "get_storages", "get_disk_devices",
"get_media_devices", "get_net_devices"):
getattr(proxy, getter).return_value = []
proxy.get_hostdevs.return_value = ([], [])
proxy.get_hostdevs.return_value = ([], [], [])
proxy.get_snapshot.side_effect = lambda flag: {
libvirt.VIR_DOMAIN_SNAPSHOT_LIST_INTERNAL: list(internal),
libvirt.VIR_DOMAIN_SNAPSHOT_LIST_EXTERNAL: list(external),

View file

@ -221,7 +221,7 @@ class DetailStateTests(TestCase):
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_hostdevs.return_value = ([], [], [])
proxy.get_status.return_value = state
page = self.client.get(reverse("instances:instance", args=[vm.id])).content.decode()
self.assertIn(f'">{label}</span>', page.replace("\n", "").replace(" ", ""))

View file

@ -137,7 +137,7 @@ ALLOWED_HTML_SINKS = {
("accounts/templates/login.html", "$btn.html("): "static spinner markup",
("accounts/templates/accounts/otp_login.html", "$btn.html("): "static spinner markup",
("instances/templates/instance.html", "//sto_input.innerHTML = pool;"): "comment",
("instances/templates/instance.html", "hostUsb.innerHTML = html;"): "the panel's own fragment, host_usb_form.html, escaped by Django",
("instances/templates/instance.html", "hostDevices.innerHTML = html;"): "the panel's own fragment, host_devices_form.html, escaped by Django",
}

View file

@ -57,9 +57,11 @@ urlpatterns = [
path("<int:pk>/change_network/", views.change_network, name="change_network"),
path("<int:pk>/add_network/", views.add_network, name="add_network"),
path("<int:pk>/delete_network/", views.delete_network, name="delete_network"),
path("<int:pk>/host_usb/", views.host_usb, name="host_usb"),
path("<int:pk>/host_devices/", views.host_devices, name="host_devices"),
path("<int:pk>/add_usb_hostdev/", views.add_usb_hostdev, name="add_usb_hostdev"),
path("<int:pk>/delete_usb_hostdev/", views.delete_usb_hostdev, name="delete_usb_hostdev"),
path("<int:pk>/add_pci_hostdev/", views.add_pci_hostdev, name="add_pci_hostdev"),
path("<int:pk>/delete_pci_hostdev/", views.delete_pci_hostdev, name="delete_pci_hostdev"),
path("<int:pk>/set_link_state/", views.set_link_state, name="set_link_state"),
path("<int:pk>/set_qos/", views.set_qos, name="set_qos"),
path("<int:pk>/unset_qos/", views.unset_qos, name="unset_qos"),

View file

@ -49,7 +49,7 @@ from vrtManager import util
from vrtManager.create import cpu_choices, wvmCreate
from vrtManager.instance import USAGE_MAX_WINDOW
from vrtManager.interface import wvmInterface
from vrtManager.nodedevs import hostdev_problems, node_devices, usb_names
from vrtManager.nodedevs import device_names, hostdev_problems, node_devices, pci_problems
from vrtManager.storage import wvmStorage
from vrtManager.util import randomPasswd
@ -309,13 +309,15 @@ def _instance_page(request, pk, instance, compute):
instance.drbd = drbd_status(request, pk)
instance.save()
usb_hostdevs, other_hostdevs = instance.proxy.get_hostdevs()
if usb_hostdevs:
names = usb_names(instance.proxy)
usb_hostdevs, pci_hostdevs, other_hostdevs = instance.proxy.get_hostdevs()
if usb_hostdevs or pci_hostdevs:
names = device_names(instance.proxy)
for row in usb_hostdevs:
row["name"] = names.get((row["vendor"], row["product"]), "")
for row in pci_hostdevs:
row["name"] = names.get(row["address"], "")
# owners see the devices their VM has; only superusers change them
show_hostdevs = request.user.is_superuser or bool(usb_hostdevs or other_hostdevs)
show_hostdevs = request.user.is_superuser or bool(usb_hostdevs or pci_hostdevs or other_hostdevs)
show_settings = show_settings or show_hostdevs
job_resource = claims.instance_key(instance.uuid)
@ -1795,30 +1797,42 @@ def delete_network(request, pk):
return _back(request, pk, "network")
def _host_usb(instance):
"""The host's USB devices, each with why it cannot be given to the VM
(hostdev_problems; none: it can) and how the VM would name it: by its
address when the host has more than one of its model, else by model."""
_pci, usb = node_devices(instance.proxy)
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
named by its address when the host has more than one of its model, else
by model; a PCI device is checked with the managed PCI devices of the
VM's next start, as libvirt takes them from the host along with it."""
pci, usb = node_devices(instance.proxy)
own_pci = instance.proxy.get_hostdevs()[1]
managed = {row["address"] for row in own_pci if row["managed"] and row["next"]}
by_address = {device["address"]: device for device in pci}
for device in pci:
device["problems"] = pci_problems(instance.name, device, by_address, managed | {device["address"]})
if device["address"] in {row["address"] for row in own_pci}:
device["problems"].append(_("The VM has it"))
for device in usb:
address = (device["bus"], device["device"]) if device["same_model"] else None
device["selector"] = (*device["model"], address)
device["problems"] = hostdev_problems(instance.name, [], [device], set(), [device["selector"]])
device["problems"] = hostdev_problems(instance.name, pci, [device], set(), [device["selector"]])
if instance.name in device["vms"]:
device["problems"].append(_("The VM has it"))
return usb
return pci, usb
@superuser_only
def host_usb(request, pk):
"""The add form of the Host devices tab, loaded when the tab opens: its
choices scan every VM of the host."""
def host_devices(request, pk):
"""The add forms of the Host devices tab, loaded when the tab opens:
their choices scan every VM of the host."""
instance = get_instance(request.user, pk)
try:
context = {"instance": instance, "host_usb": _host_usb(instance)}
pci, usb = _host_devices(instance)
domain = instance.proxy.instance
context = {"instance": instance, "host_pci": pci, "host_usb": usb,
"running": domain.isActive() or domain.hasManagedSaveImage(0)}
except libvirtError as err:
context = {"instance": instance, "error": err}
return render(request, "instances/host_usb_form.html", context)
return render(request, "instances/host_devices_form.html", context)
@require_POST
@ -1829,7 +1843,7 @@ def add_usb_hostdev(request, pk):
claim, so no other VM gets it meanwhile."""
instance = get_instance(request.user, pk)
chosen = request.POST.get("usb_device", "")
device = next((d for d in _host_usb(instance) if f"{d['bus']}/{d['device']}" == chosen), None)
device = next((d for d in _host_devices(instance)[1] if f"{d['bus']}/{d['device']}" == chosen), None)
if device is None:
messages.error(request, _("The host has no USB device %(device)s") % {"device": chosen})
elif device["problems"]:
@ -1841,6 +1855,36 @@ def add_usb_hostdev(request, pk):
return _back(request, pk, "hostdevs")
@require_POST
@superuser_only
@serialize_compute_mutation
def add_pci_hostdev(request, pk):
"""Gives the shut-off VM a PCI device of its host; checked under the
compute's claim, so no other VM gets it or its IOMMU group meanwhile."""
instance = get_instance(request.user, pk)
chosen = request.POST.get("pci_device", "")
device = next((d for d in _host_devices(instance)[0] if d["address"] == chosen), None)
if device is None:
messages.error(request, _("The host has no PCI device %(device)s") % {"device": chosen})
elif device["problems"]:
messages.error(request, "; ".join(device["problems"]))
else:
with audit_vm(request, instance, f"add PCI device {device['address']} ({device['product']})"):
instance.proxy.add_pci_hostdev(device["address"])
return _back(request, pk, "hostdevs")
@require_POST
@superuser_only
@serialize_instance_mutation
def delete_pci_hostdev(request, pk):
instance = get_instance(request.user, pk)
address = request.POST.get("address", "")
with audit_vm(request, instance, f"remove PCI device {address}"):
instance.proxy.delete_pci_hostdev(address)
return _back(request, pk, "hostdevs")
@require_POST
@superuser_only
@serialize_instance_mutation