diff --git a/computes/balance.py b/computes/balance.py index 525ee1ef..35841e1f 100644 --- a/computes/balance.py +++ b/computes/balance.py @@ -1,5 +1,7 @@ -"""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.""" +"""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).""" def propose(loads, vms, room): @@ -58,3 +60,29 @@ def _steps(loads, vms, room, per_memory): room[target] -= ram left.remove(vm) moves.append((pk, source, target)) + + +def spread(loads, vms, room): + """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). + + 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.""" + loads = {host: list(load) for host, load in loads.items()} + room = dict(room) + placed = {} + for pk, ram, vcpus, holds, targets in sorted(vms, key=lambda vm: (-vm[1], -vm[2], vm[0])): + 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)) + loads[target][0] += ram + loads[target][1] += vcpus + if holds: + room[target] -= ram + placed[pk] = target + return placed, loads diff --git a/computes/jobs.py b/computes/jobs.py index 567c7a26..a467a9c6 100644 --- a/computes/jobs.py +++ b/computes/jobs.py @@ -135,29 +135,39 @@ class Migrations(Kind): @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.""" + """Migrates the chosen VMs of a host to other hosts, one or several, + 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"]})} + moves = {int(vm): int(target) for vm, target in raw["moves"]} + return {"compute": int(raw["compute"]), "parallel": int(raw["parallel"]), + "moves": [[vm, target] for vm, target in sorted(moves.items())]} def moves(self, params): - return [(vm, params["compute"], params["target"]) for vm in params["instances"]] + return [(vm, params["compute"], target) for vm, target in params["moves"]] + + def validate(self, user, params): + super().validate(user, params) + targets = {target for _vm, target in params["moves"]} + if params["compute"] in targets: + raise util.OperationError(gettext_noop("A VM is already on its destination")) + if Compute.objects.filter(pk__in=targets).count() != len(targets): + raise util.OperationError(gettext_noop("A destination host was deleted")) def plan(self, user, params): compute = Compute.objects.get(pk=params["compute"]) - target = Compute.objects.get(pk=params["target"]) + targets = {target for _vm, target in params["moves"]} + names = Compute.objects.filter(pk__in=targets).order_by("name").values_list("name", flat=True) return Plan(claims={claims.bulk_migrate_key(): Claim.EXCLUSIVE}, resource=claims.compute_key(compute.pk), - label=f"{compute.name} -> {target.name}", + label=f"{compute.name} -> {', '.join(names)}", 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}" + source, _sep, targets = op.resource_label.partition(" -> ") + message = f"Bulk migrate to {targets}" return source, "", "", message if state == Operation.SUCCEEDED else f"{message} ({state})" diff --git a/computes/reach.py b/computes/reach.py new file mode 100644 index 00000000..110df1ce --- /dev/null +++ b/computes/reach.py @@ -0,0 +1,61 @@ +"""Where the VMs of a bulk migration or a balance can migrate without a disk +copy, each host and each directory a pair of hosts may share asked once: +the pages ask it for every VM and destination.""" + +import os + +from django.utils.translation import gettext_lazy as _ +from libvirt import VIR_DOMAIN_XML_INACTIVE, libvirtError +from vrtManager.instance import file_disks, wvmInstances +from webvirtcloud.middleware import error_text + + +class Reach: + def __init__(self, request): + self.request = request + self.conns = {} # compute pk: its connection + self.hosts = set() # (source pk, target pk) a VM of the source was found able to go to + self.shared = {} # (source pk, target pk, directory): whether both hosts see it as one, or why not known + self.directories = {} # VM pk: the directories of its file disks, or the error that read them + + def _conn(self, compute): + if compute.pk not in self.conns: + self.conns[compute.pk] = wvmInstances(compute.hostname, compute.login, compute.password, compute.type) + return self.conns[compute.pk] + + def refusal(self, instance, target): + """Why the VM cannot migrate to target in a bulk migration, or None: + target is another host the panel reaches, and both hosts see every + disk file of the VM, now and at its next start (one they do not + takes a copy, chosen on the VM's Migrate tab).""" + from instances.jobs import migration_target + + pair = (instance.compute_id, target.pk) + if pair not in self.hosts: + # kept once it passed: a refusal may be the VM's own (gone meanwhile), not the hosts' + try: + migration_target(instance, target.pk) + self.hosts.add(pair) + except libvirtError as err: + return error_text(self.request, err) + if instance.pk not in self.directories: + try: + domain = instance.proxy.instance + xmls = (domain.XMLDesc(0), domain.XMLDesc(VIR_DOMAIN_XML_INACTIVE)) + self.directories[instance.pk] = {os.path.dirname(path) for xml in xmls for _disk, path in file_disks(xml)} + except libvirtError as err: + self.directories[instance.pk] = error_text(self.request, err) + if isinstance(self.directories[instance.pk], str): + return self.directories[instance.pk] + for directory in sorted(self.directories[instance.pk]): + key = (*pair, directory) + if key not in self.shared: + try: + self.shared[key] = self._conn(target).shares(self._conn(instance.compute), directory) + except libvirtError as err: # a host's pools could not be read: not that destination + self.shared[key] = error_text(self.request, err) + if isinstance(self.shared[key], str): + return self.shared[key] + if not self.shared[key]: + return _("A disk file is not on storage both hosts share: migrate it from its page") + return None diff --git a/computes/templates/computes/bulk_migrate.html b/computes/templates/computes/bulk_migrate.html index 3782e2da..27163bd9 100644 --- a/computes/templates/computes/bulk_migrate.html +++ b/computes/templates/computes/bulk_migrate.html @@ -12,30 +12,36 @@ {% include "computes/host_nav.html" with section="instances" detail=True %} -{% if not target %} +{% if not targets %}
{% 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." %}
-{# another destination reloads the list: which VMs can go depends on it #} - +{% if unreachable %} +