feat: get_clusters() and create_vm_from_cloud_init(node=)
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 13s
driver / types (pull_request) Failing after 1m2s
driver / test (3.12) (pull_request) Failing after 57s
driver / test (3.13) (pull_request) Failing after 52s
driver / lowest (pull_request) Failing after 25s
driver / build (pull_request) Successful in 24s
driver / security (pull_request) Successful in 57s
CI / driver (pull_request) Failing after 2m21s
driver / publish (pull_request) Skipped
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 13s
driver / types (pull_request) Failing after 1m2s
driver / test (3.12) (pull_request) Failing after 57s
driver / test (3.13) (pull_request) Failing after 52s
driver / lowest (pull_request) Failing after 25s
driver / build (pull_request) Successful in 24s
driver / security (pull_request) Successful in 57s
CI / driver (pull_request) Failing after 2m21s
driver / publish (pull_request) Skipped
vCenter reports each cluster compute resource, and each standalone host it runs as a cluster of one, identified by "<instanceUuid>/<moref>"; an ESXi host reports itself. Nodes carry state, maintenance, CPU and memory; datastores and port groups carry the hosts that see them. create_vm_from_cloud_init(node=) places the VM on that host and refuses one that does not exist or cannot take it, before anything is created. Placement now runs before the image download, so a refused host fails at once instead of after the download. Refs NetOrk/netork#484, NetOrk/netork#1822
This commit is contained in:
1 parent
1bf8de4c23
commit
52c802ed41
14 files changed
+812
-28
No files matched your search
@@ -8,6 +8,7 @@ from typing import Any, ClassVar
|
||||
from napalm.base.exceptions import ConnectionException
|
||||
from napalm_device_types import HypervisorDriver, LicenseMixin
|
||||
from napalm_device_types.models import (
|
||||
ClusterDict,
|
||||
HypervisorHostDict,
|
||||
LicenseDict,
|
||||
SnapshotDict,
|
||||
@@ -18,6 +19,7 @@ from napalm_device_types.models import (
|
||||
|
||||
from napalm_vmware import _session, paths
|
||||
from napalm_vmware._inventory import Inventory
|
||||
from napalm_vmware.parse.clusters import ClusterSources, host_cluster, manager_clusters
|
||||
from napalm_vmware.parse.environment import environment
|
||||
from napalm_vmware.parse.hosts import hypervisor_hosts
|
||||
from napalm_vmware.parse.licenses import license_list
|
||||
@@ -160,5 +162,23 @@ class VmwareBaseDriver(LicenseMixin, HypervisorDriver):
|
||||
def get_hypervisor_hosts(self) -> list[HypervisorHostDict]:
|
||||
return hypervisor_hosts(self._hosts(), standalone=self.STANDALONE)
|
||||
|
||||
def get_clusters(self) -> list[ClusterDict]:
|
||||
collect = self._inventory.collect
|
||||
src = ClusterSources(
|
||||
hosts=self._hosts(),
|
||||
datastores=collect("Datastore", paths.DATASTORE),
|
||||
networks=collect("Network", paths.NETWORK),
|
||||
dv_portgroups=collect("DistributedVirtualPortgroup", paths.DV_PORTGROUP),
|
||||
)
|
||||
if self.STANDALONE:
|
||||
return [host_cluster(src)]
|
||||
clusters = collect("ClusterComputeResource", paths.CLUSTER)
|
||||
return manager_clusters(
|
||||
collect("ComputeResource", paths.CLUSTER),
|
||||
{c["_moref"] for c in clusters},
|
||||
src,
|
||||
instance_uuid=self._inventory.about().get("instanceUuid"),
|
||||
)
|
||||
|
||||
def get_licenses(self) -> list[LicenseDict]:
|
||||
return license_list(self._inventory.licenses())
|
||||
@@ -0,0 +1,225 @@
|
||||
"""``get_clusters``: clusters, their hosts, and the datastores and port groups they see.
|
||||
|
||||
A vCenter runs two kinds of compute resource: a ``ClusterComputeResource``,
|
||||
and a plain ``ComputeResource`` for a host added to a datacenter directly.
|
||||
Each is one cluster here; the plain one has no name, since the contract keeps
|
||||
names for clusters an operator made. An ESXi host is a cluster of one.
|
||||
|
||||
A cluster's datastores and port groups are the ones its hosts list, each with
|
||||
the hosts that list it. vSphere has no cluster quorum and no cpuinfo flags, so
|
||||
``quorate`` and ``cpu_flags`` are always None.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from napalm_device_types.models import (
|
||||
ClusterDict,
|
||||
ClusterNetworkDict,
|
||||
ClusterNodeDict,
|
||||
ClusterStorageDict,
|
||||
)
|
||||
|
||||
from napalm_vmware.parse.networks import dv_vlan, is_uplink
|
||||
|
||||
Row = dict[str, Any]
|
||||
|
||||
_MB = 1024 * 1024
|
||||
_STATUS = {"connected": "online", "disconnected": "offline", "notResponding": "offline"}
|
||||
#: What a datastore can hold for netOrk: VM disks and the cloud-init seed ISO.
|
||||
_CONTENT = ["images", "iso"]
|
||||
#: A standard port group's "VLAN" 4095 trunks every VLAN to the guest.
|
||||
_TRUNK = 4095
|
||||
|
||||
|
||||
@dataclass
|
||||
class ClusterSources:
|
||||
"""The inventory rows every cluster draws from."""
|
||||
|
||||
hosts: list[Row]
|
||||
datastores: list[Row]
|
||||
networks: list[Row] # ``Network`` objects, distributed port groups included
|
||||
dv_portgroups: list[Row]
|
||||
|
||||
|
||||
def manager_clusters(
|
||||
compute_resources: list[Row],
|
||||
cluster_refs: set[str],
|
||||
src: ClusterSources,
|
||||
*,
|
||||
instance_uuid: str | None,
|
||||
) -> list[ClusterDict]:
|
||||
"""vCenter: one cluster per compute resource; ``cluster_refs`` are the real clusters.
|
||||
|
||||
The id is ``<instanceUuid>/<MoRef>``: a MoRef alone repeats across vCenters.
|
||||
"""
|
||||
hosts = {h["_moref"]: h for h in src.hosts}
|
||||
clusters = []
|
||||
for cr in compute_resources:
|
||||
members = [hosts[ref] for ref in cr.get("host") or [] if ref in hosts]
|
||||
name = cr.get("name") if cr["_moref"] in cluster_refs else None
|
||||
ident = f"{instance_uuid}/{cr['_moref']}" if instance_uuid else cr["_moref"]
|
||||
clusters.append(_cluster(ident, name, members, src, local=False))
|
||||
return sorted(clusters, key=lambda c: (c["name"] is None, c["name"] or _first_node(c)))
|
||||
|
||||
|
||||
def host_cluster(src: ClusterSources) -> ClusterDict:
|
||||
"""ESXi: the host itself, a cluster of one with no name."""
|
||||
if not src.hosts:
|
||||
raise RuntimeError("The inventory shows no host")
|
||||
host = src.hosts[0]
|
||||
ident = (host.get("hardware.systemInfo") or {}).get("uuid")
|
||||
return _cluster(ident, None, [host], src, local=True)
|
||||
|
||||
|
||||
def _first_node(cluster: ClusterDict) -> str:
|
||||
return cluster["nodes"][0]["name"] if cluster["nodes"] else ""
|
||||
|
||||
|
||||
def _cluster(
|
||||
ident: str | None, name: str | None, hosts: list[Row], src: ClusterSources, *, local: bool
|
||||
) -> ClusterDict:
|
||||
hosts = sorted(hosts, key=_host_name)
|
||||
return {
|
||||
"id": ident,
|
||||
"name": name,
|
||||
"quorate": None,
|
||||
"nodes": [_node(h, local) for h in hosts],
|
||||
"storages": _storages(hosts, src.datastores),
|
||||
"networks": _networks(hosts, src),
|
||||
}
|
||||
|
||||
|
||||
def _host_name(host: Row) -> str:
|
||||
return str(host.get("name") or host["_moref"])
|
||||
|
||||
|
||||
# -- nodes ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def _node(host: Row, local: bool) -> ClusterNodeDict:
|
||||
status = _STATUS.get(host.get("runtime.connectionState") or "", "unknown")
|
||||
hardware: Row = {}
|
||||
stats: Row = {}
|
||||
# A host vCenter cannot reach reports what it last knew, if anything.
|
||||
if status != "offline":
|
||||
hardware = host.get("summary.hardware") or {}
|
||||
stats = host.get("summary.quickStats") or {}
|
||||
memory_used = stats.get("overallMemoryUsage")
|
||||
return {
|
||||
"name": _host_name(host),
|
||||
"status": status,
|
||||
"local": local,
|
||||
"maintenance": host.get("runtime.inMaintenanceMode"),
|
||||
"cpu_threads": hardware.get("numCpuThreads"),
|
||||
"cpu_cores": hardware.get("numCpuCores"),
|
||||
"cpu_model": hardware.get("cpuModel"),
|
||||
"cpu_flags": None,
|
||||
"cpu_usage": _cpu_usage(hardware, stats),
|
||||
"memory_total": hardware.get("memorySize"),
|
||||
"memory_used": memory_used * _MB if memory_used is not None else None,
|
||||
}
|
||||
|
||||
|
||||
def _cpu_usage(hardware: Row, stats: Row) -> float | None:
|
||||
"""Used MHz over the host's total MHz (``cpuMhz`` per core)."""
|
||||
used = stats.get("overallCpuUsage")
|
||||
total = (hardware.get("cpuMhz") or 0) * (hardware.get("numCpuCores") or 0)
|
||||
if used is None or not total:
|
||||
return None
|
||||
return min(1.0, float(used) / total)
|
||||
|
||||
|
||||
# -- storages ------------------------------------------------------------------
|
||||
|
||||
|
||||
def _mounts(hosts: list[Row], key: str) -> dict[str, list[str]]:
|
||||
"""MoRef -> names of the hosts whose ``key`` list holds it, in host order."""
|
||||
seen: dict[str, list[str]] = {}
|
||||
for host in hosts:
|
||||
for ref in host.get(key) or []:
|
||||
seen.setdefault(ref, []).append(_host_name(host))
|
||||
return seen
|
||||
|
||||
|
||||
def _storages(hosts: list[Row], datastores: list[Row]) -> list[ClusterStorageDict]:
|
||||
mounts = _mounts(hosts, "datastore")
|
||||
result: list[ClusterStorageDict] = []
|
||||
for ds in datastores:
|
||||
summary = ds.get("summary") or {}
|
||||
if ds["_moref"] not in mounts or not summary.get("accessible"):
|
||||
continue
|
||||
total = summary.get("capacity")
|
||||
free = summary.get("freeSpace")
|
||||
result.append(
|
||||
{
|
||||
"name": ds.get("name") or summary.get("name") or ds["_moref"],
|
||||
"type": str(summary.get("type", "")).lower(),
|
||||
"shared": bool(summary.get("multipleHostAccess")),
|
||||
"content": list(_CONTENT),
|
||||
"nodes": mounts[ds["_moref"]],
|
||||
"total": total,
|
||||
"used": total - free if total is not None and free is not None else None,
|
||||
}
|
||||
)
|
||||
return sorted(result, key=lambda s: s["name"])
|
||||
|
||||
|
||||
# -- networks ------------------------------------------------------------------
|
||||
|
||||
|
||||
def _networks(hosts: list[Row], src: ClusterSources) -> list[ClusterNetworkDict]:
|
||||
return [
|
||||
{
|
||||
"name": name,
|
||||
"kind": "portgroup",
|
||||
# The port group fixes the VLAN; a NIC cannot add a tag of its own.
|
||||
"vlan_aware": False,
|
||||
"fixed_vlan_tag": _fixed_tag(vlans),
|
||||
"nodes": nodes,
|
||||
}
|
||||
for name, (nodes, vlans) in sorted(_seen_networks(hosts, src).items())
|
||||
]
|
||||
|
||||
|
||||
def _seen_networks(
|
||||
hosts: list[Row], src: ClusterSources
|
||||
) -> dict[str, tuple[list[str], set[int | None]]]:
|
||||
"""Port group name -> (the hosts that have it, the VLAN it carries on each)."""
|
||||
names = {n["_moref"]: n.get("name") or n["_moref"] for n in src.networks}
|
||||
dv = {pg["_moref"]: pg for pg in src.dv_portgroups}
|
||||
seen: dict[str, tuple[list[str], set[int | None]]] = {}
|
||||
for host in hosts:
|
||||
for ref in _vm_networks(host, dv):
|
||||
name = names.get(ref, ref)
|
||||
nodes, vlans = seen.setdefault(name, ([], set()))
|
||||
if _host_name(host) not in nodes:
|
||||
nodes.append(_host_name(host))
|
||||
vlans.add(_vlan(ref, name, host, dv))
|
||||
return seen
|
||||
|
||||
|
||||
def _vm_networks(host: Row, dv: dict[str, Row]) -> list[str]:
|
||||
"""The host's networks a VM can use: a vDS's uplink port group carries none."""
|
||||
return [ref for ref in host.get("network") or [] if not (ref in dv and is_uplink(dv[ref]))]
|
||||
|
||||
|
||||
def _vlan(ref: str, name: str, host: Row, dv: dict[str, Row]) -> int | None:
|
||||
"""The VLAN ``ref`` carries on ``host``; None where it cannot be read."""
|
||||
if ref in dv:
|
||||
return dv_vlan(dv[ref].get("config.defaultPortConfig"))
|
||||
for pg in host.get("config.network.portgroup") or []:
|
||||
spec = pg.get("spec") or {}
|
||||
if spec.get("name") == name:
|
||||
return int(spec.get("vlanId", 0))
|
||||
return None
|
||||
|
||||
|
||||
def _fixed_tag(vlans: set[int | None]) -> int | None:
|
||||
"""One VLAN on every host, and a single tag at that; else None."""
|
||||
if len(vlans) != 1:
|
||||
return None
|
||||
(vlan,) = vlans
|
||||
return vlan if vlan not in (None, 0, _TRUNK) else None
|
||||
@@ -76,7 +76,7 @@ def _network(name: str, kind: str, bridge: str, vlan: int) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _is_uplink(pg: dict[str, Any]) -> bool:
|
||||
def is_uplink(pg: dict[str, Any]) -> bool:
|
||||
if "config.uplink" in pg:
|
||||
return bool(pg["config.uplink"])
|
||||
return bool(_UPLINK_NAME.search(pg.get("name", "")))
|
||||
@@ -97,7 +97,7 @@ def virtual_networks(
|
||||
)
|
||||
switch_names = {s["_moref"]: s.get("name", s["_moref"]) for s in dv_switches}
|
||||
for pg in dv_portgroups:
|
||||
if _is_uplink(pg):
|
||||
if is_uplink(pg):
|
||||
continue
|
||||
dvs = pg.get("config.distributedVirtualSwitch", "")
|
||||
vlan = dv_vlan(pg.get("config.defaultPortConfig"))
|
||||
|
||||
@@ -78,6 +78,11 @@ COMPUTE_RESOURCE = ("parent", "resourcePool")
|
||||
FOLDER = ("parent",)
|
||||
DATACENTER = ("name", "vmFolder")
|
||||
|
||||
# get_clusters: every compute resource and its hosts. Read once as
|
||||
# ComputeResource (clusters included, a subtype) and once as
|
||||
# ClusterComputeResource to tell the two apart.
|
||||
CLUSTER = ("name", "host")
|
||||
|
||||
#: Managed object type name -> paths, in the order harvest.py dumps them.
|
||||
ALL = {
|
||||
"HostSystem": HOST,
|
||||
@@ -86,7 +91,8 @@ ALL = {
|
||||
"DistributedVirtualPortgroup": DV_PORTGROUP,
|
||||
"DistributedVirtualSwitch": DV_SWITCH,
|
||||
"Network": NETWORK,
|
||||
"ComputeResource": COMPUTE_RESOURCE,
|
||||
"ComputeResource": tuple(dict.fromkeys(COMPUTE_RESOURCE + CLUSTER)),
|
||||
"ClusterComputeResource": CLUSTER,
|
||||
"Folder": FOLDER,
|
||||
"Datacenter": DATACENTER,
|
||||
}
|
||||
@@ -2,9 +2,10 @@
|
||||
|
||||
A host qualifies when it is connected, not in maintenance mode, and sees both
|
||||
a usable datastore and every requested network. Among those, the pair with
|
||||
the most free space wins -- or the named datastore, when one is given. The
|
||||
resource pool comes from the host's compute resource and the VM folder from
|
||||
the datacenter above it; a standalone ESXi host has the same shape
|
||||
the most free space wins -- or the named datastore, when one is given; a
|
||||
named host narrows the choice to that host and is refused if it does not
|
||||
qualify. The resource pool comes from the host's compute resource and the VM
|
||||
folder from the datacenter above it; a standalone ESXi host has the same shape
|
||||
(``ha-compute-res`` under ``ha-datacenter``), so one path serves both.
|
||||
"""
|
||||
|
||||
@@ -16,6 +17,10 @@ from typing import Any
|
||||
Row = dict[str, Any]
|
||||
|
||||
|
||||
class NodeRefused(ValueError):
|
||||
"""The host named for a new VM does not exist or cannot take it."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class Inventory:
|
||||
hosts: list[Row]
|
||||
@@ -71,15 +76,35 @@ def _datacenter(inv: Inventory, compute_resource: str) -> Row:
|
||||
return datacenters[node]
|
||||
|
||||
|
||||
def choose_placement(inv: Inventory, storage: str | None, networks: list[str]) -> Placement:
|
||||
usable = _usable_datastores(inv, storage)
|
||||
names = {n["_moref"]: n.get("name", "") for n in inv.networks}
|
||||
def _refusal(host: Row) -> str | None:
|
||||
"""Why ``host`` cannot take a new VM, or None if it can."""
|
||||
if host.get("runtime.connectionState") != "connected":
|
||||
return "is not connected"
|
||||
if host.get("runtime.inMaintenanceMode"):
|
||||
return "is in maintenance mode"
|
||||
return None
|
||||
|
||||
|
||||
def _candidates(inv: Inventory, host_name: str | None) -> list[Row]:
|
||||
"""The hosts placement may choose from: every eligible one, or the named one."""
|
||||
hosts = sorted(inv.hosts, key=lambda h: h.get("name", ""))
|
||||
if host_name is None:
|
||||
return [h for h in hosts if _refusal(h) is None]
|
||||
named = [h for h in hosts if h.get("name") == host_name]
|
||||
if not named:
|
||||
raise NodeRefused(f"There is no host named {host_name!r}")
|
||||
reason = _refusal(named[0])
|
||||
if reason:
|
||||
raise NodeRefused(f"Host {host_name} {reason}")
|
||||
return named[:1]
|
||||
|
||||
|
||||
def _best(
|
||||
hosts: list[Row], usable: dict[str, Row], names: dict[str, str], networks: list[str]
|
||||
) -> tuple[Row, Row, list[str]] | None:
|
||||
"""The host/datastore pair with the most free space, and the host's networks."""
|
||||
best: tuple[int, Row, Row, list[str]] | None = None
|
||||
for host in sorted(inv.hosts, key=lambda h: h.get("name", "")):
|
||||
if host.get("runtime.connectionState") != "connected" or host.get(
|
||||
"runtime.inMaintenanceMode"
|
||||
):
|
||||
continue
|
||||
for host in hosts:
|
||||
host_nets = _host_networks(host, names, networks)
|
||||
if host_nets is None:
|
||||
continue
|
||||
@@ -88,11 +113,26 @@ def choose_placement(inv: Inventory, storage: str | None, networks: list[str]) -
|
||||
free = int((ds or {}).get("summary", {}).get("freeSpace", 0))
|
||||
if ds is not None and (best is None or free > best[0]):
|
||||
best = (free, host, ds, host_nets)
|
||||
return best[1:] if best else None
|
||||
|
||||
|
||||
def choose_placement(
|
||||
inv: Inventory, storage: str | None, networks: list[str], *, host_name: str | None = None
|
||||
) -> Placement:
|
||||
"""Where a VM on ``storage`` with ``networks`` goes; ``host_name`` pins the host.
|
||||
|
||||
Raises NodeRefused (a ValueError) when the named host does not exist or
|
||||
cannot take the VM, and ValueError when no host can.
|
||||
"""
|
||||
usable = _usable_datastores(inv, storage)
|
||||
names = {n["_moref"]: n.get("name", "") for n in inv.networks}
|
||||
best = _best(_candidates(inv, host_name), usable, names, networks)
|
||||
wanted = f"datastore {storage or '(any)'} and networks {networks}"
|
||||
if best is None and host_name is not None:
|
||||
raise NodeRefused(f"Host {host_name} does not see {wanted}")
|
||||
if best is None:
|
||||
raise ValueError(
|
||||
f"There is no host that sees datastore {storage or '(any)'} and networks {networks}"
|
||||
)
|
||||
_, host, ds, host_nets = best
|
||||
raise ValueError(f"There is no host that sees {wanted}")
|
||||
host, ds, host_nets = best
|
||||
compute = next(c for c in inv.compute_resources if c["_moref"] == host.get("parent"))
|
||||
dc = _datacenter(inv, compute["_moref"])
|
||||
return Placement(
|
||||
|
||||
@@ -35,7 +35,7 @@ from napalm_vmware.provision import transfer
|
||||
from napalm_vmware.provision.image import ImageCache
|
||||
from napalm_vmware.provision.ovf import ovf_descriptor
|
||||
from napalm_vmware.provision.placement import Inventory as PlacementInventory
|
||||
from napalm_vmware.provision.placement import Placement, choose_placement
|
||||
from napalm_vmware.provision.placement import NodeRefused, Placement, choose_placement
|
||||
from napalm_vmware.provision.seed import meta_data, nocloud_iso, user_data
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -153,6 +153,7 @@ class VmwareProvisioningMixin:
|
||||
storage: str | None = None,
|
||||
cpu_type: str | None = None,
|
||||
guest_os: str = "linux",
|
||||
node: str | None = None,
|
||||
download_timeout: int = 300,
|
||||
timeout: int = 180,
|
||||
) -> VMProvisionResultDict:
|
||||
@@ -163,13 +164,11 @@ class VmwareProvisioningMixin:
|
||||
# one, and there is no get_vm_cpu_types() that could offer a model.
|
||||
raise ValueError(f"VMware cannot give a single VM a CPU type ({cpu_type!r})")
|
||||
self._check_nics(nics)
|
||||
place = self._place(storage, nics, node)
|
||||
try:
|
||||
vmdk, image_size = ImageCache(self._image_cache_dir).vmdk(
|
||||
image_url, image_checksum, download_timeout
|
||||
)
|
||||
place = choose_placement(
|
||||
self._placement_inventory(), storage, [n["bridge"] for n in nics]
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise RuntimeError(str(exc)) from exc
|
||||
descriptor = ovf_descriptor(
|
||||
@@ -196,6 +195,24 @@ class VmwareProvisioningMixin:
|
||||
)
|
||||
return {"vmid": props["config.instanceUuid"], "name": name, "node": place.host_name}
|
||||
|
||||
def _place(self, storage: str | None, nics: list[NICConfigDict], node: str | None) -> Placement:
|
||||
"""Where the VM goes, decided before the image is fetched.
|
||||
|
||||
A ``node`` that does not exist or cannot take the VM stays a
|
||||
ValueError, as the contract has it; no host at all is a RuntimeError.
|
||||
"""
|
||||
try:
|
||||
return choose_placement(
|
||||
self._placement_inventory(),
|
||||
storage,
|
||||
[n["bridge"] for n in nics],
|
||||
host_name=node,
|
||||
)
|
||||
except NodeRefused:
|
||||
raise
|
||||
except ValueError as exc:
|
||||
raise RuntimeError(str(exc)) from exc
|
||||
|
||||
def _run_task(self, call: Any, *args: Any, **kwargs: Any) -> None:
|
||||
wait_for_task(self._inventory, invoke(call, *args, **kwargs), _TASK_TIMEOUT)
|
||||
|
||||
|
||||
Reference in new issue
Block a user