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

feat(migrations): a migration's bandwidth can be capped

A migration took all the network it could, its disk copies too, and the VMs
on both hosts felt it. Settings has a Migrations group with "Migration
bandwidth" (MiB/s, 0: libvirt's default, the default); every migration, by
hand, in bulk or for maintenance, passes it to libvirt, and its log line
names it. libvirt applies it to the memory until the final switchover and to
each copied disk on its own; the help and README say so. A refused setting
is now named in the page's language.
This commit is contained in:
catborise 2026-11-20 09:17:45 +03:00
parent 46931bdbdb
commit 3da55342da
14 changed files with 438 additions and 333 deletions

View file

@ -334,6 +334,7 @@ Firewall: the compute's VNC ports (`5900`–`65535`) must accept connections **o
- **Without shared storage:** after choosing the destination, the **Disks** list shows each disk and the destination pools that can take a copy (directory, filesystem and NFS pools; a pool with a file of the same name refuses it); a disk on storage both hosts share can stay there. Plain raw or qcow2 disks without a backing file are copied, through the destination's migration port range (49152-49215 by default). **Delete the source files of copied disks** removes them after the migration, unless another VM or volume uses them.
- **Shut-off VMs:** a shut-off VM moves offline, with its NVRAM file (UEFI). When its disks are copied or it has a TPM, it is started paused for the migration instead (its CPUs never run) and shut off on the destination.
- **Encryption:** QEMU sends a VM's memory and copied disks in the clear. With **Encrypt migrations (TLS)** ticked on both hosts' edit pages (Advanced), it sends them over TLS. Each host needs QEMU's certificates from one CA: `ca-cert.pem`, `server-cert.pem`, `server-key.pem`, `client-cert.pem` and `client-key.pem` in `/etc/pki/qemu`, readable by QEMU (owner `root`, group the one QEMU runs as: `qemu` on the RHEL family and openSUSE, `kvm` on Debian and Ubuntu; keys `0640`), the server certificate naming the host's migration address (or the address the panel reaches it at) as it is written there, a name or an IP. A host without them refuses the migration before anything moves: `Unable to access credentials /etc/pki/qemu/ca-cert.pem`.
- **Bandwidth:** **Settings → Migrations** gives libvirt a limit in MiB/s, so a migration leaves room for the VMs' own traffic. It applies to the memory transfer until the final switchover and to each copied disk on its own (two disks may take twice it); a shut-off VM's UEFI variables file is not limited. 0 leaves libvirt's default, no limit unless one was set on the host.
If libvirt warns `Host SMBIOS information is not available`, install `dmidecode` (`apt-get`, `dnf` or `zypper install -y dmidecode`) and restart `libvirtd` (`virtqemud` on the RHEL family 10).

View file

@ -0,0 +1,29 @@
from django.core.management.color import no_style
from django.db import migrations
from django.utils.translation import gettext_noop as _
SETTING = (_("Migration bandwidth"), "MIGRATION_BANDWIDTH", "0",
_("MiB/s for the memory and each copied disk, not the final switchover; 0: libvirt's default"))
def add_setting(apps, schema_editor):
setting = apps.get_model("appsettings", "AppSettings")
db_alias = schema_editor.connection.alias
# see 0014: move a PostgreSQL id sequence past the fixed ids first
with schema_editor.connection.cursor() as cursor:
for sql in schema_editor.connection.ops.sequence_reset_sql(no_style(), [setting]):
cursor.execute(sql)
name, key, value, description = SETTING
setting.objects.using(db_alias).get_or_create(
key=key, defaults={"name": name, "value": value, "choices": "", "description": description})
def del_setting(apps, schema_editor):
apps.get_model("appsettings", "AppSettings").objects.using(schema_editor.connection.alias).filter(
key=SETTING[1]).delete()
class Migration(migrations.Migration):
dependencies = [("appsettings", "0027_alert_settings")]
operations = [migrations.RunPython(add_setting, del_setting)]

View file

@ -72,6 +72,11 @@ class AppSettingsTestCase(TestCase):
self.assertEqual(AppSettings.objects.get(key="WORKER_CONCURRENCY").value, "4")
self.assertTrue(any("between 1 and 16" in str(m) for m in get_messages(response.wsgi_request)))
def test_a_refused_setting_is_named_in_the_pages_language(self):
response = self.client.post(reverse("appsettings"), {"MIGRATION_BANDWIDTH": "-1"}, HTTP_ACCEPT_LANGUAGE="tr")
self.assertEqual(AppSettings.objects.get(key="MIGRATION_BANDWIDTH").value, "0")
self.assertTrue(any(str(m).startswith("Taşıma bant genişliği") for m in get_messages(response.wsgi_request)))
def post(self, key, value):
response = self.client.post(reverse("appsettings"), {key: value})
# not followed: the messages would stay in the cookie for the next post

View file

@ -129,8 +129,9 @@ class RepairNumbersTestCase(TestCase):
def test_a_number_an_older_version_saved_goes_back_to_its_default(self):
from appsettings.views import NUMBERS
# the same ranges as the Settings page checks
self.assertEqual({key: bounds[:2] for key, bounds in repair_numbers.NUMBERS.items()}, NUMBERS)
# the same ranges as the Settings page checks (a setting added since is not the migration's)
self.assertEqual({key: bounds[:2] for key, bounds in repair_numbers.NUMBERS.items()},
{key: NUMBERS[key] for key in repair_numbers.NUMBERS})
for key, value in (("LOGS_PER_PAGE", "abc"), ("WORKER_CONCURRENCY", "0"), ("LOGIN_FAILURE_LIMIT", "")):
AppSettings.objects.filter(key=key).update(value=value)
AppSettings.objects.filter(key="LOG_RETENTION_DAYS").update(value="90")

View file

@ -56,6 +56,7 @@ GROUPS = [
"ALLOW_INSTANCE_MULTIPLE_OWNER", "QUOTA_DEBUG"]),
(gettext_noop("Snapshots and jobs"), ["SNAPSHOT_FREE_SPACE_PERCENT", "SNAPSHOT_FREE_SPACE_MIN_GIB",
"WORKER_CONCURRENCY", "JOB_RETENTION_DAYS"]),
(gettext_noop("Migrations"), ["MIGRATION_BANDWIDTH"]),
(gettext_noop("Login"), ["LOGIN_FAILURE_LIMIT", "LOGIN_LOCKOUT_MINUTES"]),
(gettext_noop("Alerts"), ["ALERT_EMAILS", "ALERT_WEBHOOK"]),
(gettext_noop("Lists and pages"), ["VIEW_INSTANCES_LIST_STYLE", "VM_DRBD_STATUS", "LOGS_PER_PAGE",
@ -67,18 +68,18 @@ def refusal(setting, value):
"""Why the value cannot be saved for the setting, or None."""
if len(value) > AppSettings._meta.get_field("value").max_length:
return _("%(setting)s takes at most %(length)s characters") % {
"setting": setting.name, "length": AppSettings._meta.get_field("value").max_length}
"setting": _(setting.name), "length": AppSettings._meta.get_field("value").max_length}
if setting.key in NUMBERS:
low, high = NUMBERS[setting.key]
if not (value.isascii() and value.isdigit() and len(value) <= 10 and low <= int(value) <= high):
return _("%(setting)s must be a whole number between %(low)s and %(high)s") % {
"setting": setting.name, "low": low, "high": high}
"setting": _(setting.name), "low": low, "high": high}
elif setting.choices and value not in setting.choices_as_list():
return _("%(setting)s must be one of %(choices)s") % {
"setting": setting.name, "choices": ", ".join(setting.choices_as_list())}
"setting": _(setting.name), "choices": ", ".join(setting.choices_as_list())}
elif setting.key == "CLONE_INSTANCE_DEFAULT_PREFIX" and not re.fullmatch(r"[a-zA-Z0-9-]+", value):
# a clone's name is the prefix and a number, and takes only these
return _("%(setting)s takes letters, digits and '-' only") % {"setting": setting.name}
return _("%(setting)s takes letters, digits and '-' only") % {"setting": _(setting.name)}
try:
if setting.key == "ALERT_EMAILS":
for address in filter(None, (a.strip() for a in value.split(","))):
@ -88,7 +89,7 @@ def refusal(setting, value):
if "@" in urlsplit(value.strip()).netloc: # urllib would take user:password@ for the host
raise ValidationError("credentials in the URL")
except ValidationError:
return _("%(setting)s: %(value)s is not an e-mail address or an http(s) URL") % {"setting": setting.name, "value": value}
return _("%(setting)s: %(value)s is not an e-mail address or an http(s) URL") % {"setting": _(setting.name), "value": value}
return None

View file

@ -12,6 +12,7 @@ from computes.models import Compute
from computes.validators import validate_migration_address
from instances.models import Instance
from instances.utils import migrate_instance
from appsettings.models import AppSettings
class MigrationAddressTests(TestCase):
@ -71,3 +72,13 @@ class MigrationAddressTests(TestCase):
instances.return_value.moveto.return_value = ("live", [])
migrate_instance(dest, vm, user, live=True)
self.assertEqual(instances.return_value.moveto.call_args.kwargs["uri"], "tcp://198.51.100.9")
self.assertEqual(instances.return_value.moveto.call_args.kwargs["bandwidth"], 0) # the default: no limit
AppSettings.objects.filter(key="MIGRATION_BANDWIDTH").update(value="200")
vm = Instance.objects.create(compute=source, name="vm2", uuid="u-ma2") # the first was moved
with patch.object(Compute, "status", True), \
patch("instances.utils.wvmInstances") as instances, \
patch("instances.utils.wvmInstance"), \
patch.object(Instance, "proxy", MagicMock()):
instances.return_value.moveto.return_value = ("live", [])
migrate_instance(dest, vm, user, live=True)
self.assertEqual(instances.return_value.moveto.call_args.kwargs["bandwidth"], 200)

View file

@ -19,6 +19,7 @@ from django.utils.translation import gettext_noop
from libvirt import libvirtError
from logs.audit import reason, write
from operations.models import Operation
from operations.utils import migration_bandwidth
from vrtManager.connection import counted_thread, other_hosts, wvmConnect
from vrtManager.instance import wvmInstance, wvmInstances
from vrtManager.util import ConnectionFailed, HostBusy, message, vol_dev_type
@ -345,6 +346,7 @@ def migrate_instance(
compress,
uri=new_compute.migration_uri,
tls=source.migration_tls and new_compute.migration_tls,
bandwidth=migration_bandwidth(),
pools=disk_pools,
on_copy=on_copy,
running_only=running_only,

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

@ -61,7 +61,8 @@ 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)}
BOUNDS = {"WORKER_CONCURRENCY": (1, 16, 4), "JOB_RETENTION_DAYS": (1, 3650, 30), "LOG_RETENTION_DAYS": (1, 3650, 365),
"MIGRATION_BANDWIDTH": (0, 100000, 0)}
def safe_text(text):
@ -225,3 +226,8 @@ def retention_days():
def log_retention_days():
return _value("LOG_RETENTION_DAYS")
def migration_bandwidth():
"""MiB/s a migration may take at most; 0: no limit."""
return _value("MIGRATION_BANDWIDTH")

View file

@ -46,6 +46,7 @@ from libvirt import (
VIR_MIGRATE_PARAM_MIGRATE_DISKS,
VIR_MIGRATE_PARAM_PERSIST_XML,
VIR_MIGRATE_PARAM_URI,
VIR_MIGRATE_PARAM_BANDWIDTH,
VIR_MIGRATE_PERSIST_DEST,
VIR_MIGRATE_UNDEFINE_SOURCE,
VIR_MIGRATE_UNSAFE,
@ -160,7 +161,7 @@ class wvmInstances(wvmConnect):
return sorted(missing), sorted(unlike)
def moveto(self, conn, name, live, unsafe, offline, autoconverge=False, compress=False, uri=None,
pools=None, on_copy=None, running_only=False, tls=False):
pools=None, on_copy=None, running_only=False, tls=False, bandwidth=0):
"""Migrates the VM of conn (a wvmInstance on the source) here.
The mode follows the VM's state, read once: a running VM migrates
@ -176,7 +177,8 @@ class wvmInstances(wvmConnect):
called with the copies ({pool, dest}: a pool here and its path) before
libvirt makes them. tls: QEMU sends the memory and disks over TLS (the
hosts' certificates in /etc/pki/qemu); a shut-off VM's definition alone
sends none. Returns the mode and options used, for the log,
sends none. bandwidth: MiB/s of libvirt's limit, for the memory before the final switchover and for each
copied disk; 0 leaves libvirt's own (none unless set on the host). Returns the mode and options used, for the log,
and each copied disk's path and the path of its copy here."""
state = conn.get_status()
if running_only and state != 1:
@ -259,10 +261,12 @@ class wvmInstances(wvmConnect):
if tls and (state != 5 or copies or tpm_state):
flags |= VIR_MIGRATE_TLS
mode.append("TLS")
if bandwidth and (state != 5 or copies or tpm_state): # an offline move sends only its definition (and NVRAM)
mode.append(f"{bandwidth} MiB/s")
if copies or (state == 5 and tpm_state):
if copies and on_copy is not None:
on_copy([{"pool": copy["pool"].name(), "dest": copy["dest"]} for copy in copies])
note = self.migrate_running(conn, state, flags, uri, copies)
note = self.migrate_running(conn, state, flags, uri, copies, bandwidth)
if note:
mode.append(note)
elif state == 5:
@ -272,10 +276,10 @@ class wvmInstances(wvmConnect):
# dom.migrate.
self.move_definition(dom, conn)
else:
dom.migrate(self.wvm, flags, None, uri, 0)
dom.migrate(self.wvm, flags, None, uri, bandwidth)
return ", ".join(mode), [(copy["path"], copy["dest"]) for copy in copies]
def migrate_running(self, conn, state, flags, uri, copies):
def migrate_running(self, conn, state, flags, uri, copies, bandwidth=0):
"""Migrates the VM of conn as a running VM, which carries its TPM
state, while libvirt copies the disks of copies into their pools here
(NON_SHARED_DISK), the definitions naming the new paths. A shut-off
@ -295,6 +299,8 @@ class wvmInstances(wvmConnect):
flags |= VIR_MIGRATE_NON_SHARED_DISK
if uri:
params[VIR_MIGRATE_PARAM_URI] = uri
if bandwidth:
params[VIR_MIGRATE_PARAM_BANDWIDTH] = bandwidth
try:
if state == 5:
flags &= ~VIR_MIGRATE_OFFLINE

View file

@ -120,6 +120,19 @@ class DiskCopyTestCase(unittest.TestCase):
source.instance.migrate.assert_called_once()
source.instance.migrate3.assert_not_called()
def test_the_bandwidth_limit_goes_to_libvirt(self):
# MiB/s; 0: none
source = Source(1, domain(disk(f"{IMAGES}/vm.qcow2")))
self.assertEqual(migrate(destination(Pool("default", IMAGES), shared=True), source, {}, bandwidth=100),
("live, 100 MiB/s", []))
self.assertEqual(source.instance.migrate.call_args.args[4], 100)
source = Source(1, domain(disk(f"{IMAGES}/vm.qcow2")))
migrate(destination(Pool("default", IMAGES)), source, {"vda": "default"}, bandwidth=100)
self.assertEqual(source.instance.migrate3.call_args.args[1][libvirt.VIR_MIGRATE_PARAM_BANDWIDTH], 100)
source = Source(1, domain(disk(f"{IMAGES}/vm.qcow2")))
migrate(destination(Pool("default", IMAGES)), source, {"vda": "default"})
self.assertNotIn(libvirt.VIR_MIGRATE_PARAM_BANDWIDTH, source.instance.migrate3.call_args.args[1])
def test_a_disk_the_destination_does_not_share_needs_a_pool(self):
for pools, shared in (((IMAGES,), False), ((), True)): # not shared; no pool to probe on the source
with self.subTest(pools=pools):