feat: map hypervisor clusters to NetBox clusters automatically

- Read the vCenter/ESXi compute resource and the Proxmox cluster name
  (node name when standalone) for every VM
- Match each hypervisor cluster to a NetBox cluster by name, normalized
  name or unique similarity; remember manual choices per profile and
  offer to create missing clusters (with cluster type)
- Import wizard: per-cluster mapping table instead of a single cluster,
  tenant prefilled from the mapped clusters, review shows the mapping
- Show the hypervisor cluster in the VM table

fix: graphic glitches
- Empty state text no longer clipped by the buttons
- Combo boxes open a plain drop-down list instead of the overlay popup
- Status bar badges keep their height and no longer get cut off

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-10-12 15:24:00 +02:00
1 parent 4878275f2a
commit c3b5fb547e
12 files changed
+300 -50

No files matched your search

+4
View File
@@ -110,6 +110,8 @@ def empty_profile(name):
"netbox_ignore_ssl": False,
"sources": [],
"switches": [],
# Remembered assignment "<source id>:<hypervisor cluster>" -> NetBox cluster name.
"cluster_map": {},
}
@@ -154,6 +156,7 @@ class ProfileStore:
"netbox_url": record.get("netbox_url", ""),
"netbox_token": self._decrypt(record.get("netbox_token_encrypted", ""), f"{name}: NetBox-Token"),
"netbox_ignore_ssl": bool(record.get("netbox_ignore_ssl", record.get("ignore_ssl_errors", False))),
"cluster_map": dict(record.get("cluster_map", {})),
})
for source in record.get("sources", []):
profile["sources"].append(self._decrypt_record(source, f"{name}: {source.get('name', 'Quelle')}"))
@@ -214,6 +217,7 @@ class ProfileStore:
"netbox_ignore_ssl": bool(profile.get("netbox_ignore_ssl", False)),
"sources": [self._encrypt_record(source) for source in profile.get("sources", [])],
"switches": [self._encrypt_record(switch) for switch in profile.get("switches", [])],
"cluster_map": dict(profile.get("cluster_map", {})),
})
payload = {
+33 -3
View File
@@ -69,7 +69,7 @@ def load_vmware_source(source, log=_noop):
type=vim.VirtualMachine, all=False, pathSet=[
"name", "config.hardware.memoryMB", "config.hardware.numCPU",
"config.hardware.device", "config.guestFullName", "config.template",
"runtime.powerState", "guest.net",
"runtime.powerState", "runtime.host", "guest.net",
],
)
filter_spec = vim.PropertyCollector.FilterSpec(objectSet=[object_spec], propSet=[property_spec])
@@ -80,11 +80,15 @@ def load_vmware_source(source, log=_noop):
while result and result.token:
result = content.propertyCollector.ContinueRetrievePropertiesEx(result.token)
objects.extend(result.objects or [])
host_clusters = _vmware_host_clusters(content, vim)
normalized = []
for item in objects:
properties = {prop.name: prop.val for prop in (item.propSet or [])}
if properties.get("name") and not properties.get("config.template"):
normalized.append(_normalize_vmware_vm(properties, source, vim))
vm = _normalize_vmware_vm(properties, source, vim)
host = properties.get("runtime.host")
vm["cluster"] = host_clusters.get(getattr(host, "_moId", None), "")
normalized.append(vm)
return normalized
finally:
view.Destroy()
@@ -92,6 +96,20 @@ def load_vmware_source(source, log=_noop):
Disconnect(service_instance)
def _vmware_host_clusters(content, vim):
"""Map ESXi host IDs to their cluster name (or the host name when standalone)."""
result = {}
view = content.viewManager.CreateContainerView(content.rootFolder, [vim.ComputeResource], True)
try:
for resource in view.view:
name = resource.name
for host in resource.host or []:
result[host._moId] = name
finally:
view.Destroy()
return result
def _normalize_vmware_vm(properties, source, vim):
disks = sum(
round(device.capacityInKB / 1024)
@@ -176,6 +194,7 @@ def load_proxmox_source(source, log=_noop):
resources = _proxmox_resources_by_node(session, source)
log(f"{source['name']}: Node-Abfrage meldet {len(resources)} Ressourcen")
cluster_name = _proxmox_cluster_name(session, source)
result = []
for resource in resources:
kind = resource.get("type")
@@ -184,7 +203,9 @@ def load_proxmox_source(source, log=_noop):
if kind == "lxc" and not source.get("include_lxc", True):
continue
try:
result.append(_normalize_proxmox_guest(session, source, resource))
guest = _normalize_proxmox_guest(session, source, resource)
guest["cluster"] = cluster_name or resource.get("node", "")
result.append(guest)
except Exception as error: # noqa: BLE001 - one broken guest must not stop the source
log(f"{source['name']} / VMID {resource.get('vmid')}: {error}", "warning")
if not result:
@@ -195,6 +216,15 @@ def load_proxmox_source(source, log=_noop):
return result
def _proxmox_cluster_name(session, source):
"""Name of the Proxmox cluster, or ``""`` for a standalone node (the node name is used then)."""
try:
status = _proxmox_get(session, source["url"], "/cluster/status") or []
except (requests.RequestException, PermissionError, ValueError):
return ""
return next((item.get("name", "") for item in status if item.get("type") == "cluster"), "")
def _proxmox_resources_by_node(session, source):
resources = []
kinds = ["qemu"] + (["lxc"] if source.get("include_lxc", True) else [])
+58
View File
@@ -1,6 +1,7 @@
"""Import virtual machines, interfaces, IP addresses and prefixes into NetBox."""
import ipaddress
import re
from netbox_sync.core.netbox import assign_mac, related_id, related_name
from netbox_sync.core.virtualization import ip_with_prefix, valid_guest_ip
@@ -22,6 +23,21 @@ def suggested_prefixlen(interface):
return 24 if interface.version == 4 else interface.network.prefixlen
def cluster_key(vm):
"""Identifies the hypervisor cluster of a VM across sources."""
return f"{vm.get('source_id', vm.get('source', ''))}:{vm.get('cluster', '')}"
def _compact(name):
return re.sub(r"[^0-9a-z]", "", (name or "").casefold())
CLUSTER_TYPES = {
"VMware": ("VMware vSphere", "vmware-vsphere"),
"Proxmox": ("Proxmox VE", "proxmox-ve"),
}
def prefix_choices(host_address, detected_prefixlen):
host = ipaddress.ip_address(host_address)
if host.version == 4:
@@ -107,6 +123,48 @@ class VMSyncEngine:
self.log(f"VRF erstellt: {vrf_name}", "success")
return vrf.id
def match_cluster(self, source_cluster, remembered=None):
"""Find the NetBox cluster for a hypervisor cluster.
Returns ``(netbox_cluster_name, how)`` where ``how`` is ``remembered``,
``name`` or ``similar``; ``(None, None)`` if nothing matches uniquely.
"""
if remembered and remembered in self.clusters:
return remembered, "remembered"
if not source_cluster:
return None, None
wanted = source_cluster.casefold()
exact = [name for name in self.clusters if name.casefold() == wanted]
if len(exact) == 1:
return exact[0], "name"
compact = _compact(source_cluster)
same = [name for name in self.clusters if _compact(name) == compact]
if len(same) == 1:
return same[0], "name"
if len(compact) >= 3:
similar = [name for name in self.clusters
if compact in _compact(name) or (len(_compact(name)) >= 3 and _compact(name) in compact)]
if len(similar) == 1:
return similar[0], "similar"
return None, None
def create_cluster(self, name, source_type, tenant_id=None):
"""Create a NetBox cluster (and its cluster type if necessary)."""
if name in self.clusters:
return self.clusters[name]
type_name, slug = CLUSTER_TYPES.get(source_type, (f"{source_type}", _compact(source_type) or "virtualization"))
cluster_type = self.nb.virtualization.cluster_types.get(slug=slug)
if not cluster_type:
cluster_type = self.nb.virtualization.cluster_types.create({"name": type_name, "slug": slug})
self.log(f"Cluster-Typ erstellt: {type_name}", "success")
payload = {"name": name, "type": cluster_type.id, "status": "active"}
if tenant_id:
payload["tenant"] = tenant_id
cluster = self.nb.virtualization.clusters.create(payload)
self.clusters[name] = cluster.id
self.log(f"Cluster erstellt: {name}", "success")
return cluster.id
def get_platform_id(self, guest_os):
guest_os = (guest_os or "").lower()
if not guest_os: