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

feat(instances): a superuser limits a disk's I/O

One VM's busy disk could take its storage from all the others. Under a
disk's Device details on the Disks tab a superuser sets an I/O limit, IOPS
and MiB/s for reads and writes together (0: none). libvirt applies it to each
definition that has the disk: the running VM's at once, and the one for its
next start; a transient VM's live only. A disk whose tuning is more than this
(a throttle group, a burst, read and write apart, bytes not whole MiB/s)
shows "Set in the VM's XML" and is changed there; a disk the next start
replaces is refused until then.
This commit is contained in:
catborise 2026-11-20 10:33:49 +03:00
parent 79f3b906dd
commit 2b60b79a5f
11 changed files with 1016 additions and 620 deletions

View file

@ -866,6 +866,7 @@ What an update from an older version changes for operators and users. `manage.py
- A template VM is changed or deleted only by superusers and staff owners with the matching permission; other owners can still view, open the console and clone it.
- On a running VM the edit forms show the settings as they will be at the next start, so saving an edit no longer reverts another pending change.
- External snapshots need libvirt 9.9 or newer on the computes. libvirt 9.10 (openEuler 24.03 LTS) refuses to revert a snapshot taken without memory of a running or paused VM ("Invalid target domain state 'disk-snapshot'"); 11.10 reverts it. A VM's snapshots form one chain: after a revert, delete the newer snapshots before taking another. An internal snapshot is reverted only on a shut-off VM. Snapshot names no longer get an `s1.` prefix. A snapshot an older version took of a UEFI VM can only be deleted, not reverted. On NFS, the qemu user needs write access to the image directory to remove merged snapshot files.
- A superuser limits a disk's I/O (IOPS and MiB/s, reads and writes together) under its Device details on the Disks tab; a running VM gets the limit at once.
- A storage volume a VM still needs (a disk, a backing file or a snapshot's file) is not deleted; deleting a VM with its files keeps a file another compute's VM or volume uses at the same path, and is refused before the VM is stopped when one of the other computes cannot be reached. A pool's page names the VMs of its host that use each volume and lists those the host does not use.
- A VM that vanishes from its compute, or whose compute is deleted, keeps its owners, tags, protection and schedules for `INSTANCE_OWNERSHIP_RETENTION_DAYS` (30) in case the same UUID comes back, and its backups are linked to it again; superusers manage these records on the "Removed VMs" page.
- The Logs page records who changed what (computes, users, groups, VM owners, settings, SSH keys, host networks, pools, volumes, interfaces, secrets and network filters), every login, failed login and lockout, and every page or API call answered 401 or 403 to a signed-in user or a request with credentials, with the address and the result (a VM hidden with 404 is not logged).

View file

@ -195,6 +195,12 @@ class Instance(models.Model):
edit does not post the live value back over it."""
return self.proxy.get_disk_devices(config=True)
@cached_property
def live_custom_iotune(self) -> set:
"""The disks whose running definition has I/O tuning set in the XML (custom_iotune): the
Disks tab shows the next start's, and set_disk_limit refuses these too."""
return {disk["dev"] for disk in self.disks if disk.get("iotune_custom")}
@cached_property
def config_vcpu(self) -> int:
"""vCPUs of the persistent definition, which the CPU form changes."""

View file

@ -261,8 +261,27 @@
<dt class="col-6 fw-normal text-body-secondary">{% trans "Detect zeroes" %}</dt><dd class="col-6 mb-1">{{ disk.detect_zeroes }}</dd>
<dt class="col-6 fw-normal text-body-secondary">{% trans "Serial" %}</dt><dd class="col-6 mb-1">{{ disk.serial|default:"—" }}</dd>
<dt class="col-6 fw-normal text-body-secondary">{% trans "Read-only" %}</dt><dd class="col-6 mb-1">{{ disk.readonly|yesno }}</dd>
<dt class="col-6 fw-normal text-body-secondary">{% trans "Shareable" %}</dt><dd class="col-6 mb-0">{{ disk.shareable|yesno }}</dd>
<dt class="col-6 fw-normal text-body-secondary">{% trans "Shareable" %}</dt><dd class="col-6 mb-1">{{ disk.shareable|yesno }}</dd>
<dt class="col-6 fw-normal text-body-secondary">{% trans "I/O limit" %}</dt>
<dd class="col-6 mb-0">{% if disk.iotune_custom or disk.dev in instance.live_custom_iotune %}{% trans "Set in the VM's XML" %}{% elif disk.iops or disk.mibps %}{% blocktrans with iops=disk.iops|default:"–" mibps=disk.mibps|default:"–" %}{{ iops }} IOPS, {{ mibps }} MiB/s{% endblocktrans %}{% else %}{% trans "None" %}{% endif %}</dd>
</dl>
{% if request.user.is_superuser and not disk.iotune_custom and disk.dev not in instance.live_custom_iotune %}
{# reads and writes together; applied at once on a running VM #}
<form class="d-flex flex-wrap align-items-end gap-2 mt-2" action="{% url 'instances:set_disk_limit' instance.id %}" method="post">{% csrf_token %}
<input type="hidden" name="dev" value="{{ disk.dev }}">
<input type="hidden" name="path" value="{{ disk.path|default:'' }}">
<div>
<label class="form-label mb-1" for="iops-{{ disk.dev }}">{% trans "IOPS" %}</label>
<input class="form-control form-control-sm" type="number" min="0" max="10000000" name="iops" id="iops-{{ disk.dev }}" value="{{ disk.iops }}" required style="width: 8rem">
</div>
<div>
<label class="form-label mb-1" for="mibps-{{ disk.dev }}">{% trans "MiB/s" %}</label>
<input class="form-control form-control-sm" type="number" min="0" max="1000000" name="mibps" id="mibps-{{ disk.dev }}" value="{{ disk.mibps }}" required style="width: 8rem">
</div>
<button type="submit" class="btn btn-sm btn-outline-secondary">{% trans "Set the limit" %}</button>
<span class="form-text w-100 mt-0">{% trans "Reads and writes together; 0: no limit. A running VM gets it at once." %}</span>
</form>
{% endif %}
</details>
</article>
{% endfor %}

View file

@ -0,0 +1,167 @@
"""A disk's I/O limit (IOPS and MiB/s, reads and writes together; 0: none):
set by a superuser on the Disks tab, at once on a running VM and from its next start."""
from unittest.mock import MagicMock, patch
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from django.contrib.messages import get_messages
from libvirt import VIR_DOMAIN_AFFECT_CONFIG, VIR_DOMAIN_AFFECT_LIVE, VIR_DOMAIN_XML_INACTIVE, libvirtError
from accounts.models import UserInstance
from instances.models import Instance
from instances.tests import test_pending_edits
from instances.tests.test_pending_edits import disk
from logs.models import Logs
from vrtManager import util
from vrtManager.instance import wvmInstance
def limited(dev, iops=0, mibps=0):
return {**disk(dev, "default", ""), "iops": iops, "mibps": mibps, "iotune_custom": False}
class DiskLimitTestCase(TestCase):
setUp = test_pending_edits.PendingEditsTestCase.setUp
page = test_pending_edits.PendingEditsTestCase.page # the VM page with its host faked
def post(self, data):
with patch.object(Instance, "proxy", MagicMock()) as proxy:
proxy.get_disk_devices.return_value = [limited("vda")]
response = self.client.post(reverse("instances:set_disk_limit", args=[self.instance.id]),
{"path": "/pool/vda.qcow2", **data})
return response, proxy
def test_a_superuser_sets_it_in_bytes(self):
_response, proxy = self.post({"dev": "vda", "iops": "500", "mibps": "100"})
proxy.set_disk_limit.assert_called_once_with("vda", 500, 100 * 2**20)
self.assertEqual(Logs.objects.get(instance="pe-vm").message.split(": ")[-1], "disk vda I/O limit 500 IOPS, 100 MiB/s")
def test_a_wrong_or_missing_value_is_refused(self):
# a missing one would clear its limit; "²" is a digit to Python but not a number
for data in ({"dev": "vda", "iops": "-1", "mibps": "0"}, {"dev": "vda", "iops": "x", "mibps": "0"},
{"dev": "vda", "iops": "²", "mibps": "0"}, {"dev": "vda", "iops": "1"},
{"dev": "vda", "iops": "0", "mibps": "1000001"}, {"dev": "vda", "iops": "9" * 5000, "mibps": "0"}):
with self.subTest(data=data):
response, proxy = self.post(data)
proxy.set_disk_limit.assert_not_called()
self.assertIn("whole numbers of IOPS and MiB/s", " ".join(map(str, get_messages(response.wsgi_request))))
def test_what_libvirt_refuses_is_told(self):
# the panel's own refusal and libvirt's: a message on the Disks tab, not an error page
for error in (util.OperationError("The VM has a saved state: start it, then set the limit"),
libvirtError("unsupported configuration: block I/O throttling is not supported")):
with self.subTest(error=error), patch.object(Instance, "proxy", MagicMock()) as proxy:
self.client.cookies.pop("messages", None) # each case's own message
proxy.get_disk_devices.return_value = [limited("vda")]
proxy.set_disk_limit.side_effect = error
response = self.client.post(reverse("instances:set_disk_limit", args=[self.instance.id]),
{"dev": "vda", "path": "/pool/vda.qcow2", "iops": "1", "mibps": "1"})
self.assertRedirects(response, reverse("instances:instance", args=[self.instance.id]) + "#disks",
fetch_redirect_response=False)
self.assertEqual([str(m) for m in get_messages(response.wsgi_request)], [str(error)])
def test_a_disk_replaced_since_the_page_was_loaded_is_not_tuned(self):
response, proxy = self.post({"dev": "vda", "path": "/pool/old.qcow2", "iops": "1", "mibps": "1"})
proxy.set_disk_limit.assert_not_called()
self.assertIn("has changed since the page was loaded", " ".join(map(str, get_messages(response.wsgi_request))))
def test_an_owner_may_not(self):
owner = get_user_model().objects.create_user("dl-owner", password="x")
UserInstance.objects.create(instance=self.instance, user=owner, is_change=True)
self.client.force_login(owner)
response, proxy = self.post({"dev": "vda", "iops": "0", "mibps": "0"})
self.assertEqual(response.status_code, 403)
proxy.set_disk_limit.assert_not_called()
def test_the_disk_tells_its_limit(self):
doc = self.page(live=[limited("vda", 500, 100)], config=[limited("vda", 500, 100)])
text = " ".join(doc.xpath("string(//article[@aria-labelledby='disk-vda'])").split())
self.assertIn("I/O limit 500 IOPS, 100 MiB/s", text)
(form,) = doc.xpath("//form[@action=$a]", a=reverse("instances:set_disk_limit", args=[self.instance.id]))
self.assertEqual(form.xpath(".//input[@name='iops']/@value"), ["500"])
self.assertEqual(form.xpath(".//input[@name='mibps']/@value"), ["100"])
# tuning set in the XML, of the next start or of the running VM alone: no form
custom = {**limited("vda"), "iotune_custom": True}
for live, config in (([custom], [custom]), ([custom], [limited("vda")])):
doc = self.page(live=live, config=config)
self.assertIn("Set in the VM's XML", doc.text_content())
self.assertFalse(doc.xpath("//form[@action=$a]", a=reverse("instances:set_disk_limit", args=[self.instance.id])))
def domain(*disks):
return "<domain><devices>" + "".join(disks) + "</devices></domain>"
def disk_xml(dev="vda", source="/pool/vda.qcow2", iotune=""):
return (f"<disk type='file' device='disk'><source file='{source}'/><target dev='{dev}' bus='virtio'/>"
f"{f'<iotune>{iotune}</iotune>' if iotune else ''}</disk>")
class SetDiskLimitTestCase(TestCase):
"""The flags and refusals of wvmInstance.set_disk_limit, from the VM's two definitions."""
def vm(self, live, config, active=1, persistent=1):
vm = wvmInstance.__new__(wvmInstance) # no connection: only these calls
vm.instance = MagicMock(**{"isActive.return_value": active, "isPersistent.return_value": persistent,
"hasManagedSaveImage.return_value": 0})
vm.instance.XMLDesc.side_effect = lambda flags: config if flags & VIR_DOMAIN_XML_INACTIVE else live
return vm
def flags(self, vm):
vm.set_disk_limit("vda", 500, 2**20)
dev, params, flags = vm.instance.setBlockIoTune.call_args.args
self.assertEqual((dev, params), ("vda", {"total_iops_sec": 500, "total_bytes_sec": 2**20}))
return flags
def test_each_definition_that_has_the_disk(self):
both = domain(disk_xml())
self.assertEqual(self.flags(self.vm(both, both)), VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)
self.assertEqual(self.flags(self.vm(both, both, active=0)), VIR_DOMAIN_AFFECT_CONFIG)
self.assertEqual(self.flags(self.vm(both, both, persistent=0)), VIR_DOMAIN_AFFECT_LIVE) # transient
self.assertEqual(self.flags(self.vm(domain(), both)), VIR_DOMAIN_AFFECT_CONFIG) # attached for the next start
# a running VM's source has more attributes: the same disk all the same
running = domain(disk_xml().replace("<source file='/pool/vda.qcow2'/>", "<source file='/pool/vda.qcow2' index='1'/>"))
self.assertEqual(self.flags(self.vm(running, both)), VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)
def test_refused(self):
for case, live, config, text in (
("no such disk", domain(), domain(), "no disk vda"),
("another disk at the next start", domain(disk_xml()), domain(disk_xml(source="/pool/new.qcow2")),
"another disk from the next start"),
("a throttle group", domain(disk_xml(iotune="<total_iops_sec>5</total_iops_sec><group_name>db</group_name>")),
domain(), "VM's XML"),
("a throttle filter", domain(), domain(disk_xml().replace(
"</disk>", "<throttlefilters><throttlefilter group='db'/></throttlefilters></disk>")), "VM's XML"),
("past the form's range", domain(disk_xml(iotune="<total_iops_sec>10000001</total_iops_sec>")), domain(),
"VM's XML"),
("another pool's volume of that name",
domain("<disk type='volume' device='disk'><source pool='old' volume='root.qcow2'/><target dev='vda'/></disk>"),
domain("<disk type='volume' device='disk'><source pool='new' volume='root.qcow2'/><target dev='vda'/></disk>"),
"another disk from the next start"),
("a burst", domain(disk_xml(iotune="<total_iops_sec>5</total_iops_sec><total_iops_sec_max>9</total_iops_sec_max>")),
domain(), "VM's XML"),
("read and write apart", domain(), domain(disk_xml(iotune="<read_iops_sec>5</read_iops_sec>")), "VM's XML"),
("not whole MiB/s", domain(disk_xml(iotune="<total_bytes_sec>524288</total_bytes_sec>")), domain(), "VM's XML"),
):
with self.subTest(case):
vm = self.vm(live, config)
with self.assertRaisesRegex(util.OperationError, text):
vm.set_disk_limit("vda", 500, 2**20)
vm.instance.setBlockIoTune.assert_not_called()
def test_a_saved_state_is_resumed_first(self):
# it would resume with the saved definition and its old limit
vm = self.vm(domain(), domain(disk_xml()), active=0)
vm.instance.hasManagedSaveImage.return_value = 1
with self.assertRaisesRegex(util.OperationError, "saved state"):
vm.set_disk_limit("vda", 500, 2**20)
vm.instance.setBlockIoTune.assert_not_called()
def test_the_disk_reads_its_limit(self):
vm = self.vm(None, domain(disk_xml(iotune="<total_iops_sec>500</total_iops_sec><total_bytes_sec>104857600</total_bytes_sec>"
"<read_bytes_sec>0</read_bytes_sec>"),
disk_xml("vdb", "/pool/vdb.qcow2", "<total_iops_sec>5</total_iops_sec><group_name>db</group_name>"), disk_xml("vdc", "/pool/vdc.qcow2")))
with patch.object(wvmInstance, "_volume_details", return_value=None):
disks = {d["dev"]: (d["iops"], d["mibps"], d["iotune_custom"]) for d in vm.get_disk_devices(config=True)}
self.assertEqual(disks, {"vda": (500, 100, False), "vdb": (5, 0, True), "vdc": (0, 0, False)})

View file

@ -79,6 +79,7 @@ urlpatterns = [
path("<int:pk>/change_options/", views.change_options, name="change_options"),
path("<int:pk>/set_template/", views.set_template, name="set_template"),
path("<int:pk>/set_protected/", views.set_protected, name="set_protected"),
path("<int:pk>/set_disk_limit/", views.set_disk_limit, name="set_disk_limit"),
path("<int:pk>/set_tags/", views.set_tags, name="set_tags"),
path(
"<int:pk>/getvvfile/", views.getvvfile, name="getvvfile"

View file

@ -59,7 +59,7 @@ from webvirtcloud.middleware import error_text, same_origin_referer
from vrtManager import util
from vrtManager.connection import CONNECT_TIMEOUT
from vrtManager.create import cpu_choices, wvmCreate
from vrtManager.instance import USAGE_MAX_WINDOW, VIR_ERR_AGENT_COMMAND_TIMEOUT, wvmInstances
from vrtManager.instance import BYTES_MAX, IOPS_MAX, USAGE_MAX_WINDOW, VIR_ERR_AGENT_COMMAND_TIMEOUT, wvmInstances
from vrtManager.interface import wvmInterface
from vrtManager.nodedevs import (check_hostdevs, device_names, hostdev_problems, hostdev_users, managed_pci,
node_devices, pci_problems, usb_unmatched)
@ -2547,6 +2547,29 @@ def set_template(request, pk):
return _back(request, pk, "options")
@require_POST
@superuser_only
@serialize_instance_mutation
def set_disk_limit(request, pk):
"""A disk's I/O limit, IOPS and MiB/s (0: none), at once on a running VM and from its next start."""
instance = get_instance(request.user, pk)
dev = request.POST.get("dev", "")
iops, mibps = (request.POST.get(field, "").strip() for field in ("iops", "mibps"))
# both given, as plain digits: a missing one would clear its limit
if not all(value.isascii() and value.isdigit() and len(value) <= 8 for value in (iops, mibps)) \
or int(iops) > IOPS_MAX or int(mibps) * 2**20 > BYTES_MAX:
messages.error(request, _("An I/O limit is whole numbers of IOPS and MiB/s, 0 for none"))
return _back(request, pk, "disks")
if _disk_changed(request, instance.config_disks): # the form's disk was replaced since
return _back(request, pk, "disks")
try:
with audit_vm(request, instance, f"disk {dev} I/O limit {int(iops)} IOPS, {int(mibps)} MiB/s"):
instance.proxy.set_disk_limit(dev, int(iops), int(mibps) * 2**20)
except libvirtError as err: # the panel's refusals (OperationError) and libvirt's
messages.error(request, error_text(request, err))
return _back(request, pk, "disks")
@require_POST
@superuser_only
@serialize_instance_mutation # not while a deletion or a restore over it runs: it would not stop them

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

@ -689,6 +689,38 @@ def check_snapshot_name(name):
raise util.OperationError(gettext_noop("Snapshot names are 1-64 letters, digits, '.', '_' or '-' and do not start with '.'"))
# the most the Disks tab's form takes (instances.views.set_disk_limit): IOPS, and bytes/s (MiB/s whole)
IOPS_MAX, BYTES_MAX = 10**7, 10**6 * 2**20
def custom_iotune(disk):
"""Whether a disk element's I/O tuning is more than set_disk_limit sets: a
throttle group or filter, a burst or size, separate read and write limits,
or totals the form cannot show (bytes not whole MiB/s, past its range).
Such tuning is changed in the VM's XML."""
if disk.xpath("throttlefilters/*"):
return True
for element in disk.xpath("iotune/*"):
value = (element.text or "0").strip()
if element.tag == "total_iops_sec" and value.isdigit() and int(value) <= IOPS_MAX:
continue
if element.tag == "total_bytes_sec" and value.isdigit() and int(value) <= BYTES_MAX and int(value) % 2**20 == 0:
continue
if element.tag == "group_name" or value != "0":
return True
return False
def disk_source(disk):
"""A disk element's storage, to tell two definitions' disks apart: its type
and its source's attributes and hosts, not those a running VM adds (index)."""
source = disk.find("source")
if source is None:
return disk.get("type"), ()
return (disk.get("type"), tuple(sorted((k, v) for k, v in source.attrib.items() if k != "index")),
tuple(tuple(sorted(host.attrib.items())) for host in source.findall("host")))
def agent_command(dom, command, arguments=None):
"""The answer of one guest agent command that waits AGENT_TIMEOUT seconds
at most: libvirt's own calls for it wait for a hung agent indefinitely,
@ -1084,6 +1116,8 @@ class wvmInstance(wvmConnect):
disk_cache = disk_io = disk_discard = disk_zeroes = "default"
readonly = shareable = serial = None
backing_file = None
iops = mibps = 0
iotune_custom = False
device = disk.xpath("@device")[0]
if device == "disk":
@ -1118,6 +1152,11 @@ class wvmInstance(wvmConnect):
with contextlib.suppress(Exception):
backing_file = disk.xpath("backingStore/source/@file")[0]
with contextlib.suppress(ValueError): # set_disk_limit's; 0: none
iops = int(disk.findtext("iotune/total_iops_sec") or 0)
mibps = int(disk.findtext("iotune/total_bytes_sec") or 0) // 2**20
iotune_custom = custom_iotune(disk)
readonly = bool(disk.xpath("readonly"))
shareable = bool(disk.xpath("shareable"))
serial = (
@ -1157,6 +1196,9 @@ class wvmInstance(wvmConnect):
"readonly": readonly,
"shareable": shareable,
"serial": serial,
"iops": iops,
"mibps": mibps,
"iotune_custom": iotune_custom,
}
)
return result
@ -1164,6 +1206,32 @@ class wvmInstance(wvmConnect):
flags = VIR_DOMAIN_XML_INACTIVE | VIR_DOMAIN_XML_SECURE if config else 0
return util.get_xml_path(self._XMLDesc(flags), func=disks)
def set_disk_limit(self, dev, iops, bytes_sec):
"""Limits disk dev to iops and bytes_sec, reads and writes together (0: no limit), in each
definition that has it: the running VM's, at once, and the one for its next start. Refused
for tuning set in the XML (custom_iotune), and for a disk the next start changes."""
if not self.instance.isActive() and self.instance.hasManagedSaveImage(0):
# it would resume with the saved definition, and its limit then
raise util.OperationError(gettext_noop("The VM has a saved state: start it, then set the limit"))
flags, sources = 0, set()
for affect, has, xml_flags in ((VIR_DOMAIN_AFFECT_LIVE, self.instance.isActive(), 0),
(VIR_DOMAIN_AFFECT_CONFIG, self.instance.isPersistent(), VIR_DOMAIN_XML_INACTIVE)):
disk = etree.fromstring(self.instance.XMLDesc(xml_flags)).xpath(
"devices/disk[@device='disk'][target/@dev=$dev]", dev=dev) if has else []
if not disk:
continue
if custom_iotune(disk[0]):
raise util.OperationError(gettext_noop("The I/O tuning of %(dev)s is set in the VM's XML: change it there"),
dev=dev)
sources.add(disk_source(disk[0]))
flags |= affect
if not flags:
raise util.OperationError(gettext_noop("The VM has no disk %(dev)s"), dev=dev)
if len(sources) > 1:
raise util.OperationError(gettext_noop("%(dev)s is another disk from the next start: set its limit then"),
dev=dev)
self.instance.setBlockIoTune(dev, {"total_iops_sec": iops, "total_bytes_sec": bytes_sec}, flags)
def _volume_details(self, path):
"""(name, capacity, allocation, pool name) of the volume at path, or
None when no pool holds it."""