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

feat(computes): a host in maintenance takes no new VM or migration

After a host was emptied with Bulk Migrate for its maintenance, Balance
proposed moving VMs back onto it, and new VMs and migrations could still be
sent there. A superuser now puts a host in maintenance on its page (and
takes it out), each change audited; the form names the state it sets, so a
second page sent meanwhile does not turn it back.

A host in maintenance (Compute.maintenance, refuse_new_vms):
- takes no migration: migration_target refuses it, so the Migrate tab,
  Bulk Migrate, Balance and queued migrate jobs follow one rule; Bulk
  Migrate leaves it out of its destinations and its spread;
- takes no new VM: the create and clone jobs refuse it when asked for and
  again before they start (the REST API submits the same jobs); the create
  pages and the XML define send the user back to the VM list, and the New VM
  dialog lists it without a link;
- is left out of Balance: its VMs neither count nor move, and the Balance
  job refuses a move from it too, before each migration starts.
Its VMs run on; a migration already started finishes. The Computes page and
the host's page show that it is in maintenance.
This commit is contained in:
catborise 2026-11-16 15:56:01 +03:00
parent 070a4b99da
commit 22362de068
19 changed files with 704 additions and 362 deletions

View file

@ -44,6 +44,13 @@ class Migrations(Kind):
def hosts(self, params):
return {host for _vm, source, target in self.moves(params) for host in (source, target)}
def check_move(self, source, target):
"""Refuses (OperationError) a move to a host in maintenance, when the
job is asked for and again before the VM's migration starts; the
migrate job checks the rest."""
if host := Compute.objects.filter(pk=target).first():
host.refuse_new_vms()
def validate(self, user, params):
if not user.is_superuser:
raise PermissionDenied
@ -52,6 +59,8 @@ class Migrations(Kind):
if not 1 <= params["parallel"] <= parallel_limit():
raise util.OperationError(gettext_noop("At most %(limit)s migrations can run at once"),
limit=parallel_limit())
for _vm, source, target in self.moves(params):
self.check_move(source, target)
def precheck(self, op, ctx):
if op.user is None or not op.user.is_active or not op.user.is_superuser:
@ -96,6 +105,7 @@ class Migrations(Kind):
raw = {"instance": vm, "source": source, "target": target, "live": True, "autoconverge": True,
**self.options}
try:
self.check_move(source, target) # a host put in maintenance since
child = jobs.submit("instance.migrate", op.user, raw, f"bulk-{op.pk.hex}-{vm}", parent=op)
except claims.Busy as busy:
if busy.blocker is not None and busy.blocker.state == Operation.UNCERTAIN:
@ -189,6 +199,13 @@ class Balance(Migrations):
def moves(self, params):
return [tuple(move) for move in params["moves"]]
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():
raise util.OperationError(gettext_noop("%(compute)s is in maintenance: Balance leaves it out"),
compute=host.name)
def validate(self, user, params):
super().validate(user, params)
if any(source == target for _vm, source, target in self.moves(params)):

View file

@ -0,0 +1,18 @@
# Generated by Django 5.2.18 on 2026-11-16 12:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('computes', '0009_host_uuid'),
]
operations = [
migrations.AddField(
model_name='compute',
name='maintenance',
field=models.BooleanField(default=False, editable=False),
),
]

View file

@ -2,12 +2,14 @@ from ipaddress import ip_address
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
from django.db.models import CharField, IntegerField, Model, Q, UniqueConstraint
from django.db.models import BooleanField, CharField, 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
from libvirt import libvirtError, virConnect
from computes.validators import validate_gstfsd_key, validate_hostname, validate_login, validate_migration_address
from vrtManager import util
from vrtManager.connection import connection_manager
from vrtManager.hostdetails import wvmHostDetails
@ -50,9 +52,19 @@ class Compute(Model):
# 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)
# in maintenance: no new VM and no migration comes to the host, and Balance
# leaves it out; its VMs run on and Bulk Migrate empties it (refuse_new_vms)
maintenance = BooleanField(default=False, editable=False)
class Meta:
constraints = [UniqueConstraint(fields=["host_uuid"], condition=~Q(host_uuid=""), name="one_compute_per_host")]
def refuse_new_vms(self):
"""Refuses a VM made on or migrated to the host while it is in maintenance."""
if self.maintenance:
raise util.OperationError(gettext_noop("%(compute)s is in maintenance: no new VM or migration comes to it"),
compute=self.name)
@property
def migration_uri(self):
"""The native migration URI for VMs migrated to this host: its

View file

@ -16,6 +16,9 @@
{% if unreachable %}
<div class="alert alert-warning shadow-sm">{% trans "These hosts cannot be read and are left out:" %} {{ unreachable|join:", " }}</div>
{% endif %}
{% if resting %}
<div class="alert alert-secondary shadow-sm">{% trans "These hosts are in maintenance and are left out:" %} {{ resting|join:", " }}</div>
{% endif %}
{# each host's running VMs: the share of its memory now and, light to dark, after the migrations #}
<div class="row row-cols-1 row-cols-md-2 row-cols-xl-3 g-3 mb-4">

View file

@ -75,6 +75,7 @@
{% else %}
<span class="badge text-bg-danger">{% trans "Not connected" %}</span>
{% endif %}
{% if compute.maintenance %}<span class="badge text-bg-warning">{% trans "In maintenance" %}</span>{% endif %}
<span class="badge text-bg-light border">{{ compute.connection_name }}</span>
</div>
<div class="small text-body-secondary font-monospace mt-1">{{ compute.hostname }}</div>

View file

@ -6,6 +6,15 @@
{% block title %}{% trans "Overview" %} - {{ compute.name }}{% endblock %}
{% block page_heading_extra %}
<form method="post" action="{% url 'compute_maintenance' compute.id %}" class="d-inline">{% csrf_token %}
{% if compute.maintenance %}
<input type="hidden" name="maintenance" value="off">
<button type="submit" class="btn btn-sm btn-warning">{% bs_icon 'wrench-adjustable' %} {% trans "End maintenance" %}</button>
{% else %}
<input type="hidden" name="maintenance" value="on">
<button type="submit" class="btn btn-sm btn-outline-warning" data-confirm="{% trans "Put the host in maintenance? No new VM or migration comes to it and Balance leaves it out; its VMs keep running." %}">{% bs_icon 'wrench-adjustable' %} {% trans "Put in maintenance" %}</button>
{% endif %}
</form>
<a class="btn btn-sm btn-outline-primary" href="{% url 'compute_update' compute.id %}">{% bs_icon 'pencil' %} {% trans "Edit connection" %}</a>
<a class="btn btn-sm btn-outline-danger" href="{% url 'compute_delete' compute.id %}">{% bs_icon 'x-circle' %} {% trans "Remove from panel" %}</a>
{% endblock page_heading_extra %}
@ -27,6 +36,13 @@
{% include "computes/host_nav.html" with section="overview" %}
{% if compute.maintenance %}
<div class="alert alert-warning" role="status">
{% url 'bulk_migrate' compute.id as bulk_url %}
{% blocktrans %}In maintenance: no new VM or migration comes to this host and Balance leaves it out. <a href="{{ bulk_url }}">Bulk Migrate</a> moves its VMs to the other hosts.{% endblocktrans %}
</div>
{% endif %}
{% if not connected %}
<div class="alert alert-warning" role="alert">
<div class="mb-2">{% trans "The panel cannot reach this host, so its VMs, capacity and load are not shown:" %} {{ compute.connection_error }}</div>

View file

@ -167,6 +167,14 @@ class BalancePageTests(TestCase):
self.assertEqual(self.moved(page), [])
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)
page = self.page()
self.assertEqual(self.moved(page), [])
self.assertEqual(list(self.response.context["hosts"]), [self.compute])
self.assertIn("in maintenance and are left out: ba-other", page.xpath("//div[contains(@class, 'alert-secondary')]")[0].text_content())
self.assertEqual(page.xpath("//div[contains(@class, 'alert-warning')]"), []) # not said to be unreadable
def test_the_moves_shown_go_in_one_balance_job(self):
vm = self.vms["ba-1"].pk
response = self.client.post(reverse("balance"), {"instance": [vm], "source": [self.compute.pk],

View file

@ -66,6 +66,12 @@ class BulkMigratePageTests(TestCase):
self.assertIsNotNone(local.get("disabled"))
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)
page = self.page()
self.assertEqual(page.xpath("//select[@id='bulk-migrate-target']"), []) # one destination left: no choice
self.assertNotIn("ev-rest", page.text_content())
def bulk_migrate(self, target, chosen):
return self.client.post(reverse("bulk_migrate", args=[self.compute.id]),
{"target": target, "instance": chosen, "parallel": "2", "submission_key": "evac0000key"})

View file

@ -0,0 +1,106 @@
"""A host in maintenance takes no new VM and no migration, and Balance leaves
it out; its VMs run on. A superuser puts it in maintenance and takes it out
on its page, each change audited."""
from types import SimpleNamespace
from unittest.mock import patch
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.urls import reverse
from instances.jobs import CloneInstance, CreateInstance, migration_target
from instances.models import Instance
from logs.models import Logs
from operations.models import Operation
from vrtManager import util
REFUSED = "is in maintenance: no new VM or migration comes to it"
class MaintenanceSwitchTests(TestCase):
def setUp(self):
self.compute = Compute.objects.create(name="mt", hostname="192.0.2.61", login="", password="", type=4)
self.client.force_login(get_user_model().objects.create_superuser("mt-admin", "mt@example.com", "pw"))
Logs.objects.all().delete() # the login's row
def switch(self, state):
return self.client.post(reverse("compute_maintenance", args=[self.compute.pk]), {"maintenance": state})
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)
self.switch("off")
self.compute.refresh_from_db()
self.assertFalse(self.compute.maintenance)
self.assertEqual(list(Logs.objects.order_by("id").values_list("message", flat=True)),
["Compute mt: maintenance on", "Compute mt: maintenance on", "Compute mt: maintenance off"])
def test_only_a_post_changes_it(self):
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.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"])):
response = self.client.get(url, follow=True)
self.assertRedirects(response, reverse("instances:index"))
self.assertContains(response, f"mt {REFUSED}")
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)
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):
with self.assertRaisesRegex(util.OperationError, f"mg {REFUSED}"):
migration_target(Instance(compute=self.other, name="vm"), self.host.pk)
def test_no_vm_is_created_on_it_nor_by_a_job_queued_before(self):
with self.assertRaisesRegex(util.OperationError, REFUSED):
CreateInstance().validate(self.admin, {"compute": self.host.pk})
with self.assertRaisesRegex(util.OperationError, REFUSED):
CreateInstance().precheck(SimpleNamespace(user=self.admin, params={"compute": self.host.pk, "name": "new"}),
None)
def test_no_vm_is_cloned_on_it(self):
with patch("instances.jobs._clonable", return_value=Instance(compute=self.host, name="vm")), \
self.assertRaisesRegex(util.OperationError, REFUSED):
CloneInstance().plan(self.admin, {"instance": 1, "fields": {}})
class BalanceLeavesItOutTests(TestCase):
def setUp(self):
self.admin = get_user_model().objects.create_superuser("mb-admin", "mb@example.com", "pw")
self.hosts = [Compute.objects.create(name=f"mb-{n}", hostname=f"192.0.2.7{n}", login="", password="", type=4)
for n in range(2)]
self.vm = Instance.objects.create(compute=self.hosts[0], name="mb-vm", uuid="00000000-0000-4000-8000-000000000201")
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)
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)
self.maintenance(host)
with self.assertRaisesRegex(util.OperationError, text):
Balance().validate(self.admin, Balance().normalize(self.params))
def test_a_host_put_in_maintenance_after_the_job_was_asked_for_gives_no_vm(self):
op = Operation.objects.create(kind="host.balance", user=self.admin, username=self.admin.username,
submission_key="key-mb000001", params=self.params,
intent=Balance().plan(self.admin, self.params).intent)
self.maintenance(self.hosts[0])
with self.assertRaisesRegex(util.OperationError, "mb-vm: mb-0 is in maintenance"):
Balance().run(op, Ctx(op))
self.assertFalse(Operation.objects.filter(kind="instance.migrate").exists())

View file

@ -60,6 +60,7 @@ urlpatterns = [
path("", views.overview, name="overview"),
path("update/", views.compute_update, name="compute_update"),
path("delete/", views.compute_delete, name="compute_delete"),
path("maintenance/", views.maintenance, name="compute_maintenance"),
path("statistics", views.compute_graph, name="compute_graph"),
path("capacity/", views.capacity, name="compute_capacity"),
path("instances/", views.instances, name="instances"),

View file

@ -16,6 +16,7 @@ from django.urls import reverse
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from django.views.decorators.debug import sensitive_post_parameters
from django.views.decorators.http import require_POST
from webvirtcloud.middleware import error_text
from instances.models import Instance
from instances.utils import read_list_rows, vm_states
@ -269,7 +270,8 @@ def bulk_migrate(request, compute_id):
from computes.reach import Reach
compute = get_object_or_404(Compute, pk=compute_id)
targets = list(Compute.objects.exclude(pk=compute.pk).order_by("name"))
# 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"))
if request.method == "POST":
chosen = request.POST.getlist("instance")
if request.POST.get("spread"):
@ -305,7 +307,7 @@ def bulk_migrate(request, compute_id):
# the other hosts' loads: the VMs of this one are read above, also when its capacity cannot be
_computes, hosts, _instances, loads, room, sizes = read_fleet()
others = {pk: host for pk, host in hosts.items() if pk != compute.pk}
others = {pk: host for pk, host in hosts.items() if pk != compute.pk and not host.maintenance}
shown, ticked = request.GET.getlist("shown"), request.GET.getlist("vm")
vms = []
for instance in instances:
@ -360,7 +362,11 @@ def balance(request):
return redirect("balance")
computes, hosts, instances, loads, room, sizes = read_fleet()
running = [instance for instance in instances if instance.info and instance.info[0] == 1]
# a host in maintenance is left out: its VMs neither count nor move, and it takes none
resting = [hosts.pop(pk) for pk in [pk for pk, compute in hosts.items() if compute.maintenance]]
loads, room, sizes = ({pk: part[pk] for pk in hosts} for part in (loads, room, sizes))
running = [instance for instance in instances
if instance.info and instance.info[0] == 1 and instance.compute_id in hosts]
pinned = set(request.GET.getlist("shown")) - set(request.GET.getlist("vm"))
movable, unmovable, reach = [], [], Reach(request)
for instance in running:
@ -383,7 +389,8 @@ def balance(request):
for vm, _source, target in moves:
by_pk[vm].target = hosts[target]
return render(request, "computes/balance.html", {
"hosts": hosts.values(), "unreachable": [compute for compute in computes if compute.pk not in hosts],
"hosts": hosts.values(), "resting": resting,
"unreachable": [compute for compute in computes if compute.pk not in hosts and compute not in resting],
"moves": [by_pk[vm] for vm, _source, _target in moves],
"pinned": [instance for instance in running if str(instance.pk) in pinned],
"unmovable": unmovable, "parallel": range(1, parallel_limit() + 1)})
@ -440,6 +447,20 @@ def compute_update(request, compute_id):
return render(request, "computes/form.html", {"form": form})
@require_POST
@superuser_only
def maintenance(request, compute_id):
"""Puts the host in maintenance or takes it out (Compute.maintenance), as
the form asks: the state it names, not the other one of the moment, so
a second page sent meanwhile does not turn it back."""
compute = get_object_or_404(Compute, pk=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)
return redirect("overview", compute.pk)
@superuser_only
def compute_delete(request, compute_id):
compute = get_object_or_404(Compute, pk=compute_id)

View file

@ -605,6 +605,7 @@ class CloneInstance(Kind):
def plan(self, user, params):
instance = _clonable(user, params["instance"])
instance.compute.refuse_new_vms() # the clone is made on the VM's host
# the source once a request: a running VM's NICs read its guest agent, which may take its whole timeout
with instance.proxy.cached_reads():
data, quota = clone_data(user, instance, params["fields"])
@ -624,6 +625,7 @@ class CloneInstance(Kind):
instance = _clonable(op.user, op.params["instance"])
if instance.compute_id != op.intent["compute"]:
raise util.OperationError(MOVED)
instance.compute.refuse_new_vms()
# a VM found on a host since the job was queued may have taken the name
if Instance.objects.filter(name=op.intent["name"]).exists():
raise util.OperationError(_("Instance '%(clone_name)s' already exists!"), clone_name=op.intent["name"])
@ -904,6 +906,7 @@ class CreateInstance(Kind):
raise PermissionDenied
data = params
c = get_object_or_404(Compute, pk=data["compute"])
c.refuse_new_vms()
conn = wvmCreate(c.hostname, c.login, c.password, c.type)
cdrom_buses = [bus for bus in conn.get_disk_bus_types(data["arch"], data["machine"]) if bus in CDROM_BUSES]
if data["name"] in conn.get_instances():
@ -951,6 +954,7 @@ class CreateInstance(Kind):
if Instance.objects.filter(name__exact=op.params["name"]).exists():
raise util.OperationError(_("There is an instance with same name. Remove it and try again!"))
c = Compute.objects.get(pk=op.params["compute"])
c.refuse_new_vms() # put in maintenance since the job was queued
conn = wvmCreate(c.hostname, c.login, c.password, c.type)
if op.params["name"] in conn.get_instances():
raise util.OperationError(_("A virtual machine with this name already exists"))
@ -1080,10 +1084,12 @@ MIGRATE_OPTIONS = ("live", "unsafe", "offline", "autoconverge", "compress", "del
def migration_target(instance, target_pk):
"""The destination; refused when the VM is already there, also under
another record of its host, or it cannot be reached."""
another record of its host, it is in maintenance, or it cannot be
reached."""
target = Compute.objects.get(pk=target_pk)
if target.pk == instance.compute_id:
raise util.OperationError(_("The instance is already on %(compute)s"), compute=target.name)
target.refuse_new_vms()
if not target.status:
raise util.OperationError(_("%(compute)s is not reachable"), compute=target.name)
if target.proxy.host_uuid() == instance.proxy.host_uuid():

View file

@ -16,6 +16,13 @@
<div class="text-body-secondary mb-3">{% trans "Choose the host the VM runs on." %}</div>
<div class="list-group">
{% for compute in reachable_computes %}
{% if compute.maintenance %}
<div class="list-group-item py-3" aria-disabled="true">
<span class="fw-semibold text-body-secondary">{{ compute.name }}</span>
<span class="badge text-bg-warning ms-2">{% trans "In maintenance" %}</span>
<div class="small text-body-secondary">{% trans "No new VM comes to a host in maintenance." %}</div>
</div>
{% else %}
<a class="list-group-item list-group-item-action py-3" href="{% url 'instances:create_instance_select_type' compute.id %}">
<div class="row g-2 align-items-center">
<div class="col-12 col-md-3 fw-semibold">{{ compute.name }}</div>
@ -43,6 +50,7 @@
<div class="col-12 col-md-8 offset-md-3 small text-body-secondary compute-capacity" data-url="{% url 'compute_capacity' compute.id %}"></div>
</div>
</a>
{% endif %}
{% empty %}
{% url 'computes' as computes_url %}
{% if computes %}

View file

@ -145,6 +145,14 @@ class CreateDialogHostsTestCase(TestCase):
self.assertEqual([e.text for e in dialog.xpath(".//a/div/div[1]")], ["cd2"])
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)
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']")
self.assertIn("cd1", item.text_content())
self.assertIn("In maintenance", item.text_content())
def test_no_reachable_compute_is_said(self):
dialog = self.dialog(set())
self.assertEqual(dialog.xpath(".//a[contains(@class, 'list-group-item')]"), [])

View file

@ -2542,6 +2542,16 @@ def getvvfile(request, pk):
return response
def in_maintenance(request, compute):
"""Back to the VM list, saying why, when the host a VM is made on is in maintenance."""
try:
compute.refuse_new_vms()
except util.OperationError as err:
messages.error(request, str(err))
return redirect("instances:index")
return None
@superuser_only
def create_instance_select_type(request, compute_id):
"""
@ -2551,6 +2561,8 @@ def create_instance_select_type(request, compute_id):
"""
compute = get_object_or_404(Compute, pk=compute_id)
if refused := in_maintenance(request, compute):
return refused
conn = wvmCreate(compute.hostname, compute.login, compute.password, compute.type)
instances = conn.get_instances()
@ -2636,6 +2648,8 @@ def create_instance(request, compute_id, arch, machine):
"""
compute = get_object_or_404(Compute, pk=compute_id)
if refused := in_maintenance(request, compute):
return refused
vm_form = None
refused = False
disk_source = request.POST.get("disk_source", "new")

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