mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-03 17:36:05 +00:00
feat(computes): a host evacuates its chosen VMs to another host
The host's Instances page gets an Evacuate button. Its page lists the
host's VMs for a chosen destination: running ones ticked, shut-off ones
left to choose ("Also migrate the shut-off VMs"), and a VM with a disk
file the two hosts do not share refused with the reason, since it needs
a copy chosen on its own Migrate tab.
One "Evacuate host" job migrates them: a migrate job each (live with
auto converge; a shut-off VM offline), at most the chosen number at
once, so a VM that fails stays on the host and the rest go on. The
choice goes up to half the worker's slots, which a host's jobs may take,
less the evacuation's own. Cancelling it cancels the migrations that
run and starts no more. One evacuation runs at a time: it waits in a
worker slot, and several could leave none for their migrations. A VM
that left the host meanwhile is skipped (a migrate job takes the host it
is to leave from the evacuation and refuses another); a host whose record points
elsewhere since, or a worker lowered to one slot, stops it before the
next VM. A busy VM lets the others go first; one an uncertain job holds is
not waited for.
Migrations now hold the hosts' VM sets shared, so several migrate at
once; creates, clones, deletes and the VM list reconcile still wait for
them. A destination gone since the form was shown is refused, not
replaced by another. The uses of the NVRAM directory's pool take turns
(NVRAM_LOCK): two UEFI migrations at once would share a transient pool
that the first destroys under the second.
This commit is contained in:
parent
c9fef349d5
commit
d20254f757
18 changed files with 861 additions and 106 deletions
130
computes/jobs.py
Normal file
130
computes/jobs.py
Normal file
|
|
@ -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})"
|
||||
81
computes/templates/computes/evacuate.html
Normal file
81
computes/templates/computes/evacuate.html
Normal file
|
|
@ -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 %}
|
||||
<div class="row">
|
||||
<div class="col-lg-12">
|
||||
{% include "computes/host_nav.html" with section="instances" detail=True %}
|
||||
</div>
|
||||
</div>
|
||||
{% if not target %}
|
||||
<div class="alert alert-warning shadow-sm">{% trans "There is no other host to migrate to." %}</div>
|
||||
{% else %}
|
||||
<p class="text-body-secondary">{% 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." %}</p>
|
||||
<form method="get" class="row g-2 align-items-end mb-3">
|
||||
<div class="col-auto">
|
||||
<label class="form-label" for="evacuate-target">{% trans "Destination" %}</label>
|
||||
<select name="target" id="evacuate-target" class="form-select">
|
||||
{% for host in targets %}<option value="{{ host.pk }}"{% if host == target %} selected{% endif %}>{{ host.name }}</option>{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-auto"><button type="submit" class="btn btn-outline-secondary">{% trans "Check" %}</button></div>
|
||||
</form>
|
||||
{% if not parallel %}
|
||||
<div class="alert alert-warning shadow-sm">{% trans "The worker runs one job at a time: set Worker Concurrency to 2 or more on the Settings page." %}</div>
|
||||
{% elif not instances %}
|
||||
<div class="alert alert-info shadow-sm">{% trans "The host has no VMs." %}</div>
|
||||
{% else %}
|
||||
<form method="post">{% csrf_token %}{% submission_key %}
|
||||
<input type="hidden" name="target" value="{{ target.pk }}">
|
||||
<div class="form-check mb-2">
|
||||
<input class="form-check-input" type="checkbox" id="evacuate-shut-off">
|
||||
<label class="form-check-label" for="evacuate-shut-off">{% trans "Also migrate the shut-off VMs" %}</label>
|
||||
</div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover align-middle">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col"><span class="visually-hidden">{% trans "Migrate" %}</span></th>
|
||||
<th scope="col">{% trans "Name" %}</th>
|
||||
<th scope="col">{% trans "Status" %}</th>
|
||||
<th scope="col">{% trans "VCPU" %}</th>
|
||||
<th scope="col" class="text-end">{% trans "Memory" %}</th>
|
||||
<th scope="col"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for instance in instances %}
|
||||
<tr>
|
||||
<td>
|
||||
<input class="form-check-input" type="checkbox" name="instance" value="{{ instance.pk }}" id="evacuate-{{ instance.pk }}"
|
||||
{% if instance.info.0 == 5 %} data-shut-off{% elif not instance.refusal %} checked{% endif %}{% if instance.refusal %} disabled{% endif %}>
|
||||
</td>
|
||||
<td><label for="evacuate-{{ instance.pk }}">{{ instance.name }}</label></td>
|
||||
<td>{% include 'instance_state.html' %}</td>
|
||||
<td>{{ instance.info.3 }}</td>
|
||||
<td class="text-end">{% if instance.info %}{% widthratio instance.info.2 1024 1 %} MiB{% endif %}</td>
|
||||
<td class="small text-danger">{{ instance.refusal|default:"" }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="evacuate-parallel">{% trans "Migrations at once" %}</label>
|
||||
<select name="parallel" id="evacuate-parallel" class="form-select w-auto">
|
||||
{% for n in parallel %}<option value="{{ n }}"{% if forloop.last %} selected{% endif %}>{{ n }}</option>{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
{% blocktrans with source=compute.name dest=target.name asvar question %}Migrate the chosen VMs from {{ source }} to {{ dest }}?{% endblocktrans %}
|
||||
<button type="submit" class="btn btn-primary" data-confirm="{{ question }}">{% trans "Migrate" %}</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
{% block script %}
|
||||
<script src="{% static 'js/evacuate.js' %}"></script>
|
||||
{% endblock %}
|
||||
|
|
@ -12,6 +12,7 @@
|
|||
{% bs_icon 'plus-circle-fill' %}
|
||||
</a>
|
||||
{% if instances %}
|
||||
<a href="{% url 'evacuate' compute.id %}" class="btn btn-outline-primary mt-1 me-1 float-end">{% trans "Evacuate" %}</a>
|
||||
{% include 'search_block.html' %}
|
||||
{% endif %}
|
||||
{% endblock page_heading_extra %}
|
||||
|
|
|
|||
218
computes/tests/test_evacuate.py
Normal file
218
computes/tests/test_evacuate.py
Normal file
|
|
@ -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 = """<domain type='test'><name>{name}</name><memory unit='MiB'>128</memory><vcpu>1</vcpu>
|
||||
<os><type arch='i686'>hvm</type></os>{disk}</domain>"""
|
||||
LOCAL = "<devices><disk type='file' device='disk'><source file='/local/{name}.img'/><target dev='vda'/></disk></devices>"
|
||||
|
||||
|
||||
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")
|
||||
|
|
@ -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/<str:pool>/volumes/", get_volumes, name="volumes"),
|
||||
|
|
|
|||
|
|
@ -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)}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue