1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-03 17:36:05 +00:00

feat(computes): Balance and the spread count each host's share of its size

Balance evened out the memory, then the vCPUs, the hosts give their running
VMs, and the Bulk Migrate spread sent a VM to the host with the least
memory: a host twice as large got the same as a small one. Both now count
each host's load against its memory and CPUs: propose lowers the sum of
each host's load squared over its size, least when every host has the same
share; spread sends a VM to the host with the least share after it. With
hosts of one size the proposal is the same as before.

The Balance page shows each host's memory, its CPUs next to the vCPUs, and
the bars as the share of the host's own memory.
This commit is contained in:
catborise 2026-11-16 13:41:17 +03:00
parent ea20f12bc8
commit 070a4b99da
8 changed files with 179 additions and 133 deletions

View file

@ -1,10 +1,25 @@
"""Where VMs migrate: the Balance page's proposal (propose), which running
VMs to migrate so that the hosts give their running VMs about the same
memory, then the same vCPUs; and a bulk migration's spread over the other
hosts (spread)."""
share of their memory, then of their CPUs; and a bulk migration's spread
over the other hosts (spread). A host twice as large takes twice as much."""
from fractions import Fraction
def propose(loads, vms, room):
def _share(load, size):
"""The load (memory KiB, vCPUs) as shares of the host's size (memory KiB, CPUs), exact."""
return tuple(Fraction(part, max(whole, 1)) for part, whole in zip(load, size))
def _spread_of(load, size):
"""What a host adds to the sums propose lowers: each part of its load
squared over its size. The sums are least when every host has the same
share, as a sum of squared shares is not: it is least when a host twice
as large has half the share."""
return tuple(Fraction(part ** 2, max(whole, 1)) for part, whole in zip(load, size))
def propose(loads, vms, room, sizes):
"""The moves [(VM, source, target)] and the loads after them.
loads: {host: (memory KiB, vCPUs)} that each host gives its running VMs,
@ -12,26 +27,27 @@ def propose(loads, vms, room):
(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.
sizes: {host: (memory KiB, CPUs)}.
The proposal is made twice, step by step, each step taking the move
that most lowers the sum of the squared memory loads, then of the
squared vCPU loads: once the move that lowers it most, once the move
that most lowers the sum of the hosts' memory, then vCPUs, squared over
their size (_spread_of): once the move that lowers it most, once the move
that lowers it most for the memory it moves. The one that evens out the
hosts more is taken, and of two that do it as well, the one that moves
less memory: small VMs rather than a large one."""
sizes = {vm[0]: vm[2] for vm in vms}
memory = {vm[0]: vm[2] for vm in vms}
def rank(plan):
moves, after = plan
squares = tuple(sum(load[i] ** 2 for load in after.values()) for i in (0, 1))
return squares, sum(sizes[pk] for pk, _source, _target in moves)
spreads = [_spread_of(load, sizes[host]) for host, load in after.items()]
return tuple(sum(part[i] for part in spreads) for i in (0, 1)), sum(memory[pk] for pk, _source, _target in moves)
return min((_steps(loads, vms, room, per_memory) for per_memory in (False, True)), key=rank)
return min((_steps(loads, vms, room, sizes, per_memory) for per_memory in (False, True)), key=rank)
def _steps(loads, vms, room, per_memory):
def _steps(loads, vms, room, sizes, per_memory):
"""The moves and the loads after them, a move at a time while one lowers
the sums of squares; each VM moves at most once."""
the sums (_spread_of); each VM moves at most once."""
loads = {host: list(load) for host, load in loads.items()}
room = dict(room)
left, moves = sorted(vms), []
@ -42,9 +58,11 @@ def _steps(loads, vms, room, per_memory):
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)))
# the change of each sum: ((s - x)² - s²) / S + ((t + x)² - t²) / T
change = tuple(
Fraction(size * (size - 2 * loads[source][i]), max(sizes[source][i], 1))
+ Fraction(size * (size + 2 * loads[target][i]), max(sizes[target][i], 1))
for i, size in enumerate((ram, vcpus)))
if change >= (0, 0):
continue
gain = (change[0] / ram, change[1]) if per_memory and ram else change
@ -62,16 +80,16 @@ def _steps(loads, vms, room, per_memory):
moves.append((pk, source, target))
def spread(loads, vms, room):
def spread(loads, vms, room, sizes):
"""Where each VM of a host being emptied goes: {VM: target}, and the
loads after. loads and room as propose's, of the hosts the VMs may go
to. vms: (VM, memory KiB, vCPUs, whether it holds its memory (not shut
off), the hosts it may go to).
loads after. loads, room and sizes as propose's, of the hosts the VMs
may go to. vms: (VM, memory KiB, vCPUs, whether it holds its memory (not
shut off), the hosts it may go to).
The largest VMs first, each to the host it may go to that has the least
memory, then vCPUs, with it; one that holds its memory only where it
fits the room. A shut-off VM counts too: it takes its memory when it
starts. A VM no host takes is left out."""
share of its memory, then of its CPUs, with it; one that holds its
memory only where it fits the room. A shut-off VM counts too: it takes
its memory when it starts. A VM no host takes is left out."""
loads = {host: list(load) for host, load in loads.items()}
room = dict(room)
placed = {}
@ -79,7 +97,7 @@ def spread(loads, vms, room):
fits = sorted(target for target in targets if not holds or ram <= room[target])
if not fits:
continue
target = min(fits, key=lambda host: (loads[host][0] + ram, loads[host][1] + vcpus))
target = min(fits, key=lambda host: _share((loads[host][0] + ram, loads[host][1] + vcpus), sizes[host]))
loads[target][0] += ram
loads[target][1] += vcpus
if holds:

View file

@ -12,24 +12,25 @@
<li class="breadcrumb-item active fw-bold" aria-current="page">{% trans "Balance" %}</li>
</ol>
</nav>
<p class="text-body-secondary">{% trans "Migrations that share the memory, then the vCPUs, of running VMs evenly among the hosts." %}</p>
<p class="text-body-secondary">{% trans "Migrations that give each host about the same share of its memory, then of its CPUs, for its running VMs: a host twice as large takes twice as much." %}</p>
{% if unreachable %}
<div class="alert alert-warning shadow-sm">{% trans "These hosts cannot be read and are left out:" %} {{ unreachable|join:", " }}</div>
{% endif %}
{# each host's running VMs: memory now and, light to dark, after the migrations; all bars on one scale #}
{# each host's running VMs: the share of its memory now and, light to dark, after the migrations #}
<div class="row row-cols-1 row-cols-md-2 row-cols-xl-3 g-3 mb-4">
{% for host in hosts %}
<div class="col">
<div class="card h-100 shadow-sm"><div class="card-body">
<div class="fw-semibold mb-2">{{ host.name }}</div>
<div class="d-flex justify-content-between mb-2"><span class="fw-semibold">{{ host.name }}</span>
<span class="small text-body-secondary">{% widthratio host.size.0 1 1024 as bytes %}{{ bytes|filesizeformat }}</span></div>
{% for bar in host.bars %}{% if forloop.first or moves %}
{% if forloop.first %}{% with memory=host.before.0 vcpus=host.before.1 %}
<div class="d-flex justify-content-between small"><span class="text-body-secondary">{% if moves %}{% trans "Now" %}{% else %}{% trans "Running VMs" %}{% endif %}</span>
<span>{% widthratio memory 1 1024 as bytes %}{{ bytes|filesizeformat }}, {% blocktrans count counter=vcpus %}{{ counter }} vCPU{% plural %}{{ counter }} vCPUs{% endblocktrans %}</span></div>
<span>{% widthratio memory 1 1024 as bytes %}{{ bytes|filesizeformat }}, {% blocktrans count counter=vcpus %}{{ counter }} vCPU{% plural %}{{ counter }} vCPUs{% endblocktrans %} {% blocktrans count counter=host.size.1 %}on {{ counter }} CPU{% plural %}on {{ counter }} CPUs{% endblocktrans %}</span></div>
{% endwith %}{% else %}{% with memory=host.after.0 vcpus=host.after.1 %}
<div class="d-flex justify-content-between small mt-2"><span class="text-body-secondary">{% trans "After" %}</span>
<span class="fw-semibold">{% widthratio memory 1 1024 as bytes %}{{ bytes|filesizeformat }}, {% blocktrans count counter=vcpus %}{{ counter }} vCPU{% plural %}{{ counter }} vCPUs{% endblocktrans %}</span></div>
<span class="fw-semibold">{% widthratio memory 1 1024 as bytes %}{{ bytes|filesizeformat }}, {% blocktrans count counter=vcpus %}{{ counter }} vCPU{% plural %}{{ counter }} vCPUs{% endblocktrans %} {% blocktrans count counter=host.size.1 %}on {{ counter }} CPU{% plural %}on {{ counter }} CPUs{% endblocktrans %}</span></div>
{% endwith %}{% endif %}
<div class="progress" role="progressbar" style="--bs-progress-height: 0.6rem;" aria-label="{% if forloop.first %}{% trans "Memory now" %}{% else %}{% trans "Memory after" %}{% endif %}"
aria-valuenow="{{ bar|floatformat:0 }}" aria-valuemin="0" aria-valuemax="100">

View file

@ -1,6 +1,6 @@
"""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."""
"""Balance proposes migrations of running VMs that even out the share of
their memory, then of their CPUs, 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
@ -20,6 +20,7 @@ DOMAIN = """<domain type='test'><name>{name}</name><memory unit='MiB'>128</memor
<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}
SIZES = {host: (64, 16) for host in "abcd"} # hosts of one size
class ProposeTests(SimpleTestCase):
@ -28,64 +29,83 @@ class ProposeTests(SimpleTestCase):
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)
moves, after = propose(loads, vms, ROOM, SIZES)
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)
moves, after = propose(loads, vms, ROOM, SIZES)
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)
moves, _after = propose(loads, [(1, "a", 6, 0, {"b"}), (2, "a", 6, 0, {"b"})], ROOM, SIZES)
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]}))
self.assertEqual(propose(loads, [(1, "a", 30, 0, {"b"})], {"a": 40, "b": 20}, SIZES), ([], {"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")])
self.assertEqual(propose(loads, vms, {"a": 0, "b": 0, "c": 100}, SIZES)[0], [(2, "b", "c")])
def test_small_vms_move_rather_than_a_large_one_for_the_same_balance(self):
# a: a large VM (16) and two small ones (1, 2); b: one small VM (1). Moving the large VM to b and
# the small one back ends as even as moving the two small ones, which moves far less memory
loads = {"a": (19, 7), "b": (1, 4)}
vms = [(1, "a", 16, 2, {"b"}), (2, "a", 1, 1, {"b"}), (3, "a", 2, 4, {"b"}), (4, "b", 1, 4, {"a"})]
moves, after = propose(loads, vms, ROOM)
moves, after = propose(loads, vms, ROOM, SIZES)
self.assertEqual(moves, [(2, "a", "b"), (3, "a", "b")])
self.assertEqual(after, {"a": [16, 2], "b": [4, 9]})
def test_a_large_vm_moves_when_only_it_evens_out_the_hosts(self):
loads = {"a": (20, 0), "b": (0, 0)}
vms = [(1, "a", 10, 0, {"b"}), (2, "a", 1, 0, {"b"})]
self.assertEqual(propose(loads, vms, {"a": 100, "b": 100})[0], [(1, "a", "b")])
self.assertEqual(propose(loads, vms, {"a": 100, "b": 100}, SIZES)[0], [(1, "a", "b")])
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], [])
self.assertEqual(propose(loads, [(1, "a", 4, 2, {"b"})], ROOM, SIZES)[0], [])
def test_a_host_twice_as_large_takes_twice_the_memory(self):
loads = {"a": (12, 0), "b": (0, 0)}
vms = [(n, "a", 2, 0, {"b"}) for n in range(1, 7)]
moves, after = propose(loads, vms, ROOM, {"a": (32, 8), "b": (64, 8)})
self.assertEqual(len(moves), 4)
self.assertEqual(after, {"a": [4, 0], "b": [8, 0]})
def test_the_vcpus_count_against_the_cpus_of_each_host(self):
loads = {"a": (0, 6), "b": (0, 0)}
_moves, after = propose(loads, [(n, "a", 0, 1, {"b"}) for n in range(1, 7)], ROOM, {"a": (64, 4), "b": (64, 8)})
self.assertEqual(after, {"a": [0, 2], "b": [0, 4]})
class SpreadTests(SimpleTestCase):
def test_the_largest_vm_goes_first_each_to_the_emptiest_host(self):
loads = {"b": (4, 0), "c": (0, 0)}
vms = [(1, 2, 1, True, {"b", "c"}), (2, 6, 1, True, {"b", "c"}), (3, 3, 1, False, {"b", "c"})]
placed, after = spread(loads, vms, ROOM)
placed, after = spread(loads, vms, ROOM, SIZES)
self.assertEqual(placed, {2: "c", 3: "b", 1: "c"})
self.assertEqual(after, {"b": [7, 1], "c": [8, 2]})
def test_a_running_vm_goes_only_where_it_fits_and_a_shut_off_one_anywhere(self):
loads = {"b": (0, 0)}
placed, _after = spread(loads, [(1, 8, 1, True, {"b"}), (2, 8, 1, False, {"b"})], {"b": 4})
placed, _after = spread(loads, [(1, 8, 1, True, {"b"}), (2, 8, 1, False, {"b"})], {"b": 4}, SIZES)
self.assertEqual(placed, {2: "b"})
def test_the_larger_host_takes_more(self):
loads = {"b": (0, 0), "c": (0, 0)}
vms = [(n, 2, 0, False, {"b", "c"}) for n in range(1, 7)]
_placed, after = spread(loads, vms, ROOM, {"b": (32, 8), "c": (64, 8)})
self.assertEqual(after, {"b": [4, 0], "c": [8, 0]})
class BalancePageTests(TestCase):
def setUp(self):

View file

@ -233,8 +233,9 @@ def read_fleet():
"""The computes; those the panel reads now, {pk: compute}, read side by
side and bounded (one that does not answer is left out); their VMs, with
their info; what each gives its running VMs, {pk: [memory KiB, vCPUs]};
and the memory KiB its running and paused VMs, also those the panel does
not list, leave of its memory, {pk: KiB}."""
the memory KiB its running and paused VMs, also those the panel does not
list, leave of its memory, {pk: KiB}; and its size, {pk: (memory KiB,
CPUs)}."""
computes = list(Compute.objects.order_by("name"))
read_hosts(computes)
hosts = {compute.pk: compute for compute in computes if compute.status is True and compute.shown_capacity}
@ -249,7 +250,8 @@ def read_fleet():
loads[instance.compute_id][1] += instance.info[3]
room = {pk: (compute.shown_capacity["memory"] - compute.shown_capacity["assigned"]["running"]) // 1024
for pk, compute in hosts.items()}
return computes, hosts, instances, loads, room
sizes = {pk: (compute.shown_capacity["memory"] // 1024, compute.shown_capacity["cpus"]) for pk, compute in hosts.items()}
return computes, hosts, instances, loads, room, sizes
@superuser_only
@ -302,7 +304,7 @@ def bulk_migrate(request, compute_id):
"parallel": range(1, parallel_limit() + 1)})
# the other hosts' loads: the VMs of this one are read above, also when its capacity cannot be
_computes, hosts, _instances, loads, room = read_fleet()
_computes, hosts, _instances, loads, room, sizes = read_fleet()
others = {pk: host for pk, host in hosts.items() if pk != compute.pk}
shown, ticked = request.GET.getlist("shown"), request.GET.getlist("vm")
vms = []
@ -317,7 +319,7 @@ def bulk_migrate(request, compute_id):
# at first the VMs that are not shut off, as with one destination; then the ticked ones
if instance.info and (str(instance.pk) in ticked if shown else not shut_off):
vms.append((instance.pk, instance.info[2], instance.info[3], not shut_off, can_go))
placed, _after = spread({pk: loads[pk] for pk in others}, vms, {pk: room[pk] for pk in others})
placed, _after = spread({pk: loads[pk] for pk in others}, vms, {pk: room[pk] for pk in others}, sizes)
for instance in instances:
instance.target = others.get(placed.get(instance.pk))
if instance.target is None and any(vm[0] == instance.pk for vm in vms):
@ -333,8 +335,9 @@ def bulk_migrate(request, compute_id):
@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
"""Proposes migrations of running VMs that even out the share of their
memory, then of their CPUs, 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")."""
@ -356,7 +359,7 @@ def balance(request):
return redirect("computes")
return redirect("balance")
computes, hosts, instances, loads, room = read_fleet()
computes, hosts, instances, loads, room, sizes = read_fleet()
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"))
movable, unmovable, reach = [], [], Reach(request)
@ -371,12 +374,11 @@ def balance(request):
elif refusals:
instance.refusals = [f"{target.name}: {refusal}" for target, refusal in refusals.items()]
unmovable.append(instance)
moves, after = propose(loads, movable, room)
# the bars of each host's memory before and after, on the scale of the largest
scale = max([load[0] for load in (*loads.values(), *after.values())] + [1])
moves, after = propose(loads, movable, room, sizes)
# the bars: the share of each host's memory before and after
for pk, compute in hosts.items():
compute.before, compute.after = loads[pk], after[pk]
compute.bars = [load[0] * 100 / scale for load in (loads[pk], after[pk])]
compute.before, compute.after, compute.size = loads[pk], after[pk], sizes[pk]
compute.bars = [min(load[0] * 100 / max(sizes[pk][0], 1), 100) for load in (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]