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

feat(computes): putting a host in maintenance migrates its VMs; ready once none runs

A host was put in maintenance with its VMs still on it, and emptying it was
a separate step. "Put in maintenance" on a host with VMs that run now opens
Bulk Migrate, whose button migrates the chosen VMs and puts the host in
maintenance in one transaction: with the job admitted, or not at all; a
form sent again finds its job and does not put back a host taken out of
maintenance since. The page also puts it in maintenance without migrating,
for VMs that cannot move or when no host can take them.

Maintenance is not refused while VMs run: it must be on before they move,
or a new VM or Balance could take their place. The host shows instead
whether it is ready: "Maintenance requested" while VMs other than shut-off
ones remain on it (or it cannot be read), with its bulk migration's state;
"In maintenance" once none does. None of its VMs starts or resumes there
meanwhile. Ending maintenance during the bulk migration lets it go on.
This commit is contained in:
catborise 2026-11-16 16:47:55 +03:00
parent 22362de068
commit d96fe940e9
14 changed files with 962 additions and 537 deletions

View file

@ -153,8 +153,10 @@ class BulkMigrate(Migrations):
def normalize(self, raw):
moves = {int(vm): int(target) for vm, target in raw["moves"]}
# maintenance: the host was put in maintenance with the job (computes.views.bulk_migrate)
return {"compute": int(raw["compute"]), "parallel": int(raw["parallel"]),
"moves": [[vm, target] for vm, target in sorted(moves.items())]}
"moves": [[vm, target] for vm, target in sorted(moves.items())],
"maintenance": bool(raw.get("maintenance"))}
def moves(self, params):
return [(vm, params["compute"], target) for vm, target in params["moves"]]

View file

@ -52,8 +52,9 @@ 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)
# 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)
class Meta:
@ -65,6 +66,12 @@ class Compute(Model):
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:
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)
@property
def migration_uri(self):
"""The native migration URI for VMs migrated to this host: its

View file

@ -12,6 +12,16 @@
{% include "computes/host_nav.html" with section="instances" detail=True %}
</div>
</div>
{% if entering %}
{# asked from "Put in maintenance": the host goes in maintenance with its VMs' migration, or without one #}
<div class="alert alert-warning shadow-sm d-flex flex-wrap align-items-center gap-2">
<div class="me-auto">{% blocktrans with host=compute.name %}Put {{ host }} in maintenance: from then on no new VM or migration comes to it, its VMs cannot be started there, and Balance leaves it out. Migrate its VMs below, or put it in maintenance without migrating them.{% endblocktrans %}</div>
<form method="post" action="{% url 'compute_maintenance' compute.id %}">{% csrf_token %}
<input type="hidden" name="maintenance" value="on">
<button type="submit" class="btn btn-sm btn-warning" data-confirm="{% trans "Put the host in maintenance without migrating its VMs?" %}">{% trans "Put in maintenance without migrating" %}</button>
</form>
</div>
{% endif %}
{% if not targets %}
<div class="alert alert-warning shadow-sm">{% trans "There is no other host to migrate to." %}</div>
{% else %}
@ -21,6 +31,7 @@
{% endif %}
{# another destination reloads the list: which VMs can go depends on it; spread over the hosts, so does a VM ticked #}
<form method="get" id="bulk-migrate-choose"{% if spreading %} data-spread{% endif %}>
{% if entering %}<input type="hidden" name="maintenance" value="on">{% endif %}
{% if spreading %}{% for instance in instances %}{% if not instance.refusal %}<input type="hidden" name="shown" value="{{ instance.pk }}">{% endif %}{% endfor %}{% endif %}
</form>
{% if not parallel %}
@ -29,6 +40,7 @@
<div class="alert alert-info shadow-sm">{% trans "The host has no VMs." %}</div>
{% else %}
<form method="post" class="card shadow-sm">{% csrf_token %}{% submission_key %}
{% if entering %}<input type="hidden" name="maintenance" value="on">{% endif %}
{% if spreading %}<input type="hidden" name="spread" value="1">{% else %}<input type="hidden" name="target" value="{{ target.pk }}">{% endif %}
<div class="card-header d-flex flex-wrap align-items-center gap-2">
<span class="fw-semibold">{{ compute.name }}</span> {% bs_icon 'arrow-right' %}
@ -88,13 +100,15 @@
<select name="parallel" id="bulk-migrate-parallel" class="form-select form-select-sm w-auto">
{% for n in parallel %}<option value="{{ n }}"{% if forloop.last %} selected{% endif %}>{{ n }}</option>{% endfor %}
</select>
{% if spreading %}
{% if entering %}
{% blocktrans with source=compute.name asvar question %}Put {{ source }} in maintenance and migrate the chosen VMs?{% endblocktrans %}
{% elif spreading %}
{% blocktrans with source=compute.name asvar question %}Migrate the chosen VMs from {{ source }} to the hosts shown?{% endblocktrans %}
{% else %}
{% blocktrans with source=compute.name dest=target.name asvar question %}Migrate the chosen VMs from {{ source }} to {{ dest }}?{% endblocktrans %}
{% endif %}
<button type="submit" class="btn btn-primary ms-auto" id="bulk-migrate-submit" data-confirm="{{ question }}">
{% trans "Migrate the chosen VMs" %} <span class="badge text-bg-light" id="bulk-migrate-count"></span>
{% if entering %}{% trans "Migrate and put in maintenance" %}{% else %}{% trans "Migrate the chosen VMs" %}{% endif %} <span class="badge text-bg-light" id="bulk-migrate-count"></span>
</button>
</div>
</form>

View file

@ -75,7 +75,8 @@
{% 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 %}
{% if compute.maintenance %}{# ready once none of its VMs runs; while that is not known, only asked for #}
<span class="badge text-bg-warning">{% if compute.shown_capacity and not compute.shown_capacity.active %}{% trans "In maintenance" %}{% else %}{% trans "Maintenance requested" %}{% endif %}</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

@ -2,19 +2,25 @@
{% load i18n %}
{% load static %}
{% load bootstrap_icons %}
{% load operations %}
{% block title %}{% trans "Overview" %} - {{ compute.name }}{% endblock %}
{% block page_heading_extra %}
{% if compute.maintenance %}
<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 %}
<button type="submit" class="btn btn-sm btn-warning"{% if bulk_running %} data-confirm="{% trans "Allow new VMs and migrations on the host again? Its bulk migration goes on." %}"{% endif %}>{% bs_icon 'wrench-adjustable' %} {% trans "End maintenance" %}</button>
</form>
{% elif given.active %}
{# its VMs are migrated with it: the Bulk Migrate page puts it in maintenance, with or without moving them #}
<a class="btn btn-sm btn-outline-warning" href="{% url 'bulk_migrate' compute.id %}?maintenance=on">{% bs_icon 'wrench-adjustable' %} {% trans "Put in maintenance" %}</a>
{% else %}
<form method="post" action="{% url 'compute_maintenance' compute.id %}" class="d-inline">{% csrf_token %}
<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, its VMs cannot be started there, and Balance leaves it out." %}">{% bs_icon 'wrench-adjustable' %} {% trans "Put in maintenance" %}</button>
</form>
{% endif %}
<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 %}
@ -37,9 +43,28 @@
{% include "computes/host_nav.html" with section="overview" %}
{% if compute.maintenance %}
{# ready once none of its VMs runs: the state comes from its VMs, not from a job #}
<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 %}
{% if not given %}
{% trans "Maintenance requested: the host cannot be read, so whether its VMs still run is not known." %}
{% elif given.active %}
{% blocktrans count counter=given.active %}Maintenance requested: {{ counter }} VM still runs on this host.{% plural %}Maintenance requested: {{ counter }} VMs still run on this host.{% endblocktrans %}
{% blocktrans %}<a href="{{ bulk_url }}">Bulk Migrate</a> moves them to the other hosts; shut down those that cannot move.{% endblocktrans %}
{% else %}
<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 bulk and not given or bulk and given.active %}
<div class="mt-2 small">
{% url 'operations:job' bulk.pk as job_url %}
{% if bulk_running %}
{% blocktrans %}Its VMs are being migrated: <a href="{{ job_url }}">see the job</a>.{% endblocktrans %}
{% else %}
{% blocktrans with state=bulk.state|state_label when=bulk.created_at|date:"SHORT_DATETIME_FORMAT" %}Its last bulk migration, of {{ when }}: {{ state }}. <a href="{{ job_url }}">See the job</a>.{% endblocktrans %}
{% endif %}
</div>
{% endif %}
</div>
{% endif %}

View file

@ -82,7 +82,8 @@ class BulkMigratePageTests(TestCase):
self.assertRedirects(response, reverse("instances", args=[self.compute.id]), fetch_redirect_response=False)
(op,) = Operation.objects.all()
self.assertEqual((op.kind, op.params), ("host.bulk_migrate", {
"compute": self.compute.pk, "parallel": 2, "moves": [[pk, self.other.pk] for pk in sorted(chosen)]}))
"compute": self.compute.pk, "parallel": 2, "moves": [[pk, self.other.pk] for pk in sorted(chosen)],
"maintenance": False}))
def test_a_destination_gone_since_the_form_was_shown_is_refused(self):
gone = self.other.pk

View file

@ -2,8 +2,9 @@
it out; its VMs run on. A superuser puts it in maintenance and takes it out
on its page, each change audited."""
from datetime import timedelta
from types import SimpleNamespace
from unittest.mock import patch
from unittest.mock import MagicMock, patch
from computes.jobs import Balance
from computes.models import Compute
@ -11,10 +12,13 @@ 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 django.utils import timezone
from instances.jobs import CloneInstance, CreateInstance, _finish_clone, _revert_start, migration_target
from instances.models import Instance
from libvirt import libvirtError
from logs.models import Logs
from operations.models import Operation
from operations.jobs import SUBMISSION_KEY_TTL
from operations.models import Claim, Operation
from vrtManager import util
REFUSED = "is in maintenance: no new VM or migration comes to it"
@ -104,3 +108,169 @@ class BalanceLeavesItOutTests(TestCase):
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())
class NoStartTests(TestCase):
"""None of the VMs of a host in maintenance starts there, also for its owner."""
def setUp(self):
self.compute = Compute.objects.create(name="ms", hostname="192.0.2.81", login="", password="", type=1,
maintenance=True)
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"))
self.proxy = MagicMock()
patcher = patch.object(Instance, "proxy", new_callable=lambda: self.proxy)
patcher.start()
self.addCleanup(patcher.stop)
def test_a_vm_is_not_started_nor_resumed_nor_power_cycled(self):
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.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
def test_no_revert_starts_a_shut_off_vm(self):
self.proxy.get_status.return_value = 5
for state, refused in (("running", True), ("paused", True), ("shutoff", False), ("disk-snapshot", False)):
self.proxy._snapshot.return_value.getXMLDesc.return_value = (
f"<domainsnapshot><state>{state}</state></domainsnapshot>")
if refused:
with self.assertRaisesRegex(util.OperationError, "its VMs cannot be started there"):
_revert_start(self.instance, self.proxy, {"name": "s", "external": False})
else:
_revert_start(self.instance, self.proxy, {"name": "s", "external": False})
self.proxy.get_status.return_value = 3 # paused: a running snapshot resumes it
self.proxy._snapshot.return_value.getXMLDesc.return_value = "<domainsnapshot><state>running</state></domainsnapshot>"
with self.assertRaisesRegex(util.OperationError, "its VMs cannot be started there"):
_revert_start(self.instance, self.proxy, {"name": "s", "external": False})
self.proxy.get_status.return_value = 1 # running already: the revert starts nothing
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_a_running_vm_still_stops(self):
self.client.post(reverse("instances:poweroff", args=[self.instance.pk]))
self.proxy.shutdown.assert_called_once()
class MaintenanceWithMigrationTests(TestCase):
""""Put in maintenance" on a host with running VMs opens Bulk Migrate,
which puts the host in maintenance with the job, or without migrating."""
def setUp(self):
self.compute = Compute.objects.create(name="me", hostname="192.0.2.91", login="", password="", type=4)
self.other = Compute.objects.create(name="me-other", hostname="192.0.2.92", login="", password="", type=4)
self.vm = Instance.objects.create(compute=self.compute, name="me-vm", uuid="00000000-0000-4000-8000-000000000401")
self.admin = get_user_model().objects.create_superuser("me-admin", "me@example.com", "pw")
self.client.force_login(self.admin)
Logs.objects.all().delete()
def post(self, key="mnt00000key", moves=True):
return self.client.post(reverse("bulk_migrate", args=[self.compute.pk]), {
"target": self.other.pk, "instance": [self.vm.pk] if moves else [], "parallel": "1",
"maintenance": "on", "submission_key": key})
def maintenance(self):
self.compute.refresh_from_db()
return self.compute.maintenance
def test_the_host_goes_in_maintenance_with_the_job(self):
self.assertRedirects(self.post(), reverse("instances", args=[self.compute.pk]), fetch_redirect_response=False)
(op,) = Operation.objects.all()
self.assertTrue(op.params["maintenance"])
self.assertTrue(self.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):
response = self.post(moves=False)
self.assertRedirects(response, reverse("bulk_migrate", args=[self.compute.pk]) + f"?target={self.other.pk}"
"&maintenance=on", fetch_redirect_response=False)
self.assertFalse(Operation.objects.exists())
self.assertFalse(self.maintenance())
def test_the_form_sent_after_its_key_expired_puts_it_back_with_its_new_job(self):
self.post()
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)
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
self.post()
self.assertFalse(self.maintenance())
self.assertEqual(Operation.objects.count(), 1)
def page(self, **query):
def read_list_rows(instances, computes): # a running VM, without asking a host
for instance in instances:
instance.__dict__["info"] = [1, 131072, 131072, 1, 0]
with patch("computes.views.utils.refresh_instance_database"), \
patch("computes.views.read_list_rows", side_effect=read_list_rows), \
patch("computes.reach.Reach.refusal", return_value=None):
return self.client.get(reverse("bulk_migrate", args=[self.compute.pk]), query)
def test_the_page_offers_both_ways_into_maintenance(self):
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
self.assertNotContains(self.page(maintenance="on"), "Put in maintenance without migrating")
class MaintenanceStateTests(TestCase):
"""A host in maintenance is ready once none of its VMs runs; until then,
or while it cannot be read, its maintenance is only asked for."""
def setUp(self):
self.compute = Compute.objects.create(name="mz", hostname="192.0.2.95", login="", password="", type=4,
maintenance=True)
self.client.force_login(get_user_model().objects.create_superuser("mz-admin", "mz@example.com", "pw"))
@staticmethod
def given(**vms):
return {"vms": {"running": 0, "paused": 0, "shutoff": 0, "other": 0, **vms}, "cpus": 1, "memory": 1,
"vcpus": {"all": 0, "running": 0}, "assigned": {"all": 0, "running": 0}}
def overview(self, given):
with patch.object(Compute, "status", True), patch("computes.views.wvmHostDetails", side_effect=libvirtError("not read")), \
patch.object(Compute, "capacity", given), patch("computes.views.host_pools"):
return self.client.get(reverse("overview", args=[self.compute.pk]))
def test_running_or_paused_vms_keep_it_requested(self):
response = self.overview(self.given(running=1, paused=1, shutoff=3))
self.assertContains(response, "Maintenance requested: 2 VMs still run on this host.")
self.assertNotContains(response, "In maintenance: no VM runs")
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_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 test_put_in_maintenance_leads_to_bulk_migrate_while_vms_run(self):
Compute.objects.filter(pk=self.compute.pk).update(maintenance=False)
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))
self.assertContains(response, reverse("compute_maintenance", args=[self.compute.pk]))
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)
op = SimpleNamespace(intent={"compute": compute.pk, "name": "mc-clone",
"uuid": "00000000-0000-4000-8000-000000000501"},
username="mc-admin", client_ip=None)
with patch("instances.jobs.wvmInstance") as proxy:
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"]))

View file

@ -9,7 +9,7 @@ from admin.decorators import superuser_only
from django.conf import settings
from django.contrib import messages
from django.core import signing
from django.db import IntegrityError
from django.db import IntegrityError, transaction
from django.http import HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
@ -23,6 +23,7 @@ from instances.utils import read_list_rows, vm_states
from libvirt import libvirtError
from logs.audit import audit, changed_fields, snapshot
from operations import claims, jobs
from operations.models import Operation
from operations.utils import busy_message
from vrtManager.connection import CONN_SOCKET, CONN_SSH, CONN_TCP, CONN_TLS
from vrtManager.hostdetails import wvmHostDetails
@ -65,6 +66,8 @@ def shown_capacity(compute):
cpu_scale = max(vcpus["all"], cpus) or 1
given["cpu_bar"] = {"running": vcpus["running"] * 100 / cpu_scale, "stopped": vcpus["stopped"] * 100 / cpu_scale}
given["vm_count"] = sum(given["vms"].values())
# the VMs that keep a host in maintenance from being ready: all but the shut-off ones
given["active"] = given["vm_count"] - given["vms"]["shutoff"]
return given
@ -194,7 +197,11 @@ def overview(request, compute_id):
compute = get_object_or_404(Compute, pk=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}
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
"bulk": Operation.objects.filter(kind="host.bulk_migrate", resource=claims.compute_key(compute.pk))
.order_by("-created_at").first()}
context["bulk_running"] = context["bulk"] is not None and context["bulk"].state in Operation.ACTIVE
if context["connected"]:
try:
conn = wvmHostDetails(compute.hostname, compute.login, compute.password, compute.type)
@ -264,7 +271,11 @@ def bulk_migrate(request, compute_id):
VM ticked or unticked then makes the spread again, as the form sends the
VMs it showed ("shown") and the ticked ones ("vm"). A VM with a disk file
the hosts do not share is not offered: it takes a copy, chosen on its
own Migrate tab."""
own Migrate tab.
Asked from the host's "Put in maintenance" ("maintenance"), the page
puts the host in maintenance with the job, in one transaction: with
the job admitted, or not at all."""
from computes.balance import spread
from computes.jobs import parallel_limit
from computes.reach import Reach
@ -280,9 +291,19 @@ def bulk_migrate(request, compute_id):
# the destination the form showed, not another one taken in its place
target = get_object_or_404(Compute.objects.exclude(pk=compute.pk), pk=request.POST.get("target", "") or None)
moves, again = [(pk, target.pk) for pk in chosen], target.pk
raw = {"compute": compute.pk, "parallel": request.POST.get("parallel", ""), "moves": moves}
entering = request.POST.get("maintenance") == "on"
raw = {"compute": compute.pk, "parallel": request.POST.get("parallel", ""), "moves": moves, "maintenance": entering}
key = request.POST.get("submission_key", "")
try:
op = jobs.submit("host.bulk_migrate", request.user, raw, request.POST.get("submission_key", ""))
with transaction.atomic():
Compute.objects.select_for_update().filter(pk=compute.pk).first() # one maintenance change at a time
# a form sent again finds its job: it does not put back a host taken out of maintenance since;
# one sent after its key expired makes a new job, and puts it in maintenance with it
found = Operation.objects.filter(user=request.user, submission_key=key).values_list("pk", flat=True).first()
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)
except claims.Busy as busy:
messages.error(request, busy_message(busy, request.user))
except (ValueError, jobs.SubmissionConflict, libvirtError) as err:
@ -290,8 +311,10 @@ def bulk_migrate(request, compute_id):
else:
jobs.remember_job(request, op)
return redirect("instances", compute.pk)
return redirect(reverse("bulk_migrate", args=[compute.pk]) + f"?target={again}")
return redirect(reverse("bulk_migrate", args=[compute.pk]) + f"?target={again}"
+ ("&maintenance=on" if entering else ""))
entering = request.GET.get("maintenance") == "on" and not compute.maintenance
reach = Reach(request)
spreading = len(targets) > 1 and request.GET.get("target", "spread") == "spread"
utils.refresh_instance_database(compute)
@ -303,7 +326,7 @@ def bulk_migrate(request, compute_id):
instance.refusal = reach.refusal(instance, target)
return render(request, "computes/bulk_migrate.html",
{"compute": compute, "targets": targets, "target": target, "instances": instances,
"parallel": range(1, parallel_limit() + 1)})
"parallel": range(1, parallel_limit() + 1), "entering": entering})
# 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()
@ -328,7 +351,7 @@ def bulk_migrate(request, compute_id):
instance.note = _("No other host has room for it")
going = [instance for instance in instances if instance.target]
return render(request, "computes/bulk_migrate.html",
{"compute": compute, "targets": targets, "spreading": True, "instances": instances,
{"compute": compute, "targets": targets, "spreading": True, "instances": instances, "entering": entering,
"all_ticked": len(going) == len([instance for instance in instances if not instance.refusal]),
"shut_off_ticked": any(instance.info[0] == 5 for instance in going),
"unreachable": [host for host in targets if host.pk not in others],

View file

@ -239,6 +239,7 @@ def _finish_clone(op, clone, warning):
if clone.get("memory"):
proxy.resize_mem(clone["memory"], clone["memory"])
if clone.get("start"):
c.refuse_start() # put in maintenance while the disks were copied: the clone stays off
proxy.start()
except libvirtError as err:
notes += say(_("The clone is made, but not as asked: %(error)s"), error=err)
@ -494,6 +495,18 @@ def _revert_quota(user, instance, proxy, params):
quota=utils.quota_message(quota), name=params["name"])
def _revert_start(instance, proxy, params):
"""A revert to a snapshot of the VM running or paused (with its memory)
starts a shut-off VM, and one of it running resumes a paused VM: not on
a host in maintenance (Compute.refuse_start). A disk-only one
("disk-snapshot") keeps the VM as it is."""
snapshot = proxy._snapshot(params["name"], params["external"])
state = util.get_xml_path(snapshot.getXMLDesc(0), "/domainsnapshot/state")
status = proxy.get_status()
if status == 5 and state in ("running", "paused") or status == 3 and state == "running":
instance.compute.refuse_start()
@register
class RevertSnapshot(Kind):
name = "snapshot.revert"
@ -507,7 +520,7 @@ class RevertSnapshot(Kind):
def validate(self, user, params):
instance = _authorized(user, params["instance"])
proxy = _proxy(instance)
proxy._snapshot(params["name"], params["external"])
_revert_start(instance, proxy, params)
_revert_quota(user, instance, proxy, params)
def plan(self, user, params):
@ -528,8 +541,10 @@ class RevertSnapshot(Kind):
proxy.check_external_revert(op.params["name"])
else:
proxy.check_internal_revert()
instance = _instance(op.params["instance"])
_revert_start(instance, proxy, op.params) # put in maintenance meanwhile, or the VM shut off
# again: a resize while it was queued may have used the quota
_revert_quota(op.user, _instance(op.params["instance"]), proxy, op.params)
_revert_quota(op.user, instance, proxy, op.params)
# a revert gives the VM the host devices it had then: not one given since to another VM
has_hostdevs, definitions = _snapshot_definitions(proxy, op.params)
if has_hostdevs:

View file

@ -853,10 +853,12 @@ 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.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.proxy.start()
@ -873,6 +875,7 @@ def powercycle(request, pk):
messages.warning(request, _("Templates cannot be started."))
else:
with audit_vm(request, instance, "power cycle") as entry:
instance.compute.refuse_start() # before it stops: it would not start again
instance.proxy.check_start_hostdevs(restore=False) # before it stops
instance.proxy.force_shutdown()
try:
@ -916,6 +919,7 @@ def suspend(request, pk):
def resume(request, pk):
instance = get_instance(request.user, pk)
with audit_vm(request, instance, "resume"):
instance.compute.refuse_start()
instance.proxy.resume()
return get_safe_redirect(
request, default=reverse("instances:instance", args=[instance.id])

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