Compare commits

...
3 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 773b3527db chore: release 4.2.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:35:23 +01:00
MrBlakeandClaude Opus 5.5 02f2d19e55 feat: map hypervisor hosts to NetBox devices during VM import
The import wizard asks for every ESXi host / Proxmox node which NetBox
device it corresponds to (names rarely match); the choice is remembered
per profile and set as the VM's device.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:35:17 +01:00
MrBlakeandClaude Opus 5.5 25dfa5e231 feat: export ESXi host / Proxmox node per VM in offline JSON
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:29:43 +01:00
7 changed files with 116 additions and 9 deletions

No files matched your search

+1 -1
View File
@@ -3,7 +3,7 @@
#define AppName "NetBox Synchronizer" #define AppName "NetBox Synchronizer"
#ifndef AppVersion #ifndef AppVersion
#define AppVersion "4.1.1" #define AppVersion "4.2.0"
#endif #endif
#define AppPublisher "Louis-Alexander Kerst" #define AppPublisher "Louis-Alexander Kerst"
#define AppExeName "NetBoxSynchronizer.exe" #define AppExeName "NetBoxSynchronizer.exe"
+1 -1
View File
@@ -1,7 +1,7 @@
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox.""" """NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
APP_NAME = "NetBox Synchronizer" APP_NAME = "NetBox Synchronizer"
APP_VERSION = "4.1.1" APP_VERSION = "4.2.0"
APP_PUBLISHER = "Louis-Alexander Kerst" APP_PUBLISHER = "Louis-Alexander Kerst"
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer" APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
+3
View File
@@ -115,6 +115,7 @@ def empty_profile(name):
"switches": [], "switches": [],
# Remembered assignment "<source id>:<hypervisor cluster>" -> NetBox cluster name. # Remembered assignment "<source id>:<hypervisor cluster>" -> NetBox cluster name.
"cluster_map": {}, "cluster_map": {},
"host_map": {},
# Windows client scan: targets and options, never a password. # Windows client scan: targets and options, never a password.
"clients": dict(DEFAULT_CLIENT_OPTIONS), "clients": dict(DEFAULT_CLIENT_OPTIONS),
} }
@@ -162,6 +163,7 @@ class ProfileStore:
"netbox_token": self._decrypt(record.get("netbox_token_encrypted", ""), f"{name}: NetBox-Token"), "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))), "netbox_ignore_ssl": bool(record.get("netbox_ignore_ssl", record.get("ignore_ssl_errors", False))),
"cluster_map": dict(record.get("cluster_map", {})), "cluster_map": dict(record.get("cluster_map", {})),
"host_map": dict(record.get("host_map", {})),
"clients": {**DEFAULT_CLIENT_OPTIONS, **{key: value for key, value in record.get("clients", {}).items() "clients": {**DEFAULT_CLIENT_OPTIONS, **{key: value for key, value in record.get("clients", {}).items()
if key in DEFAULT_CLIENT_OPTIONS}}, if key in DEFAULT_CLIENT_OPTIONS}},
}) })
@@ -225,6 +227,7 @@ class ProfileStore:
"sources": [self._encrypt_record(source) for source in profile.get("sources", [])], "sources": [self._encrypt_record(source) for source in profile.get("sources", [])],
"switches": [self._encrypt_record(switch) for switch in profile.get("switches", [])], "switches": [self._encrypt_record(switch) for switch in profile.get("switches", [])],
"cluster_map": dict(profile.get("cluster_map", {})), "cluster_map": dict(profile.get("cluster_map", {})),
"host_map": dict(profile.get("host_map", {})),
"clients": dict(profile.get("clients", DEFAULT_CLIENT_OPTIONS)), "clients": dict(profile.get("clients", DEFAULT_CLIENT_OPTIONS)),
}) })
+1
View File
@@ -75,6 +75,7 @@ def validate(data):
raise ExchangeError("Die Datei enthält eine VM ohne Name oder Quelle.") raise ExchangeError("Die Datei enthält eine VM ohne Name oder Quelle.")
vm.setdefault("interfaces", []) vm.setdefault("interfaces", [])
vm.setdefault("cluster", "") vm.setdefault("cluster", "")
vm.setdefault("host", "")
vm.setdefault("status", "offline") vm.setdefault("status", "offline")
for key in ("vcpus", "memory", "disk"): for key in ("vcpus", "memory", "disk"):
vm[key] = int(vm.get(key) or 0) vm[key] = int(vm.get(key) or 0)
+4 -3
View File
@@ -87,7 +87,7 @@ def load_vmware_source(source, log=_noop):
if properties.get("name") and not properties.get("config.template"): if properties.get("name") and not properties.get("config.template"):
vm = _normalize_vmware_vm(properties, source, vim) vm = _normalize_vmware_vm(properties, source, vim)
host = properties.get("runtime.host") host = properties.get("runtime.host")
vm["cluster"] = host_clusters.get(getattr(host, "_moId", None), "") vm["cluster"], vm["host"] = host_clusters.get(getattr(host, "_moId", None), ("", ""))
normalized.append(vm) normalized.append(vm)
return normalized return normalized
finally: finally:
@@ -97,14 +97,14 @@ def load_vmware_source(source, log=_noop):
def _vmware_host_clusters(content, vim): def _vmware_host_clusters(content, vim):
"""Map ESXi host IDs to their cluster name (or the host name when standalone).""" """Map ESXi host IDs to ``(cluster name, host name)``; standalone hosts use their own name as cluster."""
result = {} result = {}
view = content.viewManager.CreateContainerView(content.rootFolder, [vim.ComputeResource], True) view = content.viewManager.CreateContainerView(content.rootFolder, [vim.ComputeResource], True)
try: try:
for resource in view.view: for resource in view.view:
name = resource.name name = resource.name
for host in resource.host or []: for host in resource.host or []:
result[host._moId] = name result[host._moId] = (name, host.name)
finally: finally:
view.Destroy() view.Destroy()
return result return result
@@ -205,6 +205,7 @@ def load_proxmox_source(source, log=_noop):
try: try:
guest = _normalize_proxmox_guest(session, source, resource) guest = _normalize_proxmox_guest(session, source, resource)
guest["cluster"] = cluster_name or resource.get("node", "") guest["cluster"] = cluster_name or resource.get("node", "")
guest["host"] = resource.get("node", "")
result.append(guest) result.append(guest)
except Exception as error: # noqa: BLE001 - one broken guest must not stop the source except Exception as error: # noqa: BLE001 - one broken guest must not stop the source
log(f"{source['name']} / VMID {resource.get('vmid')}: {error}", "warning") log(f"{source['name']} / VMID {resource.get('vmid')}: {error}", "warning")
+38 -2
View File
@@ -28,6 +28,11 @@ def cluster_key(vm):
return f"{vm.get('source_id', vm.get('source', ''))}:{vm.get('cluster', '')}" return f"{vm.get('source_id', vm.get('source', ''))}:{vm.get('cluster', '')}"
def host_key(vm):
"""Identifies the hypervisor host (ESXi host / Proxmox node) of a VM across sources."""
return f"{vm.get('source', '')}:{vm.get('host', '')}"
def _compact(name): def _compact(name):
return re.sub(r"[^0-9a-z]", "", (name or "").casefold()) return re.sub(r"[^0-9a-z]", "", (name or "").casefold())
@@ -60,6 +65,7 @@ class VMSyncEngine:
self.tenants = {} self.tenants = {}
self.vrfs = [] self.vrfs = []
self.platforms = [] self.platforms = []
self.devices = {}
self.existing_vms = {} self.existing_vms = {}
self._reset_run_state() self._reset_run_state()
@@ -86,12 +92,19 @@ class VMSyncEngine:
if tenant_id and tenant_name: if tenant_id and tenant_name:
self.cluster_tenants[cluster.name] = {"id": tenant_id, "name": tenant_name} self.cluster_tenants[cluster.name] = {"id": tenant_id, "name": tenant_name}
self.tenants.setdefault(tenant_name, tenant_id) self.tenants.setdefault(tenant_name, tenant_id)
self.devices = {}
for device in self.nb.dcim.devices.all():
if device.name:
self.devices[device.id] = {
"name": device.name, "site": related_name(device, "site") or "",
"cluster_id": related_id(device, "cluster"),
}
self.existing_vms = {} self.existing_vms = {}
for vm in self.nb.virtualization.virtual_machines.filter(brief=True): for vm in self.nb.virtualization.virtual_machines.filter(brief=True):
self.existing_vms.setdefault(vm.name, []).append(vm.id) self.existing_vms.setdefault(vm.name, []).append(vm.id)
self.log( self.log(
f"NetBox: {len(self.clusters)} Cluster, {len(self.tenants)} Mandanten, " f"NetBox: {len(self.clusters)} Cluster, {len(self.tenants)} Mandanten, "
f"{len(self.vrfs)} VRFs, {sum(map(len, self.existing_vms.values()))} VMs" f"{len(self.vrfs)} VRFs, {len(self.devices)} Geräte, {sum(map(len, self.existing_vms.values()))} VMs"
) )
def tenant_vrfs(self, tenant_id): def tenant_vrfs(self, tenant_id):
@@ -301,7 +314,28 @@ class VMSyncEngine:
raise RuntimeError(f"IP-Adresse {host_address} ist in dieser VRF mehrfach vorhanden") raise RuntimeError(f"IP-Adresse {host_address} ist in dieser VRF mehrfach vorhanden")
return candidates[0] if candidates else None return candidates[0] if candidates else None
def sync_vm(self, source_vm, cluster_id, tenant_id, vrf_id): def device_label(self, device_id):
device = self.devices[device_id]
return f"{device['name']} ({device['site']})" if device["site"] else device["name"]
def prepare_host_device(self, device_id, cluster_id):
"""Make sure the device may host VMs of the cluster; NetBox requires both to match.
A device without cluster is added to it. Returns ``False`` if it belongs to another cluster.
"""
device = self.devices[device_id]
if device["cluster_id"] == cluster_id:
return True
if device["cluster_id"]:
self.log(f"Gerät {device['name']} gehört in NetBox zu einem anderen Cluster – "
"wird nicht als Host eingetragen", "warning")
return False
self.nb.dcim.devices.get(device_id).update({"cluster": cluster_id})
device["cluster_id"] = cluster_id
self.log(f"Gerät {device['name']} dem Cluster zugeordnet", "success")
return True
def sync_vm(self, source_vm, cluster_id, tenant_id, vrf_id, device_id=None):
"""Create or update one VM. Returns ``"created"`` or ``"updated"``.""" """Create or update one VM. Returns ``"created"`` or ``"updated"``."""
payload = { payload = {
"name": source_vm["name"], "cluster": cluster_id, "status": source_vm["status"], "name": source_vm["name"], "cluster": cluster_id, "status": source_vm["status"],
@@ -311,6 +345,8 @@ class VMSyncEngine:
platform_id = self.get_platform_id(source_vm.get("guest_os")) platform_id = self.get_platform_id(source_vm.get("guest_os"))
if platform_id: if platform_id:
payload["platform"] = platform_id payload["platform"] = platform_id
if device_id and self.prepare_host_device(device_id, cluster_id):
payload["device"] = device_id
netbox_vm = self._find_vm(source_vm["name"], cluster_id) netbox_vm = self._find_vm(source_vm["name"], cluster_id)
if netbox_vm: if netbox_vm:
+68 -2
View File
@@ -22,7 +22,7 @@ from PySide6.QtWidgets import (
QWidget, QWidget,
) )
from netbox_sync.core.vm_sync import cluster_key, prefix_choices, vrf_label from netbox_sync.core.vm_sync import cluster_key, host_key, prefix_choices, vrf_label
from netbox_sync.ui.icons import icon from netbox_sync.ui.icons import icon
from netbox_sync.ui.tasks import log_bus from netbox_sync.ui.tasks import log_bus
from netbox_sync.ui.theme import theme from netbox_sync.ui.theme import theme
@@ -31,6 +31,7 @@ from netbox_sync.ui.widgets import Banner, SearchableComboBox, button, checkbox,
NEW_VRF = "__new__" NEW_VRF = "__new__"
NEW_CLUSTER = "__new_cluster__" NEW_CLUSTER = "__new_cluster__"
GLOBAL_VRF = "__global__" GLOBAL_VRF = "__global__"
NO_DEVICE = "__no_device__"
STEPS = ("Ziel", "Netzwerke", "Prüfen", "Import") STEPS = ("Ziel", "Netzwerke", "Prüfen", "Import")
@@ -127,6 +128,53 @@ class ImportWizard(QDialog):
group["vms"].append(vm) group["vms"].append(vm)
return sorted(groups.values(), key=lambda item: (item["source"].casefold(), item["cluster"].casefold())) return sorted(groups.values(), key=lambda item: (item["source"].casefold(), item["cluster"].casefold()))
def _host_groups(self):
groups = {}
for vm in self.vms:
if vm.get("host"):
key = host_key(vm)
groups.setdefault(key, {"key": key, "host": vm["host"], "source": vm.get("source", ""), "vms": []})
groups[key]["vms"].append(vm)
return sorted(groups.values(), key=lambda item: (item["source"].casefold(), item["host"].casefold()))
def _build_host_table(self):
"""Hypervisor host → NetBox device. Names rarely match, so the user always chooses."""
self.host_groups = self._host_groups()
remembered = (self.state.profile or {}).get("host_map", {})
devices = sorted(((self.engine.device_label(device_id), device_id) for device_id in self.engine.devices),
key=lambda item: item[0].casefold())
table = QTableWidget(len(self.host_groups), 3)
table.setHorizontalHeaderLabels(["Hypervisor-Host", "VMs", "NetBox-Gerät"])
table.verticalHeader().setVisible(False)
table.verticalHeader().setDefaultSectionSize(46)
table.setShowGrid(False)
table.setAlternatingRowColors(True)
table.setSelectionMode(QTableWidget.NoSelection)
table.setFocusPolicy(Qt.NoFocus)
table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
table.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
table.setColumnWidth(1, 60)
table.setFixedHeight(46 * min(len(self.host_groups), 4) + 40)
for row, group in enumerate(self.host_groups):
item = QTableWidgetItem(f"{group['host']} · {group['source']}")
item.setToolTip("\n".join(sorted(vm["name"] for vm in group["vms"])))
table.setItem(row, 0, item)
count = QTableWidgetItem(str(len(group["vms"])))
count.setTextAlignment(Qt.AlignCenter)
table.setItem(row, 1, count)
combo = SearchableComboBox("NetBox-Gerät suchen …")
current = remembered.get(group["key"])
if current not in self.engine.devices and current != NO_DEVICE:
current = None
combo.set_items([("– nicht zuordnen –", NO_DEVICE), *devices], current)
holder = QWidget()
holder_layout = QHBoxLayout(holder)
holder_layout.setContentsMargins(0, 4, 8, 4)
holder_layout.addWidget(combo)
table.setCellWidget(row, 2, holder)
group["combo"] = combo
return table
def _build_target_page(self): def _build_target_page(self):
page = QWidget() page = QWidget()
layout = QVBoxLayout(page) layout = QVBoxLayout(page)
@@ -187,6 +235,11 @@ class ImportWizard(QDialog):
group["status"] = status group["status"] = status
combo.activated.connect(lambda _index, g=group: (g.update(how="manual"), self._clusters_changed())) combo.activated.connect(lambda _index, g=group: (g.update(how="manual"), self._clusters_changed()))
layout.addWidget(self.cluster_table) layout.addWidget(self.cluster_table)
host_table = self._build_host_table()
if self.host_groups:
layout.addWidget(label("Auf welches NetBox-Gerät soll jeder Hypervisor-Host gemappt werden?",
muted=True, wrap=True))
layout.addWidget(host_table)
form = QFormLayout() form = QFormLayout()
form.setHorizontalSpacing(18) form.setHorizontalSpacing(18)
@@ -290,6 +343,10 @@ class ImportWizard(QDialog):
if self._selected_cluster(group) is None] if self._selected_cluster(group) is None]
if missing: if missing:
return None, "Bitte für folgende Hypervisor-Cluster einen NetBox-Cluster wählen: " + ", ".join(missing) return None, "Bitte für folgende Hypervisor-Cluster einen NetBox-Cluster wählen: " + ", ".join(missing)
unmapped = [group["host"] for group in self.host_groups if group["combo"].valid_data() is None]
if unmapped:
return None, ("Bitte für folgende Hypervisor-Hosts ein NetBox-Gerät wählen "
"(oder „nicht zuordnen“): " + ", ".join(unmapped))
tenant = self.tenant.valid_data() tenant = self.tenant.valid_data()
vrf = self.vrf.currentData() vrf = self.vrf.currentData()
if not tenant: if not tenant:
@@ -307,8 +364,10 @@ class ImportWizard(QDialog):
"label": group["cluster"] or "(ohne Cluster)", "label": group["cluster"] or "(ohne Cluster)",
"count": len(group["vms"]), "count": len(group["vms"]),
} }
hosts = {group["key"]: group["combo"].valid_data() for group in self.host_groups}
return { return {
"clusters": clusters, "clusters": clusters,
"hosts": hosts,
"tenant": tenant, "tenant": tenant,
"tenant_id": self.engine.tenants[tenant], "tenant_id": self.engine.tenants[tenant],
"vrf_mode": "new" if vrf == NEW_VRF else ("global" if vrf == GLOBAL_VRF else "existing"), "vrf_mode": "new" if vrf == NEW_VRF else ("global" if vrf == GLOBAL_VRF else "existing"),
@@ -508,6 +567,10 @@ class ImportWizard(QDialog):
] ]
rows = [ rows = [
("Cluster", "\n".join(cluster_lines)), ("Cluster", "\n".join(cluster_lines)),
*([("Hosts", "\n".join(
f"{group['host']} → " + ("nicht zuordnen" if target["hosts"][group["key"]] == NO_DEVICE
else self.engine.device_label(target["hosts"][group["key"]]))
for group in self.host_groups))] if self.host_groups else []),
("Mandant", target["tenant"]), ("Mandant", target["tenant"]),
("Standard-VRF", vrf_text), ("Standard-VRF", vrf_text),
("Virtuelle Maschinen", f"{len(self.vms)} gesamt · {new} werden angelegt · {existing} aktualisiert"), ("Virtuelle Maschinen", f"{len(self.vms)} gesamt · {new} werden angelegt · {existing} aktualisiert"),
@@ -581,6 +644,7 @@ class ImportWizard(QDialog):
if self.state.profile is not None: if self.state.profile is not None:
remembered = self.state.profile.setdefault("cluster_map", {}) remembered = self.state.profile.setdefault("cluster_map", {})
remembered.update({key: item["name"] for key, item in target["clusters"].items()}) remembered.update({key: item["name"] for key, item in target["clusters"].items()})
self.state.profile.setdefault("host_map", {}).update(target["hosts"])
self.state.touch() self.state.touch()
log_bus.entry.connect(self._append_log) log_bus.entry.connect(self._append_log)
self.run_progress.setRange(0, len(vms)) self.run_progress.setRange(0, len(vms))
@@ -607,7 +671,9 @@ class ImportWizard(QDialog):
break break
ctx.progress(index, len(vms), vm["name"]) ctx.progress(index, len(vms), vm["name"])
try: try:
outcome = engine.sync_vm(vm, cluster_ids[cluster_key(vm)], target["tenant_id"], vrf_id) device_id = target["hosts"].get(host_key(vm))
outcome = engine.sync_vm(vm, cluster_ids[cluster_key(vm)], target["tenant_id"], vrf_id,
None if device_id == NO_DEVICE else device_id)
results[outcome] += 1 results[outcome] += 1
except Exception as error: # noqa: BLE001 except Exception as error: # noqa: BLE001
results["failed"].append(f"{vm['name']}: {error}") results["failed"].append(f"{vm['name']}: {error}")