1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-03 17:36:05 +00:00

fix(computes): a libvirt host is one compute, and a compute's VMs stay on their host

One host could be added twice, under another name, as TCP and SSH, or by
another address: its VMs were listed once per record, each with its own
owners, and counted twice in the capacity totals. A compute with VMs could
also be pointed at another host: the owners of a VM then reached the
VM with the same UUID there, a restored or copied one.

A compute now keeps its libvirt host UUID. Adding a compute or changing
its connection, on the web or the API, connects and reads it: a host that
is already a compute is refused, and a compute with VMs moves only to an
address of the same host, which must answer. Computes added before are
read when another one is checked.
This commit is contained in:
catborise 2026-11-12 08:42:04 +03:00
parent 2db25314ea
commit 29ec20682b
17 changed files with 567 additions and 259 deletions

View file

@ -1,3 +1,5 @@
from copy import copy
from computes.models import Compute
from computes.validators import validate_gstfsd_key
from rest_framework import serializers
@ -35,6 +37,14 @@ class ComputeSerializer(serializers.ModelSerializer):
def validate_gstfsd_key(self, value):
return value or (self.instance.gstfsd_key if self.instance else value)
def validate(self, attrs):
# as the web form: the connection is tried and its host checked (Compute.clean)
compute = copy(self.instance) if self.instance else Compute()
for field, value in attrs.items():
setattr(compute, field, value)
compute.clean()
return {**attrs, "host_uuid": compute.host_uuid}
class Meta:
model = Compute
fields = ["id", "name", "hostname", "login", "password", "type", "details", "migration_address", "gstfsd_key"]

View file

@ -1,6 +1,6 @@
from admin.permissions import IsSuperUser
from computes.models import Compute
from computes.utils import libvirt_compute_lock
from computes.utils import hosts_lock
from django.shortcuts import get_object_or_404
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema
@ -22,20 +22,30 @@ class ComputeViewSet(viewsets.ModelViewSet):
serializer_class = ComputeSerializer
permission_classes = [IsSuperUser]
# checked and saved under hosts_lock, as on the web (Compute.clean)
def create(self, request, *args, **kwargs):
with hosts_lock():
return super().create(request, *args, **kwargs)
def update(self, request, *args, **kwargs):
# the row is written here, as on the web: a busy compute is refused with one too
compute = self.get_object()
with audit(request, compute, f"Compute {compute.name} ({compute.hostname})", "change") as self.entry, \
hosts_lock(compute):
self.entry.skip = True # until a change is saved
return super().update(request, *args, **kwargs)
def perform_create(self, serializer):
data = serializer.validated_data
with audit(self.request, data["name"], f"Compute {data['name']} ({data['hostname']})", "add"):
serializer.save()
def perform_update(self, serializer):
compute = serializer.instance
subject = f"Compute {compute.name} ({compute.hostname})"
before = snapshot(compute)
with audit(self.request, compute, subject, "change") as entry, libvirt_compute_lock(compute):
serializer.save()
fields = changed_fields(before, snapshot(compute))
entry.action = "change " + ", ".join(fields)
entry.skip = not fields
before = snapshot(serializer.instance)
serializer.save()
fields = changed_fields(before, snapshot(serializer.instance))
self.entry.action = "change " + ", ".join(fields)
self.entry.skip = not fields
def perform_destroy(self, instance):
with audit(self.request, instance, f"Compute {instance.name} ({instance.hostname})", "delete"):

View file

@ -0,0 +1,22 @@
# Generated by Django 5.2.18 on 2026-11-12 05:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('computes', '0008_migration_address_help'),
]
operations = [
migrations.AddField(
model_name='compute',
name='host_uuid',
field=models.CharField(blank=True, default='', editable=False, max_length=36),
),
migrations.AddConstraint(
model_name='compute',
constraint=models.UniqueConstraint(condition=models.Q(('host_uuid', ''), _negated=True), fields=('host_uuid',), name='one_compute_per_host'),
),
]

View file

@ -1,7 +1,8 @@
from ipaddress import ip_address
from django.db import transaction
from django.db.models import CharField, IntegerField, Model
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
from django.db.models import CharField, IntegerField, Model, Q, UniqueConstraint
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from libvirt import libvirtError, virConnect
@ -11,6 +12,10 @@ from vrtManager.connection import connection_manager
from vrtManager.hostdetails import wvmHostDetails
# what the panel connects to a compute with
ENDPOINT = ("hostname", "login", "password", "type")
class Compute(Model):
name = CharField(_("name"), max_length=64, unique=True)
hostname = CharField(_("hostname"), max_length=64, validators=[validate_hostname])
@ -41,6 +46,13 @@ class Compute(Model):
),
)
# the libvirt host's UUID (its capabilities), read when the panel first
# reaches it: one host is one compute, and a compute's VMs stay on it
host_uuid = CharField(max_length=36, blank=True, default="", editable=False)
class Meta:
constraints = [UniqueConstraint(fields=["host_uuid"], condition=~Q(host_uuid=""), name="one_compute_per_host")]
@property
def migration_uri(self):
"""The native migration URI for VMs migrated to this host: its
@ -129,6 +141,55 @@ class Compute(Model):
def __str__(self):
return self.name
def record_host(self):
"""Reads and keeps the UUID of the host the compute reaches (host_uuid)
while its connection is still the one read with; its UUID, or ""
when it cannot be read. IntegrityError when another compute is that host."""
try:
uuid = self.proxy.host_uuid()
except libvirtError:
return ""
with transaction.atomic():
same = {field: getattr(self, field) for field in ENDPOINT}
if not Compute.objects.filter(pk=self.pk, host_uuid="", **same).update(host_uuid=uuid):
return ""
self.host_uuid = uuid
return uuid
# why a new or changed connection could not be tried (clean), for the form to tell
unreachable = None
def clean(self):
"""A host is one compute, and a compute's VMs stay on their host: a
new or changed connection is tried and its host UUID read
(host_uuid). Refused when another compute is that host, or when the
compute has VMs and the host is not theirs, cannot be reached, or
theirs is not known. Callers hold hosts_lock (computes.utils)."""
before = Compute.objects.filter(pk=self.pk).values(*ENDPOINT, "host_uuid").first() if self.pk else None
if before and all(before[field] == getattr(self, field) for field in ENDPOINT):
return
try:
uuid = wvmHostDetails(self.hostname, self.login, self.password, self.type).host_uuid()
except libvirtError as error:
uuid, self.unreachable = "", str(error)
if uuid and (other := Compute.objects.exclude(pk=self.pk).filter(host_uuid=uuid).first()):
raise ValidationError(_("This host is already added as %(name)s"), params={"name": other.name})
if before and self.instance_set.exists():
if not uuid:
raise ValidationError(_("The panel cannot reach the host to tell that its VMs are there: %(error)s"),
params={"error": self.unreachable})
try:
recorded = before["host_uuid"] or Compute.objects.get(pk=self.pk).record_host()
except IntegrityError:
recorded = ""
if not recorded:
raise ValidationError(_("The host its VMs are on is not known yet: change the connection when "
"the panel has reached the host at its current one"))
if uuid != recorded:
raise ValidationError(_("This is another host than the one its VMs are on: "
"add it as a new host"))
self.host_uuid = uuid
def delete(self, *args, **kwargs):
"""Its VMs keep running on the host: their owners wait in tombstones,
or follow a VM already listed on another compute. The compute is held

View file

@ -1,5 +1,18 @@
"""Test doubles for the computes tests."""
from unittest.mock import patch
from libvirt import libvirtError
def no_host_answers(test):
"""For test: the hosts a compute form or API call tries (Compute.clean)
cannot be reached, so none is connected to, the machine's own libvirt
least of all."""
patcher = patch("computes.models.wvmHostDetails", side_effect=libvirtError("unreachable"))
patcher.start()
test.addCleanup(patcher.stop)
class Domain:
"""A libvirt domain as the VM list reads it: its name and UUID."""

View file

@ -9,6 +9,7 @@ from operations.models import Claim
from operations.utils import busy_message
from computes.models import Compute
from computes.tests.fakes import no_host_answers
class ComputeAuditRowTests(TestCase):
@ -16,6 +17,7 @@ class ComputeAuditRowTests(TestCase):
self.admin = get_user_model().objects.create_superuser("audit-admin", "audit@example.com", "pw")
self.client.force_login(self.admin)
Logs.objects.all().delete() # the login's row
no_host_answers(self)
def messages(self):
return list(Logs.objects.order_by("id").values_list("message", flat=True))

View file

@ -6,11 +6,13 @@ from django.test import TestCase
from django.urls import reverse
from computes.models import Compute
from computes.tests.fakes import no_host_answers
class ComputePasswordTests(TestCase):
def setUp(self):
self.client.force_login(get_user_model().objects.create_superuser("cp-admin", "cp@example.com", "pw"))
no_host_answers(self)
def edit(self, compute, password):
data = {"name": compute.name, "hostname": compute.hostname, "login": "admin", "password": password,

View file

@ -6,6 +6,7 @@ from django.test import TestCase
from django.urls import reverse
from computes.models import Compute
from computes.tests.fakes import no_host_answers
KEY, OTHER = "5e" * 32, "a1" * 32
@ -13,6 +14,7 @@ KEY, OTHER = "5e" * 32, "a1" * 32
class GstfsdKeyTests(TestCase):
def setUp(self):
self.client.force_login(get_user_model().objects.create_superuser("gk-admin", "gk@example.com", "pw"))
no_host_answers(self)
def edit(self, compute, key):
data = {"name": compute.name, "hostname": compute.hostname, "login": "admin", "password": "",

View file

@ -0,0 +1,108 @@
"""One libvirt host is one compute, and a compute's VMs stay on their host:
the host UUID of a new or changed connection is read and checked."""
from unittest.mock import MagicMock, PropertyMock, patch
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from instances.models import Instance
from libvirt import libvirtError
from operations import claims
from operations.models import Claim
from computes.models import Compute
# the host each address reaches, by its UUID; an address not here does not answer
HOSTS = {"192.0.2.1": "11111111-1111-1111-1111-111111111111", "kvm1.example.org": "11111111-1111-1111-1111-111111111111",
"192.0.2.2": "22222222-2222-2222-2222-222222222222"}
def host(hostname, login, password, conn_type):
if hostname not in HOSTS:
raise libvirtError(f"{hostname} did not answer within 5 s")
return MagicMock(**{"host_uuid.return_value": HOSTS[hostname]})
class HostIdentityTests(TestCase):
def setUp(self):
self.client.force_login(get_user_model().objects.create_superuser("hi-admin", "hi@example.com", "pw"))
patcher = patch("computes.models.wvmHostDetails", side_effect=host)
patcher.start()
self.addCleanup(patcher.stop)
def add(self, name, hostname):
return self.client.post(reverse("add_tcp_host"), {"name": name, "hostname": hostname, "login": "wvc",
"password": "pw", "details": "", "type": 1})
def edit(self, compute, hostname):
return self.client.post(reverse("compute_update", args=[compute.id]),
{"name": compute.name, "hostname": hostname, "login": "wvc", "password": "",
"details": "", "type": 1})
def test_a_host_is_added_once_whatever_it_is_reached_by(self):
self.add("kvm1", "192.0.2.1")
self.assertEqual(Compute.objects.get(name="kvm1").host_uuid, HOSTS["192.0.2.1"])
response = self.add("kvm1-again", "kvm1.example.org")
self.assertContains(response, "This host is already added as kvm1")
self.assertFalse(Compute.objects.filter(name="kvm1-again").exists())
def test_a_compute_added_before_is_recorded_on_the_computes_page(self):
Compute.objects.create(name="old", hostname="192.0.2.1", login="wvc", password="pw", type=1)
with patch.object(Compute, "status", new_callable=PropertyMock, return_value=True), \
patch("computes.views.shown_capacity", return_value=None):
self.client.get(reverse("computes"))
self.assertEqual(Compute.objects.get(name="old").host_uuid, HOSTS["192.0.2.1"])
self.assertContains(self.add("new", "kvm1.example.org"), "This host is already added as old")
def test_a_compute_with_vms_whose_host_is_not_known_keeps_its_connection(self):
compute = Compute.objects.create(name="old", hostname="192.0.2.9", login="wvc", password="pw", type=1)
Instance.objects.create(compute=compute, name="web-1", uuid="33333333-3333-3333-3333-333333333333")
self.assertContains(self.edit(compute, "192.0.2.2"), "The host its VMs are on is not known yet")
compute.refresh_from_db()
self.assertEqual(compute.hostname, "192.0.2.9")
def test_a_compute_with_vms_moves_only_to_an_address_of_their_host(self):
self.add("kvm1", "192.0.2.1")
compute = Compute.objects.get(name="kvm1")
Instance.objects.create(compute=compute, name="web-1", uuid="33333333-3333-3333-3333-333333333333")
self.assertContains(self.edit(compute, "192.0.2.2"), "This is another host than the one its VMs")
self.assertContains(self.edit(compute, "192.0.2.9"), "The panel cannot reach the host to tell that its VMs")
self.edit(compute, "kvm1.example.org")
compute.refresh_from_db()
self.assertEqual((compute.hostname, compute.host_uuid), ("kvm1.example.org", HOSTS["192.0.2.1"]))
def test_a_compute_without_vms_may_be_another_host_or_none_yet(self):
self.add("kvm", "192.0.2.9") # added while it does not answer
compute = Compute.objects.get(name="kvm")
self.assertEqual(compute.host_uuid, "")
self.edit(compute, "192.0.2.2")
compute.refresh_from_db()
self.assertEqual(compute.host_uuid, HOSTS["192.0.2.2"])
def test_a_change_is_checked_while_the_compute_is_held(self):
# no VM list can add the old host's VMs between the check and the save
compute = Compute.objects.create(name="kvm", hostname="192.0.2.9", login="wvc", password="pw", type=1)
held = []
def checked(*args):
held.append(set(Claim.objects.values_list("resource", "mode")))
return host(*args)
with patch("computes.models.wvmHostDetails", side_effect=checked):
self.edit(compute, "192.0.2.2")
self.client.patch(f"/api/v1/computes/{compute.id}/", {"hostname": "192.0.2.1"}, content_type="application/json")
for claimed in held:
self.assertLessEqual({(claims.compute_key(compute.id), Claim.EXCLUSIVE), (claims.hosts_key(), Claim.EXCLUSIVE)},
claimed)
self.assertEqual(len(held), 2)
def test_the_api_checks_the_host_too(self):
self.add("kvm1", "192.0.2.1")
data = {"name": "kvm1-api", "hostname": "kvm1.example.org", "login": "wvc", "password": "pw", "type": 1}
response = self.client.post("/api/v1/computes/", data, content_type="application/json")
self.assertEqual(response.status_code, 400)
self.assertIn("This host is already added as kvm1", str(response.json()))
data["hostname"] = "192.0.2.2"
self.assertEqual(self.client.post("/api/v1/computes/", data, content_type="application/json").status_code, 201)
self.assertEqual(Compute.objects.get(name="kvm1-api").host_uuid, HOSTS["192.0.2.2"])

View file

@ -9,6 +9,7 @@ from libvirt import libvirtError
from vrtManager.connection import CONN_SOCKET, connection_manager
from computes.models import Compute
from computes.tests.fakes import no_host_answers
from vrtManager.tests import livetest
TEST_COMPUTE_HOST = os.environ.get("TEST_LIBVIRT_HOST", "localhost")
@ -58,6 +59,7 @@ class ComputesTestCase(TestCase):
@patch.object(Compute, "connection", new_callable=PropertyMock, return_value=libvirtError("unreachable"))
def test_create_update_delete(self, connection):
no_host_answers(self)
response = self.client.get(reverse("add_socket_host"))
self.assertEqual(response.status_code, 200)

View file

@ -28,6 +28,18 @@ def libvirt_compute_lock(compute, *, shared=False):
yield
@contextmanager
def hosts_lock(compute=None):
"""A compute added or its connection changed: checked (Compute.clean)
and saved one at a time, so two cannot be one host; a compute changed
is held exclusive, so its VMs are not listed from the old host meanwhile."""
wanted = {claims.hosts_key(): Claim.EXCLUSIVE}
if compute is not None:
wanted[claims.compute_key(compute.pk)] = Claim.EXCLUSIVE
with claims.hold(wanted):
yield
@contextmanager
def user_quota_lock(user):
"""One user's quota check and the change it allows run one at a time."""

View file

@ -1,9 +1,11 @@
import json
import logging
from contextlib import suppress
from admin.decorators import superuser_only
from django.conf import settings
from django.core import signing
from django.db import IntegrityError
from django.http import HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
@ -85,6 +87,10 @@ def computes(request):
"vcpus": 0, "cpus": 0, "assigned": 0, "memory": 0}
for compute in computes:
compute.connection_name = CONNECTIONS.get(compute.type, "")
if compute.status is True and not compute.host_uuid:
# one added before host UUIDs were kept (Compute.clean); none for a second record of a host
with suppress(IntegrityError):
compute.record_host()
compute.shown_capacity = given = shown_capacity(compute)
totals["connected"] += compute.status is True
if given:
@ -153,11 +159,13 @@ def instances(request, compute_id):
@superuser_only
def compute_create(request, FormClass):
form = FormClass(request.POST or None)
if form.is_valid():
compute = form.instance
with audit(request, compute, f"Compute {compute.name} ({compute.hostname})", "add"):
form.save()
return redirect(reverse("computes"))
if request.method == "POST":
with utils.hosts_lock():
if form.is_valid():
compute = form.instance
with audit(request, compute, f"Compute {compute.name} ({compute.hostname})", "add"):
form.save()
return redirect(reverse("computes"))
return render(request, "computes/form.html", {"form": form})
@ -179,14 +187,17 @@ def compute_update(request, compute_id):
subject = f"Compute {compute.name} ({compute.hostname})"
before = snapshot(compute)
form = FormClass(request.POST or None, instance=compute)
if form.is_valid():
if request.method == "POST":
# held as a delete holds it: a job on the compute keeps the host it was admitted for
with audit(request, compute, subject, "change") as entry, utils.libvirt_compute_lock(compute):
form.save()
fields = changed_fields(before, snapshot(compute))
entry.action = "change " + ", ".join(fields)
entry.skip = not fields
return redirect(reverse("computes"))
with audit(request, compute, subject, "change") as entry, utils.hosts_lock(compute):
entry.skip = True # a refused form changes nothing
if form.is_valid():
form.save()
fields = changed_fields(before, snapshot(compute))
entry.action = "change " + ", ".join(fields)
entry.skip = not fields
if form.is_valid():
return redirect(reverse("computes"))
return render(request, "computes/form.html", {"form": form})