1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 17:06:09 +00:00

fix: power jobs name their action, refuse what does not apply and recover by the VM's state

Audit and review (Codex) of the bulk power and disk I/O limit:
- the Jobs page showed "Power" for a start, a shut down and a force off
  alike: each is a job kind of its own (instance.start, .shutdown,
  .force_off) named by its action;
- forcing off a VM already shut off made libvirt refuse after the job had
  recorded its intent: it ended uncertain and kept the VM locked. Each job now
  refuses a VM its action does not apply to before anything changes, and
  recovery reads the VM's state (running after a start, shut off after a
  shut down or force off) instead of ending uncertain;
- the Jobs page left out its kind and state filters for owners, whom the VM
  list sends there: they apply to every user;
- a running NBD disk's tls, which libvirt fills in, no longer makes it
  another disk than the next start's;
- a disk whose running limit differs from the next start's shows both.
This commit is contained in:
catborise 2026-11-20 11:53:09 +03:00
parent 35c794c50c
commit b36f674542
14 changed files with 1045 additions and 849 deletions

View file

@ -15,7 +15,7 @@ from django.template.loader import render_to_string
from django.utils.translation import gettext_noop
from django.utils.translation import gettext_noop as _
from libvirt import (VIR_CONNECT_LIST_STORAGE_POOLS_ACTIVE, VIR_DOMAIN_JOB_NONE, VIR_DOMAIN_SNAPSHOT_LIST_EXTERNAL,
VIR_DOMAIN_SHUTOFF, VIR_DOMAIN_UNDEFINE_CHECKPOINTS_METADATA, VIR_DOMAIN_UNDEFINE_KEEP_NVRAM, VIR_DOMAIN_UNDEFINE_MANAGED_SAVE,
VIR_DOMAIN_RUNNING, VIR_DOMAIN_SHUTOFF, VIR_DOMAIN_UNDEFINE_CHECKPOINTS_METADATA, VIR_DOMAIN_UNDEFINE_KEEP_NVRAM, VIR_DOMAIN_UNDEFINE_MANAGED_SAVE,
VIR_DOMAIN_UNDEFINE_NVRAM, VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA, VIR_DOMAIN_XML_INACTIVE,
VIR_ERR_NO_DOMAIN, VIR_ERR_NO_STORAGE_VOL, libvirtError)
from lxml import etree
@ -1519,12 +1519,8 @@ class DeleteInstance(Kind):
return _log(op, state, "delete")
# the power actions the VM list's chosen VMs take (instance.power), by the name its form sends, and their log words
POWER = {
"start": "power on",
"shutdown": "power off",
"force_off": "force off",
}
# the power actions the VM list's chosen VMs take, by the name its form sends: their job kind
POWER = {"start": "instance.start", "shutdown": "instance.shutdown", "force_off": "instance.force_off"}
def _powerable(user, pk):
@ -1539,19 +1535,16 @@ def _powerable(user, pk):
raise PermissionDenied from None
@register
class PowerVM(Kind):
class _Power(Kind):
"""Starts, shuts down or forces off one VM chosen on the VM list: a job of
its own, so each VM is held, checked when it runs, scheduled and recovered
on its own, and has its own log row."""
on its own, and has its own log row. A kind for each action, which its
label names on the Jobs page."""
name = "instance.power"
label = gettext_noop("Power")
action = "" # its log row's words
def normalize(self, raw):
if raw["action"] not in POWER:
raise ValueError(raw["action"])
return {"instance": int(raw["instance"]), "action": raw["action"]}
return {"instance": int(raw["instance"])}
def validate(self, user, params):
# the owner only: whether an administrator paused it is read by the worker, not in the request
@ -1566,27 +1559,90 @@ class PowerVM(Kind):
if _powerable(op.user, op.params["instance"]).compute_id != op.intent["compute"]:
raise util.OperationError(MOVED)
def check(self, instance):
"""Refuses, before anything changes, a VM the action does not apply to."""
raise NotImplementedError
def power(self, proxy):
raise NotImplementedError
def done(self, dom):
"""Whether the VM, its domain or None when its host has none, is as the action leaves it, for recovery."""
raise NotImplementedError
def run(self, op, ctx):
instance, action = _instance(op.params["instance"]), op.params["action"]
if action == "start": # the start button's checks, before anything changes
if instance.is_template:
raise util.OperationError(gettext_noop("Templates cannot be started."))
instance.proxy.check_start_hostdevs()
instance.compute.refuse_start()
ctx.record_intent(powering=True) # libvirt is asked from here: recovery cannot tell what it did
if action == "start":
instance.proxy.start()
elif action == "shutdown":
instance.proxy.shutdown()
else:
instance.proxy.force_shutdown()
instance = _instance(op.params["instance"])
self.check(instance)
ctx.record_intent(powering=True) # libvirt is asked from here: recovery reads what it did
self.power(instance.proxy)
return {}
# recovery's word when the VM is not as the action leaves it
not_done = gettext_noop("The VM was not powered")
def reconcile(self, op):
if not op.intent.get("powering"):
return Outcome(Operation.FAILED, error=say(gettext_noop("The job stopped before the VM was powered")))
return Outcome(Operation.UNCERTAIN, error=say(gettext_noop(
"The job stopped while the VM was powered: check its state")))
return Outcome(Operation.FAILED, error=say(self.not_done))
if self.done(_domain(op.intent["compute"], op.intent["uuid"])):
return Outcome(Operation.SUCCEEDED)
return Outcome(Operation.FAILED, error=say(self.not_done))
def log_entry(self, op, state):
return _log(op, state, POWER[op.params["action"]])
return _log(op, state, self.action)
@register
class StartVM(_Power):
name = "instance.start"
label = gettext_noop("Start")
action = "power on"
def check(self, instance): # the start button's checks
if instance.is_template:
raise util.OperationError(gettext_noop("Templates cannot be started."))
if instance.proxy.get_status() != 5:
raise util.OperationError(gettext_noop("The VM is not shut off"))
instance.proxy.check_start_hostdevs()
instance.compute.refuse_start()
def power(self, proxy):
proxy.start()
def done(self, dom): # running: not a guest that crashed while starting
return dom is not None and dom.state()[0] == VIR_DOMAIN_RUNNING
@register
class ShutdownVM(_Power):
name = "instance.shutdown"
label = gettext_noop("Shut down")
action = "power off"
def check(self, instance):
if instance.proxy.get_status() != 1:
raise util.OperationError(gettext_noop("The VM is not running"))
not_done = gettext_noop("The VM was still running when the job was checked: its guest may still shut it down")
def power(self, proxy):
proxy.shutdown()
def done(self, dom): # shut off, or gone: a transient VM is removed as it stops
return dom is None or not dom.isActive()
@register
class ForceOffVM(_Power):
name = "instance.force_off"
label = gettext_noop("Force off")
action = "force off"
def check(self, instance):
if instance.proxy.get_status() == 5:
raise util.OperationError(gettext_noop("The VM is already shut off"))
def power(self, proxy):
proxy.force_shutdown()
def done(self, dom): # shut off, or gone: a transient VM is removed as it stops
return dom is None or not dom.isActive()

View file

@ -196,10 +196,12 @@ class Instance(models.Model):
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")}
def live_iotune(self) -> dict:
"""{dev: (IOPS, MiB/s, set in the XML)} of the running definition's disks (custom_iotune): the Disks
tab shows the next start's, the running one's too when it differs, and set_disk_limit refuses either
when it is set in the XML."""
return {disk["dev"]: (disk.get("iops", 0), disk.get("mibps", 0), disk.get("iotune_custom", False))
for disk in self.disks}
@cached_property
def config_vcpu(self) -> int:

View file

@ -57,7 +57,7 @@
</nav>
{% include 'common/tag_filter.html' %}
{% if powerable %}
{# the VMs chosen in the list (bulk_power_box.html), an instance.power job each; bulk_power.js counts those on screen #}
{# the VMs chosen in the list (bulk_power_box.html), a job each (instances.jobs.POWER); bulk_power.js counts those on screen #}
<form id="bulk-power" class="d-flex flex-wrap align-items-center gap-2 mb-2" action="{% url 'instances:bulk_power' %}" method="post">{% csrf_token %}{% submission_key %}
<div class="form-check mb-0">
<input class="form-check-input" type="checkbox" id="bulk-power-shown">

View file

@ -1,6 +1,7 @@
{% load i18n %}
{% load django_bootstrap5 %}
{% load bootstrap_icons %}
{% load vm_states %}
{% load operations %}
<div class="tab-pane" id="settings" role="tabpanel">
<!-- Nav tabs -->
@ -263,9 +264,13 @@
<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-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>
{% with running=disk|running_limit:instance %}
<dd class="col-6 mb-0">{% if disk.iotune_custom %}{% 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 %}
{# the running VM's, when the next start's above differs from it #}
{% if running %}<div class="text-body-secondary">{% if running.2 %}{% trans "Running: set in the VM's XML" %}{% elif running.0 or running.1 %}{% blocktrans with iops=running.0|default:"–" mibps=running.1|default:"–" %}Running: {{ iops }} IOPS, {{ mibps }} MiB/s{% endblocktrans %}{% else %}{% trans "Running: none" %}{% endif %}</div>{% endif %}</dd>
{% endwith %}
</dl>
{% if request.user.is_superuser and not disk.iotune_custom and disk.dev not in instance.live_custom_iotune %}
{% with running=disk|running_limit:instance %}{% if request.user.is_superuser and not disk.iotune_custom and not running.2 %}
{# 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 }}">
@ -281,7 +286,7 @@
<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 %}
{% endif %}{% endwith %}
</details>
</article>
{% endfor %}

View file

@ -32,3 +32,14 @@ def disk_seen(disk):
shows it, which a form sends back; the file is not shown. Keyed: an owner
cannot try likely paths against it."""
return salted_hmac("instances.disk_seen", disk["path"] or "", algorithm="sha256").hexdigest()
@register.filter
def running_limit(disk, instance):
"""{{ disk|running_limit:instance }}: the running VM's I/O limit of disk, (IOPS, MiB/s, set in the
XML), when it differs from the next start's the Disks tab shows; else None."""
running = instance.live_iotune.get(disk["dev"])
if running is None or running == (disk.get("iops", 0), disk.get("mibps", 0), disk.get("iotune_custom", False)):
return None
return running

View file

@ -1,6 +1,7 @@
"""Start, shut down or force off the VMs chosen on the VM list: an
instance.power job each, so each VM is held, checked when it runs and
recovered on its own, with its own log row. A VM the user may not power, or
"""Start, shut down or force off the VMs chosen on the VM list: a job each
(instance.start, .shutdown, .force_off), so each VM is held, checked when it
runs and recovered on its own, with its own log row and its action named on
the Jobs page. A VM the user may not power, or
that another job holds, is named and the others are queued. Who may power a
VM may choose it, as on its own page."""
from types import SimpleNamespace
@ -15,7 +16,7 @@ from lxml import html
from accounts.models import UserInstance
from computes.models import Compute
from instances.jobs import PowerVM
from instances.jobs import ForceOffVM, ShutdownVM, StartVM
from instances.models import Instance
from operations import claims
from operations.jobs import Context
@ -48,16 +49,17 @@ class BulkPowerTestCase(TransactionTestCase):
Operation.objects.filter(pk=op.pk).update(state=Operation.RUNNING, worker="wvc-test:1:a")
op.refresh_from_db()
ctx = Context(op, SimpleNamespace(identity="wvc-test:1:a"))
PowerVM().precheck(op, ctx)
return PowerVM().run(op, ctx)
kind = {"instance.start": StartVM, "instance.shutdown": ShutdownVM, "instance.force_off": ForceOffVM}[op.kind]()
kind.precheck(op, ctx)
return kind.run(op, ctx)
def test_the_list_queues_a_job_for_each_vm(self):
response, said = self.submit("start", self.vms)
self.assertRedirects(response, reverse("operations:jobs") + "?kind=instance.power", fetch_redirect_response=False)
self.assertRedirects(response, reverse("operations:jobs") + "?kind=instance.start", fetch_redirect_response=False)
self.assertEqual(said, ["2 VMs are queued; the Jobs page follows them."])
ops = list(Operation.objects.order_by("resource_label"))
self.assertEqual([(op.kind, op.params, op.resource_label) for op in ops],
[("instance.power", {"instance": vm.pk, "action": "start"}, f"bp-host/{vm.name}") for vm in self.vms])
[("instance.start", {"instance": vm.pk}, f"bp-host/{vm.name}") for vm in self.vms])
# each holds its VM and shares its host, as a job on the VM's page does
self.assertEqual(set(Claim.objects.filter(operation=ops[0]).values_list("resource", "mode")),
{(f"compute:{self.vms[0].compute_id}", "shared"), (f"instance:{self.vms[0].uuid}", "exclusive")})
@ -67,6 +69,8 @@ class BulkPowerTestCase(TransactionTestCase):
self.assertEqual(Operation.objects.count(), 2)
def test_each_job_powers_its_vm(self):
for proxy in self.proxies.values():
proxy.get_status.return_value = 1 # running
self.submit("force_off", self.vms)
for op in Operation.objects.all():
self.run_job(op)
@ -81,7 +85,60 @@ class BulkPowerTestCase(TransactionTestCase):
_response, said = self.submit("shutdown", self.vms)
self.assertTrue(said[0].startswith("bp-vm1: "), said)
self.assertEqual(said[1:], ["1 VM is queued; the Jobs page follows it."])
self.assertEqual(Operation.objects.get(kind="instance.power").params["instance"], self.vms[1].pk)
self.assertEqual(Operation.objects.get(kind="instance.shutdown").params["instance"], self.vms[1].pk)
def test_an_action_that_does_not_apply_fails_before_libvirt_is_asked(self):
# an already shut off VM forced off, a running one started: refused, its claims go with the failed job
for action, status in (("force_off", 5), ("shutdown", 5), ("start", 1)):
with self.subTest(action=action):
Operation.objects.all().delete()
self.proxies["bp-vm1"].get_status.return_value = status
self.submit(action, self.vms[:1])
op = Operation.objects.get()
with self.assertRaises(OperationError):
self.run_job(op)
op.refresh_from_db()
self.assertNotIn("powering", op.intent)
for call in ("start", "shutdown", "force_shutdown"):
getattr(self.proxies["bp-vm1"], call).assert_not_called()
def test_recovery_reads_what_libvirt_did(self):
op = SimpleNamespace(intent={"compute": 1, "uuid": "u", "powering": True})
dom = {name: MagicMock(**{"state.return_value": [state, 0], "isActive.return_value": active})
for name, state, active in (("running", 1, 1), ("crashed", 6, 1), ("off", 5, 0))}
for kind, found, state in ((StartVM, "running", Operation.SUCCEEDED), (StartVM, "crashed", Operation.FAILED),
(StartVM, "off", Operation.FAILED), (StartVM, None, Operation.FAILED),
(ForceOffVM, "off", Operation.SUCCEEDED), (ForceOffVM, "running", Operation.FAILED),
(ForceOffVM, None, Operation.SUCCEEDED), # a transient VM is removed as it stops
(ShutdownVM, "off", Operation.SUCCEEDED), (ShutdownVM, None, Operation.SUCCEEDED),
(ShutdownVM, "running", Operation.FAILED)):
with self.subTest(kind=kind.name, found=found), patch("instances.jobs._domain", return_value=dom.get(found)):
self.assertEqual(kind().reconcile(op).state, state)
with patch("instances.jobs._domain", return_value=dom["running"]): # its guest may yet shut it down
self.assertIn("may still shut it down", ShutdownVM().reconcile(op).error[0]["text"])
def test_a_refused_job_frees_its_vm(self):
# through the worker: the job fails and its claims go, so the VM can be powered again
from operations.worker import execute
self.proxies["bp-vm1"].get_status.return_value = 5
self.submit("force_off", self.vms[:1])
op = Operation.objects.get()
acquire("wvc-test:1:a", "wvc-test")
Operation.objects.filter(pk=op.pk).update(state=Operation.RUNNING, worker="wvc-test:1:a")
execute(SimpleNamespace(identity="wvc-test:1:a", recovery=MagicMock()), op.pk)
op.refresh_from_db()
self.assertEqual((op.state, Claim.objects.filter(operation=op).count()), (Operation.FAILED, 0))
def test_the_jobs_page_follows_an_owners_power_jobs(self):
# an owner is sent to ?kind=...: the page filters it for them too
owner = get_user_model().objects.create_user("bp-owner4", password="pw")
UserInstance.objects.create(instance=self.vms[0], user=owner)
response, _said = self.submit("start", self.vms[:1], user=owner)
Operation.objects.create(kind="instance.snapshot", user=owner, username="bp-owner4", state=Operation.SUCCEEDED,
resource="y", resource_label="bp-host/bp-vm1")
page = self.client.get(response.url)
self.assertEqual([op.kind for op, _data in page.context["rows"]], ["instance.start"])
def test_a_template_is_not_started_and_nothing_is_uncertain(self):
# refused before libvirt is asked: the job fails (its claims go), recovery is not needed
@ -92,7 +149,7 @@ class BulkPowerTestCase(TransactionTestCase):
self.run_job(op)
op.refresh_from_db()
self.assertNotIn("powering", op.intent)
self.assertEqual(PowerVM().reconcile(op).state, Operation.FAILED)
self.assertEqual(StartVM().reconcile(op).state, Operation.FAILED)
self.proxies["bp-vm1"].start.assert_not_called()
def test_a_vm_paused_by_an_administrator_or_gone_is_refused_when_the_job_runs(self):
@ -105,7 +162,7 @@ class BulkPowerTestCase(TransactionTestCase):
self.run_job(op)
Instance.objects.filter(pk=self.vms[0].pk).delete()
with self.assertRaises(PermissionDenied):
PowerVM().precheck(op, None)
StartVM().precheck(op, None)
def test_the_worker_checks_the_user_again(self):
# disabled after the form was sent: the job powers nothing

View file

@ -83,10 +83,20 @@ class DiskLimitTestCase(TestCase):
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")])):
form = reverse("instances:set_disk_limit", args=[self.instance.id])
for live, config, told in (([custom], [custom], "Set in the VM's XML"),
([custom], [limited("vda")], "Running: set in the VM's XML")):
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])))
self.assertIn(told, " ".join(doc.text_content().split()))
self.assertFalse(doc.xpath("//form[@action=$a]", a=form))
# the running VM's limit, when it differs from the next start's
for live, told in ((limited("vda", 200, 20), "Running: 200 IOPS, 20 MiB/s"), (limited("vda"), "Running: none")):
doc = self.page(live=[live], config=[limited("vda", 500, 100)])
text = " ".join(doc.text_content().split())
self.assertIn(f"I/O limit 500 IOPS, 100 MiB/s {told}", text)
self.assertTrue(doc.xpath("//form[@action=$a]", a=form))
self.assertNotIn("Running:", " ".join(self.page(live=[limited("vda", 500, 100)],
config=[limited("vda", 500, 100)]).text_content().split()))
def domain(*disks):
@ -123,6 +133,11 @@ class SetDiskLimitTestCase(TestCase):
# 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)
# and an NBD disk's tls, which libvirt fills in from the host's settings
nbd = ("<disk type='network' device='disk'><source protocol='nbd' name='export'{tls}><host name='192.0.2.5' "
"port='10809'/></source><target dev='vda' bus='virtio'/></disk>")
self.assertEqual(self.flags(self.vm(domain(nbd.format(tls=" tls='no'")), domain(nbd.format(tls="")))),
VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)
def test_refused(self):
for case, live, config, text in (

View file

@ -705,8 +705,8 @@ BULK_POWER_MAX = 500
@require_POST
def bulk_power(request):
"""Starts, shuts down or forces off the VMs chosen on the VM list: an
instance.power job each, followed on the Jobs page. A VM the user may not
"""Starts, shuts down or forces off the VMs chosen on the VM list: a job each
(instances.jobs.POWER), followed on the Jobs page. A VM the user may not
power, gone, or held by another job is named (if the user may see it);
the others are queued."""
from instances.jobs import POWER # instances.jobs imports this module
@ -727,7 +727,7 @@ def bulk_power(request):
name = seen.get(pk) or _("a chosen VM") # one the user may not see is not named
try:
# one key per VM: a resent form queues none twice
jobs.submit("instance.power", request.user, {"instance": pk, "action": action}, f"{key}-{pk}")
jobs.submit(POWER[action], request.user, {"instance": pk}, f"{key}-{pk}")
queued += 1
except claims.Busy as busy:
messages.error(request, f"{name}: {busy_message(busy, request.user)}")
@ -739,7 +739,7 @@ def bulk_power(request):
return redirect("instances:index")
messages.success(request, ngettext("%(count)s VM is queued; the Jobs page follows it.",
"%(count)s VMs are queued; the Jobs page follows them.", queued) % {"count": queued})
return redirect(reverse("operations:jobs") + "?kind=instance.power")
return redirect(reverse("operations:jobs") + f"?kind={POWER[action]}")
def from_script(request):

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

@ -37,9 +37,10 @@ def jobs(request):
qs = qs.filter(resource_label__istartswith=compute)
if username := request.GET.get("username"):
qs = qs.filter(username__icontains=username)
for field in ("state", "kind"):
if value := request.GET.get(field):
qs = qs.filter(**{field: value})
# a state or kind for every user: the VM list sends its owners to their power jobs
for field in ("state", "kind"):
if value := request.GET.get(field):
qs = qs.filter(**{field: value})
page = Paginator(qs, 50).get_page(request.GET.get("page"))
# the model for its datetimes, the serialized job for its labels
rows = [(op, OperationSerializer(op, context={"request": request}).data) for op in page.object_list]

View file

@ -713,11 +713,12 @@ def custom_iotune(disk):
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)."""
and its source's attributes and hosts, not those a running VM adds (index,
and an NBD disk's tls, which libvirt fills in from the host's settings)."""
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")),
return (disk.get("type"), tuple(sorted((k, v) for k, v in source.attrib.items() if k not in ("index", "tls"))),
tuple(tuple(sorted(host.attrib.items())) for host in source.findall("host")))