mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-02 17:06:09 +00:00
fix(computes): maintenance read at the moment of the action; autostart named and refused
An audit of host maintenance found: - refuse_start and refuse_new_vms trusted the compute as the page or job had read it: a clone started after its host went in maintenance during the disk copy, and a power-on raced the switch while host devices were checked. They now read the state from the database, and power-on checks right before the start; a VM defined from XML is refused as well. - libvirt starts autostart VMs itself when the host boots. Autostart cannot be turned on for a VM of a host in maintenance, and the host page names the VMs that would start, so that their autostart is turned off before a reboot. - The New VM dialog said "In maintenance" for a host whose maintenance was only requested: it now says "Maintenance". - Tests now cover the owner's power-on, the revert job and a stale compute.
This commit is contained in:
parent
80e68d0628
commit
a03f12aa5b
11 changed files with 452 additions and 370 deletions
|
|
@ -65,15 +65,19 @@ class Compute(Model):
|
|||
def maintenance(self):
|
||||
return self.maintenance_since is not None
|
||||
|
||||
def _in_maintenance_now(self):
|
||||
"""Read now: a page or job may hold the compute from before it went in maintenance."""
|
||||
return Compute.objects.filter(pk=self.pk, maintenance_since__isnull=False).exists()
|
||||
|
||||
def refuse_new_vms(self):
|
||||
"""Refuses a VM made on or migrated to the host while it is in maintenance."""
|
||||
if self.maintenance:
|
||||
if self._in_maintenance_now():
|
||||
raise util.OperationError(gettext_noop("%(compute)s is in maintenance: no new VM or migration comes to it"),
|
||||
compute=self.name)
|
||||
|
||||
def refuse_start(self):
|
||||
"""Refuses starting or resuming a VM of the host while it is in maintenance."""
|
||||
if self.maintenance:
|
||||
"""Refuses starting or resuming a VM of the host, or its autostart, while it is in maintenance."""
|
||||
if self._in_maintenance_now():
|
||||
raise util.OperationError(gettext_noop("%(compute)s is in maintenance: its VMs cannot be started there; "
|
||||
"migrate the VM to start it on another host"), compute=self.name)
|
||||
|
||||
|
|
|
|||
|
|
@ -55,6 +55,9 @@
|
|||
<span class="fw-semibold">{% trans "In maintenance: no VM runs on this host." %}</span>
|
||||
{% endif %}
|
||||
{% trans "No new VM or migration comes to it, its VMs cannot be started there, and Balance leaves it out." %}
|
||||
{% if autostart %}
|
||||
<div class="mt-2">{% blocktrans with vms=autostart|join:", " %}These VMs start by themselves when the host boots: {{ vms }}. Turn their autostart off before restarting the host.{% endblocktrans %}</div>
|
||||
{% endif %}
|
||||
{% if bulk and not given or bulk and given.active %}
|
||||
<div class="mt-2 small">
|
||||
{% url 'operations:job' bulk.pk as job_url %}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ from datetime import timedelta
|
|||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from accounts.models import UserInstance
|
||||
from computes.jobs import Balance
|
||||
from computes.models import Compute
|
||||
from computes.tests.test_balance import Ctx
|
||||
|
|
@ -15,7 +16,7 @@ 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
|
||||
from instances.jobs import CloneInstance, CreateInstance, RevertSnapshot, _finish_clone, _revert_start, migration_target
|
||||
from instances.models import Instance
|
||||
from libvirt import libvirtError
|
||||
from logs.models import Logs
|
||||
|
|
@ -155,6 +156,39 @@ class NoStartTests(TestCase):
|
|||
self.proxy._snapshot.return_value.getXMLDesc.return_value = "<domainsnapshot><state>running</state></domainsnapshot>"
|
||||
_revert_start(self.instance, self.proxy, {"name": "s", "external": False})
|
||||
|
||||
def test_nor_by_its_owner(self):
|
||||
owner = get_user_model().objects.create_user("ms-owner", "owner@example.com", "pw")
|
||||
UserInstance.objects.create(instance=self.instance, user=owner)
|
||||
self.client.force_login(owner)
|
||||
response = self.client.post(reverse("instances:poweron", args=[self.instance.pk]), follow=True)
|
||||
self.assertContains(response, "ms is in maintenance: its VMs cannot be started there")
|
||||
self.proxy.start.assert_not_called()
|
||||
|
||||
def test_a_revert_job_that_would_start_it_is_refused(self):
|
||||
self.proxy.get_status.return_value = 5
|
||||
self.proxy._snapshot.return_value.getXMLDesc.return_value = "<domainsnapshot><state>running</state></domainsnapshot>"
|
||||
admin = get_user_model().objects.get(username="ms-admin")
|
||||
with patch("instances.jobs._proxy", return_value=self.proxy), \
|
||||
self.assertRaisesRegex(util.OperationError, "its VMs cannot be started there"):
|
||||
RevertSnapshot().validate(admin, {"instance": self.instance.pk, "name": "s", "external": False})
|
||||
|
||||
def test_its_autostart_cannot_be_turned_on(self):
|
||||
response = self.client.post(reverse("instances:set_autostart", args=[self.instance.pk]), follow=True)
|
||||
self.assertContains(response, "ms is in maintenance: its VMs cannot be started there")
|
||||
self.proxy.set_autostart.assert_not_called()
|
||||
|
||||
def test_a_compute_read_before_the_maintenance_refuses_too(self):
|
||||
held = Compute.objects.get(pk=self.compute.pk)
|
||||
Compute.objects.filter(pk=held.pk).update(maintenance_since=None)
|
||||
held.refuse_start() # out of maintenance now, though the object says otherwise
|
||||
Compute.objects.filter(pk=held.pk).update(maintenance_since=timezone.now())
|
||||
stale = Compute.objects.get(pk=held.pk)
|
||||
stale.maintenance_since = None # as read before it went in maintenance
|
||||
with self.assertRaisesRegex(util.OperationError, "its VMs cannot be started there"):
|
||||
stale.refuse_start()
|
||||
with self.assertRaisesRegex(util.OperationError, REFUSED):
|
||||
stale.refuse_new_vms()
|
||||
|
||||
def test_a_running_vm_still_stops(self):
|
||||
self.client.post(reverse("instances:poweroff", args=[self.instance.pk]))
|
||||
self.proxy.shutdown.assert_called_once()
|
||||
|
|
@ -258,6 +292,14 @@ class MaintenanceStateTests(TestCase):
|
|||
def test_with_only_shut_off_vms_it_is_in_maintenance(self):
|
||||
self.assertContains(self.overview(self.given(shutoff=3)), "In maintenance: no VM runs on this host.")
|
||||
|
||||
def test_the_vms_that_autostart_when_the_host_boots_are_named(self):
|
||||
doms = [MagicMock(**{"name.return_value": name, "autostart.return_value": on})
|
||||
for name, on in (("mz-b", 1), ("mz-off", 0), ("mz-a", 1))]
|
||||
proxy = MagicMock(**{"wvm.listAllDomains.return_value": doms})
|
||||
with patch.object(Compute, "proxy", new_callable=lambda: proxy):
|
||||
response = self.overview(self.given(shutoff=3))
|
||||
self.assertContains(response, "These VMs start by themselves when the host boots: mz-a, mz-b.")
|
||||
|
||||
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")
|
||||
|
||||
|
|
|
|||
|
|
@ -221,6 +221,10 @@ def overview(request, compute_id):
|
|||
context["read_error"] = str(error)
|
||||
context["given"] = shown_capacity(compute)
|
||||
context["storage"] = host_pools(compute)
|
||||
if compute.maintenance:
|
||||
# libvirt starts these itself when the host boots: the panel cannot refuse that
|
||||
with suppress(libvirtError):
|
||||
context["autostart"] = sorted(dom.name() for dom in compute.proxy.wvm.listAllDomains() if dom.autostart())
|
||||
return render(request, "overview.html", context)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@
|
|||
{% 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>
|
||||
<span class="badge text-bg-warning ms-2">{% trans "Maintenance" %}</span>{# requested or ready: no new VM comes either way #}
|
||||
<div class="small text-body-secondary">{% trans "No new VM comes to a host in maintenance." %}</div>
|
||||
</div>
|
||||
{% else %}
|
||||
|
|
|
|||
|
|
@ -152,7 +152,8 @@ class CreateDialogHostsTestCase(TestCase):
|
|||
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())
|
||||
self.assertIn("Maintenance", item.text_content())
|
||||
self.assertNotIn("In maintenance", item.text_content()) # it may still be only requested
|
||||
|
||||
def test_no_reachable_compute_is_said(self):
|
||||
dialog = self.dialog(set())
|
||||
|
|
|
|||
|
|
@ -853,13 +853,13 @@ def poweron(request, pk):
|
|||
messages.warning(request, _("Templates cannot be started."))
|
||||
elif options.validated_data["fresh"]: # the saved state is discarded: the VM boots anew
|
||||
with audit_vm(request, instance, "power on without the saved state"):
|
||||
instance.compute.refuse_start()
|
||||
instance.proxy.check_start_hostdevs(restore=False)
|
||||
instance.compute.refuse_start() # right before the start: maintenance may begin while devices are checked
|
||||
instance.proxy.start(VIR_DOMAIN_START_FORCE_BOOT)
|
||||
else:
|
||||
with audit_vm(request, instance, "power on"):
|
||||
instance.compute.refuse_start()
|
||||
instance.proxy.check_start_hostdevs()
|
||||
instance.compute.refuse_start()
|
||||
instance.proxy.start()
|
||||
|
||||
return get_safe_redirect(
|
||||
|
|
@ -1860,6 +1860,7 @@ def set_autostart(request, pk):
|
|||
messages.error(request, _("Templates cannot be started."))
|
||||
return _back(request, pk, "boot_opt")
|
||||
with audit_vm(request, instance, "enable autostart"):
|
||||
instance.compute.refuse_start() # it would start there when the host boots
|
||||
instance.proxy.set_autostart(1)
|
||||
return _back(request, pk, "boot_opt")
|
||||
|
||||
|
|
@ -2597,6 +2598,7 @@ def create_instance_select_type(request, compute_id):
|
|||
else:
|
||||
with libvirt_compute_lock(compute):
|
||||
with audit(request, compute, f"VM {name}", "define from XML", instance=name) as entry:
|
||||
compute.refuse_new_vms() # put in maintenance since the page was opened
|
||||
check_hostdevs(conn, name, [etree.fromstring(xml)])
|
||||
conn._defineXML(xml)
|
||||
refresh_instance_database(compute)
|
||||
|
|
@ -2605,6 +2607,8 @@ def create_instance_select_type(request, compute_id):
|
|||
return redirect(reverse("instances:instance", args=[instance.id]))
|
||||
except util.etree.Error as err:
|
||||
xml_error = _("The XML is not well-formed: %(error)s") % {"error": err}
|
||||
except util.OperationError as err:
|
||||
xml_error = error_text(request, err)
|
||||
except libvirtError as err:
|
||||
xml_error = _("libvirt Error - %(exception)s") % {"exception": error_text(request, err)}
|
||||
|
||||
|
|
|
|||
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
Loading…
Add table
Add a link
Reference in a new issue