diff --git a/README.md b/README.md index 46ebc023..31204815 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ WebVirtCloud and `virt-manager`/`virsh` can manage the same libvirt host **concu ## Features * QEMU/KVM hypervisor management (multiple compute nodes), with each host's capacity and what its VMs were given -* Virtual machine lifecycle: create, delete, power management, clone (also of a running VM, with libvirt 11.10 or later), migrate (with or without shared storage), disk moves between pools +* Virtual machine lifecycle: create, delete, power management, clone (also of a running VM, with libvirt 11.10 or later), migrate (with or without shared storage), evacuate a host (its chosen VMs migrate to another, the chosen number at once), disk moves between pools * Long operations (create, clone, delete, snapshots, migration, disk moves, ISO upload) run as jobs that the page follows; a queued job can be cancelled, and a running clone, migration, disk move or ISO upload too * External snapshots (memory optional; without memory, guest file systems can be frozen through the agent) * **External change detection:** VMs created, deleted or renamed via `virt-manager` or `virsh` are reconciled into the database automatically diff --git a/computes/jobs.py b/computes/jobs.py new file mode 100644 index 00000000..4564882d --- /dev/null +++ b/computes/jobs.py @@ -0,0 +1,130 @@ +"""Jobs of the computes app (operations framework).""" + +import time +from contextlib import suppress + +from django.core.exceptions import PermissionDenied +from django.utils.translation import gettext_noop +from instances.models import Instance +from vrtManager import util + +from computes.models import Compute +from operations import claims, jobs, utils +from operations.jobs import Cancelled, Kind, Outcome, Plan, register +from operations.models import Claim, Operation + + +# where a host is: an evacuation stops if either host's record points elsewhere since it was asked +WHERE = ("hostname", "login", "type") + + +def _where(params): + return [list(Compute.objects.filter(pk=pk).values_list(*WHERE).first() or []) for pk in (params["compute"], params["target"])] + + +def parallel_limit(): + """The most migrations an evacuation runs at once: the worker gives a + host's jobs half of its slots, and the evacuation itself takes one.""" + slots = utils.concurrency() + return min(max(1, slots // 2), slots - 1) + + +@register +class EvacuateHost(Kind): + """Migrates the chosen VMs of a host to another, each in a migrate job + of its own, at most parallel at once: one that fails leaves its VM on + the host and the rest go on.""" + + name = "host.evacuate" + label = gettext_noop("Evacuate host") + cancellable = True + + def normalize(self, raw): + return {"compute": int(raw["compute"]), "target": int(raw["target"]), "parallel": int(raw["parallel"]), + "instances": sorted({int(pk) for pk in raw["instances"]})} + + def validate(self, user, params): + if not user.is_superuser: + raise PermissionDenied + if not params["instances"]: + raise util.OperationError(gettext_noop("Choose the VMs to migrate")) + if not 1 <= params["parallel"] <= parallel_limit(): + raise util.OperationError(gettext_noop("At most %(limit)s migrations can run at once"), + limit=parallel_limit()) + + def plan(self, user, params): + compute = Compute.objects.get(pk=params["compute"]) + target = Compute.objects.get(pk=params["target"]) + return Plan(claims={claims.evacuate_key(): Claim.EXCLUSIVE}, resource=claims.compute_key(compute.pk), + label=f"{compute.name} -> {target.name}", intent={"migrations": {}, "where": _where(params)}) + + def precheck(self, op, ctx): + if op.user is None or not op.user.is_active or not op.user.is_superuser: + raise PermissionDenied + + def run(self, op, ctx): + p = op.params + names = dict(Instance.objects.filter(pk__in=p["instances"], compute_id=p["compute"]).values_list("pk", "name")) + waiting = [pk for pk in p["instances"] if pk in names] # one moved or deleted meanwhile is left out + started, refused = {}, [] # VM: its migrate job; the VMs whose job was refused, and why + ctx.record_intent() + ctx.set_phase(gettext_noop("Migrating the VMs")) + while True: + running = list(Operation.objects.filter(pk__in=started.values(), state__in=Operation.ACTIVE) + .values_list("pk", flat=True)) + op.refresh_from_db(fields=["cancel_requested"]) + if op.cancel_requested: + for pk in running: + with suppress(Exception): # it ended meanwhile + jobs.cancel(pk, op.user) + raise Cancelled + # the worker's slots may have been lowered: this job waits in one, its migrations need others; + # once it ends, the migrations it queued run + if parallel_limit() < 1: + raise util.OperationError(gettext_noop( + "The worker now runs one job at a time: the VMs not yet started stay on the host")) + if waiting and _where(p) != op.intent["where"]: + raise util.OperationError(gettext_noop( + "A host was changed or deleted: the VMs not yet started stay on the host")) + for pk in list(waiting): + if len(running) >= min(p["parallel"], parallel_limit()): + break + waiting.remove(pk) + if not Instance.objects.filter(pk=pk, compute_id=p["compute"]).exists(): + continue # it left the host meanwhile + raw = {"instance": pk, "source": p["compute"], "target": p["target"], "live": True, "autoconverge": True} + try: + child = jobs.submit("instance.migrate", op.user, raw, f"evac-{op.pk.hex}-{pk}") + except claims.Busy as busy: + if busy.blocker is not None and busy.blocker.state == Operation.UNCERTAIN: + # it holds its claims until someone resolves it + refused.append(f"{names[pk]}: {utils.busy_message(busy, op.user)}") + else: + waiting.append(pk) # another job holds the VM or a host: asked again on the next round + except Exception as err: + refused.append(f"{names[pk]}: {utils.safe_text(err)}") + else: + started[pk] = child.pk + running.append(child.pk) + ctx.record_intent(migrations={str(vm): str(job) for vm, job in started.items()}) + if not waiting and not running: + break + time.sleep(2) + migrated = set(Operation.objects.filter(pk__in=started.values(), state=Operation.SUCCEEDED) + .values_list("pk", flat=True)) + failed = refused + [names[vm] for vm, job in started.items() if job not in migrated] + if failed: + raise util.OperationError(gettext_noop("These VMs did not migrate: %(vms)s"), vms=", ".join(failed)) + return {} + + def cancel(self, op): + """run sees the cancel and cancels the migrations that run.""" + + def reconcile(self, op): + return Outcome(Operation.FAILED, error=utils.say(gettext_noop( + "The evacuation stopped: the migrations it started go on as their own jobs; the other VMs stay"))) + + def log_entry(self, op, state): + source, _sep, target = op.resource_label.partition(" -> ") + message = f"Evacuate to {target}" + return source, "", "", message if state == Operation.SUCCEEDED else f"{message} ({state})" diff --git a/computes/templates/computes/evacuate.html b/computes/templates/computes/evacuate.html new file mode 100644 index 00000000..ae9e00e0 --- /dev/null +++ b/computes/templates/computes/evacuate.html @@ -0,0 +1,81 @@ +{% extends "base.html" %} +{% load i18n %} +{% load static %} +{% load operations %} +{% block title %}{% trans "Evacuate" %} - {{ compute.name }}{% endblock %} +{% block page_heading %}{{ compute.name }} - {% trans "Evacuate" %}{% endblock page_heading %} + +{% block content %} +
+
+ {% include "computes/host_nav.html" with section="instances" detail=True %} +
+
+{% if not target %} +
{% trans "There is no other host to migrate to." %}
+{% else %} +

{% trans "Each chosen VM migrates in a job of its own: a running VM live, a shut-off one offline. A VM that fails stays on this host." %}

+
+
+ + +
+
+
+{% if not parallel %} +
{% trans "The worker runs one job at a time: set Worker Concurrency to 2 or more on the Settings page." %}
+{% elif not instances %} +
{% trans "The host has no VMs." %}
+{% else %} +
{% csrf_token %}{% submission_key %} + +
+ + +
+
+ + + + + + + + + + + + + {% for instance in instances %} + + + + + + + + + {% endfor %} + +
{% trans "Migrate" %}{% trans "Name" %}{% trans "Status" %}{% trans "VCPU" %}{% trans "Memory" %}
+ + {% include 'instance_state.html' %}{{ instance.info.3 }}{% if instance.info %}{% widthratio instance.info.2 1024 1 %} MiB{% endif %}{{ instance.refusal|default:"" }}
+
+
+ + +
+ {% blocktrans with source=compute.name dest=target.name asvar question %}Migrate the chosen VMs from {{ source }} to {{ dest }}?{% endblocktrans %} + +
+{% endif %} +{% endif %} +{% endblock %} +{% block script %} + +{% endblock %} diff --git a/computes/templates/computes/instances.html b/computes/templates/computes/instances.html index 15f6b3e5..0459a9ae 100644 --- a/computes/templates/computes/instances.html +++ b/computes/templates/computes/instances.html @@ -12,6 +12,7 @@ {% bs_icon 'plus-circle-fill' %} {% if instances %} +{% trans "Evacuate" %} {% include 'search_block.html' %} {% endif %} {% endblock page_heading_extra %} diff --git a/computes/tests/test_evacuate.py b/computes/tests/test_evacuate.py new file mode 100644 index 00000000..ccb04730 --- /dev/null +++ b/computes/tests/test_evacuate.py @@ -0,0 +1,218 @@ +"""Evacuating a host migrates its chosen VMs in one job, a migrate job each, +the chosen number at once; the page ticks the running VMs, leaves the +shut-off ones to choose and refuses a VM with a disk the two hosts do not +share. Migrations share the hosts, so the job's migrations are admitted +together; a create still waits for them.""" + +from unittest.mock import patch + +import libvirt +from computes.models import Compute +from django.contrib.auth import get_user_model +from django.test import TestCase +from django.urls import reverse +from instances.models import Instance +from lxml import etree, html +from appsettings.models import AppSettings +from computes.jobs import EvacuateHost +from operations import claims, jobs +from operations.models import Claim, Operation +from vrtManager import util + +DOMAIN = """{name}1281 +hvm{disk}""" +LOCAL = "" + + +class EvacuateTests(TestCase): + def setUp(self): + self.conn = libvirt.open("test:///default") + self.addCleanup(self.conn.close) + self.compute = Compute.objects.create(name="ev", hostname="localhost", login="", password="", type=4) + self.other = Compute.objects.create(name="ev-other", hostname="198.51.100.31", login="", password="", type=4) + self.vms = {} + for name, running, disk in (("ev-run", True, ""), ("ev-off", False, ""), ("ev-local", True, LOCAL)): + domain = self.conn.defineXML(DOMAIN.format(name=name, disk=disk.format(name=name))) + self.addCleanup(domain.undefine) + if running: + domain.create() + self.addCleanup(domain.destroy) + self.vms[name] = Instance.objects.create(compute=self.compute, name=name, uuid=domain.UUIDString()) + self.client.force_login(get_user_model().objects.create_superuser("ev-admin", "ev@example.com", "pw")) + + def page(self): + def disk_plan(conn, xml): + return [{"shared": "/local/" not in path} for path in etree.fromstring(xml).xpath("//source/@file")] + + with patch("vrtManager.connection.connection_manager.get_connection", return_value=self.conn), \ + patch("computes.views.utils.refresh_instance_database"), \ + patch("instances.jobs.migration_target"), \ + patch("computes.views.wvmInstances") as dest: + dest.return_value.disk_plan.side_effect = disk_plan + response = self.client.get(reverse("evacuate", args=[self.compute.id])) + return html.fromstring(response.content) + + def box(self, page, name): + (box,) = page.xpath("//input[@name='instance'][@value=$pk]", pk=str(self.vms[name].pk)) + return box + + def test_running_vms_are_ticked_and_shut_off_ones_left_to_choose(self): + page = self.page() + self.assertIsNotNone(self.box(page, "ev-run").get("checked")) + off = self.box(page, "ev-off") + self.assertIsNone(off.get("checked")) + self.assertIsNotNone(off.get("data-shut-off")) + + def test_a_vm_with_a_disk_the_hosts_do_not_share_is_refused(self): + page = self.page() + local = self.box(page, "ev-local") + self.assertIsNotNone(local.get("disabled")) + self.assertIn("not on storage both hosts share", local.getparent().getparent().text_content()) + + def evacuate(self, target, chosen): + return self.client.post(reverse("evacuate", args=[self.compute.id]), + {"target": target, "instance": chosen, "parallel": "2", "submission_key": "evac0000key"}) + + def test_the_chosen_vms_go_in_one_evacuation_job(self): + chosen = [self.vms["ev-run"].pk, self.vms["ev-off"].pk] + response = self.evacuate(self.other.pk, chosen) + self.assertRedirects(response, reverse("instances", args=[self.compute.id]), fetch_redirect_response=False) + (op,) = Operation.objects.all() + self.assertEqual((op.kind, op.params), ("host.evacuate", {"compute": self.compute.pk, "target": self.other.pk, + "parallel": 2, "instances": sorted(chosen)})) + + def test_a_destination_gone_since_the_form_was_shown_is_refused(self): + gone = self.other.pk + self.other.delete() + self.assertEqual(self.evacuate(gone, [self.vms["ev-run"].pk]).status_code, 404) + self.assertFalse(Operation.objects.exists()) + + def test_a_host_with_no_other_host_says_so(self): + self.other.delete() + self.assertIn("There is no other host to migrate to.", self.page().text_content()) + + +class Ctx: + """The job context run uses, without a worker.""" + + def __init__(self, op): + self.op = op + + def record_intent(self, **values): + self.op.intent = {**self.op.intent, **values} + + def set_phase(self, text): + pass + + +class EvacuateJobTests(TestCase): + def setUp(self): + self.compute = Compute.objects.create(name="ej", hostname="192.0.2.40", login="", password="", type=4) + self.other = Compute.objects.create(name="ej-other", hostname="192.0.2.41", login="", password="", type=4) + self.vms = [Instance.objects.create(compute=self.compute, name=f"ej-{n}", uuid=f"00000000-0000-4000-8000-00000000000{n}") + for n in range(3)] + self.admin = get_user_model().objects.create_superuser("ej-admin", "ej@example.com", "pw") + patcher = patch("instances.jobs.MigrateInstance.validate") # the hosts are not asked + patcher.start() + self.addCleanup(patcher.stop) + + def run_job(self, parallel, ends): + """Runs the evacuation of every VM; each round, ends(job) gives the end state of a running migration.""" + params = {"compute": self.compute.pk, "target": self.other.pk, "parallel": parallel, + "instances": [vm.pk for vm in self.vms]} + op = Operation.objects.create(kind="host.evacuate", user=self.admin, username=self.admin.username, + submission_key="key-evac0001", params=params, + intent=EvacuateHost().plan(self.admin, params).intent) + most = [] + + def round_ends(seconds): + running = Operation.objects.filter(kind="instance.migrate", state__in=Operation.ACTIVE) + most.append(running.count()) + for job in running: + job.state = ends(job) + job.save() + + with patch("computes.jobs.time.sleep", side_effect=round_ends): + try: + return EvacuateHost().run(op, Ctx(op)), max(most) + finally: + self.migrations = Operation.objects.filter(kind="instance.migrate") + + def test_the_migrations_run_the_chosen_number_at_once(self): + result, most = self.run_job(2, lambda job: Operation.SUCCEEDED) + self.assertEqual((result, most), ({}, 2)) + self.assertEqual(sorted(job.params["instance"] for job in self.migrations), [vm.pk for vm in self.vms]) + + def test_the_vms_that_did_not_migrate_are_named(self): + fail = self.vms[1].pk + with self.assertRaisesRegex(util.OperationError, "did not migrate"): + self.run_job(1, lambda job: Operation.FAILED if job.params["instance"] == fail else Operation.SUCCEEDED) + self.assertEqual(self.migrations.count(), 3) + + def test_a_create_waits_for_the_migrations(self): + Operation.objects.all().delete() + jobs.submit("instance.migrate", self.admin, {"instance": self.vms[0].pk, "target": self.other.pk}, "key-mig00001") + jobs.submit("instance.migrate", self.admin, {"instance": self.vms[1].pk, "target": self.other.pk}, "key-mig00002") + with self.assertRaises(claims.Busy): + claims.admit({claims.reconcile_key(self.compute.pk): Claim.EXCLUSIVE}, holder="test") + + def test_a_vm_that_left_the_host_meanwhile_stays_where_it_went(self): + third = Compute.objects.create(name="ej-third", hostname="192.0.2.42", login="", password="", type=4) + left = self.vms[2] + + def ends(job): # while the first migrations run, the last VM is moved to a third host + Instance.objects.filter(pk=left.pk).update(compute=third) + return Operation.SUCCEEDED + + self.run_job(1, ends) + self.assertNotIn(left.pk, [job.params["instance"] for job in self.migrations]) + + def test_one_evacuation_runs_at_a_time(self): + raw = {"compute": self.compute.pk, "target": self.other.pk, "parallel": 1, "instances": [self.vms[0].pk]} + jobs.submit("host.evacuate", self.admin, raw, "key-evac0002") + with self.assertRaises(claims.Busy): + jobs.submit("host.evacuate", self.admin, {**raw, "compute": self.other.pk, "target": self.compute.pk}, + "key-evac0003") + + def test_a_host_changed_meanwhile_stops_the_evacuation(self): + def ends(job): + Compute.objects.filter(pk=self.other.pk).update(hostname="192.0.2.99") + return Operation.SUCCEEDED + + with self.assertRaisesRegex(util.OperationError, "changed or deleted"): + self.run_job(1, ends) + self.assertEqual(self.migrations.count(), 1) + + def test_a_worker_lowered_to_one_slot_stops_the_evacuation(self): + def ends(job): + AppSettings.objects.filter(key="WORKER_CONCURRENCY").update(value="1") + return Operation.SUCCEEDED + + with self.assertRaisesRegex(util.OperationError, "one job at a time"): + self.run_job(1, ends) + self.assertEqual(self.migrations.count(), 1) + + def test_a_busy_vm_lets_the_others_go_first(self): + held = claims.admit({claims.instance_key(self.vms[0].uuid): Claim.EXCLUSIVE}, holder=claims.holder_id()) + + def ends(job): + Claim.objects.filter(pk__in=held).delete() # the short operation on the first VM ends + return Operation.SUCCEEDED + + self.run_job(1, ends) + order = [job.params["instance"] for job in self.migrations.order_by("created_at")] + self.assertEqual(order, [self.vms[1].pk, self.vms[2].pk, self.vms[0].pk]) + + def test_a_vm_an_uncertain_job_holds_is_not_waited_for(self): + stuck = Operation.objects.create(kind="instance.migrate", user=self.admin, username=self.admin.username, + submission_key="key-stuck001", state=Operation.UNCERTAIN) + Claim.objects.create(operation=stuck, resource=claims.instance_key(self.vms[0].uuid), mode=Claim.EXCLUSIVE) + with self.assertRaisesRegex(util.OperationError, "did not migrate"): + self.run_job(2, lambda job: Operation.SUCCEEDED) + self.assertEqual(self.migrations.exclude(pk=stuck.pk).count(), 2) + + def test_a_migration_from_a_host_the_vm_left_is_refused(self): + third = Compute.objects.create(name="ej-third", hostname="192.0.2.42", login="", password="", type=4) + raw = {"instance": self.vms[0].pk, "source": third.pk, "target": self.other.pk} + with self.assertRaisesRegex(util.OperationError, "moved to another compute"): + jobs.submit("instance.migrate", self.admin, raw, "key-mig00003") diff --git a/computes/urls.py b/computes/urls.py index 1cd54de6..a42af6a1 100644 --- a/computes/urls.py +++ b/computes/urls.py @@ -62,6 +62,7 @@ urlpatterns = [ path("statistics", views.compute_graph, name="compute_graph"), path("capacity/", views.capacity, name="compute_capacity"), path("instances/", views.instances, name="instances"), + path("evacuate/", views.evacuate, name="evacuate"), path("nodedevs/", nodedevs, name="nodedevs"), path("storages/", storages, name="storages"), path("storage//volumes/", get_volumes, name="volumes"), diff --git a/computes/views.py b/computes/views.py index 3decd515..6340774d 100644 --- a/computes/views.py +++ b/computes/views.py @@ -16,13 +16,16 @@ 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 webvirtcloud.middleware import error_text from instances.models import Instance from instances.utils import read_list_rows, vm_states -from libvirt import libvirtError +from libvirt import VIR_DOMAIN_XML_INACTIVE, libvirtError from logs.audit import audit, changed_fields, snapshot -from operations import claims +from operations import claims, jobs +from operations.utils import busy_message from vrtManager.connection import CONN_SOCKET, CONN_SSH, CONN_TCP, CONN_TLS from vrtManager.hostdetails import wvmHostDetails +from vrtManager.instance import wvmInstances from vrtManager.storage import wvmStorages from computes.forms import ( @@ -226,6 +229,56 @@ def instances(request, compute_id): ) +@superuser_only +def evacuate(request, compute_id): + """Migrates the chosen VMs of the host to another in one job, for the + host's maintenance: a migrate job each, the chosen number at once; a + running VM live, a shut-off one offline. A VM with a disk file the two + hosts do not share is not offered: it takes a copy, chosen on its own + Migrate tab.""" + from computes.jobs import parallel_limit + from instances.jobs import migration_target + + compute = get_object_or_404(Compute, pk=compute_id) + targets = list(Compute.objects.exclude(pk=compute.pk).order_by("name")) + if request.method == "POST": + # 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) + raw = {"compute": compute.pk, "target": target.pk, "parallel": request.POST.get("parallel", ""), + "instances": [pk for pk in request.POST.getlist("instance") if pk.isdigit()]} + try: + op = jobs.submit("host.evacuate", request.user, raw, request.POST.get("submission_key", "")) + except claims.Busy as busy: + messages.error(request, busy_message(busy, request.user)) + except (ValueError, jobs.SubmissionConflict, libvirtError) as err: + messages.error(request, error_text(request, err)) + else: + jobs.remember_job(request, op) + return redirect("instances", compute.pk) + return redirect(reverse("evacuate", args=[compute.pk]) + f"?target={target.pk}") + + chosen = request.GET.get("target") + target = next((t for t in targets if str(t.pk) == chosen), targets[0] if targets else None) + utils.refresh_instance_database(compute) + instances = list(Instance.objects.filter(compute=compute).order_by("name")) + read_list_rows(instances, [compute]) + dest = None + for instance in instances if target else (): + instance.refusal = None + try: + migration_target(instance, target.pk) + dest = dest or wvmInstances(target.hostname, target.login, target.password, target.type) + domain = instance.proxy.instance + for xml in (domain.XMLDesc(0), domain.XMLDesc(VIR_DOMAIN_XML_INACTIVE)): + if not all(disk["shared"] for disk in dest.disk_plan(instance.proxy, xml)): + instance.refusal = _("A disk file is not on storage both hosts share: migrate it from its page") + except libvirtError as err: + instance.refusal = error_text(request, err) + return render(request, "computes/evacuate.html", + {"compute": compute, "targets": targets, "target": target, "instances": instances, + "parallel": range(1, parallel_limit() + 1)}) + + # the form of each kind of compute, by Compute.type FORMS = {form.conn_type: form for form in (TcpComputeForm, SshComputeForm, TlsComputeForm, SocketComputeForm)} diff --git a/instances/jobs.py b/instances/jobs.py index 097aab7e..be073f28 100644 --- a/instances/jobs.py +++ b/instances/jobs.py @@ -1165,7 +1165,9 @@ class MigrateInstance(Kind): def normalize(self, raw): # disk_pools: {target: pool of the destination} of the disks to copy there + # source: the host an evacuation migrates the VM from; one that left it since is refused return {"instance": int(raw["instance"]), "target": int(raw["target"]), + "source": int(raw["source"]) if raw.get("source") else None, "disk_pools": {str(k): str(v) for k, v in (raw.get("disk_pools") or {}).items() if v}, **{k: bool(raw.get(k)) for k in MIGRATE_OPTIONS}} @@ -1176,9 +1178,14 @@ class MigrateInstance(Kind): def plan(self, user, params): instance = _instance(params["instance"]) + if params["source"] not in (None, instance.compute_id): + raise util.OperationError(MOVED) keys = vm_claims(Compute.objects.get(pk=params["target"]), instance.name) - keys.update({claims.compute_key(instance.compute_id): Claim.SHARED, - claims.reconcile_key(instance.compute_id): Claim.EXCLUSIVE, + # migrations share the hosts' VM sets, so a host evacuates several VMs at once; + # creates, clones, deletes and the VM list reconcile still wait for them + keys.update({claims.reconcile_key(params["target"]): Claim.SHARED, + claims.compute_key(instance.compute_id): Claim.SHARED, + claims.reconcile_key(instance.compute_id): Claim.SHARED, claims.instance_key(instance.uuid): Claim.EXCLUSIVE}) if params["disk_pools"]: # a copy takes its file's name in the chosen pool; the source file may go diff --git a/instances/tests/test_live_jobs.py b/instances/tests/test_live_jobs.py index f359b8bf..5205a9cc 100644 --- a/instances/tests/test_live_jobs.py +++ b/instances/tests/test_live_jobs.py @@ -10,6 +10,7 @@ import subprocess import unittest import libvirt +from lxml import html from django.contrib.auth import get_user_model from django.core.files.uploadedfile import SimpleUploadedFile from django.test import TransactionTestCase @@ -91,8 +92,8 @@ class LiveJobsTestCase(TransactionTestCase): op.refresh_from_db() self.assertEqual(DeleteExternalSnapshot().reconcile(op).state, Operation.SUCCEEDED) - def run_job(self, op): - worker = Worker(concurrency=1, tick=0.1, heartbeat_every=1, progress_every=1, exit_on_lost_lease=False) + def run_job(self, op, concurrency=1): + worker = Worker(concurrency=concurrency, tick=0.1, heartbeat_every=1, progress_every=1, exit_on_lost_lease=False) thread = fakes.start_worker(worker) try: self.assertTrue(wait_for(lambda: Operation.objects.get(pk=op.pk).state in Operation.TERMINAL, 300)) @@ -182,6 +183,26 @@ class LiveJobsTestCase(TransactionTestCase): self.assertFalse(self.conn.lookupByUUIDString(uuid).isActive()) # defined on the source again self.assertEqual(Instance.objects.get(uuid=uuid).compute, self.compute) + def test_an_evacuation_migrates_the_chosen_vms_two_at_once(self): + dest, dest_conn = self.second_host() + vms = [] + for name, running in (("evac-run", True), ("evac-off", False)): + dom = livetest.define_vm(self.conn, P + name, []) + if running: + dom.create() + vms.append(Instance.objects.create(compute=self.compute, name=dom.name(), uuid=dom.UUIDString())) + local = self.vm("evac-disk")[0] # its disk is in a pool of this host only + local = Instance.objects.create(compute=self.compute, name=local.name(), uuid=local.UUIDString()) + self.client.force_login(self.admin) + page = html.fromstring(self.client.get(reverse("evacuate", args=[self.compute.pk]) + f"?target={dest.pk}").content) + disabled = {int(box.get("value")): box.get("disabled") is not None for box in page.xpath("//input[@name='instance']")} + self.assertEqual([disabled[vm.pk] for vm in (*vms, local)], [False, False, True]) # the host's other VMs as they are + raw = {"compute": self.compute.pk, "target": dest.pk, "parallel": 2, "instances": [vm.pk for vm in vms]} + self.run_job(jobs.submit("host.evacuate", self.admin, raw, "key-evac0001"), concurrency=4) + self.assertEqual(Operation.objects.filter(kind="instance.migrate", state=Operation.SUCCEEDED).count(), 2) + self.assertEqual([dest_conn.lookupByUUIDString(vm.uuid).isActive() for vm in vms], [True, False]) + self.assertEqual({vm.compute for vm in Instance.objects.filter(pk__in=[vm.pk for vm in vms])}, {dest}) + def test_a_disk_neither_host_shares_is_copied_there_and_back(self): """The test pool is a directory of each host's own: the disk is copied into it, running there with its source file deleted on diff --git a/instances/tests/test_migrate_job.py b/instances/tests/test_migrate_job.py index 4751f1d7..f6c3ff1c 100644 --- a/instances/tests/test_migrate_job.py +++ b/instances/tests/test_migrate_job.py @@ -58,8 +58,8 @@ class MigrateJobTestCase(TransactionTestCase): op = self.queue(live_migrate="true") self.assertEqual(set(Claim.objects.values_list("resource", "mode")), { (f"instance:{UUID}", "exclusive"), ("name:mig-vm", "exclusive"), - (f"compute:{self.source.pk}", "shared"), (f"reconcile:{self.source.pk}", "exclusive"), - (f"compute:{self.dest.pk}", "shared"), (f"reconcile:{self.dest.pk}", "exclusive")}) + (f"compute:{self.source.pk}", "shared"), (f"reconcile:{self.source.pk}", "shared"), + (f"compute:{self.dest.pk}", "shared"), (f"reconcile:{self.dest.pk}", "shared")}) self.dest_conn.moveto.assert_not_called() # nothing ran in the request ctx = self.start(op) get_kind(op.kind).precheck(op, ctx) diff --git a/locale/tr/LC_MESSAGES/django.mo b/locale/tr/LC_MESSAGES/django.mo index 969ab168..ba6d4cec 100644 Binary files a/locale/tr/LC_MESSAGES/django.mo and b/locale/tr/LC_MESSAGES/django.mo differ diff --git a/locale/tr/LC_MESSAGES/django.po b/locale/tr/LC_MESSAGES/django.po index 192b349c..c3852fbb 100644 --- a/locale/tr/LC_MESSAGES/django.po +++ b/locale/tr/LC_MESSAGES/django.po @@ -11,7 +11,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2026-11-14 21:31+0000\n" +"POT-Creation-Date: 2026-11-15 14:47+0000\n" "PO-Revision-Date: 2020-11-04 12:00+0000\n" "Last-Translator: catborise , 2020\n" "Language-Team: Turkish (https://www.transifex.com/catborise/teams/110663/tr/)\n" @@ -64,7 +64,8 @@ msgstr "Açık anahtar zaten mevcut" msgid "Invalid key" msgstr "Geçersiz anahtar" -#: accounts/forms.py:95 computes/templates/computes/instances.html:45 +#: accounts/forms.py:95 computes/templates/computes/evacuate.html:43 +#: computes/templates/computes/instances.html:46 #: instances/templates/add_instance_volume.html:39 #: instances/templates/allinstances_index_grouped.html:11 #: instances/templates/allinstances_index_nongrouped.html:6 @@ -723,7 +724,7 @@ msgstr "Listelerde tüm sanal makineleri ve sunucuları salt okunur görme" #: admin/forms.py:89 admin/templates/admin/logs.html:39 #: admin/templates/admin/user_list.html:24 #: admin/templates/admin/user_list.html:34 -#: computes/templates/computes/instances.html:46 +#: computes/templates/computes/instances.html:47 #: instances/templates/add_instance_owner_block.html:17 #: instances/templates/instances/stats_tab.html:70 #: operations/templates/operations/job.html:21 @@ -767,7 +768,8 @@ msgstr "" msgid "vCPUs" msgstr "vCPU" -#: admin/forms.py:209 computes/templates/computes/instances.html:49 +#: admin/forms.py:209 computes/templates/computes/evacuate.html:46 +#: computes/templates/computes/instances.html:50 #: computes/templates/computes/list.html:59 computes/templates/overview.html:66 #: computes/templates/overview.html:150 #: instances/templates/allinstances_index_grouped.html:17 @@ -1886,7 +1888,7 @@ msgstr "Diğer" msgid "Stored, leave empty to keep" msgstr "Kayıtlı, korumak için boş bırakın" -#: computes/forms.py:31 computes/templates/computes/instances.html:45 +#: computes/forms.py:31 computes/templates/computes/instances.html:46 #: instances/templates/instances/settings_tab.html:872 #: instances/templates/instances/settings_tab.html:904 #: instances/templates/instances/snapshots_tab.html:27 @@ -1934,6 +1936,50 @@ msgstr "Yerel" msgid "the libvirt of the host the panel runs on, by its socket" msgstr "panelin çalıştığı sunucunun libvirt'i, soketi üzerinden" +#: computes/jobs.py:39 +msgid "Evacuate host" +msgstr "Sunucuyu boşalt" + +#: computes/jobs.py:50 +msgid "Choose the VMs to migrate" +msgstr "Taşınacak sanal makineleri seçin" + +#: computes/jobs.py:52 +#, python-format +msgid "At most %(limit)s migrations can run at once" +msgstr "Aynı anda en fazla %(limit)s taşıma çalışabilir" + +#: computes/jobs.py:71 +msgid "Migrating the VMs" +msgstr "Sanal makineler taşınıyor" + +#: computes/jobs.py:84 +msgid "" +"The worker now runs one job at a time: the VMs not yet started stay on the " +"host" +msgstr "" +"İş yürütücü artık aynı anda tek iş çalıştırıyor: henüz başlatılmamış sanal " +"makineler sunucuda kalıyor" + +#: computes/jobs.py:87 +msgid "A host was changed or deleted: the VMs not yet started stay on the host" +msgstr "" +"Bir sunucu değiştirildi ya da silindi: henüz başlatılmamış sanal makineler " +"sunucuda kalıyor" + +#: computes/jobs.py:111 +#, python-format +msgid "These VMs did not migrate: %(vms)s" +msgstr "Bu sanal makineler taşınamadı: %(vms)s" + +#: computes/jobs.py:119 +msgid "" +"The evacuation stopped: the migrations it started go on as their own jobs; " +"the other VMs stay" +msgstr "" +"Boşaltma durdu: başlattığı taşımalar kendi işleri olarak sürüyor; diğer sanal" +" makineler yerinde kalıyor" + #: computes/models.py:21 msgid "hostname" msgstr "sunucuadı" @@ -2109,6 +2155,79 @@ msgstr "Kapalı sanal makinelerin vCPU'ları" msgid "%(stopped)s of the host's %(cpus)s CPUs" msgstr "Sunucunun %(cpus)s CPU'sundan %(stopped)s" +#: computes/templates/computes/evacuate.html:5 +#: computes/templates/computes/evacuate.html:6 +#: computes/templates/computes/instances.html:15 +msgid "Evacuate" +msgstr "Boşalt" + +#: computes/templates/computes/evacuate.html:15 instances/views.py:379 +msgid "There is no other host to migrate to." +msgstr "Taşınacak başka bir sunucu yok." + +#: computes/templates/computes/evacuate.html:17 +msgid "" +"Each chosen VM migrates in a job of its own: a running VM live, a shut-off " +"one offline. A VM that fails stays on this host." +msgstr "" +"Seçilen her sanal makine kendi işinde taşınır: çalışan sanal makine canlı, " +"kapalı olan çevrimdışı. Taşınamayan sanal makine bu sunucuda kalır." + +#: computes/templates/computes/evacuate.html:20 +msgid "Destination" +msgstr "Hedef" + +#: computes/templates/computes/evacuate.html:25 +msgid "Check" +msgstr "Denetle" + +#: computes/templates/computes/evacuate.html:28 +msgid "" +"The worker runs one job at a time: set Worker Concurrency to 2 or more on the" +" Settings page." +msgstr "" +"İş yürütücü aynı anda tek iş çalıştırıyor: Ayarlar sayfasında Eş zamanlı iş " +"sayısı değerini 2 veya daha fazla yapın." + +#: computes/templates/computes/evacuate.html:30 +msgid "The host has no VMs." +msgstr "Bu sunucuda sanal makine yok." + +#: computes/templates/computes/evacuate.html:36 +msgid "Also migrate the shut-off VMs" +msgstr "Kapalı sanal makineleri de taşı" + +#: computes/templates/computes/evacuate.html:42 +#: computes/templates/computes/evacuate.html:74 +#: instances/templates/instances/settings_tab.html:60 +#: instances/templates/instances/settings_tab.html:617 +#: instances/templates/instances/settings_tab.html:620 +msgid "Migrate" +msgstr "Taşı" + +#: computes/templates/computes/evacuate.html:44 +#: computes/templates/computes/instances.html:48 +#: instances/templates/allinstances_index_grouped.html:12 +#: instances/templates/allinstances_index_nongrouped.html:10 +msgid "Status" +msgstr "Durum" + +#: computes/templates/computes/evacuate.html:45 +#: computes/templates/computes/instances.html:49 +msgid "VCPU" +msgstr "VCPU" + +#: computes/templates/computes/evacuate.html:68 +msgid "Migrations at once" +msgstr "Aynı anda taşıma" + +#: computes/templates/computes/evacuate.html:73 +#, python-format +msgid "Migrate the chosen VMs from %(source)s to %(dest)s?" +msgstr "" +"Seçilen sanal makineler %(source)s sunucusundan %(dest)s sunucusuna taşınsın " +"mı?" + #: computes/templates/computes/form.html:5 msgid "Edit host" msgstr "Sunucuyu düzenle" @@ -2238,31 +2357,21 @@ msgstr "Aygıtlar" msgid "New Instance" msgstr "Yeni sanal makine" -#: computes/templates/computes/instances.html:30 +#: computes/templates/computes/instances.html:31 #, python-format msgid "Problem occurred with host %(name)s: %(error)s" msgstr "%(name)s sunucusuyla ilgili bir sorun oluştu: %(error)s" -#: computes/templates/computes/instances.html:36 +#: computes/templates/computes/instances.html:37 #: computes/templates/computes/list.html:16 msgid "Warning" msgstr "Uyarı" -#: computes/templates/computes/instances.html:37 +#: computes/templates/computes/instances.html:38 msgid "Hypervisor doesn't have any Instances" msgstr "Hipervizör üzerinde hiç sanal makine yok" -#: computes/templates/computes/instances.html:47 -#: instances/templates/allinstances_index_grouped.html:12 -#: instances/templates/allinstances_index_nongrouped.html:10 -msgid "Status" -msgstr "Durum" - -#: computes/templates/computes/instances.html:48 -msgid "VCPU" -msgstr "VCPU" - -#: computes/templates/computes/instances.html:50 +#: computes/templates/computes/instances.html:51 #: computes/templates/computes/list.html:60 #: instances/templates/allinstances_index_grouped.html:18 #: instances/templates/allinstances_index_nongrouped.html:16 @@ -2506,17 +2615,24 @@ msgstr "" "Sunucudaki /etc/default/webvirt-gstfsd içindeki GSTFSD_KEY değerinin 64 " "onaltılık karakterini girin" -#: computes/views.py:148 +#: computes/views.py:151 #, python-format msgid "The host did not answer within %(seconds)s seconds" msgstr "Sunucu %(seconds)s saniye içinde yanıt vermedi" -#: computes/views.py:236 +#: computes/views.py:274 +msgid "" +"A disk file is not on storage both hosts share: migrate it from its page" +msgstr "" +"Bir disk dosyası iki sunucunun paylaştığı depolamada değil: sanal makineyi " +"kendi sayfasından taşıyın" + +#: computes/views.py:289 #, python-format msgid "The host was saved, but the panel cannot connect to it: %(error)s" msgstr "Sunucu kaydedildi, ancak panel ona bağlanamıyor: %(error)s" -#: computes/views.py:292 +#: computes/views.py:345 #, python-format msgid "" "Its VMs keep running on the host and leave the panel; their owners are kept " @@ -3292,78 +3408,78 @@ msgstr "Sanal makine taşındı, ancak NVRAM dosyası kaynakta kaldı: %(error)s msgid "Migrate VM" msgstr "Sanal makineyi taşı" -#: instances/jobs.py:1209 +#: instances/jobs.py:1212 msgid "Migrating the VM" msgstr "Sanal makine taşınıyor" -#: instances/jobs.py:1258 +#: instances/jobs.py:1261 msgid "libvirt is still migrating the VM" msgstr "libvirt sanal makineyi hâlâ taşıyor" -#: instances/jobs.py:1270 +#: instances/jobs.py:1273 msgid "The VM stayed on the source host" msgstr "Sanal makine kaynak sunucuda kaldı" -#: instances/jobs.py:1272 +#: instances/jobs.py:1275 msgid "" "The VM is on both computes or on neither; check them, then resolve this job." msgstr "" "Sanal makine ya iki sunucuda da var ya da hiçbirinde yok; kontrol edin, sonra" " bu işi çözün." -#: instances/jobs.py:1291 +#: instances/jobs.py:1294 msgid "Move disk" msgstr "Diski taşı" -#: instances/jobs.py:1298 +#: instances/jobs.py:1301 msgid "Choose a disk of the VM" msgstr "Sanal makinenin bir diskini seçin" -#: instances/jobs.py:1322 +#: instances/jobs.py:1325 msgid "Copying the disk" msgstr "Disk kopyalanıyor" -#: instances/jobs.py:1364 +#: instances/jobs.py:1367 #, python-format msgid "Another block job runs on %(dev)s; check the VM" msgstr "" "%(dev)s üzerinde başka bir blok işi çalışıyor; sanal makineyi kontrol edin" -#: instances/jobs.py:1370 +#: instances/jobs.py:1373 #, python-format msgid "The disk stayed in %(path)s; remove %(dest)s if it is there" msgstr "Disk %(path)s içinde kaldı; varsa %(dest)s dosyasını silin" -#: instances/jobs.py:1372 +#: instances/jobs.py:1375 #, python-format msgid "The definitions of %(dev)s name %(paths)s; check the VM" msgstr "%(dev)s tanımları %(paths)s gösteriyor; sanal makineyi kontrol edin" -#: instances/jobs.py:1379 +#: instances/jobs.py:1382 #, python-format msgid "Disk %(path)s was kept: a disk file that stays needs it" msgstr "%(path)s diski korundu: kalan bir disk dosyası ona ihtiyaç duyuyor" -#: instances/jobs.py:1380 +#: instances/jobs.py:1383 #, python-format msgid "The VM is removed, but disk %(path)s was not deleted: %(err)s" msgstr "Sanal makine kaldırıldı, ancak %(path)s diski silinmedi: %(err)s" -#: instances/jobs.py:1381 +#: instances/jobs.py:1384 #, python-format msgid "Disk %(path)s is used by another VM and was kept" msgstr "" "%(path)s diski başka bir sanal makine tarafından kullanılıyor ve korundu" -#: instances/jobs.py:1435 +#: instances/jobs.py:1438 msgid "Delete VM" msgstr "Sanal makineyi sil" -#: instances/jobs.py:1465 +#: instances/jobs.py:1468 msgid "Deleting the VM" msgstr "Sanal makine siliniyor" -#: instances/jobs.py:1477 +#: instances/jobs.py:1480 msgid "The VM was not deleted; it may have been shut off" msgstr "Sanal makine silinmedi; kapatılmış olabilir" @@ -5018,12 +5134,6 @@ msgstr "Ağ" msgid "Host devices" msgstr "Sunucu aygıtları" -#: instances/templates/instances/settings_tab.html:60 -#: instances/templates/instances/settings_tab.html:617 -#: instances/templates/instances/settings_tab.html:620 -msgid "Migrate" -msgstr "Taşı" - #: instances/templates/instances/settings_tab.html:65 msgid "XML" msgstr "XML" @@ -6320,10 +6430,6 @@ msgstr " Üzerindeki işler menüdeki İşler bölümünden izlenebilir." msgid "'%(name)s' is no longer on its host." msgstr "'%(name)s' artık sunucusunda yok." -#: instances/views.py:379 -msgid "There is no other host to migrate to." -msgstr "Taşınacak başka bir sunucu yok." - #: instances/views.py:381 msgid "A VM migrates when it is running, paused or shut off." msgstr "" diff --git a/locale/zh/LC_MESSAGES/django.mo b/locale/zh/LC_MESSAGES/django.mo index 3a6c14bd..ae27b775 100644 Binary files a/locale/zh/LC_MESSAGES/django.mo and b/locale/zh/LC_MESSAGES/django.mo differ diff --git a/locale/zh/LC_MESSAGES/django.po b/locale/zh/LC_MESSAGES/django.po index 31bd99e1..8e7ae86f 100644 --- a/locale/zh/LC_MESSAGES/django.po +++ b/locale/zh/LC_MESSAGES/django.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2026-11-14 21:31+0000\n" +"POT-Creation-Date: 2026-11-15 14:47+0000\n" "PO-Revision-Date: \n" "Last-Translator: \n" "Language-Team: \n" @@ -61,7 +61,8 @@ msgstr "公钥已存在" msgid "Invalid key" msgstr "无效的密钥" -#: accounts/forms.py:95 computes/templates/computes/instances.html:45 +#: accounts/forms.py:95 computes/templates/computes/evacuate.html:43 +#: computes/templates/computes/instances.html:46 #: instances/templates/add_instance_volume.html:39 #: instances/templates/allinstances_index_grouped.html:11 #: instances/templates/allinstances_index_nongrouped.html:6 @@ -703,7 +704,7 @@ msgstr "在列表中查看所有虚拟机和主机(只读)" #: admin/forms.py:89 admin/templates/admin/logs.html:39 #: admin/templates/admin/user_list.html:24 #: admin/templates/admin/user_list.html:34 -#: computes/templates/computes/instances.html:46 +#: computes/templates/computes/instances.html:47 #: instances/templates/add_instance_owner_block.html:17 #: instances/templates/instances/stats_tab.html:70 #: operations/templates/operations/job.html:21 @@ -744,7 +745,8 @@ msgstr "NEW_USER_DEFAULT_INSTANCES:%(name)s 已有所有者,且只允许一 msgid "vCPUs" msgstr "vCPU" -#: admin/forms.py:209 computes/templates/computes/instances.html:49 +#: admin/forms.py:209 computes/templates/computes/evacuate.html:46 +#: computes/templates/computes/instances.html:50 #: computes/templates/computes/list.html:59 computes/templates/overview.html:66 #: computes/templates/overview.html:150 #: instances/templates/allinstances_index_grouped.html:17 @@ -1823,7 +1825,7 @@ msgstr "其他" msgid "Stored, leave empty to keep" msgstr "已保存,留空则保持不变" -#: computes/forms.py:31 computes/templates/computes/instances.html:45 +#: computes/forms.py:31 computes/templates/computes/instances.html:46 #: instances/templates/instances/settings_tab.html:872 #: instances/templates/instances/settings_tab.html:904 #: instances/templates/instances/snapshots_tab.html:27 @@ -1871,6 +1873,44 @@ msgstr "本地" msgid "the libvirt of the host the panel runs on, by its socket" msgstr "面板所在主机的 libvirt,通过其套接字连接" +#: computes/jobs.py:39 +msgid "Evacuate host" +msgstr "疏散主机" + +#: computes/jobs.py:50 +msgid "Choose the VMs to migrate" +msgstr "请选择要迁移的虚拟机" + +#: computes/jobs.py:52 +#, python-format +msgid "At most %(limit)s migrations can run at once" +msgstr "最多可同时运行 %(limit)s 个迁移" + +#: computes/jobs.py:71 +msgid "Migrating the VMs" +msgstr "正在迁移虚拟机" + +#: computes/jobs.py:84 +msgid "" +"The worker now runs one job at a time: the VMs not yet started stay on the " +"host" +msgstr "任务执行器现在一次只运行一个任务:尚未开始的虚拟机留在主机上" + +#: computes/jobs.py:87 +msgid "A host was changed or deleted: the VMs not yet started stay on the host" +msgstr "有主机被修改或删除:尚未开始的虚拟机留在主机上" + +#: computes/jobs.py:111 +#, python-format +msgid "These VMs did not migrate: %(vms)s" +msgstr "以下虚拟机未能迁移:%(vms)s" + +#: computes/jobs.py:119 +msgid "" +"The evacuation stopped: the migrations it started go on as their own jobs; " +"the other VMs stay" +msgstr "疏散已停止:已启动的迁移作为各自的任务继续进行;其他虚拟机保持不动" + #: computes/models.py:21 msgid "hostname" msgstr "主机名" @@ -2025,6 +2065,73 @@ msgstr "已关机虚拟机的 vCPU" msgid "%(stopped)s of the host's %(cpus)s CPUs" msgstr "占主机 %(cpus)s 个 CPU 中的 %(stopped)s" +#: computes/templates/computes/evacuate.html:5 +#: computes/templates/computes/evacuate.html:6 +#: computes/templates/computes/instances.html:15 +msgid "Evacuate" +msgstr "疏散" + +#: computes/templates/computes/evacuate.html:15 instances/views.py:379 +msgid "There is no other host to migrate to." +msgstr "没有其他可迁移到的主机。" + +#: computes/templates/computes/evacuate.html:17 +msgid "" +"Each chosen VM migrates in a job of its own: a running VM live, a shut-off " +"one offline. A VM that fails stays on this host." +msgstr "每台选中的虚拟机在各自的任务中迁移:运行中的虚拟机在线迁移,已关机的离线迁移。迁移失败的虚拟机留在此主机上。" + +#: computes/templates/computes/evacuate.html:20 +msgid "Destination" +msgstr "目标主机" + +#: computes/templates/computes/evacuate.html:25 +msgid "Check" +msgstr "检查" + +#: computes/templates/computes/evacuate.html:28 +msgid "" +"The worker runs one job at a time: set Worker Concurrency to 2 or more on the" +" Settings page." +msgstr "任务执行器一次只运行一个任务:请在设置页面将工作进程并发数设为 2 或更大。" + +#: computes/templates/computes/evacuate.html:30 +msgid "The host has no VMs." +msgstr "此主机没有虚拟机。" + +#: computes/templates/computes/evacuate.html:36 +msgid "Also migrate the shut-off VMs" +msgstr "同时迁移已关机的虚拟机" + +#: computes/templates/computes/evacuate.html:42 +#: computes/templates/computes/evacuate.html:74 +#: instances/templates/instances/settings_tab.html:60 +#: instances/templates/instances/settings_tab.html:617 +#: instances/templates/instances/settings_tab.html:620 +msgid "Migrate" +msgstr "迁移" + +#: computes/templates/computes/evacuate.html:44 +#: computes/templates/computes/instances.html:48 +#: instances/templates/allinstances_index_grouped.html:12 +#: instances/templates/allinstances_index_nongrouped.html:10 +msgid "Status" +msgstr "状态" + +#: computes/templates/computes/evacuate.html:45 +#: computes/templates/computes/instances.html:49 +msgid "VCPU" +msgstr "VCPU" + +#: computes/templates/computes/evacuate.html:68 +msgid "Migrations at once" +msgstr "同时迁移数" + +#: computes/templates/computes/evacuate.html:73 +#, python-format +msgid "Migrate the chosen VMs from %(source)s to %(dest)s?" +msgstr "将选中的虚拟机从 %(source)s 迁移到 %(dest)s?" + #: computes/templates/computes/form.html:5 msgid "Edit host" msgstr "编辑主机" @@ -2154,31 +2261,21 @@ msgstr "设备" msgid "New Instance" msgstr "新建虚拟机" -#: computes/templates/computes/instances.html:30 +#: computes/templates/computes/instances.html:31 #, python-format msgid "Problem occurred with host %(name)s: %(error)s" msgstr "主机 %(name)s 出现问题:%(error)s" -#: computes/templates/computes/instances.html:36 +#: computes/templates/computes/instances.html:37 #: computes/templates/computes/list.html:16 msgid "Warning" msgstr "警告" -#: computes/templates/computes/instances.html:37 +#: computes/templates/computes/instances.html:38 msgid "Hypervisor doesn't have any Instances" msgstr "虚拟机管理程序中没有任何虚拟机" -#: computes/templates/computes/instances.html:47 -#: instances/templates/allinstances_index_grouped.html:12 -#: instances/templates/allinstances_index_nongrouped.html:10 -msgid "Status" -msgstr "状态" - -#: computes/templates/computes/instances.html:48 -msgid "VCPU" -msgstr "VCPU" - -#: computes/templates/computes/instances.html:50 +#: computes/templates/computes/instances.html:51 #: computes/templates/computes/list.html:60 #: instances/templates/allinstances_index_grouped.html:18 #: instances/templates/allinstances_index_nongrouped.html:16 @@ -2414,17 +2511,22 @@ msgid "" "/etc/default/webvirt-gstfsd" msgstr "请输入主机 /etc/default/webvirt-gstfsd 中 GSTFSD_KEY 的 64 个十六进制字符" -#: computes/views.py:148 +#: computes/views.py:151 #, python-format msgid "The host did not answer within %(seconds)s seconds" msgstr "主机未在 %(seconds)s 秒内响应" -#: computes/views.py:236 +#: computes/views.py:274 +msgid "" +"A disk file is not on storage both hosts share: migrate it from its page" +msgstr "有磁盘文件不在两台主机共享的存储上:请在该虚拟机的页面上迁移它" + +#: computes/views.py:289 #, python-format msgid "The host was saved, but the panel cannot connect to it: %(error)s" msgstr "主机已保存,但面板无法连接到它:%(error)s" -#: computes/views.py:292 +#: computes/views.py:345 #, python-format msgid "" "Its VMs keep running on the host and leave the panel; their owners are kept " @@ -3140,74 +3242,74 @@ msgstr "虚拟机已迁移,但其 NVRAM 文件仍留在源主机上:%(error) msgid "Migrate VM" msgstr "迁移虚拟机" -#: instances/jobs.py:1209 +#: instances/jobs.py:1212 msgid "Migrating the VM" msgstr "正在迁移虚拟机" -#: instances/jobs.py:1258 +#: instances/jobs.py:1261 msgid "libvirt is still migrating the VM" msgstr "libvirt 仍在迁移虚拟机" -#: instances/jobs.py:1270 +#: instances/jobs.py:1273 msgid "The VM stayed on the source host" msgstr "虚拟机留在了源主机上" -#: instances/jobs.py:1272 +#: instances/jobs.py:1275 msgid "" "The VM is on both computes or on neither; check them, then resolve this job." msgstr "虚拟机同时位于两个计算节点上,或都不在;请检查后处理此任务。" -#: instances/jobs.py:1291 +#: instances/jobs.py:1294 msgid "Move disk" msgstr "移动磁盘" -#: instances/jobs.py:1298 +#: instances/jobs.py:1301 msgid "Choose a disk of the VM" msgstr "请选择虚拟机的一个磁盘" -#: instances/jobs.py:1322 +#: instances/jobs.py:1325 msgid "Copying the disk" msgstr "正在复制磁盘" -#: instances/jobs.py:1364 +#: instances/jobs.py:1367 #, python-format msgid "Another block job runs on %(dev)s; check the VM" msgstr "%(dev)s 上正在运行另一个块任务;请检查虚拟机" -#: instances/jobs.py:1370 +#: instances/jobs.py:1373 #, python-format msgid "The disk stayed in %(path)s; remove %(dest)s if it is there" msgstr "磁盘仍在 %(path)s;如果 %(dest)s 存在,请将其删除" -#: instances/jobs.py:1372 +#: instances/jobs.py:1375 #, python-format msgid "The definitions of %(dev)s name %(paths)s; check the VM" msgstr "%(dev)s 的定义指向 %(paths)s;请检查虚拟机" -#: instances/jobs.py:1379 +#: instances/jobs.py:1382 #, python-format msgid "Disk %(path)s was kept: a disk file that stays needs it" msgstr "磁盘 %(path)s 已保留:某个保留的磁盘文件依赖它" -#: instances/jobs.py:1380 +#: instances/jobs.py:1383 #, python-format msgid "The VM is removed, but disk %(path)s was not deleted: %(err)s" msgstr "虚拟机已删除,但磁盘 %(path)s 未被删除:%(err)s" -#: instances/jobs.py:1381 +#: instances/jobs.py:1384 #, python-format msgid "Disk %(path)s is used by another VM and was kept" msgstr "磁盘 %(path)s 正被另一台虚拟机使用,已保留" -#: instances/jobs.py:1435 +#: instances/jobs.py:1438 msgid "Delete VM" msgstr "删除虚拟机" -#: instances/jobs.py:1465 +#: instances/jobs.py:1468 msgid "Deleting the VM" msgstr "正在删除虚拟机" -#: instances/jobs.py:1477 +#: instances/jobs.py:1480 msgid "The VM was not deleted; it may have been shut off" msgstr "虚拟机未被删除;它可能已被关闭" @@ -4775,12 +4877,6 @@ msgstr "网络" msgid "Host devices" msgstr "主机设备" -#: instances/templates/instances/settings_tab.html:60 -#: instances/templates/instances/settings_tab.html:617 -#: instances/templates/instances/settings_tab.html:620 -msgid "Migrate" -msgstr "迁移" - #: instances/templates/instances/settings_tab.html:65 msgid "XML" msgstr "XML" @@ -5975,10 +6071,6 @@ msgstr " 其上的任务可在菜单的“任务”中跟踪。" msgid "'%(name)s' is no longer on its host." msgstr "“%(name)s”已不在其主机上。" -#: instances/views.py:379 -msgid "There is no other host to migrate to." -msgstr "没有其他可迁移到的主机。" - #: instances/views.py:381 msgid "A VM migrates when it is running, paused or shut off." msgstr "虚拟机在运行、暂停或关机状态下均可迁移。" diff --git a/operations/claims.py b/operations/claims.py index a9990317..806261c6 100644 --- a/operations/claims.py +++ b/operations/claims.py @@ -41,6 +41,12 @@ def reconcile_key(compute_id): return f"reconcile:{compute_id}" +def evacuate_key(): + """The evacuations: one at a time. One waits in a worker slot for its + migrations; several could take every slot and leave none for them.""" + return "evacuate" + + def instance_key(uuid): return f"instance:{uuid}" diff --git a/static/js/evacuate.js b/static/js/evacuate.js new file mode 100644 index 00000000..97ea3756 --- /dev/null +++ b/static/js/evacuate.js @@ -0,0 +1,6 @@ +// The evacuate page: "Also migrate the shut-off VMs" ticks or unticks them. +document.getElementById("evacuate-shut-off")?.addEventListener("change", function (event) { + document.querySelectorAll("input[data-shut-off]:not(:disabled)").forEach(function (box) { + box.checked = event.target.checked; + }); +}); diff --git a/vrtManager/connection.py b/vrtManager/connection.py index 822ea896..abce0883 100644 --- a/vrtManager/connection.py +++ b/vrtManager/connection.py @@ -194,6 +194,11 @@ UNREAD_DISKS = etree.XPath("devices/disk[@device='disk'][not(driver/@type='raw') "devices/disk[@device='disk'][not(driver/@type='raw')]/source/@dev") +# One use of NVRAM_DIR's pool at a time (_nvram_pool), on every host: a copy +# holds two hosts' pools, and locks per host taken by migrations both ways +# could deadlock. Reentrant, as that copy takes it twice. +NVRAM_LOCK = threading.RLock() + class wvmConnection(object): """ class representing a single connection stored in the Connection Manager @@ -1041,7 +1046,13 @@ class wvmConnect(object): @contextlib.contextmanager def _nvram_pool(self): """An active, refreshed pool on NVRAM_DIR: libvirt reads and deletes - files only as volumes of a pool. A transient one when none exists.""" + files only as volumes of a pool. A transient one when none exists, + destroyed after: one use at a time (NVRAM_LOCK), as another would + take that pool for the host's and lose it midway.""" + with NVRAM_LOCK: + yield from self._nvram_pool_unlocked() + + def _nvram_pool_unlocked(self): pool = self.pool_at(NVRAM_DIR) if pool is not None: pool.refresh(0) diff --git a/vrtManager/tests/test_remove_nvram.py b/vrtManager/tests/test_remove_nvram.py index d5604207..1957bc8b 100644 --- a/vrtManager/tests/test_remove_nvram.py +++ b/vrtManager/tests/test_remove_nvram.py @@ -3,6 +3,7 @@ source when it is in libvirt's per-host NVRAM directory and the destination does not share that directory; a VM later created on the source with the same name would otherwise start with the old UEFI variables.""" +import threading from unittest import TestCase from unittest.mock import MagicMock @@ -130,3 +131,24 @@ class RemoveNvramTestCase(TestCase): conn = connect([], transient) self.assertFalse(conn.remove_nvram(PATH, local_destination())) transient.destroy.assert_called_once_with() + + +class NvramPoolTests(TestCase): + def test_a_second_use_waits_until_the_first_destroyed_its_transient_pool(self): + conn = object.__new__(wvmConnect) + conn.wvm = MagicMock() + conn.pool_at = MagicMock(return_value=None) # no pool on NVRAM_DIR: each use makes a transient one + transient = conn.wvm.storagePoolCreateXML.return_value + seen = [] + + def second(): + with conn._nvram_pool(): + seen.append(transient.destroy.call_count) + + with conn._nvram_pool(): + other = threading.Thread(target=second) + other.start() + other.join(0.2) + self.assertEqual(seen, []) # still waiting + other.join(5) + self.assertEqual((seen, transient.destroy.call_count), ([1], 2))