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

fix(computes): a host's maintenance shows only its own bulk migration; the panel's refusals are not libvirt errors

The host page in maintenance showed the host's latest bulk migration even
when it was from before the maintenance, as a job of the morning that
"succeeded" while a VM still ran. The host now keeps when it went in
maintenance (maintenance_since; a job that puts it there sets it to the
job's own time), and the page shows a bulk migration from then on, or one
still running.

A refusal of the panel's own (OperationError), such as a VM start on a
host in maintenance, was shown as "libvirt Error - ...": it is shown as is.
This commit is contained in:
catborise 2026-11-16 20:04:37 +03:00
parent d96fe940e9
commit 80e68d0628
9 changed files with 110 additions and 31 deletions

View file

@ -204,7 +204,7 @@ class Balance(Migrations):
def check_move(self, source, target):
"""Balance leaves a host in maintenance out: it takes no VM and gives none."""
super().check_move(source, target)
if host := Compute.objects.filter(pk=source, maintenance=True).first():
if host := Compute.objects.filter(pk=source, maintenance_since__isnull=False).first():
raise util.OperationError(gettext_noop("%(compute)s is in maintenance: Balance leaves it out"),
compute=host.name)

View file

@ -0,0 +1,27 @@
from django.db import migrations, models
from django.utils import timezone
def keep_maintenance(apps, schema_editor):
# a host in maintenance stays in it, from now on
apps.get_model("computes", "Compute").objects.filter(maintenance=True).update(maintenance_since=timezone.now())
class Migration(migrations.Migration):
dependencies = [
("computes", "0010_maintenance"),
]
operations = [
migrations.AddField(
model_name="compute",
name="maintenance_since",
field=models.DateTimeField(blank=True, editable=False, null=True),
),
migrations.RunPython(keep_maintenance, migrations.RunPython.noop),
migrations.RemoveField(
model_name="compute",
name="maintenance",
),
]

View file

@ -2,7 +2,7 @@ from ipaddress import ip_address
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
from django.db.models import BooleanField, CharField, IntegerField, Model, Q, UniqueConstraint
from django.db.models import CharField, DateTimeField, IntegerField, Model, Q, UniqueConstraint
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from django.utils.translation import gettext_noop
@ -54,12 +54,17 @@ class Compute(Model):
# in maintenance: no new VM and no migration comes to the host, none of its
# VMs starts there, and Balance leaves it out; Bulk Migrate empties it, and
# it is ready once none of its VMs runs (refuse_new_vms, refuse_start)
maintenance = BooleanField(default=False, editable=False)
# it is ready once none of its VMs runs (refuse_new_vms, refuse_start);
# since when: the host's bulk migrations from then on are its own
maintenance_since = DateTimeField(null=True, blank=True, editable=False)
class Meta:
constraints = [UniqueConstraint(fields=["host_uuid"], condition=~Q(host_uuid=""), name="one_compute_per_host")]
@property
def maintenance(self):
return self.maintenance_since is not None
def refuse_new_vms(self):
"""Refuses a VM made on or migrated to the host while it is in maintenance."""
if self.maintenance:

View file

@ -8,6 +8,7 @@ import libvirt
from computes.balance import propose, spread
from computes.jobs import Balance
from computes.models import Compute
from django.utils import timezone
from django.contrib.auth import get_user_model
from django.test import SimpleTestCase, TestCase
from django.urls import reverse
@ -168,7 +169,7 @@ class BalancePageTests(TestCase):
self.assertIn("ba-other", page.xpath("//div[contains(@class, 'alert-warning')]")[0].text_content())
def test_a_host_in_maintenance_is_left_out(self):
Compute.objects.filter(pk=self.other.pk).update(maintenance=True)
Compute.objects.filter(pk=self.other.pk).update(maintenance_since=timezone.now())
page = self.page()
self.assertEqual(self.moved(page), [])
self.assertEqual(list(self.response.context["hosts"]), [self.compute])

View file

@ -8,6 +8,7 @@ from unittest.mock import patch
import libvirt
from computes.models import Compute
from django.utils import timezone
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
@ -67,7 +68,7 @@ class BulkMigratePageTests(TestCase):
self.assertIn("not on storage both hosts share", local.getparent().getparent().text_content())
def test_a_host_in_maintenance_is_no_destination(self):
Compute.objects.create(name="ev-rest", hostname="198.51.100.32", login="", password="", type=4, maintenance=True)
Compute.objects.create(name="ev-rest", hostname="198.51.100.32", login="", password="", type=4, maintenance_since=timezone.now())
page = self.page()
self.assertEqual(page.xpath("//select[@id='bulk-migrate-target']"), []) # one destination left: no choice
self.assertNotIn("ev-rest", page.text_content())

View file

@ -10,7 +10,9 @@ from computes.jobs import Balance
from computes.models import Compute
from computes.tests.test_balance import Ctx
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.db import connection
from django.db.migrations.executor import MigrationExecutor
from django.test import TestCase, TransactionTestCase
from django.urls import reverse
from django.utils import timezone
from instances.jobs import CloneInstance, CreateInstance, _finish_clone, _revert_start, migration_target
@ -35,9 +37,11 @@ class MaintenanceSwitchTests(TestCase):
def test_the_form_sets_the_state_it_names_and_each_change_is_audited(self):
self.assertRedirects(self.switch("on"), reverse("overview", args=[self.compute.pk]), fetch_redirect_response=False)
self.switch("on") # a second page sent meanwhile does not turn it back
self.compute.refresh_from_db()
self.assertTrue(self.compute.maintenance)
since = self.compute.maintenance_since
self.switch("on") # a second page sent meanwhile does not turn it back, nor starts it anew
self.compute.refresh_from_db()
self.assertEqual(self.compute.maintenance_since, since)
self.switch("off")
self.compute.refresh_from_db()
self.assertFalse(self.compute.maintenance)
@ -48,7 +52,7 @@ class MaintenanceSwitchTests(TestCase):
self.assertEqual(self.client.get(reverse("compute_maintenance", args=[self.compute.pk])).status_code, 405)
def test_a_vm_cannot_be_created_from_its_pages(self):
self.compute.maintenance = True
self.compute.maintenance_since = timezone.now()
self.compute.save()
for url in (reverse("instances:create_instance_select_type", args=[self.compute.pk]),
reverse("instances:create_instance", args=[self.compute.pk, "x86_64", "q35"])):
@ -61,7 +65,7 @@ class MaintenanceGuardTests(TestCase):
def setUp(self):
self.admin = get_user_model().objects.create_superuser("mg-admin", "mg@example.com", "pw")
self.host = Compute.objects.create(name="mg", hostname="192.0.2.62", login="", password="", type=4,
maintenance=True)
maintenance_since=timezone.now())
self.other = Compute.objects.create(name="mg-other", hostname="192.0.2.63", login="", password="", type=4)
def test_no_vm_migrates_to_it(self):
@ -90,12 +94,12 @@ class BalanceLeavesItOutTests(TestCase):
self.params = {"parallel": 1, "moves": [[self.vm.pk, self.hosts[0].pk, self.hosts[1].pk]]}
def maintenance(self, host):
Compute.objects.filter(pk=host.pk).update(maintenance=True)
Compute.objects.filter(pk=host.pk).update(maintenance_since=timezone.now())
def test_a_move_from_or_to_a_host_in_maintenance_is_refused(self):
for host, text in ((self.hosts[0], "mb-0 is in maintenance: Balance leaves it out"),
(self.hosts[1], f"mb-1 {REFUSED}")):
Compute.objects.update(maintenance=False)
Compute.objects.update(maintenance_since=None)
self.maintenance(host)
with self.assertRaisesRegex(util.OperationError, text):
Balance().validate(self.admin, Balance().normalize(self.params))
@ -115,7 +119,7 @@ class NoStartTests(TestCase):
def setUp(self):
self.compute = Compute.objects.create(name="ms", hostname="192.0.2.81", login="", password="", type=1,
maintenance=True)
maintenance_since=timezone.now())
self.instance = Instance.objects.create(compute=self.compute, name="ms-vm",
uuid="00000000-0000-4000-8000-000000000301")
self.client.force_login(get_user_model().objects.create_superuser("ms-admin", "ms@example.com", "pw"))
@ -128,6 +132,7 @@ class NoStartTests(TestCase):
for action in ("poweron", "resume", "powercycle"):
response = self.client.post(reverse(f"instances:{action}", args=[self.instance.pk]), follow=True)
self.assertContains(response, "ms is in maintenance: its VMs cannot be started there")
self.assertNotContains(response, "libvirt Error") # the panel's own refusal
self.proxy.start.assert_not_called()
self.proxy.resume.assert_not_called()
self.proxy.force_shutdown.assert_not_called() # a power cycle would leave it off
@ -181,6 +186,7 @@ class MaintenanceWithMigrationTests(TestCase):
(op,) = Operation.objects.all()
self.assertTrue(op.params["maintenance"])
self.assertTrue(self.maintenance())
self.assertEqual(self.compute.maintenance_since, op.created_at) # the job is of this maintenance
self.assertEqual(list(Logs.objects.values_list("message", flat=True)), ["Compute me: maintenance on"])
def test_a_refused_job_leaves_the_host_out_of_maintenance(self):
@ -195,14 +201,14 @@ class MaintenanceWithMigrationTests(TestCase):
Operation.objects.update(created_at=timezone.now() - SUBMISSION_KEY_TTL - timedelta(minutes=1),
state=Operation.SUCCEEDED)
Claim.objects.all().delete() # it ended
Compute.objects.filter(pk=self.compute.pk).update(maintenance=False)
Compute.objects.filter(pk=self.compute.pk).update(maintenance_since=None)
self.post()
self.assertTrue(self.maintenance())
self.assertEqual(Operation.objects.count(), 2)
def test_the_form_sent_again_does_not_put_it_back(self):
self.post()
Compute.objects.filter(pk=self.compute.pk).update(maintenance=False) # taken out since
Compute.objects.filter(pk=self.compute.pk).update(maintenance_since=None) # taken out since
self.post()
self.assertFalse(self.maintenance())
self.assertEqual(Operation.objects.count(), 1)
@ -221,7 +227,7 @@ class MaintenanceWithMigrationTests(TestCase):
response = self.page(maintenance="on")
self.assertContains(response, "Put in maintenance without migrating")
self.assertContains(response, '<input type="hidden" name="maintenance" value="on">', count=3)
Compute.objects.filter(pk=self.compute.pk).update(maintenance=True) # already: the plain page
Compute.objects.filter(pk=self.compute.pk).update(maintenance_since=timezone.now()) # already: the plain page
self.assertNotContains(self.page(maintenance="on"), "Put in maintenance without migrating")
@ -231,7 +237,7 @@ class MaintenanceStateTests(TestCase):
def setUp(self):
self.compute = Compute.objects.create(name="mz", hostname="192.0.2.95", login="", password="", type=4,
maintenance=True)
maintenance_since=timezone.now())
self.client.force_login(get_user_model().objects.create_superuser("mz-admin", "mz@example.com", "pw"))
@staticmethod
@ -255,8 +261,26 @@ class MaintenanceStateTests(TestCase):
def test_a_host_that_cannot_be_read_is_not_said_ready(self):
self.assertContains(self.overview(None), "whether its VMs still run is not known")
def bulk(self, state, before):
op = Operation.objects.create(kind="host.bulk_migrate", user=None, username="mz-admin", state=state,
resource=f"compute:{self.compute.pk}")
if before:
Operation.objects.filter(pk=op.pk).update(created_at=self.compute.maintenance_since - timedelta(hours=1))
return op
def test_only_a_bulk_migration_of_this_maintenance_or_one_still_running_is_shown(self):
self.bulk(Operation.SUCCEEDED, before=True) # an earlier one
response = self.overview(self.given(running=1))
self.assertNotContains(response, "bulk migration")
self.assertNotContains(response, "being migrated")
running = self.bulk(Operation.RUNNING, before=True)
self.assertContains(self.overview(self.given(running=1)), "Its VMs are being migrated")
Operation.objects.filter(pk=running.pk).update(state=Operation.FAILED)
self.bulk(Operation.FAILED, before=False)
self.assertContains(self.overview(self.given(running=1)), "Its last bulk migration")
def test_put_in_maintenance_leads_to_bulk_migrate_while_vms_run(self):
Compute.objects.filter(pk=self.compute.pk).update(maintenance=False)
Compute.objects.filter(pk=self.compute.pk).update(maintenance_since=None)
response = self.overview(self.given(running=1))
self.assertContains(response, reverse("bulk_migrate", args=[self.compute.pk]) + "?maintenance=on")
response = self.overview(self.given(shutoff=1))
@ -266,7 +290,7 @@ class MaintenanceStateTests(TestCase):
class CloneStaysOffTests(TestCase):
def test_a_clone_made_while_the_host_went_in_maintenance_stays_off(self):
compute = Compute.objects.create(name="mc", hostname="192.0.2.97", login="", password="", type=1,
maintenance=True)
maintenance_since=timezone.now())
op = SimpleNamespace(intent={"compute": compute.pk, "name": "mc-clone",
"uuid": "00000000-0000-4000-8000-000000000501"},
username="mc-admin", client_ip=None)
@ -274,3 +298,17 @@ class CloneStaysOffTests(TestCase):
result = _finish_clone(op, {"start": True}, "")
proxy.return_value.start.assert_not_called()
self.assertIn("is in maintenance: its VMs cannot be started there", str(result["warning"]))
class MaintenanceSinceMigrationTests(TransactionTestCase):
"""A host in maintenance before maintenance_since stays in maintenance."""
def test_a_host_in_maintenance_stays_in_it(self):
executor = MigrationExecutor(connection)
executor.migrate([("computes", "0010_maintenance")])
old = executor.loader.project_state([("computes", "0010_maintenance")]).apps.get_model("computes", "Compute")
old.objects.create(name="mm-on", hostname="192.0.2.97", login="", password="", type=4, maintenance=True)
old.objects.create(name="mm-off", hostname="192.0.2.98", login="", password="", type=4)
executor = MigrationExecutor(connection)
executor.migrate(executor.loader.graph.leaf_nodes())
self.assertEqual({c.name: c.maintenance for c in Compute.objects.all()}, {"mm-on": True, "mm-off": False})

View file

@ -10,6 +10,7 @@ from django.conf import settings
from django.contrib import messages
from django.core import signing
from django.db import IntegrityError, transaction
from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
@ -198,9 +199,11 @@ def overview(request, compute_id):
# the connection itself, not a TCP probe: ssh aliases and ProxyJump hosts
# are not reachable by name and port from here
context = {"compute": compute, "connected": compute.status is True,
# the host's latest bulk migration: in maintenance, whether its VMs are being moved, or how that ended
# in maintenance, the host's latest bulk migration of that maintenance, or one still running:
# whether its VMs are being moved, or how that ended
"bulk": Operation.objects.filter(kind="host.bulk_migrate", resource=claims.compute_key(compute.pk))
.order_by("-created_at").first()}
.filter(Q(created_at__gte=compute.maintenance_since) | Q(state__in=Operation.ACTIVE))
.order_by("-created_at").first() if compute.maintenance else None}
context["bulk_running"] = context["bulk"] is not None and context["bulk"].state in Operation.ACTIVE
if context["connected"]:
try:
@ -282,7 +285,7 @@ def bulk_migrate(request, compute_id):
compute = get_object_or_404(Compute, pk=compute_id)
# a host in maintenance takes no VM (Compute.refuse_new_vms)
targets = list(Compute.objects.exclude(pk=compute.pk).filter(maintenance=False).order_by("name"))
targets = list(Compute.objects.exclude(pk=compute.pk).filter(maintenance_since=None).order_by("name"))
if request.method == "POST":
chosen = request.POST.getlist("instance")
if request.POST.get("spread"):
@ -303,7 +306,7 @@ def bulk_migrate(request, compute_id):
op = jobs.submit("host.bulk_migrate", request.user, raw, key)
if entering and op.pk != found:
with audit(request, compute, f"Compute {compute.name}", "maintenance on"):
Compute.objects.filter(pk=compute.pk).update(maintenance=True)
Compute.objects.filter(pk=compute.pk).update(maintenance_since=op.created_at)
except claims.Busy as busy:
messages.error(request, busy_message(busy, request.user))
except (ValueError, jobs.SubmissionConflict, libvirtError) as err:
@ -480,7 +483,10 @@ def maintenance(request, compute_id):
wanted = request.POST.get("maintenance") == "on"
action = "maintenance on" if wanted else "maintenance off"
with audit(request, compute, f"Compute {compute.name}", action):
Compute.objects.filter(pk=compute.pk).update(maintenance=wanted)
if wanted: # already in maintenance: since then still
Compute.objects.filter(pk=compute.pk, maintenance_since=None).update(maintenance_since=timezone.now())
else:
Compute.objects.filter(pk=compute.pk).update(maintenance_since=None)
return redirect("overview", compute.pk)

View file

@ -10,6 +10,7 @@ import unittest
from unittest.mock import PropertyMock, patch
from computes.models import Compute
from django.utils import timezone
from django.conf import settings
from django.contrib.auth import get_user_model
from django.test import TestCase
@ -146,7 +147,7 @@ class CreateDialogHostsTestCase(TestCase):
self.assertNotIn("No compute is reachable", dialog.text_content())
def test_a_host_in_maintenance_is_listed_but_cannot_be_chosen(self):
Compute.objects.filter(name="cd1").update(maintenance=True)
Compute.objects.filter(name="cd1").update(maintenance_since=timezone.now())
dialog = self.dialog({"cd1", "cd2"})
self.assertEqual([e.text for e in dialog.xpath(".//a/div/div[1]")], ["cd2"])
(item,) = dialog.xpath(".//div[@aria-disabled='true']")

View file

@ -12,7 +12,7 @@ from logs.audit import request_ip, write
from operations import claims, jobs
from operations.utils import busy_message, public_error_text, said, summary, words
from vrtManager.util import ConnectionFailed, InUse
from vrtManager.util import ConnectionFailed, InUse, OperationError
from webvirtcloud import log_context
from webvirtcloud.log_context import current_request
@ -151,10 +151,10 @@ class ExceptionMiddleware:
messages.error(request, busy_message(exception, request.user))
return redirect(request.get_full_path())
if isinstance(exception, libvirtError):
messages.error(
request,
_("libvirt Error - %(exception)s") % {"exception": error_text(request, exception)},
)
text = error_text(request, exception)
# the panel's own refusal (OperationError) is not libvirt's error
messages.error(request, text if isinstance(exception, OperationError)
else _("libvirt Error - %(exception)s") % {"exception": text})
if request.method not in ("GET", "HEAD"):
# a refused form: back to the page it was on, with the reason
return redirect(same_origin_referer(request, "/"))