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

feat(computes): Balance proposes migrations that even out the hosts

A Balance button on the Computes page opens computes/balance/: the memory
and vCPUs each host gives its running VMs, before and after, and the
proposed migrations. The proposal (computes/balance.py) takes, step by
step, the one move that most lowers the sum of the squared memory loads,
then of the squared vCPU loads, and stops when none does; each VM moves
once, and the VMs moved to a host fit in the memory its running and
paused VMs leave without counting those moved away, so the moves may
run in any order. Only running VMs count and
move; one that cannot move (no destination shares its disks) still
counts on its host and is listed with the reason. Unticking a VM keeps
it where it is and makes the proposal again.

Migrate runs the moves shown in one host.balance job. It shares the bulk
migration's loop (computes.jobs.Migrations): migrate jobs, the chosen
number at once, one bulk job at a time. Its migrations take only a
running VM (moveto running_only): one stopped since stays where it is.

A job another one started now shows only on its own page: a host's page
no longer lists a bulk migration's or a balance's migrations, and the
Computes page shows the bulk jobs.
This commit is contained in:
catborise 2026-11-16 07:33:39 +03:00
parent 027896c3d4
commit 4941a8a048
19 changed files with 1179 additions and 481 deletions

41
computes/balance.py Normal file
View file

@ -0,0 +1,41 @@
"""The Balance page's proposal: which running VMs to migrate so that the
hosts give their running VMs about the same memory, then the same vCPUs."""
def propose(loads, vms, room):
"""The moves [(VM, source, target)] and the loads after them.
loads: {host: (memory KiB, vCPUs)} that each host gives its running VMs,
all of them, also those that cannot move. vms: the VMs that may move,
(VM, host, memory KiB, vCPUs, the hosts it may go to). room: {host: its
memory KiB its running and paused VMs leave}; the VMs moved to a host
fit in it without those moved away, so the moves may run in any order.
Each step takes the one move that most lowers the sum of the squared
memory loads, then of the squared vCPU loads, and stops when none does:
each VM moves at most once."""
loads = {host: list(load) for host, load in loads.items()}
room = dict(room)
left, moves = sorted(vms), []
while True:
best = None
for vm in left:
pk, source, ram, vcpus, targets = vm
for target in sorted(targets):
if ram > room[target]:
continue
# the change of each sum of squares: (s - x)² + (t + x)² - s² - t²
change = tuple(2 * size * (loads[target][i] - loads[source][i] + size)
for i, size in enumerate((ram, vcpus)))
if change < (0, 0) and (best is None or change < best[0]):
best = (change, vm, target)
if best is None:
return moves, loads
_change, vm, target = best
pk, source, ram, vcpus, _targets = vm
for i, size in enumerate((ram, vcpus)):
loads[source][i] -= size
loads[target][i] += size
room[target] -= ram
left.remove(vm)
moves.append((pk, source, target))

View file

@ -14,12 +14,12 @@ from operations.jobs import Cancelled, Kind, Outcome, Plan, register
from operations.models import Claim, Operation
# where a host is: a bulk migration stops if either host's record points elsewhere since it was asked
# where a host is: a bulk migration stops if a 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 _where(hosts):
return [list(Compute.objects.filter(pk=pk).values_list(*WHERE).first() or []) for pk in sorted(hosts)]
def parallel_limit():
@ -29,43 +29,39 @@ def parallel_limit():
return min(max(1, slots // 2), slots - 1)
@register
class BulkMigrate(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."""
class Migrations(Kind):
"""Migrates VMs, each in a migrate job of its own, at most parallel at
once: one that fails stays where it is and the rest go on. One such job
at a time (it waits in a worker slot for its migrations). A kind gives
its moves, [(VM, source, target)], and the options of its migrations."""
name = "host.bulk_migrate"
label = gettext_noop("Bulk migrate")
cancellable = True
options = {}
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 moves(self, params):
raise NotImplementedError
def hosts(self, params):
return {host for _vm, source, target in self.moves(params) for host in (source, target)}
def validate(self, user, params):
if not user.is_superuser:
raise PermissionDenied
if not params["instances"]:
if not self.moves(params):
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.bulk_migrate_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
moves = self.moves(p)
names = dict(Instance.objects.filter(pk__in=[vm for vm, _source, _target in moves]).values_list("pk", "name"))
waiting = [move for move in moves if move[0] in names] # one 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"))
@ -87,28 +83,30 @@ class BulkMigrate(Kind):
# 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:
stop(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"]:
stop(gettext_noop("A host was changed or deleted: the VMs not yet started stay on the host"))
for pk in list(waiting):
stop(gettext_noop("The worker now runs one job at a time: the VMs not yet started stay where they are"))
if waiting and _where(self.hosts(p)) != op.intent["where"]:
stop(gettext_noop("A host was changed or deleted: the VMs not yet started stay where they are"))
for move 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}
waiting.remove(move)
vm, source, target = move
if not Instance.objects.filter(pk=vm, compute_id=source).exists():
continue # it left its host meanwhile
raw = {"instance": vm, "source": source, "target": target, "live": True, "autoconverge": True,
**self.options}
try:
child = jobs.submit("instance.migrate", op.user, raw, f"bulk-{op.pk.hex}-{pk}", parent=op)
child = jobs.submit("instance.migrate", op.user, raw, f"bulk-{op.pk.hex}-{vm}", parent=op)
except claims.Busy as busy:
if busy.blocker is not None and busy.blocker.state == Operation.UNCERTAIN:
# it holds its claims until someone resolves it
refused.append(f"{names[pk]}: {utils.busy_message(busy, op.user)}")
refused.append(f"{names[vm]}: {utils.busy_message(busy, op.user)}")
else:
waiting.append(pk) # another job holds the VM or a host: asked again on the next round
waiting.append(move) # 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)}")
refused.append(f"{names[vm]}: {utils.safe_text(err)}")
else:
started[pk] = child.pk
started[vm] = 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:
@ -122,8 +120,8 @@ class BulkMigrate(Kind):
return {}
def progress(self, op):
"""(the VMs whose migration ended, the chosen VMs)."""
return op.children.filter(state__in=Operation.TERMINAL).count(), len(op.params["instances"])
"""(the VMs whose migration ended, the VMs to migrate)."""
return op.children.filter(state__in=Operation.TERMINAL).count(), len(self.moves(op.params))
def cancel(self, op):
"""run sees the cancel and cancels the migrations that run."""
@ -134,7 +132,63 @@ class BulkMigrate(Kind):
return Outcome(Operation.FAILED, error=utils.say(gettext_noop(
"The bulk migration stopped: the migrations it started go on as their own jobs; the other VMs stay")))
@register
class BulkMigrate(Migrations):
"""Migrates the chosen VMs of a host to another, for the host's
maintenance: a running VM live, a shut-off one offline."""
name = "host.bulk_migrate"
label = gettext_noop("Bulk migrate")
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 moves(self, params):
return [(vm, params["compute"], params["target"]) for vm in params["instances"]]
def plan(self, user, params):
compute = Compute.objects.get(pk=params["compute"])
target = Compute.objects.get(pk=params["target"])
return Plan(claims={claims.bulk_migrate_key(): Claim.EXCLUSIVE}, resource=claims.compute_key(compute.pk),
label=f"{compute.name} -> {target.name}",
intent={"migrations": {}, "where": _where(self.hosts(params))})
def log_entry(self, op, state):
source, _sep, target = op.resource_label.partition(" -> ")
message = f"Bulk migrate to {target}"
return source, "", "", message if state == Operation.SUCCEEDED else f"{message} ({state})"
@register
class Balance(Migrations):
"""Migrates running VMs between hosts, as the Balance page proposed, to
even out what the hosts give their running VMs. Each migration takes
only a running VM: one stopped since is left where it is."""
name = "host.balance"
label = gettext_noop("Balance")
options = {"running_only": True}
def normalize(self, raw):
moves = {int(vm): (int(source), int(target)) for vm, source, target in raw["moves"]}
return {"parallel": int(raw["parallel"]),
"moves": [[vm, source, target] for vm, (source, target) in sorted(moves.items())]}
def moves(self, params):
return [tuple(move) for move in params["moves"]]
def validate(self, user, params):
super().validate(user, params)
if any(source == target for _vm, source, target in self.moves(params)):
raise util.OperationError(gettext_noop("A VM is already on its destination"))
def plan(self, user, params):
names = Compute.objects.filter(pk__in=self.hosts(params)).order_by("name").values_list("name", flat=True)
return Plan(claims={claims.bulk_migrate_key(): Claim.EXCLUSIVE}, resource=claims.bulk_migrate_key(),
label=", ".join(names), intent={"migrations": {}, "where": _where(self.hosts(params))})
def log_entry(self, op, state):
message = f"Balance {op.resource_label}: {len(op.params['moves'])} VMs"
return "", "", "", message if state == Operation.SUCCEEDED else f"{message} ({state})"

View file

@ -0,0 +1,126 @@
{% extends "base.html" %}
{% load i18n %}
{% load static %}
{% load operations %}
{% block title %}{% trans "Balance" %}{% endblock %}
{% block page_heading %}{% trans "Balance" %}{% endblock page_heading %}
{% block content %}
<p class="text-body-secondary">{% trans "Migrations of running VMs that even out the memory, then the vCPUs, the hosts give their running VMs. Each VM migrates live in a job of its own; one that fails or stops meanwhile stays where it is." %}</p>
{% if unreachable %}
<div class="alert alert-warning shadow-sm">{% trans "These hosts cannot be read and are left out:" %} {{ unreachable|join:", " }}</div>
{% endif %}
<div class="table-responsive">
<table class="table align-middle w-auto">
<thead>
<tr>
<th scope="col">{% trans "Host" %}</th>
<th scope="col" class="text-end">{% trans "Memory" %}</th>
<th scope="col" class="text-end">{% trans "VCPU" %}</th>
</tr>
</thead>
<tbody>
{% for host in hosts %}
<tr>
<td>{{ host.name }}</td>
<td class="text-end text-nowrap">{% widthratio host.before.0 1048576 1 %} GiB{% if host.after.0 != host.before.0 %} &rarr; <strong>{% widthratio host.after.0 1048576 1 %} GiB</strong>{% endif %}</td>
<td class="text-end text-nowrap">{{ host.before.1 }}{% if host.after.1 != host.before.1 %} &rarr; <strong>{{ host.after.1 }}</strong>{% endif %}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<p class="small text-body-secondary">{% trans "After: if every migration below succeeds." %}</p>
{# unticking a VM keeps it where it is and makes the proposal again #}
<form method="get" id="balance-form">
{% for instance in moves %}<input type="hidden" name="shown" value="{{ instance.pk }}">{% endfor %}
{% for instance in pinned %}<input type="hidden" name="shown" value="{{ instance.pk }}">{% endfor %}
{% if moves %}
<div class="table-responsive">
<table class="table table-hover align-middle">
<thead>
<tr>
<th scope="col"><input class="form-check-input" type="checkbox" id="balance-all"{% if not pinned %} checked{% endif %} aria-label="{% trans "Select all" %}" title="{% trans "Select all" %}"></th>
<th scope="col">{% trans "Name" %}</th>
<th scope="col">{% trans "VCPU" %}</th>
<th scope="col" class="text-end">{% trans "Memory" %}</th>
<th scope="col">{% trans "Host" %}</th>
<th scope="col">{% trans "Destination" %}</th>
</tr>
</thead>
<tbody>
{% for instance in moves %}
<tr>
<td><input class="form-check-input" type="checkbox" name="vm" value="{{ instance.pk }}" id="balance-{{ instance.pk }}" checked></td>
<td><label for="balance-{{ instance.pk }}">{{ instance.name }}</label></td>
<td>{{ instance.info.3 }}</td>
<td class="text-end">{% widthratio instance.info.2 1024 1 %} MiB</td>
<td>{{ instance.compute.name }}</td>
<td>{{ instance.target.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<div class="alert alert-info shadow-sm">{% trans "No migration would even out the hosts more." %}</div>
{% endif %}
{% if pinned %}
<h5>{% trans "Stay where they are" %}</h5>
<div class="table-responsive">
<table class="table align-middle">
<tbody>
{% for instance in pinned %}
<tr>
<td><input class="form-check-input" type="checkbox" name="vm" value="{{ instance.pk }}" id="balance-{{ instance.pk }}" aria-label="{% trans "Let it move" %}" title="{% trans "Let it move" %}"></td>
<td><label for="balance-{{ instance.pk }}">{{ instance.name }}</label></td>
<td>{{ instance.compute.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
</form>
{% if unmovable %}
<h5>{% trans "Cannot move" %}</h5>
<div class="table-responsive">
<table class="table align-middle">
<tbody>
{% for instance in unmovable %}
<tr>
<td>{{ instance.name }}</td>
<td>{{ instance.compute.name }}</td>
<td class="small text-danger">{% for refusal in instance.refusals %}{{ refusal }}{% if not forloop.last %}<br>{% endif %}{% endfor %}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
{% if moves %}
{% 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>
{% else %}
<form method="post">{% csrf_token %}{% submission_key %}
{% for instance in moves %}
<input type="hidden" name="instance" value="{{ instance.pk }}">
<input type="hidden" name="source" value="{{ instance.compute_id }}">
<input type="hidden" name="target" value="{{ instance.target.pk }}">
{% endfor %}
<div class="mb-3">
<label class="form-label" for="balance-parallel">{% trans "Migrations at once" %}</label>
<select name="parallel" id="balance-parallel" class="form-select w-auto">
{% for n in parallel %}<option value="{{ n }}"{% if forloop.last %} selected{% endif %}>{{ n }}</option>{% endfor %}
</select>
</div>
<button type="submit" class="btn btn-primary" data-confirm="{% trans "Migrate the VMs listed?" %}">{% trans "Migrate" %}</button>
</form>
{% endif %}
{% endif %}
{% endblock %}
{% block script %}
<script src="{% static 'js/balance.js' %}"></script>
{% endblock %}

View file

@ -2,11 +2,14 @@
{% load i18n %}
{% load static %}
{% load bootstrap_icons %}
{% load operations %}
{% block title %}{% trans "Computes" %}{% endblock %}
{% block content %}
<div id="job-panel" aria-live="polite"></div>
<div class="row">
<div class="col-lg-12">
{% include 'create_comp_block.html' %}
{% if computes|length > 1 %}<a href="{% url 'balance' %}" class="btn btn-outline-primary mt-1 ms-1 float-end">{% trans "Balance" %}</a>{% endif %}
{% include 'search_block.html' %}
<h3 class="mb-3">{% trans "Computes" %}</h3>
</div>
@ -118,5 +121,7 @@
{% endblock content %}
{% block script %}
<script src="{% static 'js/poll.js' %}"></script>
{% job_panel_script job_resource %}
<script src="{% static 'js/table_filter.js' %}"></script>
{% endblock script %}

View file

@ -0,0 +1,195 @@
"""Balance proposes migrations of running VMs that even out the memory, then
the vCPUs, the hosts give their running VMs, and runs the proposal shown in
one job of migrate jobs that take only a running VM."""
from unittest.mock import patch
import libvirt
from computes.balance import propose
from computes.jobs import Balance
from computes.models import Compute
from django.contrib.auth import get_user_model
from django.test import SimpleTestCase, TestCase
from django.urls import reverse
from instances.models import Instance
from lxml import etree, html
from operations import claims, jobs
from operations.models import Operation
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>"
ROOM = {"a": 100, "b": 100, "c": 100, "d": 100}
class ProposeTests(SimpleTestCase):
def test_moves_even_out_the_memory_also_past_a_plateau_of_the_spread(self):
# the largest minus the smallest load stays 10 after the first move; the sum of squares does not
loads = {"a": (10, 0), "b": (10, 0), "c": (0, 0), "d": (0, 0)}
vms = [(1, "a", 5, 0, {"b", "c", "d"}), (2, "a", 5, 0, {"b", "c", "d"}),
(3, "b", 5, 0, {"a", "c", "d"}), (4, "b", 5, 0, {"a", "c", "d"})]
moves, after = propose(loads, vms, ROOM)
self.assertEqual(len(moves), 2)
self.assertEqual(sorted(load[0] for load in after.values()), [5, 5, 5, 5])
def test_the_memory_comes_first_then_the_vcpus(self):
loads = {"a": (8, 2), "b": (0, 6)}
vms = [(1, "a", 4, 1, {"b"}), (2, "b", 0, 3, {"a"})]
moves, after = propose(loads, vms, ROOM)
self.assertEqual(moves, [(1, "a", "b"), (2, "b", "a")])
self.assertEqual(after, {"a": [4, 4], "b": [4, 4]})
def test_a_vm_moves_once_and_only_where_it_may_go(self):
loads = {"a": (12, 0), "b": (0, 0), "c": (0, 0)}
moves, _after = propose(loads, [(1, "a", 6, 0, {"b"}), (2, "a", 6, 0, {"b"})], ROOM)
self.assertEqual(moves, [(1, "a", "b")])
def test_no_move_fills_a_host_past_its_room(self):
loads = {"a": (60, 0), "b": (50, 0)}
self.assertEqual(propose(loads, [(1, "a", 30, 0, {"b"})], {"a": 40, "b": 20}), ([], {"a": [60, 0], "b": [50, 0]}))
def test_a_vm_moved_away_makes_no_room_for_one_moved_in(self):
# b's room stays 0 after vm 2 leaves it: vm 1 would fill b before vm 2 has left, if it ran first
loads = {"a": (100, 0), "b": (80, 0), "c": (0, 0)}
vms = [(1, "a", 30, 0, {"b"}), (2, "b", 40, 0, {"c"})]
self.assertEqual(propose(loads, vms, {"a": 0, "b": 0, "c": 100})[0], [(2, "b", "c")])
def test_even_hosts_need_no_move(self):
loads = {"a": (4, 2), "b": (4, 2)}
self.assertEqual(propose(loads, [(1, "a", 4, 2, {"b"})], ROOM)[0], [])
class BalancePageTests(TestCase):
def setUp(self):
self.conn = libvirt.open("test:///default")
self.addCleanup(self.conn.close)
self.compute = Compute.objects.create(name="ba", hostname="localhost", login="", password="", type=4)
self.other = Compute.objects.create(name="ba-other", hostname="198.51.100.41", login="", password="", type=4)
self.vms = {}
for name, running, disk in (("ba-1", True, ""), ("ba-2", True, ""), ("ba-off", False, ""),
("ba-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("ba-admin", "ba@example.com", "pw"))
def page(self, **query):
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
self.response = self.client.get(reverse("balance"), query)
return html.fromstring(self.response.content)
def moved(self, page):
return page.xpath("//form[@method='post']//input[@name='instance']/@value")
def test_a_running_vm_moves_to_the_emptier_host(self):
page = self.page()
self.assertEqual(self.moved(page), [str(self.vms["ba-1"].pk)])
self.assertEqual(page.xpath("//form[@method='post']//input[@name='target']/@value"), [str(self.other.pk)])
def test_a_vm_unticked_stays_and_another_moves_instead(self):
pk = str(self.vms["ba-1"].pk)
page = self.page(shown=pk)
self.assertEqual(self.moved(page), [str(self.vms["ba-2"].pk)])
(box,) = page.xpath("//input[@name='vm'][@value=$pk]", pk=pk)
self.assertIsNone(box.get("checked")) # listed to tick again
self.assertEqual(self.moved(self.page(shown=pk, vm=pk)), [pk])
def test_a_vm_with_a_disk_the_hosts_do_not_share_cannot_move_and_still_counts(self):
page = self.page()
self.assertIn("ba-local", page.xpath("//h5[.='Cannot move']/following-sibling::div[1]")[0].text_content())
host = next(host for host in self.response.context["hosts"] if host == self.compute)
self.assertEqual(host.before, [3 * 128 * 1024, 3]) # the shut-off VM is not counted
self.assertNotIn(str(self.vms["ba-off"].pk), page.xpath("//input[@name='vm' or @name='instance']/@value"))
def test_a_host_that_does_not_answer_is_left_out(self):
def read_hosts(computes):
for compute in computes:
compute.status, compute.shown_capacity = (False, None) if compute == self.other else (True, compute.capacity)
with patch("computes.views.read_hosts", side_effect=read_hosts):
page = self.page()
self.assertEqual(self.moved(page), [])
self.assertIn("ba-other", page.xpath("//div[contains(@class, 'alert-warning')]")[0].text_content())
def test_the_moves_shown_go_in_one_balance_job(self):
vm = self.vms["ba-1"].pk
response = self.client.post(reverse("balance"), {"instance": [vm], "source": [self.compute.pk],
"target": [self.other.pk], "parallel": "1",
"submission_key": "bal00000key"})
self.assertRedirects(response, reverse("computes"), fetch_redirect_response=False)
(op,) = Operation.objects.all()
self.assertEqual((op.kind, op.params, op.resource),
("host.balance", {"parallel": 1, "moves": [[vm, self.compute.pk, self.other.pk]]},
claims.bulk_migrate_key()))
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 BalanceJobTests(TestCase):
def setUp(self):
self.hosts = [Compute.objects.create(name=f"bj-{n}", hostname=f"192.0.2.5{n}", login="", password="", type=4)
for n in range(3)]
self.vms = [Instance.objects.create(compute=self.hosts[0], name=f"bj-{n}",
uuid=f"00000000-0000-4000-8000-00000000010{n}") for n in range(2)]
self.admin = get_user_model().objects.create_superuser("bj-admin", "bj@example.com", "pw")
patcher = patch("instances.jobs.MigrateInstance.validate") # the hosts are not asked
patcher.start()
self.addCleanup(patcher.stop)
self.moves = [[self.vms[0].pk, self.hosts[0].pk, self.hosts[1].pk],
[self.vms[1].pk, self.hosts[0].pk, self.hosts[2].pk]]
def test_each_vm_migrates_to_its_own_host_and_only_while_running(self):
params = {"parallel": 2, "moves": self.moves}
op = Operation.objects.create(kind="host.balance", user=self.admin, username=self.admin.username,
submission_key="key-bal00001", params=params,
intent=Balance().plan(self.admin, params).intent)
def ends(seconds):
Operation.objects.filter(kind="instance.migrate").update(state=Operation.SUCCEEDED)
with patch("computes.jobs.time.sleep", side_effect=ends):
self.assertEqual(Balance().run(op, Ctx(op)), {})
children = Operation.objects.filter(kind="instance.migrate", parent=op)
self.assertEqual(sorted([job.params["instance"], job.params["source"], job.params["target"]] for job in children),
self.moves)
self.assertTrue(all(job.params["running_only"] for job in children))
self.assertEqual(Balance().progress(op), (2, 2))
def test_the_computes_page_shows_the_balance_and_the_hosts_pages_not_its_migrations(self):
balance = jobs.submit("host.balance", self.admin, {"parallel": 1, "moves": self.moves[:1]}, "key-bal00002")
child = jobs.submit("instance.migrate", self.admin, {"instance": self.vms[0].pk, "target": self.hosts[1].pk},
"key-mig00010", parent=balance)
self.client.force_login(self.admin)
def shown(key):
return [job["id"] for job in self.client.get(reverse("operation-resource"), {"key": key}).json()["jobs"]]
self.assertEqual(shown(claims.bulk_migrate_key()), [str(balance.pk)])
self.assertEqual(shown(claims.compute_key(self.hosts[0].pk)), [])
self.assertEqual(shown(claims.instance_key(self.vms[0].uuid)), [str(child.pk)])
def test_a_move_to_the_vms_own_host_is_refused(self):
raw = {"parallel": 1, "moves": [[self.vms[0].pk, self.hosts[0].pk, self.hosts[0].pk]]}
with self.assertRaisesRegex(Exception, "already on its destination"):
jobs.submit("host.balance", self.admin, raw, "key-bal00003")

View file

@ -0,0 +1,45 @@
"""The Balance page's script (static/js/balance.js): a ticked or unticked VM
makes the proposal again; the header box ticks or unticks every VM listed
first."""
import json
import shutil
import subprocess
import unittest
from pathlib import Path
SCRIPT = Path(__file__).resolve().parents[2] / "static" / "js" / "balance.js"
RUN = """
const vm = require("vm");
const boxes = [{name: "moves", checked: true}, {name: "stays", checked: false}];
let handler, submitted = 0;
const form = {
addEventListener: (name, fn) => { handler = fn; },
querySelectorAll: () => boxes,
submit: () => { submitted += 1; },
};
vm.runInNewContext(SCRIPT, vm.createContext({document: {getElementById: () => form}}));
const seen = [];
for (const [id, checked] of STEPS) {
handler({target: {id, checked}});
seen.push(boxes.filter((b) => b.checked).map((b) => b.name));
}
console.log(JSON.stringify({seen, submitted}));
"""
@unittest.skipUnless(shutil.which("node"), "node is not installed")
class BalanceScriptTests(unittest.TestCase):
def run_script(self, steps):
"""{seen: the ticked VMs after each step, submitted: the form's reloads}."""
code = f"const SCRIPT = {json.dumps(SCRIPT.read_text())};" + RUN.replace("STEPS", json.dumps(steps))
out = subprocess.run(["node", "-e", code], capture_output=True, text=True, check=True, timeout=30)
return json.loads(out.stdout)
def test_a_vm_box_makes_the_proposal_again(self):
self.assertEqual(self.run_script([["balance-7", False]]), {"seen": [["moves"]], "submitted": 1})
def test_select_all_ticks_or_unticks_every_vm_and_makes_the_proposal_again(self):
result = self.run_script([["balance-all", True], ["balance-all", False]])
self.assertEqual(result, {"seen": [["moves", "stays"], []], "submitted": 2})

View file

@ -28,6 +28,7 @@ def superuser_only_patterns(patterns):
urlpatterns = [
path("", views.computes, name="computes"),
path("balance/", views.balance, name="balance"),
path(
"add_tcp_host/",
views.compute_create,

View file

@ -174,7 +174,8 @@ def computes(request):
totals["cpus"] += given["cpus"]
totals["assigned"] += given["assigned"]["all"]
totals["memory"] += given["memory"]
return render(request, "computes/list.html", {"computes": computes, "totals": totals})
return render(request, "computes/list.html",
{"computes": computes, "totals": totals, "job_resource": claims.bulk_migrate_key()})
@superuser_only
@ -229,6 +230,25 @@ def instances(request, compute_id):
)
def migration_refusal(request, instance, target, dests):
"""Why the VM cannot migrate to target in a bulk migration, or None: a
disk file the two hosts do not share takes a copy, chosen on the VM's
Migrate tab. dests: {compute pk: its connection}, filled as needed."""
from instances.jobs import migration_target
try:
migration_target(instance, target.pk)
if target.pk not in dests:
dests[target.pk] = 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 dests[target.pk].disk_plan(instance.proxy, xml)):
return _("A disk file is not on storage both hosts share: migrate it from its page")
except libvirtError as err:
return error_text(request, err)
return None
@superuser_only
def bulk_migrate(request, compute_id):
"""Migrates the chosen VMs of the host to another in one job, for the
@ -237,7 +257,6 @@ def bulk_migrate(request, compute_id):
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"))
@ -262,23 +281,78 @@ def bulk_migrate(request, compute_id):
utils.refresh_instance_database(compute)
instances = list(Instance.objects.filter(compute=compute).order_by("name"))
read_list_rows(instances, [compute])
dest = None
dests = {}
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)
instance.refusal = migration_refusal(request, instance, target, dests)
return render(request, "computes/bulk_migrate.html",
{"compute": compute, "targets": targets, "target": target, "instances": instances,
"parallel": range(1, parallel_limit() + 1)})
@superuser_only
def balance(request):
"""Proposes migrations of running VMs that even out the memory, then
the vCPUs, the hosts give their running VMs (computes.balance), and
runs the proposal shown in one job. A VM unticked stays where it is and
the proposal is made again without it: the form sends the VMs it showed
("shown") and the ticked ones ("vm")."""
from computes.balance import propose
from computes.jobs import parallel_limit
if request.method == "POST":
moves = zip(request.POST.getlist("instance"), request.POST.getlist("source"), request.POST.getlist("target"))
raw = {"parallel": request.POST.get("parallel", ""), "moves": list(moves)}
try:
op = jobs.submit("host.balance", 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("computes")
return redirect("balance")
computes = list(Compute.objects.order_by("name"))
read_hosts(computes) # side by side and bounded: a host that does not answer is left out
hosts = {compute.pk: compute for compute in computes if compute.status is True and compute.shown_capacity}
for compute in hosts.values():
utils.refresh_instance_database(compute)
instances = list(Instance.objects.filter(compute__in=hosts).order_by("name"))
read_list_rows(instances, hosts.values())
running = [instance for instance in instances if instance.info and instance.info[0] == 1]
pinned = set(request.GET.getlist("shown")) - set(request.GET.getlist("vm"))
loads = {pk: [0, 0] for pk in hosts}
movable, unmovable, dests = [], [], {}
for instance in running:
loads[instance.compute_id][0] += instance.info[2]
loads[instance.compute_id][1] += instance.info[3]
if str(instance.pk) in pinned:
continue
refusals = {target: migration_refusal(request, instance, target, dests)
for target in hosts.values() if target.pk != instance.compute_id}
targets = {target.pk for target, refusal in refusals.items() if refusal is None}
if targets:
movable.append((instance.pk, instance.compute_id, instance.info[2], instance.info[3], targets))
elif refusals:
instance.refusals = [f"{target.name}: {refusal}" for target, refusal in refusals.items()]
unmovable.append(instance)
# what the running and paused VMs, also those the panel does not list, leave of each host's memory
room = {pk: (compute.shown_capacity["memory"] - compute.shown_capacity["assigned"]["running"]) // 1024
for pk, compute in hosts.items()}
moves, after = propose(loads, movable, room)
for pk, compute in hosts.items():
compute.before, compute.after = loads[pk], after[pk]
by_pk = {instance.pk: instance for instance in running}
for vm, _source, target in moves:
by_pk[vm].target = hosts[target]
return render(request, "computes/balance.html", {
"hosts": hosts.values(), "unreachable": [compute for compute in computes if compute.pk not in hosts],
"moves": [by_pk[vm] for vm, _source, _target in moves],
"pinned": [instance for instance in running if str(instance.pk) in pinned],
"unmovable": unmovable, "parallel": range(1, parallel_limit() + 1)})
# the form of each kind of compute, by Compute.type
FORMS = {form.conn_type: form for form in (TcpComputeForm, SshComputeForm, TlsComputeForm, SocketComputeForm)}

View file

@ -1075,7 +1075,7 @@ class CreateInstance(Kind):
return _log(op, state, "create")
MIGRATE_OPTIONS = ("live", "unsafe", "offline", "autoconverge", "compress", "delete_source")
MIGRATE_OPTIONS = ("live", "unsafe", "offline", "autoconverge", "compress", "delete_source", "running_only")
def migration_target(instance, target_pk):

View file

@ -306,6 +306,7 @@ def migrate_instance(
autoconverge=False,
compress=False,
delete_source=False,
running_only=False,
disk_pools=None,
ip=None,
on_moved=None,
@ -345,6 +346,7 @@ def migrate_instance(
uri=new_compute.migration_uri,
pools=disk_pools,
on_copy=on_copy,
running_only=running_only,
)
except Exception as error:
log(f"migrate to {target}", error)

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

View file

@ -50,9 +50,10 @@ class OperationViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewset
raise ValidationError({"key": "required"})
if not visible(request.user, key):
raise Http404
# the jobs on the resource and the page's own; a job another one on this page started shows in that one
active = list(Operation.objects.filter(Q(claims__resource=key) | Q(resource=key), state__in=SHOWN_STATES)
.exclude(parent__resource=key).distinct())
# the page's own jobs and the jobs on its resource; a job another one started (a bulk migration's
# migration) shows on its own page only, the one that started it on its pages
active = list(Operation.objects.filter(Q(resource=key) | Q(claims__resource=key, parent__isnull=True),
state__in=SHOWN_STATES).distinct())
mine = [op for op in active if may_see(op, request.user)]
others = [summary(op, request.user) for op in active if not may_see(op, request.user)]
seen = last_seen()

View file

@ -42,8 +42,9 @@ def reconcile_key(compute_id):
def bulk_migrate_key():
"""The bulk migrations: one at a time. One waits in a worker slot for its
migrations; several could take every slot and leave none for them."""
"""The bulk migrations and balances: one at a time. One waits in a worker
slot for its migrations; several could take every slot and leave none
for them. The Computes page shows them."""
return "bulk_migrate"

12
static/js/balance.js Normal file
View file

@ -0,0 +1,12 @@
// The Balance page: unticking a VM keeps it where it is, ticking it again
// lets it move; either makes the proposal again. The header box ticks or
// unticks every VM listed.
const form = document.getElementById("balance-form");
form?.addEventListener("change", function (event) {
if (event.target.id === "balance-all") {
form.querySelectorAll("input[name=vm]").forEach(function (box) {
box.checked = event.target.checked;
});
}
form.submit();
});

View file

@ -149,15 +149,15 @@ class wvmInstances(wvmConnect):
return sorted(missing), sorted(unlike)
def moveto(self, conn, name, live, unsafe, offline, autoconverge=False, compress=False, uri=None,
pools=None, on_copy=None):
pools=None, on_copy=None, running_only=False):
"""Migrates the VM of conn (a wvmInstance on the source) here.
The mode follows the VM's state, read once: a running VM migrates
live or, without live, paused for the transfer (non-live); a paused
VM stays paused; a shut-off VM moves offline, also when the request
was made while it ran (live). An offline request for a running or
paused VM is refused. unsafe, autoconverge (live only) and
compress apply to a running VM. uri: the native migration URI
paused VM is refused, and with running_only a VM not running.
unsafe, autoconverge (live only) and compress apply to a running VM. uri: the native migration URI
(tcp://address) on the destination; None lets libvirt use the
destination's own hostname. pools: {target: pool here} of the disks
libvirt copies into those pools during the migration (disk_copies);
@ -166,6 +166,8 @@ class wvmInstances(wvmConnect):
libvirt makes them. Returns the mode and options used, for the log,
and each copied disk's path and the path of its copy here."""
state = conn.get_status()
if running_only and state != 1:
raise util.OperationError(gettext_noop("The VM is not running"))
if state == 5:
mode = ["offline"]
elif state in (1, 3):

View file

@ -30,6 +30,17 @@ class MigrationFlagsTestCase(unittest.TestCase):
destination().moveto(source, "vm", live=True, unsafe=False, offline=False)
self.assertIsNone(source.instance.calls[0][1])
def test_running_only_refuses_a_vm_not_running(self):
for state in (3, 5):
with self.subTest(state=state):
source = FakeSource(state)
with self.assertRaisesRegex(util.OperationError, "not running"):
destination().moveto(source, "vm", live=True, unsafe=False, offline=False, running_only=True)
self.assertEqual(source.instance.calls, [])
source = FakeSource(1)
destination().moveto(source, "vm", live=True, unsafe=False, offline=False, running_only=True)
self.assertEqual(len(source.instance.calls), 1)
class ShutOffMigrationTestCase(unittest.TestCase):
"""libvirt's offline migration fails on some builds (RHEL-156800); a